1 #ifndef SQL_ITEM_INCLUDED
2 #define SQL_ITEM_INCLUDED
3 
4 /* Copyright (c) 2000, 2017, Oracle and/or its affiliates.
5    Copyright (c) 2009, 2021, MariaDB Corporation.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; version 2 of the License.
10 
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15 
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1335  USA */
19 
20 
21 #ifdef USE_PRAGMA_INTERFACE
22 #pragma interface			/* gcc class implementation */
23 #endif
24 
25 #include "sql_priv.h"                /* STRING_BUFFER_USUAL_SIZE */
26 #include "unireg.h"
27 #include "sql_const.h"                 /* RAND_TABLE_BIT, MAX_FIELD_NAME */
28 #include "field.h"                              /* Derivation */
29 #include "sql_type.h"
30 #include "sql_time.h"
31 #include "mem_root_array.h"
32 
33 C_MODE_START
34 #include <ma_dyncol.h>
35 
36 /*
37   A prototype for a C-compatible structure to store a value of any data type.
38   Currently it has to stay in /sql, as it depends on String and my_decimal.
39   We'll do the following changes:
40   1. add pure C "struct st_string" and "struct st_my_decimal"
41   2. change type of m_string to struct st_string and move inside the union
42   3. change type of m_decmal to struct st_my_decimal and move inside the union
43   4. move the definition to some file in /include
44 */
45 struct st_value
46 {
47   enum enum_dynamic_column_type m_type;
48   union
49   {
50     longlong m_longlong;
51     double m_double;
52     MYSQL_TIME m_time;
53   } value;
54   String m_string;
55   my_decimal m_decimal;
56 };
57 
58 C_MODE_END
59 
60 
61 class Value: public st_value
62 {
63 public:
is_null()64   bool is_null() const { return m_type == DYN_COL_NULL; }
is_longlong()65   bool is_longlong() const
66   {
67     return m_type == DYN_COL_UINT || m_type == DYN_COL_INT;
68   }
is_double()69   bool is_double() const { return m_type == DYN_COL_DOUBLE; }
is_temporal()70   bool is_temporal() const { return m_type == DYN_COL_DATETIME; }
is_string()71   bool is_string() const { return m_type == DYN_COL_STRING; }
is_decimal()72   bool is_decimal() const { return m_type == DYN_COL_DECIMAL; }
73 };
74 
75 
76 template<size_t buffer_size>
77 class ValueBuffer: public Value
78 {
79   char buffer[buffer_size];
reset_buffer()80   void reset_buffer()
81   {
82     m_string.set(buffer, buffer_size, &my_charset_bin);
83   }
84 public:
ValueBuffer()85   ValueBuffer()
86   {
87     reset_buffer();
88   }
89 };
90 
91 
92 #ifdef DBUG_OFF
dbug_print_item(Item * item)93 static inline const char *dbug_print_item(Item *item) { return NULL; }
94 #else
95 const char *dbug_print_item(Item *item);
96 #endif
97 
98 class Virtual_tmp_table;
99 class sp_head;
100 class Protocol;
101 struct TABLE_LIST;
102 void item_init(void);			/* Init item functions */
103 class Item_basic_value;
104 class Item_result_field;
105 class Item_field;
106 class Item_ref;
107 class Item_param;
108 class user_var_entry;
109 class JOIN;
110 struct KEY_FIELD;
111 struct SARGABLE_PARAM;
112 class RANGE_OPT_PARAM;
113 class SEL_TREE;
114 class With_sum_func_cache;
115 
116 enum precedence {
117   LOWEST_PRECEDENCE,
118   ASSIGN_PRECEDENCE,    // :=
119   OR_PRECEDENCE,        // OR, || (unless PIPES_AS_CONCAT)
120   XOR_PRECEDENCE,       // XOR
121   AND_PRECEDENCE,       // AND, &&
122   NOT_PRECEDENCE,       // NOT (unless HIGH_NOT_PRECEDENCE)
123   CMP_PRECEDENCE,       // =, <=>, >=, >, <=, <, <>, !=, IS
124   BETWEEN_PRECEDENCE,   // BETWEEN
125   IN_PRECEDENCE,        // IN, LIKE, REGEXP
126   BITOR_PRECEDENCE,     // |
127   BITAND_PRECEDENCE,    // &
128   SHIFT_PRECEDENCE,     // <<, >>
129   INTERVAL_PRECEDENCE,  // first argument in +INTERVAL
130   ADD_PRECEDENCE,       // +, -
131   MUL_PRECEDENCE,       // *, /, DIV, %, MOD
132   BITXOR_PRECEDENCE,    // ^
133   PIPES_PRECEDENCE,     // || (if PIPES_AS_CONCAT)
134   NEG_PRECEDENCE,       // unary -, ~, !, NOT (if HIGH_NOT_PRECEDENCE)
135   COLLATE_PRECEDENCE,   // BINARY, COLLATE
136   DEFAULT_PRECEDENCE,
137   HIGHEST_PRECEDENCE
138 };
139 
140 bool mark_unsupported_function(const char *where, void *store, uint result);
141 
142 /* convenience helper for mark_unsupported_function() above */
143 bool mark_unsupported_function(const char *w1, const char *w2,
144                                void *store, uint result);
145 
146 /* Bits for the split_sum_func() function */
147 #define SPLIT_SUM_SKIP_REGISTERED 1     /* Skip registered funcs */
148 #define SPLIT_SUM_SELECT 2		/* SELECT item; Split all parts */
149 
150 
151 #define NO_EXTRACTION_FL              (1 << 6)
152 #define FULL_EXTRACTION_FL            (1 << 7)
153 #define DELETION_FL                   (1 << 8)
154 #define IMMUTABLE_FL                  (1 << 9)
155 #define SUBSTITUTION_FL               (1 << 10)
156 #define EXTRACTION_MASK                                                \
157   (NO_EXTRACTION_FL | FULL_EXTRACTION_FL | DELETION_FL | IMMUTABLE_FL)
158 
159 extern const char *item_empty_name;
160 
161 void dummy_error_processor(THD *thd, void *data);
162 
163 void view_error_processor(THD *thd, void *data);
164 
165 /*
166   Instances of Name_resolution_context store the information necessary for
167   name resolution of Items and other context analysis of a query made in
168   fix_fields().
169 
170   This structure is a part of SELECT_LEX, a pointer to this structure is
171   assigned when an item is created (which happens mostly during  parsing
172   (sql_yacc.yy)), but the structure itself will be initialized after parsing
173   is complete
174 
175   TODO: move subquery of INSERT ... SELECT and CREATE ... SELECT to
176   separate SELECT_LEX which allow to remove tricks of changing this
177   structure before and after INSERT/CREATE and its SELECT to make correct
178   field name resolution.
179 */
180 struct Name_resolution_context: Sql_alloc
181 {
182   /*
183     The name resolution context to search in when an Item cannot be
184     resolved in this context (the context of an outer select)
185   */
186   Name_resolution_context *outer_context;
187 
188   /*
189     List of tables used to resolve the items of this context.  Usually these
190     are tables from the FROM clause of SELECT statement.  The exceptions are
191     INSERT ... SELECT and CREATE ... SELECT statements, where SELECT
192     subquery is not moved to a separate SELECT_LEX.  For these types of
193     statements we have to change this member dynamically to ensure correct
194     name resolution of different parts of the statement.
195   */
196   TABLE_LIST *table_list;
197   /*
198     In most cases the two table references below replace 'table_list' above
199     for the purpose of name resolution. The first and last name resolution
200     table references allow us to search only in a sub-tree of the nested
201     join tree in a FROM clause. This is needed for NATURAL JOIN, JOIN ... USING
202     and JOIN ... ON.
203   */
204   TABLE_LIST *first_name_resolution_table;
205   /*
206     Last table to search in the list of leaf table references that begins
207     with first_name_resolution_table.
208   */
209   TABLE_LIST *last_name_resolution_table;
210 
211   /* Cache first_name_resolution_table in setup_natural_join_row_types */
212   TABLE_LIST *natural_join_first_table;
213   /*
214     SELECT_LEX item belong to, in case of merged VIEW it can differ from
215     SELECT_LEX where item was created, so we can't use table_list/field_list
216     from there
217   */
218   st_select_lex *select_lex;
219 
220   /*
221     Processor of errors caused during Item name resolving, now used only to
222     hide underlying tables in errors about views (i.e. it substitute some
223     errors for views)
224   */
225   void (*error_processor)(THD *, void *);
226   void *error_processor_data;
227 
228   /*
229     When TRUE items are resolved in this context both against the
230     SELECT list and this->table_list. If FALSE, items are resolved
231     only against this->table_list.
232   */
233   bool resolve_in_select_list;
234 
235   /*
236     Security context of this name resolution context. It's used for views
237     and is non-zero only if the view is defined with SQL SECURITY DEFINER.
238   */
239   Security_context *security_ctx;
240 
Name_resolution_contextName_resolution_context241   Name_resolution_context()
242     :outer_context(0), table_list(0), select_lex(0),
243     error_processor_data(0),
244     security_ctx(0)
245     {}
246 
initName_resolution_context247   void init()
248   {
249     resolve_in_select_list= FALSE;
250     error_processor= &dummy_error_processor;
251     first_name_resolution_table= NULL;
252     last_name_resolution_table= NULL;
253   }
254 
resolve_in_table_list_onlyName_resolution_context255   void resolve_in_table_list_only(TABLE_LIST *tables)
256   {
257     table_list= first_name_resolution_table= tables;
258     resolve_in_select_list= FALSE;
259   }
260 
process_errorName_resolution_context261   void process_error(THD *thd)
262   {
263     (*error_processor)(thd, error_processor_data);
264   }
outer_selectName_resolution_context265   st_select_lex *outer_select()
266   {
267     return (outer_context ?
268             outer_context->select_lex :
269             NULL);
270   }
271 };
272 
273 
274 /*
275   Store and restore the current state of a name resolution context.
276 */
277 
278 class Name_resolution_context_state
279 {
280 private:
281   TABLE_LIST *save_table_list;
282   TABLE_LIST *save_first_name_resolution_table;
283   TABLE_LIST *save_next_name_resolution_table;
284   bool        save_resolve_in_select_list;
285   TABLE_LIST *save_next_local;
286 
287 public:
Name_resolution_context_state()288   Name_resolution_context_state() {}          /* Remove gcc warning */
289 
290 public:
291   /* Save the state of a name resolution context. */
save_state(Name_resolution_context * context,TABLE_LIST * table_list)292   void save_state(Name_resolution_context *context, TABLE_LIST *table_list)
293   {
294     save_table_list=                  context->table_list;
295     save_first_name_resolution_table= context->first_name_resolution_table;
296     save_resolve_in_select_list=      context->resolve_in_select_list;
297     save_next_local=                  table_list->next_local;
298     save_next_name_resolution_table=  table_list->next_name_resolution_table;
299   }
300 
301   /* Restore a name resolution context from saved state. */
restore_state(Name_resolution_context * context,TABLE_LIST * table_list)302   void restore_state(Name_resolution_context *context, TABLE_LIST *table_list)
303   {
304     table_list->next_local=                save_next_local;
305     table_list->next_name_resolution_table= save_next_name_resolution_table;
306     context->table_list=                   save_table_list;
307     context->first_name_resolution_table=  save_first_name_resolution_table;
308     context->resolve_in_select_list=       save_resolve_in_select_list;
309   }
310 
get_first_name_resolution_table()311   TABLE_LIST *get_first_name_resolution_table()
312   {
313     return save_first_name_resolution_table;
314   }
315 };
316 
317 class Name_resolution_context_backup
318 {
319   Name_resolution_context &ctx;
320   TABLE_LIST &table_list;
321   table_map save_map;
322   Name_resolution_context_state ctx_state;
323 
324 public:
Name_resolution_context_backup(Name_resolution_context & _ctx,TABLE_LIST & _table_list)325   Name_resolution_context_backup(Name_resolution_context &_ctx, TABLE_LIST &_table_list)
326     : ctx(_ctx), table_list(_table_list), save_map(_table_list.map)
327   {
328     ctx_state.save_state(&ctx, &table_list);
329     ctx.table_list= &table_list;
330     ctx.first_name_resolution_table= &table_list;
331   }
~Name_resolution_context_backup()332   ~Name_resolution_context_backup()
333   {
334     ctx_state.restore_state(&ctx, &table_list);
335     table_list.map= save_map;
336   }
337 };
338 
339 
340 /*
341   This enum is used to report information about monotonicity of function
342   represented by Item* tree.
343   Monotonicity is defined only for Item* trees that represent table
344   partitioning expressions (i.e. have no subselects/user vars/PS parameters
345   etc etc). An Item* tree is assumed to have the same monotonicity properties
346   as its corresponding function F:
347 
348   [signed] longlong F(field1, field2, ...) {
349     put values of field_i into table record buffer;
350     return item->val_int();
351   }
352 
353   NOTE
354   At the moment function monotonicity is not well defined (and so may be
355   incorrect) for Item trees with parameters/return types that are different
356   from INT_RESULT, may be NULL, or are unsigned.
357   It will be possible to address this issue once the related partitioning bugs
358   (BUG#16002, BUG#15447, BUG#13436) are fixed.
359 
360   The NOT_NULL enums are used in TO_DAYS, since TO_DAYS('2001-00-00') returns
361   NULL which puts those rows into the NULL partition, but
362   '2000-12-31' < '2001-00-00' < '2001-01-01'. So special handling is needed
363   for this (see Bug#20577).
364 */
365 
366 typedef enum monotonicity_info
367 {
368    NON_MONOTONIC,              /* none of the below holds */
369    MONOTONIC_INCREASING,       /* F() is unary and (x < y) => (F(x) <= F(y)) */
370    MONOTONIC_INCREASING_NOT_NULL,  /* But only for valid/real x and y */
371    MONOTONIC_STRICT_INCREASING,/* F() is unary and (x < y) => (F(x) <  F(y)) */
372    MONOTONIC_STRICT_INCREASING_NOT_NULL  /* But only for valid/real x and y */
373 } enum_monotonicity_info;
374 
375 /*************************************************************************/
376 
377 class sp_rcontext;
378 
379 /**
380   A helper class to collect different behavior of various kinds of SP variables:
381   - local SP variables and SP parameters
382   - PACKAGE BODY routine variables
383   - (there will be more kinds in the future)
384 */
385 
386 class Sp_rcontext_handler
387 {
388 public:
~Sp_rcontext_handler()389   virtual ~Sp_rcontext_handler() {}
390   /**
391     A prefix used for SP variable names in queries:
392     - EXPLAIN EXTENDED
393     - SHOW PROCEDURE CODE
394     Local variables and SP parameters have empty prefixes.
395     Package body variables are marked with a special prefix.
396     This improves readability of the output of these queries,
397     especially when a local variable or a parameter has the same
398     name with a package body variable.
399   */
400   virtual const LEX_CSTRING *get_name_prefix() const= 0;
401   /**
402     At execution time THD->spcont points to the run-time context (sp_rcontext)
403     of the currently executed routine.
404     Local variables store their data in the sp_rcontext pointed by thd->spcont.
405     Package body variables store data in separate sp_rcontext that belongs
406     to the package.
407     This method provides access to the proper sp_rcontext structure,
408     depending on the SP variable kind.
409   */
410   virtual sp_rcontext *get_rcontext(sp_rcontext *ctx) const= 0;
411 };
412 
413 
414 class Sp_rcontext_handler_local: public Sp_rcontext_handler
415 {
416 public:
417   const LEX_CSTRING *get_name_prefix() const;
418   sp_rcontext *get_rcontext(sp_rcontext *ctx) const;
419 };
420 
421 
422 class Sp_rcontext_handler_package_body: public Sp_rcontext_handler
423 {
424 public:
425   const LEX_CSTRING *get_name_prefix() const;
426   sp_rcontext *get_rcontext(sp_rcontext *ctx) const;
427 };
428 
429 
430 extern MYSQL_PLUGIN_IMPORT
431   Sp_rcontext_handler_local sp_rcontext_handler_local;
432 
433 
434 extern MYSQL_PLUGIN_IMPORT
435   Sp_rcontext_handler_package_body sp_rcontext_handler_package_body;
436 
437 
438 
439 class Item_equal;
440 
441 struct st_join_table* const NO_PARTICULAR_TAB= (struct st_join_table*)0x1;
442 
443 typedef struct replace_equal_field_arg
444 {
445   Item_equal *item_equal;
446   struct st_join_table *context_tab;
447 } REPLACE_EQUAL_FIELD_ARG;
448 
449 class Settable_routine_parameter
450 {
451 public:
452   /*
453     Set required privileges for accessing the parameter.
454 
455     SYNOPSIS
456       set_required_privilege()
457         rw        if 'rw' is true then we are going to read and set the
458                   parameter, so SELECT and UPDATE privileges might be
459                   required, otherwise we only reading it and SELECT
460                   privilege might be required.
461   */
Settable_routine_parameter()462   Settable_routine_parameter() {}
~Settable_routine_parameter()463   virtual ~Settable_routine_parameter() {}
set_required_privilege(bool rw)464   virtual void set_required_privilege(bool rw) {};
465 
466   /*
467     Set parameter value.
468 
469     SYNOPSIS
470       set_value()
471         thd       thread handle
472         ctx       context to which parameter belongs (if it is local
473                   variable).
474         it        item which represents new value
475 
476     RETURN
477       FALSE if parameter value has been set,
478       TRUE if error has occurred.
479   */
480   virtual bool set_value(THD *thd, sp_rcontext *ctx, Item **it)= 0;
481 
set_out_param_info(Send_field * info)482   virtual void set_out_param_info(Send_field *info) {}
483 
get_out_param_info()484   virtual const Send_field *get_out_param_info() const
485   { return NULL; }
486 
get_item_param()487   virtual Item_param *get_item_param() { return 0; }
488 };
489 
490 
491 /*
492   A helper class to calculate offset and length of a query fragment
493   - outside of SP
494   - inside an SP
495   - inside a compound block
496 */
497 class Query_fragment
498 {
499   uint m_pos;
500   uint m_length;
set(size_t pos,size_t length)501   void set(size_t pos, size_t length)
502   {
503     DBUG_ASSERT(pos < UINT_MAX32);
504     DBUG_ASSERT(length < UINT_MAX32);
505     m_pos= (uint) pos;
506     m_length= (uint) length;
507   }
508 public:
509   Query_fragment(THD *thd, sp_head *sphead, const char *start, const char *end);
pos()510   uint pos() const { return m_pos; }
length()511   uint length() const { return m_length; }
512 };
513 
514 
515 /**
516   This is used for items in the query that needs to be rewritten
517   before binlogging
518 
519   At the moment this applies to Item_param and Item_splocal
520 */
521 class Rewritable_query_parameter
522 {
523   public:
524   /*
525     Offset inside the query text.
526     Value of 0 means that this object doesn't have to be replaced
527     (for example SP variables in control statements)
528   */
529   my_ptrdiff_t pos_in_query;
530 
531   /*
532     Byte length of parameter name in the statement.  This is not
533     Item::name.length because name.length contains byte length of UTF8-encoded
534     name, but the query string is in the client charset.
535   */
536   uint len_in_query;
537 
538   bool limit_clause_param;
539 
540   Rewritable_query_parameter(uint pos_in_q= 0, uint len_in_q= 0)
pos_in_query(pos_in_q)541     : pos_in_query(pos_in_q), len_in_query(len_in_q),
542       limit_clause_param(false)
543   { }
544 
~Rewritable_query_parameter()545   virtual ~Rewritable_query_parameter() { }
546 
547   virtual bool append_for_log(THD *thd, String *str) = 0;
548 };
549 
550 class Copy_query_with_rewrite
551 {
552   THD *thd;
553   const char *src;
554   size_t src_len, from;
555   String *dst;
556 
copy_up_to(size_t bytes)557   bool copy_up_to(size_t bytes)
558   {
559     DBUG_ASSERT(bytes >= from);
560     return dst->append(src + from, uint32(bytes - from));
561   }
562 
563 public:
564 
Copy_query_with_rewrite(THD * t,const char * s,size_t l,String * d)565   Copy_query_with_rewrite(THD *t, const char *s, size_t l, String *d)
566     :thd(t), src(s), src_len(l), from(0), dst(d) { }
567 
append(Rewritable_query_parameter * p)568   bool append(Rewritable_query_parameter *p)
569   {
570     if (copy_up_to(p->pos_in_query) || p->append_for_log(thd, dst))
571       return true;
572     from= p->pos_in_query + p->len_in_query;
573     return false;
574   }
575 
finalize()576   bool finalize()
577   { return copy_up_to(src_len); }
578 };
579 
580 struct st_dyncall_create_def
581 {
582   Item  *key, *value;
583   CHARSET_INFO *cs;
584   uint len, frac;
585   DYNAMIC_COLUMN_TYPE type;
586 };
587 
588 typedef struct st_dyncall_create_def DYNCALL_CREATE_DEF;
589 
590 
591 typedef bool (Item::*Item_processor) (void *arg);
592 /*
593   Analyzer function
594     SYNOPSIS
595       argp   in/out IN:  Analysis parameter
596                     OUT: Parameter to be passed to the transformer
597 
598     RETURN
599       TRUE   Invoke the transformer
600       FALSE  Don't do it
601 
602 */
603 typedef bool (Item::*Item_analyzer) (uchar **argp);
604 typedef Item* (Item::*Item_transformer) (THD *thd, uchar *arg);
605 typedef void (*Cond_traverser) (const Item *item, void *arg);
606 typedef bool (Item::*Pushdown_checker) (uchar *arg);
607 
608 struct st_cond_statistic;
609 
610 struct find_selective_predicates_list_processor_data
611 {
612   TABLE *table;
613   List<st_cond_statistic> list;
614 };
615 
616 class MY_LOCALE;
617 
618 class Item_equal;
619 class COND_EQUAL;
620 
621 class st_select_lex_unit;
622 
623 class Item_func_not;
624 class Item_splocal;
625 
626 /* Item::common_flags */
627 /* Indicates that name of this Item autogenerated or set by user */
628 #define IS_AUTO_GENERATED_NAME 1
629 /* Indicates that this item is in CYCLE clause of WITH */
630 #define IS_IN_WITH_CYCLE       2
631 
632 
633 /**
634   String_copier that sends Item specific warnings.
635 */
636 class String_copier_for_item: public String_copier
637 {
638   THD *m_thd;
639 public:
640   bool copy_with_warn(CHARSET_INFO *dstcs, String *dst,
641                       CHARSET_INFO *srccs, const char *src,
642                       uint32 src_length, uint32 nchars);
String_copier_for_item(THD * thd)643   String_copier_for_item(THD *thd): m_thd(thd) { }
644 };
645 
646 
647 /**
648   A helper class describing what kind of Item created a temporary field.
649   - If m_field is set, then the temporary field was created from Field
650     (e.g. when the Item was Item_field, or Item_ref pointing to Item_field)
651   - If m_default_field is set, then there is a usable DEFAULT value.
652     (e.g. when the Item is Item_field)
653   - If m_item_result_field is set, then the temporary field was created
654     from certain sub-types of Item_result_field (e.g. Item_func)
655   See create_tmp_field() in sql_select.cc for details.
656 */
657 
658 class Tmp_field_src
659 {
660   Field *m_field;
661   Field *m_default_field;
662   Item_result_field *m_item_result_field;
663 public:
Tmp_field_src()664   Tmp_field_src()
665    :m_field(0),
666     m_default_field(0),
667     m_item_result_field(0)
668   { }
field()669   Field *field() const { return m_field; }
default_field()670   Field *default_field() const { return m_default_field; }
item_result_field()671   Item_result_field *item_result_field() const { return m_item_result_field; }
set_field(Field * field)672   void set_field(Field *field) { m_field= field; }
set_default_field(Field * field)673   void set_default_field(Field *field) { m_default_field= field; }
set_item_result_field(Item_result_field * item)674   void set_item_result_field(Item_result_field *item)
675   { m_item_result_field= item; }
676 };
677 
678 
679 /**
680   Parameters for create_tmp_field_ex().
681   See create_tmp_field() in sql_select.cc for details.
682 */
683 
684 class Tmp_field_param
685 {
686   bool m_group;
687   bool m_modify_item;
688   bool m_table_cant_handle_bit_fields;
689   bool m_make_copy_field;
690 public:
Tmp_field_param(bool group,bool modify_item,bool table_cant_handle_bit_fields,bool make_copy_field)691   Tmp_field_param(bool group,
692                   bool modify_item,
693                   bool table_cant_handle_bit_fields,
694                   bool make_copy_field)
695    :m_group(group),
696     m_modify_item(modify_item),
697     m_table_cant_handle_bit_fields(table_cant_handle_bit_fields),
698     m_make_copy_field(make_copy_field)
699   { }
group()700   bool group() const { return m_group; }
modify_item()701   bool modify_item() const { return m_modify_item; }
table_cant_handle_bit_fields()702   bool table_cant_handle_bit_fields() const
703   { return m_table_cant_handle_bit_fields; }
make_copy_field()704   bool make_copy_field() const { return m_make_copy_field; }
set_modify_item(bool to)705   void set_modify_item(bool to) { m_modify_item= to; }
706 };
707 
708 
709 class Item_const
710 {
711 public:
~Item_const()712   virtual ~Item_const() {}
713   virtual const Type_all_attributes *get_type_all_attributes_from_const() const= 0;
const_is_null()714   virtual bool const_is_null() const { return false; }
const_ptr_longlong()715   virtual const longlong *const_ptr_longlong() const { return NULL; }
const_ptr_double()716   virtual const double *const_ptr_double() const { return NULL; }
const_ptr_my_decimal()717   virtual const my_decimal *const_ptr_my_decimal() const { return NULL; }
const_ptr_mysql_time()718   virtual const MYSQL_TIME *const_ptr_mysql_time() const { return NULL; }
const_ptr_string()719   virtual const String *const_ptr_string() const { return NULL; }
720 };
721 
722 
723 /****************************************************************************/
724 
725 #define STOP_PTR ((void *) 1)
726 
727 class Item: public Value_source,
728             public Type_all_attributes
729 {
730   /**
731     The index in the JOIN::join_tab array of the JOIN_TAB this Item is attached
732     to. Items are attached (or 'pushed') to JOIN_TABs during optimization by the
733     make_cond_for_table procedure. During query execution, this item is
734     evaluated when the join loop reaches the corresponding JOIN_TAB.
735 
736     If the value of join_tab_idx >= MAX_TABLES, this means that there is no
737     corresponding JOIN_TAB.
738   */
739   uint join_tab_idx;
740 
741   static void *operator new(size_t size);
742 
743 public:
new(size_t size,MEM_ROOT * mem_root)744   static void *operator new(size_t size, MEM_ROOT *mem_root) throw ()
745   { return alloc_root(mem_root, size); }
delete(void * ptr,size_t size)746   static void operator delete(void *ptr,size_t size) { TRASH_FREE(ptr, size); }
delete(void * ptr,MEM_ROOT * mem_root)747   static void operator delete(void *ptr, MEM_ROOT *mem_root) {}
748 
749   enum Type {FIELD_ITEM= 0, FUNC_ITEM, SUM_FUNC_ITEM,
750              WINDOW_FUNC_ITEM,
751              /*
752                NOT NULL literal-alike constants, which do not change their
753                value during an SQL statement execution, but can optionally
754                change their value between statements:
755                - Item_literal               - real NOT NULL constants
756                - Item_param                 - can change between statements
757                - Item_splocal               - can change between statements
758                - Item_user_var_as_out_param - hack
759                Note, Item_user_var_as_out_param actually abuses the type code.
760                It should be moved out of the Item tree eventually.
761              */
762              CONST_ITEM,
763              NULL_ITEM,     // Item_null or Item_param bound to NULL
764              COPY_STR_ITEM, FIELD_AVG_ITEM, DEFAULT_VALUE_ITEM,
765              CONTEXTUALLY_TYPED_VALUE_ITEM,
766              PROC_ITEM,COND_ITEM, REF_ITEM, FIELD_STD_ITEM,
767              FIELD_VARIANCE_ITEM, INSERT_VALUE_ITEM,
768              SUBSELECT_ITEM, ROW_ITEM, CACHE_ITEM, TYPE_HOLDER,
769              PARAM_ITEM, TRIGGER_FIELD_ITEM,
770              EXPR_CACHE_ITEM};
771 
772   enum cond_result { COND_UNDEF,COND_OK,COND_TRUE,COND_FALSE };
773 
774   enum traverse_order { POSTFIX, PREFIX };
775 
776   /* Cache of the result of is_expensive(). */
777   int8 is_expensive_cache;
778 
779   /* Reuse size, only used by SP local variable assignment, otherwise 0 */
780   uint rsize;
781 
782 protected:
783   /*
784     str_values's main purpose is to be used to cache the value in
785     save_in_field
786   */
787   String str_value;
788 
789   SEL_TREE *get_mm_tree_for_const(RANGE_OPT_PARAM *param);
790 
791   /**
792     Create a field based on the exact data type handler.
793   */
create_table_field_from_handler(MEM_ROOT * root,TABLE * table)794   Field *create_table_field_from_handler(MEM_ROOT *root, TABLE *table)
795   {
796     const Type_handler *h= type_handler();
797     return h->make_and_init_table_field(root, &name,
798                                         Record_addr(maybe_null),
799                                         *this, table);
800   }
801   /**
802     Create a field based on field_type of argument.
803     This is used to create a field for
804     - IFNULL(x,something)
805     - time functions
806     - prepared statement placeholders
807     - SP variables with data type references: DECLARE a TYPE OF t1.a;
808     @retval  NULL  error
809     @retval  !NULL on success
810   */
tmp_table_field_from_field_type(MEM_ROOT * root,TABLE * table)811   Field *tmp_table_field_from_field_type(MEM_ROOT *root, TABLE *table)
812   {
813     DBUG_ASSERT(is_fixed());
814     const Type_handler *h= type_handler()->type_handler_for_tmp_table(this);
815     return h->make_and_init_table_field(root, &name,
816                                         Record_addr(maybe_null),
817                                         *this, table);
818   }
819   /**
820     Create a temporary field for a simple Item, which does not
821     need any special action after the field creation:
822     - is not an Item_field descendant (and not a reference to Item_field)
823     - is not an Item_result_field descendant
824     - does not need to copy any DEFAULT value to the result Field
825     - does not need to set Field::is_created_from_null_item for the result
826     See create_tmp_field_ex() for details on parameters and return values.
827   */
create_tmp_field_ex_simple(MEM_ROOT * root,TABLE * table,Tmp_field_src * src,const Tmp_field_param * param)828   Field *create_tmp_field_ex_simple(MEM_ROOT *root,
829                                     TABLE *table,
830                                     Tmp_field_src *src,
831                                     const Tmp_field_param *param)
832   {
833     DBUG_ASSERT(!param->make_copy_field());
834     DBUG_ASSERT(!is_result_field());
835     DBUG_ASSERT(type() != NULL_ITEM);
836     return tmp_table_field_from_field_type(root, table);
837   }
838   Field *create_tmp_field_int(MEM_ROOT *root, TABLE *table,
839                               uint convert_int_length);
840   Field *tmp_table_field_from_field_type_maybe_null(MEM_ROOT *root,
841                                             TABLE *table,
842                                             Tmp_field_src *src,
843                                             const Tmp_field_param *param,
844                                             bool is_explicit_null);
845 
846   void raise_error_not_evaluable();
847   void push_note_converted_to_negative_complement(THD *thd);
848   void push_note_converted_to_positive_complement(THD *thd);
849 
850   /* Helper methods, to get an Item value from another Item */
val_real_from_item(Item * item)851   double val_real_from_item(Item *item)
852   {
853     DBUG_ASSERT(is_fixed());
854     double value= item->val_real();
855     null_value= item->null_value;
856     return value;
857   }
val_int_from_item(Item * item)858   longlong val_int_from_item(Item *item)
859   {
860     DBUG_ASSERT(is_fixed());
861     longlong value= item->val_int();
862     null_value= item->null_value;
863     return value;
864   }
val_str_from_item(Item * item,String * str)865   String *val_str_from_item(Item *item, String *str)
866   {
867     DBUG_ASSERT(is_fixed());
868     String *res= item->val_str(str);
869     if (res)
870       res->set_charset(collation.collation);
871     if ((null_value= item->null_value))
872       res= NULL;
873     return res;
874   }
val_native_from_item(THD * thd,Item * item,Native * to)875   bool val_native_from_item(THD *thd, Item *item, Native *to)
876   {
877     DBUG_ASSERT(is_fixed());
878     null_value= item->val_native(thd, to);
879     DBUG_ASSERT(null_value == item->null_value);
880     return null_value;
881   }
val_native_from_field(Field * field,Native * to)882   bool val_native_from_field(Field *field, Native *to)
883   {
884     if ((null_value= field->is_null()))
885       return true;
886     return (null_value= field->val_native(to));
887   }
val_native_with_conversion_from_item(THD * thd,Item * item,Native * to,const Type_handler * handler)888   bool val_native_with_conversion_from_item(THD *thd, Item *item, Native *to,
889                                             const Type_handler *handler)
890   {
891     DBUG_ASSERT(is_fixed());
892     return null_value= item->val_native_with_conversion(thd, to, handler);
893   }
val_decimal_from_item(Item * item,my_decimal * decimal_value)894   my_decimal *val_decimal_from_item(Item *item, my_decimal *decimal_value)
895   {
896     DBUG_ASSERT(is_fixed());
897     my_decimal *value= item->val_decimal(decimal_value);
898     if ((null_value= item->null_value))
899       value= NULL;
900     return value;
901   }
get_date_from_item(THD * thd,Item * item,MYSQL_TIME * ltime,date_mode_t fuzzydate)902   bool get_date_from_item(THD *thd, Item *item,
903                           MYSQL_TIME *ltime, date_mode_t fuzzydate)
904   {
905     bool rc= item->get_date(thd, ltime, fuzzydate);
906     null_value= MY_TEST(rc || item->null_value);
907     return rc;
908   }
909 public:
910 
911   /*
912     Cache val_str() into the own buffer, e.g. to evaluate constant
913     expressions with subqueries in the ORDER/GROUP clauses.
914   */
val_str()915   String *val_str() { return val_str(&str_value); }
get_item_func()916   virtual Item_func *get_item_func() { return NULL; }
917 
918   const MY_LOCALE *locale_from_val_str();
919 
920   LEX_CSTRING name;			/* Name of item */
921   /* Original item name (if it was renamed)*/
922   const char *orig_name;
923   /**
924      Intrusive list pointer for free list. If not null, points to the next
925      Item on some Query_arena's free list. For instance, stored procedures
926      have their own Query_arena's.
927 
928      @see Query_arena::free_list
929    */
930   Item *next;
931   int  marker;
932   bool maybe_null;			/* If item may be null */
933   bool in_rollup;                       /* If used in GROUP BY list
934                                            of a query with ROLLUP */
935   bool null_value;			/* if item is null */
936   bool with_param;                      /* True if contains an SP parameter */
937   bool with_window_func;             /* True if item contains a window func */
938   /**
939     True if any item except Item_sum contains a field. Set during parsing.
940   */
941   bool with_field;
942   uint8 common_flags;
is_autogenerated_name()943   bool is_autogenerated_name()
944   { return (common_flags & IS_AUTO_GENERATED_NAME); }
945   // alloc & destruct is done as start of select on THD::mem_root
946   Item(THD *thd);
947   /*
948      Constructor used by Item_field, Item_ref & aggregate (sum) functions.
949      Used for duplicating lists in processing queries with temporary
950      tables
951      Also it used for Item_cond_and/Item_cond_or for creating
952      top AND/OR structure of WHERE clause to protect it of
953      optimisation changes in prepared statements
954   */
955   Item(THD *thd, Item *item);
~Item()956   virtual ~Item()
957   {
958 #ifdef EXTRA_DEBUG
959     name.str= 0;
960     name.length= 0;
961 #endif
962   }		/*lint -e1509 */
963   void set_name(THD *thd, const char *str, size_t length, CHARSET_INFO *cs);
set_name(THD * thd,String * str)964   void set_name(THD *thd, String *str)
965   {
966     set_name(thd, str->ptr(), str->length(), str->charset());
967   }
968   void set_name(THD *thd, const LEX_CSTRING &str,
969                 CHARSET_INFO *cs= system_charset_info)
970   {
971     set_name(thd, str.str, str.length, cs);
972   }
973   void set_name_no_truncate(THD *thd, const char *str, uint length,
974                             CHARSET_INFO *cs);
975   void init_make_send_field(Send_field *tmp_field, const Type_handler *h);
share_name_with(const Item * item)976   void share_name_with(const Item *item)
977   {
978     name= item->name;
979     common_flags= static_cast<uint8>
980      ((common_flags & ~IS_AUTO_GENERATED_NAME) |
981       (item->common_flags & IS_AUTO_GENERATED_NAME));
982   }
983   virtual void cleanup();
984   virtual void make_send_field(THD *thd, Send_field *field);
985 
fix_fields_if_needed(THD * thd,Item ** ref)986   bool fix_fields_if_needed(THD *thd, Item **ref)
987   {
988     return is_fixed() ? false : fix_fields(thd, ref);
989   }
fix_fields_if_needed_for_scalar(THD * thd,Item ** ref)990   bool fix_fields_if_needed_for_scalar(THD *thd, Item **ref)
991   {
992     return fix_fields_if_needed(thd, ref) || check_cols(1);
993   }
fix_fields_if_needed_for_bool(THD * thd,Item ** ref)994   bool fix_fields_if_needed_for_bool(THD *thd, Item **ref)
995   {
996     return fix_fields_if_needed_for_scalar(thd, ref);
997   }
fix_fields_if_needed_for_order_by(THD * thd,Item ** ref)998   bool fix_fields_if_needed_for_order_by(THD *thd, Item **ref)
999   {
1000     return fix_fields_if_needed_for_scalar(thd, ref);
1001   }
1002   /*
1003     By default we assume that an Item is fixed by the contstructor.
1004   */
fix_fields(THD *,Item **)1005   virtual bool fix_fields(THD *, Item **)
1006   {
1007     /*
1008       This should not normally be called, because usually before
1009       fix_fields() we check is_fixed() to be false.
1010       But historically we allow fix_fields() to be called for Items
1011       who return basic_const_item()==true.
1012     */
1013     DBUG_ASSERT(is_fixed());
1014     DBUG_ASSERT(basic_const_item());
1015     return false;
1016   }
is_fixed()1017   virtual bool is_fixed() const { return true; }
unfix_fields()1018   virtual void unfix_fields()
1019   {
1020     DBUG_ASSERT(0);
1021   }
1022 
1023   /*
1024     Fix after some tables has been pulled out. Basically re-calculate all
1025     attributes that are dependent on the tables.
1026   */
fix_after_pullout(st_select_lex * new_parent,Item ** ref,bool merge)1027   virtual void fix_after_pullout(st_select_lex *new_parent, Item **ref,
1028                                  bool merge)
1029     {};
1030 
1031   /*
1032     This method should be used in case where we are sure that we do not need
1033     complete fix_fields() procedure.
1034     Usually this method is used by the optimizer when it has to create a new
1035     item out of other already fixed items. For example, if the optimizer has
1036     to create a new Item_func for an inferred equality whose left and right
1037     parts are already fixed items. In some cases the optimizer cannot use
1038     directly fixed items as the arguments of the created functional item,
1039     but rather uses intermediate type conversion items. Then the method is
1040     supposed to be applied recursively.
1041   */
quick_fix_field()1042   virtual void quick_fix_field()
1043   {
1044     DBUG_ASSERT(0);
1045   }
1046 
save_in_value(THD * thd,struct st_value * value)1047   bool save_in_value(THD *thd, struct st_value *value)
1048   {
1049     return type_handler()->Item_save_in_value(thd, this, value);
1050   }
1051 
1052   /* Function returns 1 on overflow and -1 on fatal errors */
1053   int save_in_field_no_warnings(Field *field, bool no_conversions);
1054   virtual int save_in_field(Field *field, bool no_conversions);
1055   virtual bool save_in_param(THD *thd, Item_param *param);
save_org_in_field(Field * field,fast_field_copier data)1056   virtual void save_org_in_field(Field *field,
1057                                  fast_field_copier data
1058                                  __attribute__ ((__unused__)))
1059   { (void) save_in_field(field, 1); }
setup_fast_field_copier(Field * field)1060   virtual fast_field_copier setup_fast_field_copier(Field *field)
1061   { return NULL; }
save_safe_in_field(Field * field)1062   virtual int save_safe_in_field(Field *field)
1063   { return save_in_field(field, 1); }
send(Protocol * protocol,st_value * buffer)1064   virtual bool send(Protocol *protocol, st_value *buffer)
1065   {
1066     return type_handler()->Item_send(this, protocol, buffer);
1067   }
1068   virtual bool eq(const Item *, bool binary_cmp) const;
field_type()1069   enum_field_types field_type() const
1070   {
1071     return type_handler()->field_type();
1072   }
1073   virtual const Type_handler *type_handler() const= 0;
1074   /**
1075     Detects if an Item has a fixed data type which is known
1076     even before fix_fields().
1077     Currently it's important only to find Items with a fixed boolean
1078     data type. More item types can be marked in the future as having
1079     a fixed data type (e.g. all literals, all fixed type functions, etc).
1080 
1081     @retval  NULL if the Item type is not known before fix_fields()
1082     @retval  the pointer to the data type handler, if the data type
1083              is known before fix_fields().
1084   */
fixed_type_handler()1085   virtual const Type_handler *fixed_type_handler() const
1086   {
1087     return NULL;
1088   }
type_handler_for_comparison()1089   const Type_handler *type_handler_for_comparison() const
1090   {
1091     return type_handler()->type_handler_for_comparison();
1092   }
real_type_handler()1093   virtual const Type_handler *real_type_handler() const
1094   {
1095     return type_handler();
1096   }
cast_to_int_type_handler()1097   const Type_handler *cast_to_int_type_handler() const
1098   {
1099     return real_type_handler()->cast_to_int_type_handler();
1100   }
1101   /* result_type() of an item specifies how the value should be returned */
result_type()1102   Item_result result_type() const
1103   {
1104     return type_handler()->result_type();
1105   }
1106   /* ... while cmp_type() specifies how it should be compared */
cmp_type()1107   Item_result cmp_type() const
1108   {
1109     return type_handler()->cmp_type();
1110   }
string_type_handler()1111   const Type_handler *string_type_handler() const
1112   {
1113     return Type_handler::string_type_handler(max_length);
1114   }
1115   /*
1116     Calculate the maximum length of an expression.
1117     This method is used in data type aggregation for UNION, e.g.:
1118       SELECT 'b' UNION SELECT COALESCE(double_10_3_field) FROM t1;
1119 
1120     The result is usually equal to max_length, except for some numeric types.
1121     In case of the INT, FLOAT, DOUBLE data types Item::max_length and
1122     Item::decimals are ignored, so the returned value depends only on the
1123     data type itself. E.g. for an expression of the DOUBLE(10,3) data type,
1124     the result is always 53 (length 10 and precision 3 do not matter).
1125 
1126     max_length is ignored for these numeric data types because the length limit
1127     means only "expected maximum length", it is not a hard limit, so it does
1128     not impose any data truncation. E.g. a column of the type INT(4) can
1129     normally store big values up to 2147483647 without truncation. When we're
1130     aggregating such column for UNION it's important to create a long enough
1131     result column, not to lose any data.
1132 
1133     For detailed behaviour of various data types see implementations of
1134     the corresponding Type_handler_xxx::max_display_length().
1135 
1136     Note, Item_field::max_display_length() overrides this to get
1137     max_display_length() from the underlying field.
1138   */
max_display_length()1139   virtual uint32 max_display_length() const
1140   {
1141     return type_handler()->max_display_length(this);
1142   }
get_typelib()1143   const TYPELIB *get_typelib() const { return NULL; }
set_maybe_null(bool maybe_null_arg)1144   void set_maybe_null(bool maybe_null_arg) { maybe_null= maybe_null_arg; }
set_typelib(const TYPELIB * typelib)1145   void set_typelib(const TYPELIB *typelib)
1146   {
1147     // Non-field Items (e.g. hybrid functions) never have ENUM/SET types yet.
1148     DBUG_ASSERT(0);
1149   }
get_cache(THD * thd)1150   Item_cache* get_cache(THD *thd) const
1151   {
1152     return type_handler()->Item_get_cache(thd, this);
1153   }
1154   virtual enum Type type() const =0;
is_of_type(Type t,Item_result cmp)1155   bool is_of_type(Type t, Item_result cmp) const
1156   {
1157     return type() == t && cmp_type() == cmp;
1158   }
1159   /*
1160     real_type() is the type of base item.  This is same as type() for
1161     most items, except Item_ref() and Item_cache_wrapper() where it
1162     shows the type for the underlying item.
1163   */
real_type()1164   virtual enum Type real_type() const { return type(); }
1165 
1166   /*
1167     Return information about function monotonicity. See comment for
1168     enum_monotonicity_info for details. This function can only be called
1169     after fix_fields() call.
1170   */
get_monotonicity_info()1171   virtual enum_monotonicity_info get_monotonicity_info() const
1172   { return NON_MONOTONIC; }
1173 
1174   /*
1175     Convert "func_arg $CMP$ const" half-interval into "FUNC(func_arg) $CMP2$ const2"
1176 
1177     SYNOPSIS
1178       val_int_endpoint()
1179         left_endp  FALSE  <=> The interval is "x < const" or "x <= const"
1180                    TRUE   <=> The interval is "x > const" or "x >= const"
1181 
1182         incl_endp  IN   FALSE <=> the comparison is '<' or '>'
1183                         TRUE  <=> the comparison is '<=' or '>='
1184                    OUT  The same but for the "F(x) $CMP$ F(const)" comparison
1185 
1186     DESCRIPTION
1187       This function is defined only for unary monotonic functions. The caller
1188       supplies the source half-interval
1189 
1190          x $CMP$ const
1191 
1192       The value of const is supplied implicitly as the value this item's
1193       argument, the form of $CMP$ comparison is specified through the
1194       function's arguments. The calle returns the result interval
1195 
1196          F(x) $CMP2$ F(const)
1197 
1198       passing back F(const) as the return value, and the form of $CMP2$
1199       through the out parameter. NULL values are assumed to be comparable and
1200       be less than any non-NULL values.
1201 
1202     RETURN
1203       The output range bound, which equal to the value of val_int()
1204         - If the value of the function is NULL then the bound is the
1205           smallest possible value of LONGLONG_MIN
1206   */
val_int_endpoint(bool left_endp,bool * incl_endp)1207   virtual longlong val_int_endpoint(bool left_endp, bool *incl_endp)
1208   { DBUG_ASSERT(0); return 0; }
1209 
1210 
1211   /* valXXX methods must return NULL or 0 or 0.0 if null_value is set. */
1212   /*
1213     Return double precision floating point representation of item.
1214 
1215     SYNOPSIS
1216       val_real()
1217 
1218     RETURN
1219       In case of NULL value return 0.0 and set null_value flag to TRUE.
1220       If value is not null null_value flag will be reset to FALSE.
1221   */
1222   virtual double val_real()=0;
to_double_null()1223   Double_null to_double_null()
1224   {
1225     // val_real() must be caleed on a separate line. See to_longlong_null()
1226     double nr= val_real();
1227     return Double_null(nr, null_value);
1228   }
1229   /*
1230     Return integer representation of item.
1231 
1232     SYNOPSIS
1233       val_int()
1234 
1235     RETURN
1236       In case of NULL value return 0 and set null_value flag to TRUE.
1237       If value is not null null_value flag will be reset to FALSE.
1238   */
1239   virtual longlong val_int()=0;
to_longlong_hybrid()1240   Longlong_hybrid to_longlong_hybrid()
1241   {
1242     return Longlong_hybrid(val_int(), unsigned_flag);
1243   }
to_longlong_null()1244   Longlong_null to_longlong_null()
1245   {
1246     longlong nr= val_int();
1247     /*
1248       C++ does not guarantee the order of parameter evaluation,
1249       so to make sure "null_value" is passed to the constructor
1250       after the val_int() call, val_int() is caled on a separate line.
1251     */
1252     return Longlong_null(nr, null_value);
1253   }
to_longlong_hybrid_null()1254   Longlong_hybrid_null to_longlong_hybrid_null()
1255   {
1256     return Longlong_hybrid_null(to_longlong_null(), unsigned_flag);
1257   }
1258   /**
1259     Get a value for CAST(x AS SIGNED).
1260     Too large positive unsigned integer values are converted
1261     to negative complements.
1262     Values of non-integer data types are adjusted to the SIGNED range.
1263   */
val_int_signed_typecast()1264   virtual longlong val_int_signed_typecast()
1265   {
1266     return cast_to_int_type_handler()->Item_val_int_signed_typecast(this);
1267   }
1268   longlong val_int_signed_typecast_from_str();
1269   /**
1270     Get a value for CAST(x AS UNSIGNED).
1271     Negative signed integer values are converted
1272     to positive complements.
1273     Values of non-integer data types are adjusted to the UNSIGNED range.
1274   */
val_int_unsigned_typecast()1275   virtual longlong val_int_unsigned_typecast()
1276   {
1277     return cast_to_int_type_handler()->Item_val_int_unsigned_typecast(this);
1278   }
1279   longlong val_int_unsigned_typecast_from_int();
1280   longlong val_int_unsigned_typecast_from_str();
1281   longlong val_int_unsigned_typecast_from_real();
1282 
1283   /**
1284     Get a value for CAST(x AS UNSIGNED).
1285     Huge positive unsigned values are converted to negative complements.
1286   */
1287   longlong val_int_signed_typecast_from_int();
1288   longlong val_int_signed_typecast_from_real();
1289 
1290   /*
1291     This is just a shortcut to avoid the cast. You should still use
1292     unsigned_flag to check the sign of the item.
1293   */
val_uint()1294   inline ulonglong val_uint() { return (ulonglong) val_int(); }
1295 
1296   /*
1297     Return string representation of this item object.
1298 
1299     SYNOPSIS
1300       val_str()
1301       str   an allocated buffer this or any nested Item object can use to
1302             store return value of this method.
1303 
1304     NOTE
1305       The caller can modify the returned String, if it's not marked
1306       "const" (with the String::mark_as_const() method). That means that
1307       if the item returns its own internal buffer (e.g. tmp_value), it
1308       *must* be marked "const" [1]. So normally it's preferable to
1309       return the result value in the String, that was passed as an
1310       argument. But, for example, SUBSTR() returns a String that simply
1311       points into the buffer of SUBSTR()'s args[0]->val_str(). Such a
1312       String is always "const", so it's ok to use tmp_value for that and
1313       avoid reallocating/copying of the argument String.
1314 
1315       [1] consider SELECT CONCAT(f, ":", f) FROM (SELECT func() AS f);
1316       here the return value of f() is used twice in the top-level
1317       select, and if they share the same tmp_value buffer, modifying the
1318       first one will implicitly modify the second too.
1319 
1320     RETURN
1321       In case of NULL value return 0 (NULL pointer) and set null_value flag
1322       to TRUE.
1323       If value is not null null_value flag will be reset to FALSE.
1324   */
1325   virtual String *val_str(String *str)=0;
1326 
1327 
val_native_with_conversion(THD * thd,Native * to,const Type_handler * th)1328   bool val_native_with_conversion(THD *thd, Native *to, const Type_handler *th)
1329   {
1330     return th->Item_val_native_with_conversion(thd, this, to);
1331   }
val_native_with_conversion_result(THD * thd,Native * to,const Type_handler * th)1332   bool val_native_with_conversion_result(THD *thd, Native *to,
1333                                          const Type_handler *th)
1334   {
1335     return th->Item_val_native_with_conversion_result(thd, this, to);
1336   }
1337 
val_native(THD * thd,Native * to)1338   virtual bool val_native(THD *thd, Native *to)
1339   {
1340    /*
1341      The default implementation for the Items that do not need native format:
1342      - Item_basic_value (default implementation)
1343      - Item_copy
1344      - Item_exists_subselect
1345      - Item_sum_field
1346      - Item_sum_or_func (default implementation)
1347      - Item_proc
1348      - Item_type_holder (as val_xxx() are never called for it);
1349 
1350      These hybrid Item types override val_native():
1351      - Item_field
1352      - Item_param
1353      - Item_sp_variable
1354      - Item_ref
1355      - Item_cache_wrapper
1356      - Item_direct_ref
1357      - Item_direct_view_ref
1358      - Item_ref_null_helper
1359      - Item_name_const
1360      - Item_time_literal
1361      - Item_sum_or_func
1362          Note, these hybrid type Item_sum_or_func descendants
1363          override the default implementation:
1364          * Item_sum_hybrid
1365          * Item_func_hybrid_field_type
1366          * Item_func_min_max
1367          * Item_func_sp
1368          * Item_func_last_value
1369          * Item_func_rollup_const
1370    */
1371     DBUG_ASSERT(0);
1372     return null_value= true;
1373   }
val_native_result(THD * thd,Native * to)1374   virtual bool val_native_result(THD *thd, Native *to)
1375   {
1376     return val_native(thd, to);
1377   }
1378 
1379   /*
1380     Returns string representation of this item in ASCII format.
1381 
1382     SYNOPSIS
1383       val_str_ascii()
1384       str - similar to val_str();
1385 
1386     NOTE
1387       This method is introduced for performance optimization purposes.
1388 
1389       1. val_str() result of some Items in string context
1390       depends on @@character_set_results.
1391       @@character_set_results can be set to a "real multibyte" character
1392       set like UCS2, UTF16, UTF32. (We'll use only UTF32 in the examples
1393       below for convenience.)
1394 
1395       So the default string result of such functions
1396       in these circumstances is real multi-byte character set, like UTF32.
1397 
1398       For example, all numbers in string context
1399       return result in @@character_set_results:
1400 
1401       SELECT CONCAT(20010101); -> UTF32
1402 
1403       We do sprintf() first (to get ASCII representation)
1404       and then convert to UTF32;
1405 
1406       So these kind "data sources" can use ASCII representation
1407       internally, but return multi-byte data only because
1408       @@character_set_results wants so.
1409       Therefore, conversion from ASCII to UTF32 is applied internally.
1410 
1411 
1412       2. Some other functions need in fact ASCII input.
1413 
1414       For example,
1415         inet_aton(), GeometryFromText(), Convert_TZ(), GET_FORMAT().
1416 
1417       Similar, fields of certain type, like DATE, TIME,
1418       when you insert string data into them, expect in fact ASCII input.
1419       If they get non-ASCII input, for example UTF32, they
1420       convert input from UTF32 to ASCII, and then use ASCII
1421       representation to do further processing.
1422 
1423 
1424       3. Now imagine we pass result of a data source of the first type
1425          to a data destination of the second type.
1426 
1427       What happens:
1428         a. data source converts data from ASCII to UTF32, because
1429            @@character_set_results wants so and passes the result to
1430            data destination.
1431         b. data destination gets UTF32 string.
1432         c. data destination converts UTF32 string to ASCII,
1433            because it needs ASCII representation to be able to handle data
1434            correctly.
1435 
1436       As a result we get two steps of unnecessary conversion:
1437       From ASCII to UTF32, then from UTF32 to ASCII.
1438 
1439       A better way to handle these situations is to pass ASCII
1440       representation directly from the source to the destination.
1441 
1442       This is why val_str_ascii() introduced.
1443 
1444     RETURN
1445       Similar to val_str()
1446   */
1447   virtual String *val_str_ascii(String *str);
1448 
1449   /*
1450     Returns the result of val_str_ascii(), translating NULLs back
1451     to empty strings (if MODE_EMPTY_STRING_IS_NULL is set).
1452   */
1453   String *val_str_ascii_revert_empty_string_is_null(THD *thd, String *str);
1454 
1455   /*
1456     Returns the val_str() value converted to the given character set.
1457   */
1458   String *val_str(String *str, String *converter, CHARSET_INFO *to);
1459 
val_json(String * str)1460   virtual String *val_json(String *str) { return val_str(str); }
1461   /*
1462     Return decimal representation of item with fixed point.
1463 
1464     SYNOPSIS
1465       val_decimal()
1466       decimal_buffer  buffer which can be used by Item for returning value
1467                       (but can be not)
1468 
1469     NOTE
1470       Returned value should not be changed if it is not the same which was
1471       passed via argument.
1472 
1473     RETURN
1474       Return pointer on my_decimal (it can be other then passed via argument)
1475         if value is not NULL (null_value flag will be reset to FALSE).
1476       In case of NULL value it return 0 pointer and set null_value flag
1477         to TRUE.
1478   */
1479   virtual my_decimal *val_decimal(my_decimal *decimal_buffer)= 0;
1480   /*
1481     Return boolean value of item.
1482 
1483     RETURN
1484       FALSE value is false or NULL
1485       TRUE value is true (not equal to 0)
1486   */
val_bool()1487   virtual bool val_bool()
1488   {
1489     return type_handler()->Item_val_bool(this);
1490   }
1491 
eval_const_cond()1492   bool eval_const_cond()
1493   {
1494     DBUG_ASSERT(const_item());
1495     DBUG_ASSERT(!is_expensive());
1496     return val_bool();
1497   }
1498 
1499   /*
1500     save_val() is method of val_* family which stores value in the given
1501     field.
1502   */
save_val(Field * to)1503   virtual void save_val(Field *to) { save_org_in_field(to, NULL); }
1504   /*
1505     save_result() is method of val*result() family which stores value in
1506     the given field.
1507   */
save_result(Field * to)1508   virtual void save_result(Field *to) { save_val(to); }
1509   /* Helper functions, see item_sum.cc */
1510   String *val_string_from_real(String *str);
1511   String *val_string_from_int(String *str);
1512   my_decimal *val_decimal_from_real(my_decimal *decimal_value);
1513   my_decimal *val_decimal_from_int(my_decimal *decimal_value);
1514   my_decimal *val_decimal_from_string(my_decimal *decimal_value);
val_int_from_real()1515   longlong val_int_from_real()
1516   {
1517     DBUG_ASSERT(is_fixed());
1518     return Converter_double_to_longlong_with_warn(val_real(), false).result();
1519   }
1520   longlong val_int_from_str(int *error);
1521 
1522   /*
1523     Returns true if this item can be calculated during
1524     value_depends_on_sql_mode()
1525   */
value_depends_on_sql_mode_const_item()1526   bool value_depends_on_sql_mode_const_item()
1527   {
1528     /*
1529       Currently we use value_depends_on_sql_mode() only for virtual
1530       column expressions. They should not contain any expensive items.
1531       If we ever get a crash on the assert below, it means
1532       check_vcol_func_processor() is badly implemented for this item.
1533     */
1534     DBUG_ASSERT(!is_expensive());
1535     /*
1536       It should return const_item() actually.
1537       But for some reasons Item_field::const_item() returns true
1538       at value_depends_on_sql_mode() call time.
1539       This should be checked and fixed.
1540     */
1541     return basic_const_item();
1542   }
value_depends_on_sql_mode()1543   virtual Sql_mode_dependency value_depends_on_sql_mode() const
1544   {
1545     return Sql_mode_dependency();
1546   }
1547 
1548   int save_time_in_field(Field *field, bool no_conversions);
1549   int save_date_in_field(Field *field, bool no_conversions);
1550   int save_str_in_field(Field *field, bool no_conversions);
1551   int save_real_in_field(Field *field, bool no_conversions);
1552   int save_int_in_field(Field *field, bool no_conversions);
1553   int save_decimal_in_field(Field *field, bool no_conversions);
1554 
1555   int save_str_value_in_field(Field *field, String *result);
1556 
get_tmp_table_field()1557   virtual Field *get_tmp_table_field() { return 0; }
1558   virtual Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table);
full_name()1559   virtual const char *full_name() const { return name.str ? name.str : "???"; }
field_name_or_null()1560   const char *field_name_or_null()
1561   { return real_item()->type() == Item::FIELD_ITEM ? name.str : NULL; }
1562   const TABLE_SHARE *field_table_or_null();
1563 
1564   /*
1565     *result* family of methods is analog of *val* family (see above) but
1566     return value of result_field of item if it is present. If Item have not
1567     result field, it return val(). This methods set null_value flag in same
1568     way as *val* methods do it.
1569   */
val_result()1570   virtual double  val_result() { return val_real(); }
val_int_result()1571   virtual longlong val_int_result() { return val_int(); }
str_result(String * tmp)1572   virtual String *str_result(String* tmp) { return val_str(tmp); }
val_decimal_result(my_decimal * val)1573   virtual my_decimal *val_decimal_result(my_decimal *val)
1574   { return val_decimal(val); }
val_bool_result()1575   virtual bool val_bool_result() { return val_bool(); }
is_null_result()1576   virtual bool is_null_result() { return is_null(); }
1577   /*
1578     Returns 1 if result type and collation for val_str() can change between
1579     calls
1580   */
dynamic_result()1581   virtual bool dynamic_result() { return 0; }
1582   /*
1583     Bitmap of tables used by item
1584     (note: if you need to check dependencies on individual columns, check out
1585      class Field_enumerator)
1586   */
used_tables()1587   virtual table_map used_tables() const { return (table_map) 0L; }
all_used_tables()1588   virtual table_map all_used_tables() const { return used_tables(); }
1589   /*
1590     Return table map of tables that can't be NULL tables (tables that are
1591     used in a context where if they would contain a NULL row generated
1592     by a LEFT or RIGHT join, the item would not be true).
1593     This expression is used on WHERE item to determinate if a LEFT JOIN can be
1594     converted to a normal join.
1595     Generally this function should return used_tables() if the function
1596     would return null if any of the arguments are null
1597     As this is only used in the beginning of optimization, the value don't
1598     have to be updated in update_used_tables()
1599   */
not_null_tables()1600   virtual table_map not_null_tables() const { return used_tables(); }
1601   /*
1602     Returns true if this is a simple constant item like an integer, not
1603     a constant expression. Used in the optimizer to propagate basic constants.
1604   */
basic_const_item()1605   virtual bool basic_const_item() const { return 0; }
1606   /**
1607     Determines if the expression is allowed as
1608     a virtual column assignment source:
1609       INSERT INTO t1 (vcol) VALUES (10)    -> error
1610       INSERT INTO t1 (vcol) VALUES (NULL)  -> ok
1611   */
vcol_assignment_allowed_value()1612   virtual bool vcol_assignment_allowed_value() const { return false; }
1613   /**
1614     Test if "this" is an ORDER position (rather than an expression).
1615     Notes:
1616     - can be called before fix_fields().
1617     - local SP variables (even of integer types) are always expressions, not
1618       positions. (And they can't be used before fix_fields is called for them).
1619   */
is_order_clause_position()1620   virtual bool is_order_clause_position() const { return false; }
1621   /*
1622     Determines if the Item is an evaluable expression, that is
1623     it can return a value, so we can call methods val_xxx(), get_date(), etc.
1624     Most items are evaluable expressions.
1625     Examples of non-evaluable expressions:
1626     - Item_contextually_typed_value_specification (handling DEFAULT and IGNORE)
1627     - Item_type_param bound to DEFAULT and IGNORE
1628     We cannot call the mentioned methods for these Items,
1629     their method implementations typically have DBUG_ASSERT(0).
1630   */
is_evaluable_expression()1631   virtual bool is_evaluable_expression() const { return true; }
check_is_evaluable_expression_or_error()1632   bool check_is_evaluable_expression_or_error()
1633   {
1634     if (is_evaluable_expression())
1635       return false; // Ok
1636     raise_error_not_evaluable();
1637     return true;    // Error
1638   }
1639   /* cloning of constant items (0 if it is not const) */
clone_item(THD * thd)1640   virtual Item *clone_item(THD *thd) { return 0; }
1641   /* deep copy item */
build_clone(THD * thd)1642   virtual Item* build_clone(THD *thd) { return get_copy(thd); }
eq_cmp_result()1643   virtual cond_result eq_cmp_result() const { return COND_OK; }
float_length(uint decimals_par)1644   inline uint float_length(uint decimals_par) const
1645   { return decimals < FLOATING_POINT_DECIMALS ? (DBL_DIG+2+decimals_par) : DBL_DIG+8;}
1646   /* Returns total number of decimal digits */
decimal_precision()1647   virtual uint decimal_precision() const
1648   {
1649     return type_handler()->Item_decimal_precision(this);
1650   }
1651   /* Returns the number of integer part digits only */
decimal_int_part()1652   inline int decimal_int_part() const
1653   { return my_decimal_int_part(decimal_precision(), decimals); }
1654   /*
1655     Returns the number of fractional digits only.
1656     NOT_FIXED_DEC is replaced to the maximum possible number
1657     of fractional digits, taking into account the data type.
1658   */
decimal_scale()1659   uint decimal_scale() const
1660   {
1661     return type_handler()->Item_decimal_scale(this);
1662   }
1663   /*
1664     Returns how many digits a divisor adds into a division result.
1665     This is important when the integer part of the divisor can be 0.
1666     In this  example:
1667       SELECT 1 / 0.000001; -> 1000000.0000
1668     the divisor adds 5 digits into the result precision.
1669 
1670     Currently this method only replaces NOT_FIXED_DEC to
1671     TIME_SECOND_PART_DIGITS for temporal data types.
1672     This method can be made virtual, to create more efficient (smaller)
1673     data types for division results.
1674     For example, in
1675       SELECT 1/1.000001;
1676     the divisor could provide no additional precision into the result,
1677     so could any other items that are know to return a result
1678     with non-zero integer part.
1679   */
divisor_precision_increment()1680   uint divisor_precision_increment() const
1681   {
1682     return type_handler()->Item_divisor_precision_increment(this);
1683   }
1684   /**
1685     TIME or DATETIME precision of the item: 0..6
1686   */
time_precision(THD * thd)1687   uint time_precision(THD *thd)
1688   {
1689     return const_item() ? type_handler()->Item_time_precision(thd, this) :
1690                           MY_MIN(decimals, TIME_SECOND_PART_DIGITS);
1691   }
datetime_precision(THD * thd)1692   uint datetime_precision(THD *thd)
1693   {
1694     return const_item() ? type_handler()->Item_datetime_precision(thd, this) :
1695                           MY_MIN(decimals, TIME_SECOND_PART_DIGITS);
1696   }
val_int_min()1697   virtual longlong val_int_min() const
1698   {
1699     return LONGLONG_MIN;
1700   }
1701   /*
1702     Returns true if this is constant (during query execution, i.e. its value
1703     will not change until next fix_fields) and its value is known.
1704   */
const_item()1705   virtual bool const_item() const { return used_tables() == 0; }
1706   /*
1707     Returns true if this is constant but its value may be not known yet.
1708     (Can be used for parameters of prep. stmts or of stored procedures.)
1709   */
const_during_execution()1710   virtual bool const_during_execution() const
1711   { return (used_tables() & ~PARAM_TABLE_BIT) == 0; }
1712 
1713   /**
1714     This method is used for to:
1715       - to generate a view definition query (SELECT-statement);
1716       - to generate a SQL-query for EXPLAIN EXTENDED;
1717       - to generate a SQL-query to be shown in INFORMATION_SCHEMA;
1718       - debug.
1719 
1720     For more information about view definition query, INFORMATION_SCHEMA
1721     query and why they should be generated from the Item-tree, @see
1722     mysql_register_view().
1723   */
precedence()1724   virtual enum precedence precedence() const { return DEFAULT_PRECEDENCE; }
higher_precedence()1725   enum precedence higher_precedence() const
1726   { return (enum precedence)(precedence() + 1); }
1727   void print_parenthesised(String *str, enum_query_type query_type,
1728                            enum precedence parent_prec);
1729   /**
1730     This helper is used to print expressions as a part of a table definition,
1731     in particular for
1732       - generated columns
1733       - check constraints
1734       - default value expressions
1735       - partitioning expressions
1736   */
print_for_table_def(String * str)1737   void print_for_table_def(String *str)
1738   {
1739     print_parenthesised(str,
1740                      (enum_query_type)(QT_ITEM_ORIGINAL_FUNC_NULLIF |
1741                                        QT_ITEM_IDENT_SKIP_DB_NAMES |
1742                                        QT_ITEM_IDENT_SKIP_TABLE_NAMES |
1743                                        QT_NO_DATA_EXPANSION |
1744                                        QT_TO_SYSTEM_CHARSET),
1745                      LOWEST_PRECEDENCE);
1746   }
1747   virtual void print(String *str, enum_query_type query_type);
1748 
1749   class Print: public String
1750   {
1751   public:
Print(Item * item,enum_query_type type)1752     Print(Item *item, enum_query_type type)
1753     {
1754       item->print(this, type);
1755     }
1756   };
1757 
1758   void print_item_w_name(String *str, enum_query_type query_type);
1759   void print_value(String *str);
1760 
update_used_tables()1761   virtual void update_used_tables() {}
build_equal_items(THD * thd,COND_EQUAL * inheited,bool link_item_fields,COND_EQUAL ** cond_equal_ref)1762   virtual COND *build_equal_items(THD *thd, COND_EQUAL *inheited,
1763                                   bool link_item_fields,
1764                                   COND_EQUAL **cond_equal_ref)
1765   {
1766     update_used_tables();
1767     DBUG_ASSERT(!cond_equal_ref || !cond_equal_ref[0]);
1768     return this;
1769   }
1770   virtual COND *remove_eq_conds(THD *thd, Item::cond_result *cond_value,
1771                                 bool top_level);
add_key_fields(JOIN * join,KEY_FIELD ** key_fields,uint * and_level,table_map usable_tables,SARGABLE_PARAM ** sargables)1772   virtual void add_key_fields(JOIN *join, KEY_FIELD **key_fields,
1773                               uint *and_level,
1774                               table_map usable_tables,
1775                               SARGABLE_PARAM **sargables)
1776   {
1777     return;
1778   }
1779    /*
1780      Make a select tree for all keys in a condition or a condition part
1781      @param param         Context
1782      @param cond_ptr[OUT] Store a replacement item here if the condition
1783                           can be simplified, e.g.:
1784                             WHERE part1 OR part2 OR part3
1785                           with one of the partN evaluating to SEL_TREE::ALWAYS.
1786    */
1787    virtual SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr);
1788   /*
1789     Checks whether the item is:
1790     - a simple equality (field=field_item or field=constant_item), or
1791     - a row equality
1792     and form multiple equality predicates.
1793   */
check_equality(THD * thd,COND_EQUAL * cond,List<Item> * eq_list)1794   virtual bool check_equality(THD *thd, COND_EQUAL *cond, List<Item> *eq_list)
1795   {
1796     return false;
1797   }
split_sum_func(THD * thd,Ref_ptr_array ref_pointer_array,List<Item> & fields,uint flags)1798   virtual void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array,
1799                               List<Item> &fields, uint flags) {}
1800   /* Called for items that really have to be split */
1801   void split_sum_func2(THD *thd, Ref_ptr_array ref_pointer_array,
1802                        List<Item> &fields,
1803                        Item **ref, uint flags);
1804   virtual bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate)= 0;
1805   bool get_date_from_int(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate);
1806   bool get_date_from_real(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate);
1807   bool get_date_from_string(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate);
get_time(THD * thd,MYSQL_TIME * ltime)1808   bool get_time(THD *thd, MYSQL_TIME *ltime)
1809   { return get_date(thd, ltime, Time::Options(thd)); }
1810   // Get a DATE or DATETIME value in numeric packed format for comparison
val_datetime_packed(THD * thd)1811   virtual longlong val_datetime_packed(THD *thd)
1812   {
1813     return Datetime(thd, this, Datetime::Options_cmp(thd)).to_packed();
1814   }
1815   // Get a TIME value in numeric packed format for comparison
val_time_packed(THD * thd)1816   virtual longlong val_time_packed(THD *thd)
1817   {
1818     return Time(thd, this, Time::Options_cmp(thd)).to_packed();
1819   }
1820   longlong val_datetime_packed_result(THD *thd);
1821   longlong val_time_packed_result(THD *thd);
1822 
get_date_result(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)1823   virtual bool get_date_result(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate)
1824   { return get_date(thd, ltime,fuzzydate); }
1825 
1826   /*
1827     The method allows to determine nullness of a complex expression
1828     without fully evaluating it, instead of calling val/result*() then
1829     checking null_value. Used in Item_func_isnull/Item_func_isnotnull
1830     and Item_sum_count.
1831     Any new item which can be NULL must implement this method.
1832   */
is_null()1833   virtual bool is_null() { return 0; }
1834 
1835   /*
1836    Make sure the null_value member has a correct value.
1837   */
update_null_value()1838   virtual void update_null_value ()
1839   {
1840     return type_handler()->Item_update_null_value(this);
1841   }
1842 
1843   /*
1844     Inform the item that there will be no distinction between its result
1845     being FALSE or NULL.
1846 
1847     NOTE
1848       This function will be called for eg. Items that are top-level AND-parts
1849       of the WHERE clause. Items implementing this function (currently
1850       Item_cond_and and subquery-related item) enable special optimizations
1851       when they are "top level".
1852   */
top_level_item()1853   virtual void top_level_item() {}
1854   /*
1855     Return TRUE if it is item of top WHERE level (AND/OR)  and it is
1856     important, return FALSE if it not important (we can not use to simplify
1857     calculations) or not top level
1858   */
is_top_level_item()1859   virtual bool is_top_level_item() const
1860   { return FALSE; /* not important */}
1861   /*
1862     return IN/ALL/ANY subquery or NULL
1863   */
get_IN_subquery()1864   virtual Item_in_subselect* get_IN_subquery()
1865   { return NULL; /* in is not IN/ALL/ANY */ }
1866   /*
1867     set field of temporary table for Item which can be switched on temporary
1868     table during query processing (grouping and so on)
1869   */
is_result_field()1870   virtual bool is_result_field() { return 0; }
is_bool_literal()1871   virtual bool is_bool_literal() const { return false; }
1872   /* This is to handle printing of default values */
need_parentheses_in_default()1873   virtual bool need_parentheses_in_default() { return false; }
save_in_result_field(bool no_conversions)1874   virtual void save_in_result_field(bool no_conversions) {}
1875   /*
1876     Data type format implied by the CHECK CONSTRAINT,
1877     to be sent to the client in the result set metadata.
1878   */
set_format_by_check_constraint(Send_field_extended_metadata *)1879   virtual bool set_format_by_check_constraint(Send_field_extended_metadata *)
1880                                                                         const
1881   {
1882     return false;
1883   }
1884   /*
1885     set value of aggregate function in case of no rows for grouping were found
1886   */
no_rows_in_result()1887   virtual void no_rows_in_result() {}
restore_to_before_no_rows_in_result()1888   virtual void restore_to_before_no_rows_in_result() {}
copy_or_same(THD * thd)1889   virtual Item *copy_or_same(THD *thd) { return this; }
copy_andor_structure(THD * thd)1890   virtual Item *copy_andor_structure(THD *thd) { return this; }
real_item()1891   virtual Item *real_item() { return this; }
get_tmp_table_item(THD * thd)1892   virtual Item *get_tmp_table_item(THD *thd) { return copy_or_same(thd); }
make_odbc_literal(THD * thd,const LEX_CSTRING * typestr)1893   virtual Item *make_odbc_literal(THD *thd, const LEX_CSTRING *typestr)
1894   {
1895     return this;
1896   }
1897 
1898   static CHARSET_INFO *default_charset();
1899 
charset_for_protocol(void)1900   CHARSET_INFO *charset_for_protocol(void) const
1901   {
1902     return type_handler()->charset_for_protocol(this);
1903   };
1904 
walk(Item_processor processor,bool walk_subquery,void * arg)1905   virtual bool walk(Item_processor processor, bool walk_subquery, void *arg)
1906   {
1907     return (this->*processor)(arg);
1908   }
1909 
1910   virtual Item* transform(THD *thd, Item_transformer transformer, uchar *arg);
1911 
1912   /*
1913     This function performs a generic "compilation" of the Item tree.
1914     The process of compilation is assumed to go as follows:
1915 
1916     compile()
1917     {
1918       if (this->*some_analyzer(...))
1919       {
1920         compile children if any;
1921         this->*some_transformer(...);
1922       }
1923     }
1924 
1925     i.e. analysis is performed top-down while transformation is done
1926     bottom-up.
1927   */
compile(THD * thd,Item_analyzer analyzer,uchar ** arg_p,Item_transformer transformer,uchar * arg_t)1928   virtual Item* compile(THD *thd, Item_analyzer analyzer, uchar **arg_p,
1929                         Item_transformer transformer, uchar *arg_t)
1930   {
1931     if ((this->*analyzer) (arg_p))
1932       return ((this->*transformer) (thd, arg_t));
1933     return 0;
1934   }
1935 
traverse_cond(Cond_traverser traverser,void * arg,traverse_order order)1936    virtual void traverse_cond(Cond_traverser traverser,
1937                               void *arg, traverse_order order)
1938    {
1939      (*traverser)(this, arg);
1940    }
1941 
1942   /*========= Item processors, to be used with Item::walk() ========*/
remove_dependence_processor(void * arg)1943   virtual bool remove_dependence_processor(void *arg) { return 0; }
1944   virtual bool cleanup_processor(void *arg);
cleanup_excluding_fields_processor(void * arg)1945   virtual bool cleanup_excluding_fields_processor (void *arg)
1946   { return cleanup_processor(arg); }
1947   bool cleanup_excluding_immutables_processor (void *arg);
cleanup_excluding_const_fields_processor(void * arg)1948   virtual bool cleanup_excluding_const_fields_processor (void *arg)
1949   { return cleanup_processor(arg); }
collect_item_field_processor(void * arg)1950   virtual bool collect_item_field_processor(void *arg) { return 0; }
unknown_splocal_processor(void * arg)1951   virtual bool unknown_splocal_processor(void *arg) { return 0; }
collect_outer_ref_processor(void * arg)1952   virtual bool collect_outer_ref_processor(void *arg) {return 0; }
check_inner_refs_processor(void * arg)1953   virtual bool check_inner_refs_processor(void *arg) { return 0; }
find_item_in_field_list_processor(void * arg)1954   virtual bool find_item_in_field_list_processor(void *arg) { return 0; }
1955   virtual bool find_item_processor(void *arg);
change_context_processor(void * arg)1956   virtual bool change_context_processor(void *arg) { return 0; }
reset_query_id_processor(void * arg)1957   virtual bool reset_query_id_processor(void *arg) { return 0; }
is_expensive_processor(void * arg)1958   virtual bool is_expensive_processor(void *arg) { return 0; }
1959 
1960   // FIXME reduce the number of "add field to bitmap" processors
add_field_to_set_processor(void * arg)1961   virtual bool add_field_to_set_processor(void *arg) { return 0; }
register_field_in_read_map(void * arg)1962   virtual bool register_field_in_read_map(void *arg) { return 0; }
register_field_in_write_map(void * arg)1963   virtual bool register_field_in_write_map(void *arg) { return 0; }
register_field_in_bitmap(void * arg)1964   virtual bool register_field_in_bitmap(void *arg) { return 0; }
update_table_bitmaps_processor(void * arg)1965   virtual bool update_table_bitmaps_processor(void *arg) { return 0; }
1966 
enumerate_field_refs_processor(void * arg)1967   virtual bool enumerate_field_refs_processor(void *arg) { return 0; }
mark_as_eliminated_processor(void * arg)1968   virtual bool mark_as_eliminated_processor(void *arg) { return 0; }
eliminate_subselect_processor(void * arg)1969   virtual bool eliminate_subselect_processor(void *arg) { return 0; }
set_fake_select_as_master_processor(void * arg)1970   virtual bool set_fake_select_as_master_processor(void *arg) { return 0; }
view_used_tables_processor(void * arg)1971   virtual bool view_used_tables_processor(void *arg) { return 0; }
eval_not_null_tables(void * arg)1972   virtual bool eval_not_null_tables(void *arg) { return 0; }
is_subquery_processor(void * arg)1973   virtual bool is_subquery_processor(void *arg) { return 0; }
count_sargable_conds(void * arg)1974   virtual bool count_sargable_conds(void *arg) { return 0; }
limit_index_condition_pushdown_processor(void * arg)1975   virtual bool limit_index_condition_pushdown_processor(void *arg) { return 0; }
exists2in_processor(void * arg)1976   virtual bool exists2in_processor(void *arg) { return 0; }
find_selective_predicates_list_processor(void * arg)1977   virtual bool find_selective_predicates_list_processor(void *arg) { return 0; }
cleanup_is_expensive_cache_processor(void * arg)1978   bool cleanup_is_expensive_cache_processor(void *arg)
1979   {
1980     is_expensive_cache= (int8)(-1);
1981     return 0;
1982   }
1983 
1984   /**
1985     Check db/table_name if they defined in item and match arg values
1986 
1987     @param arg Pointer to Check_table_name_prm structure
1988 
1989     @retval true Match failed
1990     @retval false Match succeeded
1991   */
check_table_name_processor(void * arg)1992   virtual bool check_table_name_processor(void *arg) { return false; }
1993   /*
1994     TRUE if the expression depends only on the table indicated by tab_map
1995     or can be converted to such an exression using equalities.
1996     Not to be used for AND/OR formulas.
1997   */
excl_dep_on_table(table_map tab_map)1998   virtual bool excl_dep_on_table(table_map tab_map) { return false; }
1999   /*
2000     TRUE if the expression depends only on grouping fields of sel
2001     or can be converted to such an expression using equalities.
2002     It also checks if the expression doesn't contain stored procedures,
2003     subqueries or randomly generated elements.
2004     Not to be used for AND/OR formulas.
2005   */
excl_dep_on_grouping_fields(st_select_lex * sel)2006   virtual bool excl_dep_on_grouping_fields(st_select_lex *sel)
2007   { return false; }
2008   /*
2009     TRUE if the expression depends only on fields from the left part of
2010     IN subquery or can be converted to such an expression using equalities.
2011     Not to be used for AND/OR formulas.
2012   */
excl_dep_on_in_subq_left_part(Item_in_subselect * subq_pred)2013   virtual bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred)
2014   { return false; }
2015 
switch_to_nullable_fields_processor(void * arg)2016   virtual bool switch_to_nullable_fields_processor(void *arg) { return 0; }
find_function_processor(void * arg)2017   virtual bool find_function_processor (void *arg) { return 0; }
2018   /*
2019     Check if a partition function is allowed
2020     SYNOPSIS
2021       check_partition_func_processor()
2022       int_arg                        Ignored
2023     RETURN VALUE
2024       TRUE                           Partition function not accepted
2025       FALSE                          Partition function accepted
2026 
2027     DESCRIPTION
2028     check_partition_func_processor is used to check if a partition function
2029     uses an allowed function. An allowed function will always ensure that
2030     X=Y guarantees that also part_function(X)=part_function(Y) where X is
2031     a set of partition fields and so is Y. The problems comes mainly from
2032     character sets where two equal strings can be quite unequal. E.g. the
2033     german character for double s is equal to 2 s.
2034 
2035     The default is that an item is not allowed
2036     in a partition function. Allowed functions
2037     can never depend on server version, they cannot depend on anything
2038     related to the environment. They can also only depend on a set of
2039     fields in the table itself. They cannot depend on other tables and
2040     cannot contain any queries and cannot contain udf's or similar.
2041     If a new Item class is defined and it inherits from a class that is
2042     allowed in a partition function then it is very important to consider
2043     whether this should be inherited to the new class. If not the function
2044     below should be defined in the new Item class.
2045 
2046     The general behaviour is that most integer functions are allowed.
2047     If the partition function contains any multi-byte collations then
2048     the function check_part_func_fields will report an error on the
2049     partition function independent of what functions are used. So the
2050     only character sets allowed are single character collation and
2051     even for those only a limited set of functions are allowed. The
2052     problem with multi-byte collations is that almost every string
2053     function has the ability to change things such that two strings
2054     that are equal will not be equal after manipulated by a string
2055     function. E.g. two strings one contains a double s, there is a
2056     special german character that is equal to two s. Now assume a
2057     string function removes one character at this place, then in
2058     one the double s will be removed and in the other there will
2059     still be one s remaining and the strings are no longer equal
2060     and thus the partition function will not sort equal strings into
2061     the same partitions.
2062 
2063     So the check if a partition function is valid is two steps. First
2064     check that the field types are valid, next check that the partition
2065     function is valid. The current set of partition functions valid
2066     assumes that there are no multi-byte collations amongst the partition
2067     fields.
2068   */
check_partition_func_processor(void * arg)2069   virtual bool check_partition_func_processor(void *arg) { return 1;}
post_fix_fields_part_expr_processor(void * arg)2070   virtual bool post_fix_fields_part_expr_processor(void *arg) { return 0; }
rename_fields_processor(void * arg)2071   virtual bool rename_fields_processor(void *arg) { return 0; }
2072   /*
2073     TRUE if the function is knowingly TRUE or FALSE.
2074     Not to be used for AND/OR formulas.
2075   */
is_simplified_cond_processor(void * arg)2076   virtual bool is_simplified_cond_processor(void *arg) { return false; }
2077 
2078   /** Processor used to check acceptability of an item in the defining
2079       expression for a virtual column
2080 
2081     @param arg     always ignored
2082 
2083     @retval 0    the item is accepted in the definition of a virtual column
2084     @retval 1    otherwise
2085   */
2086   struct vcol_func_processor_result
2087   {
2088     uint errors;                                /* Bits of possible errors */
2089     const char *name;                           /* Not supported function */
2090     Alter_info *alter_info;
vcol_func_processor_resultvcol_func_processor_result2091     vcol_func_processor_result() :
2092       errors(0), name(NULL), alter_info(NULL) {}
2093   };
2094   struct func_processor_rename
2095   {
2096     LEX_CSTRING db_name;
2097     LEX_CSTRING table_name;
2098     List<Create_field> fields;
2099   };
check_vcol_func_processor(void * arg)2100   virtual bool check_vcol_func_processor(void *arg)
2101   {
2102     return mark_unsupported_function(full_name(), arg, VCOL_IMPOSSIBLE);
2103   }
check_field_expression_processor(void * arg)2104   virtual bool check_field_expression_processor(void *arg) { return 0; }
check_func_default_processor(void * arg)2105   virtual bool check_func_default_processor(void *arg) { return 0; }
2106   /*
2107     Check if an expression value has allowed arguments, like DATE/DATETIME
2108     for date functions. Also used by partitioning code to reject
2109     timezone-dependent expressions in a (sub)partitioning function.
2110   */
check_valid_arguments_processor(void * arg)2111   virtual bool check_valid_arguments_processor(void *arg) { return 0; }
update_vcol_processor(void * arg)2112   virtual bool update_vcol_processor(void *arg) { return 0; }
set_fields_as_dependent_processor(void * arg)2113   virtual bool set_fields_as_dependent_processor(void *arg) { return 0; }
2114   /*
2115     Find if some of the key parts of table keys (the reference on table is
2116     passed as an argument) participate in the expression.
2117     If there is some, sets a bit for this key in the proper key map.
2118   */
check_index_dependence(void * arg)2119   virtual bool check_index_dependence(void *arg) { return 0; }
2120   /*============== End of Item processor list ======================*/
2121 
2122   /*
2123     Given a condition P from the WHERE clause or from an ON expression of
2124     the processed SELECT S and a set of join tables from S marked in the
2125     parameter 'allowed'={T} a call of P->find_not_null_fields({T}) has to
2126     find the set fields {F} of the tables from 'allowed' such that:
2127     - each field from {F} is declared as nullable
2128     - each record of table t from {T} that contains NULL as the value for at
2129       at least one field from {F} can be ignored when building the result set
2130       for S
2131     It is assumed here that the condition P is conjunctive and all its column
2132     references belong to T.
2133 
2134     Examples:
2135       CREATE TABLE t1 (a int, b int);
2136       CREATE TABLE t2 (a int, b int);
2137 
2138       SELECT * FROM t1,t2 WHERE t1.a=t2.a and t1.b > 5;
2139       A call of find_not_null_fields() for the whole WHERE condition and {t1,t2}
2140       should find {t1.a,t1.b,t2.a}
2141 
2142       SELECT * FROM t1 LEFT JOIN ON (t1.a=t2.a and t2.a > t2.b);
2143       A call of find_not_null_fields() for the ON expression and {t2}
2144       should find {t2.a,t2.b}
2145 
2146     The function returns TRUE if it succeeds to prove that all records of
2147     a table from {T} can be ignored. Otherwise it always returns FALSE.
2148 
2149     Example:
2150       SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t2.a IS NULL;
2151     A call of find_not_null_fields() for the WHERE condition and {t1,t2}
2152     will return TRUE.
2153 
2154     It is assumed that the implementation of this virtual function saves
2155     the info on the found set of fields in the structures associates with
2156     tables from {T}.
2157   */
find_not_null_fields(table_map allowed)2158   virtual bool find_not_null_fields(table_map allowed) { return false; }
2159 
2160   /*
2161     Does not guarantee deep copy (depends on copy ctor).
2162     See build_clone() for deep copy.
2163   */
2164   virtual Item *get_copy(THD *thd)=0;
2165 
2166   bool cache_const_expr_analyzer(uchar **arg);
2167   Item* cache_const_expr_transformer(THD *thd, uchar *arg);
2168 
propagate_equal_fields(THD *,const Context &,COND_EQUAL *)2169   virtual Item* propagate_equal_fields(THD*, const Context &, COND_EQUAL *)
2170   {
2171     return this;
2172   };
2173 
2174   Item* propagate_equal_fields_and_change_item_tree(THD *thd,
2175                                                     const Context &ctx,
2176                                                     COND_EQUAL *cond,
2177                                                     Item **place);
2178 
2179   /* arg points to REPLACE_EQUAL_FIELD_ARG object */
replace_equal_field(THD * thd,uchar * arg)2180   virtual Item *replace_equal_field(THD *thd, uchar *arg) { return this; }
2181 
2182   struct Collect_deps_prm
2183   {
2184     List<Item> *parameters;
2185     /* unit from which we count nest_level */
2186     st_select_lex_unit *nest_level_base;
2187     uint count;
2188     int nest_level;
2189     bool collect;
2190   };
2191 
2192   struct Check_table_name_prm
2193   {
2194     LEX_CSTRING db;
2195     LEX_CSTRING table_name;
2196     String field;
Check_table_name_prmCheck_table_name_prm2197     Check_table_name_prm(LEX_CSTRING _db, LEX_CSTRING _table_name) :
2198       db(_db), table_name(_table_name) {}
2199   };
2200 
2201   /*
2202     For SP local variable returns pointer to Item representing its
2203     current value and pointer to current Item otherwise.
2204   */
this_item()2205   virtual Item *this_item() { return this; }
this_item()2206   virtual const Item *this_item() const { return this; }
2207 
2208   /*
2209     For SP local variable returns address of pointer to Item representing its
2210     current value and pointer passed via parameter otherwise.
2211   */
this_item_addr(THD * thd,Item ** addr_arg)2212   virtual Item **this_item_addr(THD *thd, Item **addr_arg) { return addr_arg; }
2213 
2214   // Row emulation
cols()2215   virtual uint cols() const { return 1; }
element_index(uint i)2216   virtual Item* element_index(uint i) { return this; }
addr(uint i)2217   virtual Item** addr(uint i) { return 0; }
2218   virtual bool check_cols(uint c);
2219   bool check_type_traditional_scalar(const char *opname) const;
2220   bool check_type_scalar(const char *opname) const;
2221   bool check_type_or_binary(const char *opname, const Type_handler *handler) const;
2222   bool check_type_general_purpose_string(const char *opname) const;
2223   bool check_type_can_return_int(const char *opname) const;
2224   bool check_type_can_return_decimal(const char *opname) const;
2225   bool check_type_can_return_real(const char *opname) const;
2226   bool check_type_can_return_str(const char *opname) const;
2227   bool check_type_can_return_text(const char *opname) const;
2228   bool check_type_can_return_date(const char *opname) const;
2229   bool check_type_can_return_time(const char *opname) const;
2230   // It is not row => null inside is impossible
null_inside()2231   virtual bool null_inside() { return 0; }
2232   // used in row subselects to get value of elements
bring_value()2233   virtual void bring_value() {}
2234 
type_handler_long_or_longlong()2235   const Type_handler *type_handler_long_or_longlong() const
2236   {
2237     return Type_handler::type_handler_long_or_longlong(max_char_length(),
2238                                                        unsigned_flag);
2239   }
2240 
2241   /**
2242     Create field for temporary table.
2243     @param table          Temporary table
2244     @param [OUT] src      Who created the fields
2245     @param param          Create parameters
2246     @retval               NULL (on error)
2247     @retval               a pointer to a newly create Field (on success)
2248   */
2249   virtual Field *create_tmp_field_ex(MEM_ROOT *root,
2250                                      TABLE *table,
2251                                      Tmp_field_src *src,
2252                                      const Tmp_field_param *param)= 0;
field_for_view_update()2253   virtual Item_field *field_for_view_update() { return 0; }
2254 
neg_transformer(THD * thd)2255   virtual Item *neg_transformer(THD *thd) { return NULL; }
update_value_transformer(THD * thd,uchar * select_arg)2256   virtual Item *update_value_transformer(THD *thd, uchar *select_arg)
2257   { return this; }
expr_cache_insert_transformer(THD * thd,uchar * unused)2258   virtual Item *expr_cache_insert_transformer(THD *thd, uchar *unused)
2259   { return this; }
derived_field_transformer_for_having(THD * thd,uchar * arg)2260   virtual Item *derived_field_transformer_for_having(THD *thd, uchar *arg)
2261   { return this; }
derived_field_transformer_for_where(THD * thd,uchar * arg)2262   virtual Item *derived_field_transformer_for_where(THD *thd, uchar *arg)
2263   { return this; }
grouping_field_transformer_for_where(THD * thd,uchar * arg)2264   virtual Item *grouping_field_transformer_for_where(THD *thd, uchar *arg)
2265   { return this; }
2266   /* Now is not used. */
in_subq_field_transformer_for_where(THD * thd,uchar * arg)2267   virtual Item *in_subq_field_transformer_for_where(THD *thd, uchar *arg)
2268   { return this; }
in_subq_field_transformer_for_having(THD * thd,uchar * arg)2269   virtual Item *in_subq_field_transformer_for_having(THD *thd, uchar *arg)
2270   { return this; }
in_predicate_to_in_subs_transformer(THD * thd,uchar * arg)2271   virtual Item *in_predicate_to_in_subs_transformer(THD *thd, uchar *arg)
2272   { return this; }
field_transformer_for_having_pushdown(THD * thd,uchar * arg)2273   virtual Item *field_transformer_for_having_pushdown(THD *thd, uchar *arg)
2274   { return this; }
multiple_equality_transformer(THD * thd,uchar * arg)2275   virtual Item *multiple_equality_transformer(THD *thd, uchar *arg)
2276   { return this; }
expr_cache_is_needed(THD *)2277   virtual bool expr_cache_is_needed(THD *) { return FALSE; }
2278   virtual Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs);
needs_charset_converter(uint32 length,CHARSET_INFO * tocs)2279   bool needs_charset_converter(uint32 length, CHARSET_INFO *tocs) const
2280   {
2281     /*
2282       This will return "true" if conversion happens:
2283       - between two non-binary different character sets
2284       - from "binary" to "unsafe" character set
2285         (those that can have non-well-formed string)
2286       - from "binary" to UCS2-alike character set with mbminlen>1,
2287         when prefix left-padding is needed for an incomplete character:
2288         binary 0xFF -> ucs2 0x00FF)
2289     */
2290     if (!String::needs_conversion_on_storage(length,
2291                                              collation.collation, tocs))
2292       return false;
2293     /*
2294       No needs to add converter if an "arg" is NUMERIC or DATETIME
2295       value (which is pure ASCII) and at the same time target DTCollation
2296       is ASCII-compatible. For example, no needs to rewrite:
2297         SELECT * FROM t1 WHERE datetime_field = '2010-01-01';
2298       to
2299         SELECT * FROM t1 WHERE CONVERT(datetime_field USING cs) = '2010-01-01';
2300 
2301       TODO: avoid conversion of any values with
2302       repertoire ASCII and 7bit-ASCII-compatible,
2303       not only numeric/datetime origin.
2304     */
2305     if (collation.derivation == DERIVATION_NUMERIC &&
2306         collation.repertoire == MY_REPERTOIRE_ASCII &&
2307         !(collation.collation->state & MY_CS_NONASCII) &&
2308         !(tocs->state & MY_CS_NONASCII))
2309       return false;
2310     return true;
2311   }
needs_charset_converter(CHARSET_INFO * tocs)2312   bool needs_charset_converter(CHARSET_INFO *tocs)
2313   {
2314     // Pass 1 as length to force conversion if tocs->mbminlen>1.
2315     return needs_charset_converter(1, tocs);
2316   }
2317   Item *const_charset_converter(THD *thd, CHARSET_INFO *tocs, bool lossless,
2318                                 const char *func_name);
const_charset_converter(THD * thd,CHARSET_INFO * tocs,bool lossless)2319   Item *const_charset_converter(THD *thd, CHARSET_INFO *tocs, bool lossless)
2320   { return const_charset_converter(thd, tocs, lossless, NULL); }
delete_self()2321   void delete_self()
2322   {
2323     cleanup();
2324     delete this;
2325   }
2326 
get_item_const()2327   virtual const Item_const *get_item_const() const { return NULL; }
get_item_splocal()2328   virtual Item_splocal *get_item_splocal() { return 0; }
get_rewritable_query_parameter()2329   virtual Rewritable_query_parameter *get_rewritable_query_parameter()
2330   { return 0; }
2331 
2332   /*
2333     Return Settable_routine_parameter interface of the Item.  Return 0
2334     if this Item is not Settable_routine_parameter.
2335   */
get_settable_routine_parameter()2336   virtual Settable_routine_parameter *get_settable_routine_parameter()
2337   {
2338     return 0;
2339   }
2340 
get_load_data_outvar()2341   virtual Load_data_outvar *get_load_data_outvar()
2342   {
2343     return 0;
2344   }
get_load_data_outvar_or_error()2345   Load_data_outvar *get_load_data_outvar_or_error()
2346   {
2347     Load_data_outvar *dst= get_load_data_outvar();
2348     if (dst)
2349       return dst;
2350     my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), name.str);
2351     return NULL;
2352   }
2353 
2354   /**
2355     Test whether an expression is expensive to compute. Used during
2356     optimization to avoid computing expensive expressions during this
2357     phase. Also used to force temp tables when sorting on expensive
2358     functions.
2359     @todo
2360     Normally we should have a method:
2361       cost Item::execution_cost(),
2362     where 'cost' is either 'double' or some structure of various cost
2363     parameters.
2364 
2365     @note
2366       This function is now used to prevent evaluation of expensive subquery
2367       predicates during the optimization phase. It also prevents evaluation
2368       of predicates that are not computable at this moment.
2369   */
is_expensive()2370   virtual bool is_expensive()
2371   {
2372     if (is_expensive_cache < 0)
2373       is_expensive_cache= walk(&Item::is_expensive_processor, 0, NULL);
2374     return MY_TEST(is_expensive_cache);
2375   }
2376   String *check_well_formed_result(String *str, bool send_error= 0);
2377   bool eq_by_collation(Item *item, bool binary_cmp, CHARSET_INFO *cs);
too_big_for_varchar()2378   bool too_big_for_varchar() const
2379   { return max_char_length() > CONVERT_IF_BIGGER_TO_BLOB; }
fix_length_and_charset(uint32 max_char_length_arg,CHARSET_INFO * cs)2380   void fix_length_and_charset(uint32 max_char_length_arg, CHARSET_INFO *cs)
2381   {
2382     max_length= char_to_byte_length_safe(max_char_length_arg, cs->mbmaxlen);
2383     collation.collation= cs;
2384   }
fix_char_length(size_t max_char_length_arg)2385   void fix_char_length(size_t max_char_length_arg)
2386   {
2387     max_length= char_to_byte_length_safe(max_char_length_arg,
2388                                          collation.collation->mbmaxlen);
2389   }
2390   /*
2391     Return TRUE if the item points to a column of an outer-joined table.
2392   */
is_outer_field()2393   virtual bool is_outer_field() const { DBUG_ASSERT(is_fixed()); return FALSE; }
2394 
2395   /**
2396     Checks if this item or any of its descendents contains a subquery.
2397     This is a replacement of the former Item::has_subquery() and
2398     Item::with_subselect.
2399   */
with_subquery()2400   virtual bool with_subquery() const { DBUG_ASSERT(is_fixed()); return false; }
2401 
with_sum_func()2402   virtual bool with_sum_func() const { return false; }
get_with_sum_func_cache()2403   virtual With_sum_func_cache* get_with_sum_func_cache() { return NULL; }
2404 
2405   Item* set_expr_cache(THD *thd);
2406 
get_item_equal()2407   virtual Item_equal *get_item_equal() { return NULL; }
set_item_equal(Item_equal * item_eq)2408   virtual void set_item_equal(Item_equal *item_eq) {};
find_item_equal(COND_EQUAL * cond_equal)2409   virtual Item_equal *find_item_equal(COND_EQUAL *cond_equal) { return NULL; }
2410   /**
2411     Set the join tab index to the minimal (left-most) JOIN_TAB to which this
2412     Item is attached. The number is an index is depth_first_tab() traversal
2413     order.
2414   */
set_join_tab_idx(uint join_tab_idx_arg)2415   virtual void set_join_tab_idx(uint join_tab_idx_arg)
2416   {
2417     if (join_tab_idx_arg < join_tab_idx)
2418       join_tab_idx= join_tab_idx_arg;
2419   }
get_join_tab_idx()2420   uint get_join_tab_idx() const { return join_tab_idx; }
2421 
view_used_tables(TABLE_LIST * view)2422   table_map view_used_tables(TABLE_LIST *view)
2423   {
2424     view->view_used_tables= 0;
2425     walk(&Item::view_used_tables_processor, 0, view);
2426     return view->view_used_tables;
2427   }
2428 
2429   /**
2430     Collect and add to the list cache parameters for this Item.
2431 
2432     @note Now implemented only for subqueries and in_optimizer,
2433     if we need it for general function then this method should
2434     be defined for Item_func.
2435   */
get_cache_parameters(List<Item> & parameters)2436   virtual void get_cache_parameters(List<Item> &parameters) { };
2437 
mark_as_condition_AND_part(TABLE_LIST * embedding)2438   virtual void mark_as_condition_AND_part(TABLE_LIST *embedding) {};
2439 
2440   /* how much position should be reserved for Exists2In transformation */
exists2in_reserved_items()2441   virtual uint exists2in_reserved_items() { return 0; };
2442 
2443   virtual Item *neg(THD *thd);
2444 
2445   /**
2446     Inform the item that it is located under a NOT, which is a top-level item.
2447   */
under_not(Item_func_not * upper)2448   virtual void under_not(Item_func_not * upper
2449                          __attribute__((unused))) {};
2450   /*
2451     If Item_field is wrapped in Item_direct_wrep remove this Item_direct_ref
2452     wrapper.
2453   */
remove_item_direct_ref()2454   virtual Item *remove_item_direct_ref() { return this; }
2455 
2456 
2457   void register_in(THD *thd);
2458 
depends_only_on(table_map view_map)2459   bool depends_only_on(table_map view_map)
2460   { return marker & FULL_EXTRACTION_FL; }
get_extraction_flag()2461   int get_extraction_flag()
2462   { return  marker & EXTRACTION_MASK; }
set_extraction_flag(int flags)2463   void set_extraction_flag(int flags)
2464   {
2465     marker &= ~EXTRACTION_MASK;
2466     marker|= flags;
2467   }
clear_extraction_flag()2468   void clear_extraction_flag()
2469   {
2470     marker &= ~EXTRACTION_MASK;
2471   }
2472   void check_pushable_cond(Pushdown_checker excl_dep_func, uchar *arg);
pushable_cond_checker_for_derived(uchar * arg)2473   bool pushable_cond_checker_for_derived(uchar *arg)
2474   {
2475     return excl_dep_on_table(*((table_map *)arg));
2476   }
pushable_cond_checker_for_subquery(uchar * arg)2477   bool pushable_cond_checker_for_subquery(uchar *arg)
2478   {
2479     DBUG_ASSERT(((Item*) arg)->get_IN_subquery());
2480     return excl_dep_on_in_subq_left_part(((Item*)arg)->get_IN_subquery());
2481   }
2482   Item *build_pushable_cond(THD *thd,
2483                             Pushdown_checker checker,
2484                             uchar *arg);
2485   /*
2486     Checks if this item depends only on the arg table
2487   */
pushable_equality_checker_for_derived(uchar * arg)2488   bool pushable_equality_checker_for_derived(uchar *arg)
2489   {
2490     return (used_tables() == *((table_map *)arg));
2491   }
2492   /*
2493     Checks if this item consists in the left part of arg IN subquery predicate
2494   */
2495   bool pushable_equality_checker_for_subquery(uchar *arg);
2496 };
2497 
2498 MEM_ROOT *get_thd_memroot(THD *thd);
2499 
2500 template <class T>
get_item_copy(THD * thd,T * item)2501 inline Item* get_item_copy (THD *thd, T* item)
2502 {
2503   Item *copy= new (get_thd_memroot(thd)) T(*item);
2504   if (likely(copy))
2505     copy->register_in(thd);
2506   return copy;
2507 }
2508 
2509 
2510 #ifndef DBUG_OFF
2511 /**
2512   A helper class to print the data type and the value for an Item
2513   in debug builds.
2514 */
2515 class DbugStringItemTypeValue: public StringBuffer<128>
2516 {
2517 public:
DbugStringItemTypeValue(THD * thd,const Item * item)2518   DbugStringItemTypeValue(THD *thd, const Item *item)
2519   {
2520     append('(');
2521     append(item->type_handler()->name().ptr());
2522     append(')');
2523     const_cast<Item*>(item)->print(this, QT_EXPLAIN);
2524     /* Append end \0 to allow usage of c_ptr() */
2525     append('\0');
2526     str_length--;
2527   }
2528 };
2529 #endif
2530 
2531 class With_sum_func_cache
2532 {
2533 protected:
2534   bool m_with_sum_func; // True if the owner item contains a sum func
2535 public:
With_sum_func_cache()2536   With_sum_func_cache()
2537    :m_with_sum_func(false)
2538   { }
With_sum_func_cache(const Item * a)2539   With_sum_func_cache(const Item *a)
2540    :m_with_sum_func(a->with_sum_func())
2541   { }
With_sum_func_cache(const Item * a,const Item * b)2542   With_sum_func_cache(const Item *a, const Item *b)
2543    :m_with_sum_func(a->with_sum_func() || b->with_sum_func())
2544   { }
With_sum_func_cache(const Item * a,const Item * b,const Item * c)2545   With_sum_func_cache(const Item *a, const Item *b, const Item *c)
2546    :m_with_sum_func(a->with_sum_func() || b->with_sum_func() ||
2547                     c->with_sum_func())
2548   { }
With_sum_func_cache(const Item * a,const Item * b,const Item * c,const Item * d)2549   With_sum_func_cache(const Item *a, const Item *b, const Item *c,
2550                       const Item *d)
2551    :m_with_sum_func(a->with_sum_func() || b->with_sum_func() ||
2552                     c->with_sum_func() || d->with_sum_func())
2553   { }
With_sum_func_cache(const Item * a,const Item * b,const Item * c,const Item * d,const Item * e)2554   With_sum_func_cache(const Item *a, const Item *b, const Item *c,
2555                       const Item *d, const Item *e)
2556    :m_with_sum_func(a->with_sum_func() || b->with_sum_func() ||
2557                     c->with_sum_func() || d->with_sum_func() ||
2558                     e->with_sum_func())
2559   { }
set_with_sum_func()2560   void set_with_sum_func() { m_with_sum_func= true; }
reset_with_sum_func()2561   void reset_with_sum_func() { m_with_sum_func= false; }
copy_with_sum_func(const Item * item)2562   void copy_with_sum_func(const Item *item)
2563   {
2564     m_with_sum_func= item->with_sum_func();
2565   }
join_with_sum_func(const Item * item)2566   void join_with_sum_func(const Item *item)
2567   {
2568     m_with_sum_func|= item->with_sum_func();
2569   }
2570 };
2571 
2572 
2573 /*
2574   This class is a replacement for the former member Item::with_subselect.
2575   Determines if the descendant Item is a subselect or some of
2576   its arguments is or contains a subselect.
2577 */
2578 class With_subquery_cache
2579 {
2580 protected:
2581   bool m_with_subquery;
2582 public:
With_subquery_cache()2583   With_subquery_cache(): m_with_subquery(false) { }
join(const Item * item)2584   void join(const Item *item) { m_with_subquery|= item->with_subquery(); }
2585 };
2586 
2587 
2588 /**
2589   Compare two Items for List<Item>::add_unique()
2590 */
2591 
2592 bool cmp_items(Item *a, Item *b);
2593 
2594 
2595 /**
2596   Array of items, e.g. function or aggerate function arguments.
2597 */
2598 class Item_args
2599 {
2600 protected:
2601   Item **args, *tmp_arg[2];
2602   uint arg_count;
2603   void set_arguments(THD *thd, List<Item> &list);
walk_args(Item_processor processor,bool walk_subquery,void * arg)2604   bool walk_args(Item_processor processor, bool walk_subquery, void *arg)
2605   {
2606     for (uint i= 0; i < arg_count; i++)
2607     {
2608       if (args[i]->walk(processor, walk_subquery, arg))
2609         return true;
2610     }
2611     return false;
2612   }
2613   bool transform_args(THD *thd, Item_transformer transformer, uchar *arg);
2614   void propagate_equal_fields(THD *, const Item::Context &, COND_EQUAL *);
excl_dep_on_table(table_map tab_map)2615   bool excl_dep_on_table(table_map tab_map)
2616   {
2617     for (uint i= 0; i < arg_count; i++)
2618     {
2619       if (args[i]->const_item())
2620         continue;
2621       if (!args[i]->excl_dep_on_table(tab_map))
2622         return false;
2623     }
2624     return true;
2625   }
2626   bool excl_dep_on_grouping_fields(st_select_lex *sel);
eq(const Item_args * other,bool binary_cmp)2627   bool eq(const Item_args *other, bool binary_cmp) const
2628   {
2629     for (uint i= 0; i < arg_count ; i++)
2630     {
2631       if (!args[i]->eq(other->args[i], binary_cmp))
2632         return false;
2633     }
2634     return true;
2635   }
excl_dep_on_in_subq_left_part(Item_in_subselect * subq_pred)2636   bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred)
2637   {
2638     for (uint i= 0; i < arg_count; i++)
2639     {
2640       if (args[i]->const_item())
2641         continue;
2642       if (!args[i]->excl_dep_on_in_subq_left_part(subq_pred))
2643         return false;
2644     }
2645     return true;
2646   }
2647 public:
Item_args(void)2648   Item_args(void)
2649     :args(NULL), arg_count(0)
2650   { }
Item_args(Item * a)2651   Item_args(Item *a)
2652     :args(tmp_arg), arg_count(1)
2653   {
2654     args[0]= a;
2655   }
Item_args(Item * a,Item * b)2656   Item_args(Item *a, Item *b)
2657     :args(tmp_arg), arg_count(2)
2658   {
2659     args[0]= a; args[1]= b;
2660   }
Item_args(THD * thd,Item * a,Item * b,Item * c)2661   Item_args(THD *thd, Item *a, Item *b, Item *c)
2662   {
2663     arg_count= 0;
2664     if (likely((args= (Item**) thd_alloc(thd, sizeof(Item*) * 3))))
2665     {
2666       arg_count= 3;
2667       args[0]= a; args[1]= b; args[2]= c;
2668     }
2669   }
Item_args(THD * thd,Item * a,Item * b,Item * c,Item * d)2670   Item_args(THD *thd, Item *a, Item *b, Item *c, Item *d)
2671   {
2672     arg_count= 0;
2673     if (likely((args= (Item**) thd_alloc(thd, sizeof(Item*) * 4))))
2674     {
2675       arg_count= 4;
2676       args[0]= a; args[1]= b; args[2]= c; args[3]= d;
2677     }
2678   }
Item_args(THD * thd,Item * a,Item * b,Item * c,Item * d,Item * e)2679   Item_args(THD *thd, Item *a, Item *b, Item *c, Item *d, Item* e)
2680   {
2681     arg_count= 5;
2682     if (likely((args= (Item**) thd_alloc(thd, sizeof(Item*) * 5))))
2683     {
2684       arg_count= 5;
2685       args[0]= a; args[1]= b; args[2]= c; args[3]= d; args[4]= e;
2686     }
2687   }
Item_args(THD * thd,List<Item> & list)2688   Item_args(THD *thd, List<Item> &list)
2689   {
2690     set_arguments(thd, list);
2691   }
2692   Item_args(THD *thd, const Item_args *other);
2693   bool alloc_arguments(THD *thd, uint count);
add_argument(Item * item)2694   void add_argument(Item *item)
2695   {
2696     args[arg_count++]= item;
2697   }
2698   /**
2699     Extract row elements from the given position.
2700     For example, for this input:  (1,2),(3,4),(5,6)
2701       pos=0 will extract  (1,3,5)
2702       pos=1 will extract  (2,4,6)
2703     @param  thd  - current thread, to allocate memory on its mem_root
2704     @param  rows - an array of compatible ROW-type items
2705     @param  pos  - the element position to extract
2706   */
alloc_and_extract_row_elements(THD * thd,const Item_args * rows,uint pos)2707   bool alloc_and_extract_row_elements(THD *thd, const Item_args *rows, uint pos)
2708   {
2709     DBUG_ASSERT(rows->argument_count() > 0);
2710     DBUG_ASSERT(rows->arguments()[0]->cols() > pos);
2711     if (alloc_arguments(thd, rows->argument_count()))
2712       return true;
2713     for (uint i= 0; i < rows->argument_count(); i++)
2714     {
2715       DBUG_ASSERT(rows->arguments()[0]->cols() == rows->arguments()[i]->cols());
2716       Item *arg= rows->arguments()[i]->element_index(pos);
2717       add_argument(arg);
2718     }
2719     DBUG_ASSERT(argument_count() == rows->argument_count());
2720     return false;
2721   }
arguments()2722   inline Item **arguments() const { return args; }
argument_count()2723   inline uint argument_count() const { return arg_count; }
remove_arguments()2724   inline void remove_arguments() { arg_count=0; }
2725   Sql_mode_dependency value_depends_on_sql_mode_bit_or() const;
2726 };
2727 
2728 
2729 /*
2730   Class to be used to enumerate all field references in an item tree. This
2731   includes references to outside but not fields of the tables within a
2732   subquery.
2733   Suggested usage:
2734 
2735     class My_enumerator : public Field_enumerator
2736     {
2737       virtual void visit_field() { ... your actions ...}
2738     }
2739 
2740     My_enumerator enumerator;
2741     item->walk(Item::enumerate_field_refs_processor, ...,&enumerator);
2742 
2743   This is similar to Visitor pattern.
2744 */
2745 
2746 class Field_enumerator
2747 {
2748 public:
2749   virtual void visit_field(Item_field *field)= 0;
~Field_enumerator()2750   virtual ~Field_enumerator() {};             /* purecov: inspected */
Field_enumerator()2751   Field_enumerator() {}                       /* Remove gcc warning */
2752 };
2753 
2754 class Item_string;
2755 
2756 
2757 class Item_fixed_hybrid: public Item
2758 {
2759 public:
2760   bool fixed;                           // If item was fixed with fix_fields
2761 public:
Item_fixed_hybrid(THD * thd)2762   Item_fixed_hybrid(THD *thd): Item(thd), fixed(false)
2763   { }
Item_fixed_hybrid(THD * thd,Item_fixed_hybrid * item)2764   Item_fixed_hybrid(THD *thd, Item_fixed_hybrid *item)
2765    :Item(thd, item), fixed(item->fixed)
2766   { }
fix_fields(THD * thd,Item ** ref)2767   bool fix_fields(THD *thd, Item **ref)
2768   {
2769     DBUG_ASSERT(!fixed);
2770     fixed= true;
2771     return false;
2772   }
cleanup()2773   void cleanup()
2774   {
2775     Item::cleanup();
2776     fixed= false;
2777   }
quick_fix_field()2778   void quick_fix_field() { fixed= true; }
unfix_fields()2779   void unfix_fields() { fixed= false; }
is_fixed()2780   bool is_fixed() const { return fixed; }
2781 };
2782 
2783 
2784 /**
2785   A common class for Item_basic_constant and Item_param
2786 */
2787 class Item_basic_value :public Item,
2788                         public Item_const
2789 {
2790 protected:
2791   // Value metadata, e.g. to make string processing easier
2792   class Metadata: private MY_STRING_METADATA
2793   {
2794   public:
Metadata(const String * str)2795     Metadata(const String *str)
2796     {
2797       my_string_metadata_get(this, str->charset(), str->ptr(), str->length());
2798     }
Metadata(const String * str,my_repertoire_t repertoire_arg)2799     Metadata(const String *str, my_repertoire_t repertoire_arg)
2800     {
2801       MY_STRING_METADATA::repertoire= repertoire_arg;
2802       MY_STRING_METADATA::char_length= str->numchars();
2803     }
repertoire()2804     my_repertoire_t repertoire() const
2805     {
2806       return MY_STRING_METADATA::repertoire;
2807     }
char_length()2808     size_t char_length() const { return MY_STRING_METADATA::char_length; }
2809   };
fix_charset_and_length(CHARSET_INFO * cs,Derivation dv,Metadata metadata)2810   void fix_charset_and_length(CHARSET_INFO *cs,
2811                               Derivation dv, Metadata metadata)
2812   {
2813     /*
2814       We have to have a different max_length than 'length' here to
2815       ensure that we get the right length if we do use the item
2816       to create a new table. In this case max_length must be the maximum
2817       number of chars for a string of this type because we in Create_field::
2818       divide the max_length with mbmaxlen).
2819     */
2820     collation.set(cs, dv, metadata.repertoire());
2821     fix_char_length(metadata.char_length());
2822     decimals= NOT_FIXED_DEC;
2823   }
fix_charset_and_length_from_str_value(const String & str,Derivation dv)2824   void fix_charset_and_length_from_str_value(const String &str, Derivation dv)
2825   {
2826     fix_charset_and_length(str.charset(), dv, Metadata(&str));
2827   }
Item_basic_value(THD * thd)2828   Item_basic_value(THD *thd): Item(thd) {}
2829 public:
create_tmp_field_ex(MEM_ROOT * root,TABLE * table,Tmp_field_src * src,const Tmp_field_param * param)2830   Field *create_tmp_field_ex(MEM_ROOT *root,
2831                              TABLE *table, Tmp_field_src *src,
2832                              const Tmp_field_param *param) override
2833   {
2834 
2835     /*
2836       create_tmp_field_ex() for this type of Items is called for:
2837       - CREATE TABLE ... SELECT
2838       - In ORDER BY: SELECT max(a) FROM t1 GROUP BY a ORDER BY 'const';
2839       - In CURSORS:
2840           DECLARE c CURSOR FOR SELECT 'test';
2841           OPEN c;
2842     */
2843     return tmp_table_field_from_field_type_maybe_null(root,
2844                                             table, src, param,
2845                                             type() == Item::NULL_ITEM);
2846   }
2847   bool eq(const Item *item, bool binary_cmp) const override;
get_type_all_attributes_from_const()2848   const Type_all_attributes *get_type_all_attributes_from_const() const
2849     override
2850   { return this; }
2851 };
2852 
2853 
2854 class Item_basic_constant :public Item_basic_value
2855 {
2856 public:
Item_basic_constant(THD * thd)2857   Item_basic_constant(THD *thd): Item_basic_value(thd) {};
check_vcol_func_processor(void * arg)2858   bool check_vcol_func_processor(void *arg) { return false; }
get_item_const()2859   const Item_const *get_item_const() const { return this; }
make_string_literal_concat(THD * thd,const LEX_CSTRING *)2860   virtual Item_basic_constant *make_string_literal_concat(THD *thd,
2861                                                           const LEX_CSTRING *)
2862   {
2863     DBUG_ASSERT(0);
2864     return this;
2865   }
2866 };
2867 
2868 
2869 /*****************************************************************************
2870   The class is a base class for representation of stored routine variables in
2871   the Item-hierarchy. There are the following kinds of SP-vars:
2872     - local variables (Item_splocal);
2873     - CASE expression (Item_case_expr);
2874 *****************************************************************************/
2875 
2876 class Item_sp_variable :public Item_fixed_hybrid
2877 {
2878 protected:
2879   /*
2880     THD, which is stored in fix_fields() and is used in this_item() to avoid
2881     current_thd use.
2882   */
2883   THD *m_thd;
2884 
2885   bool fix_fields_from_item(THD *thd, Item **, const Item *);
2886 public:
2887   LEX_CSTRING m_name;
2888 
2889 public:
2890 #ifdef DBUG_ASSERT_EXISTS
2891   /*
2892     Routine to which this Item_splocal belongs. Used for checking if correct
2893     runtime context is used for variable handling.
2894   */
2895   const sp_head *m_sp;
2896 #endif
2897 
2898 public:
2899   Item_sp_variable(THD *thd, const LEX_CSTRING *sp_var_name);
2900 
2901 public:
2902   bool fix_fields(THD *thd, Item **) override= 0;
2903 
2904   double val_real() override;
2905   longlong val_int() override;
2906   String *val_str(String *sp) override;
2907   my_decimal *val_decimal(my_decimal *decimal_value) override;
2908   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
2909   bool val_native(THD *thd, Native *to) override;
2910   bool is_null() override;
2911 
2912 public:
2913   void make_send_field(THD *thd, Send_field *field) override;
2914 
const_item()2915   bool const_item() const override { return true; }
2916 
create_tmp_field_ex(MEM_ROOT * root,TABLE * table,Tmp_field_src * src,const Tmp_field_param * param)2917   Field *create_tmp_field_ex(MEM_ROOT *root,
2918                              TABLE *table, Tmp_field_src *src,
2919                              const Tmp_field_param *param) override
2920   {
2921     return create_tmp_field_ex_simple(root, table, src, param);
2922   }
2923   inline int save_in_field(Field *field, bool no_conversions) override;
2924   inline bool send(Protocol *protocol, st_value *buffer) override;
check_vcol_func_processor(void * arg)2925   bool check_vcol_func_processor(void *arg) override
2926   {
2927     return mark_unsupported_function(m_name.str, arg, VCOL_IMPOSSIBLE);
2928   }
2929 };
2930 
2931 /*****************************************************************************
2932   Item_sp_variable inline implementation.
2933 *****************************************************************************/
2934 
save_in_field(Field * field,bool no_conversions)2935 inline int Item_sp_variable::save_in_field(Field *field, bool no_conversions)
2936 {
2937   return this_item()->save_in_field(field, no_conversions);
2938 }
2939 
send(Protocol * protocol,st_value * buffer)2940 inline bool Item_sp_variable::send(Protocol *protocol, st_value *buffer)
2941 {
2942   return this_item()->send(protocol, buffer);
2943 }
2944 
2945 
2946 /*****************************************************************************
2947   A reference to local SP variable (incl. reference to SP parameter), used in
2948   runtime.
2949 *****************************************************************************/
2950 
2951 class Item_splocal :public Item_sp_variable,
2952                     private Settable_routine_parameter,
2953                     public Rewritable_query_parameter,
2954                     public Type_handler_hybrid_field_type
2955 {
2956 protected:
2957   const Sp_rcontext_handler *m_rcontext_handler;
2958 
2959   uint m_var_idx;
2960 
2961   Type m_type;
2962 
2963   bool append_value_for_log(THD *thd, String *str);
2964 
2965   sp_rcontext *get_rcontext(sp_rcontext *local_ctx) const;
2966   Item_field *get_variable(sp_rcontext *ctx) const;
2967 
2968 public:
2969   Item_splocal(THD *thd, const Sp_rcontext_handler *rh,
2970                const LEX_CSTRING *sp_var_name, uint sp_var_idx,
2971                const Type_handler *handler,
2972                uint pos_in_q= 0, uint len_in_q= 0);
2973 
2974   bool fix_fields(THD *, Item **) override;
2975   Item *this_item() override;
2976   const Item *this_item() const override;
2977   Item **this_item_addr(THD *thd, Item **) override;
2978 
2979   void print(String *str, enum_query_type query_type) override;
2980 
2981 public:
2982   inline const LEX_CSTRING *my_name() const;
2983 
2984   inline uint get_var_idx() const;
2985 
type()2986   Type type() const override { return m_type; }
type_handler()2987   const Type_handler *type_handler() const override
2988   { return Type_handler_hybrid_field_type::type_handler(); }
cols()2989   uint cols() const override { return this_item()->cols(); }
element_index(uint i)2990   Item* element_index(uint i) override
2991   { return this_item()->element_index(i); }
addr(uint i)2992   Item** addr(uint i) override { return this_item()->addr(i); }
2993   bool check_cols(uint c) override;
2994 
2995 private:
2996   bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override;
2997 
2998 public:
get_item_splocal()2999   Item_splocal *get_item_splocal() override { return this; }
3000 
get_rewritable_query_parameter()3001   Rewritable_query_parameter *get_rewritable_query_parameter() override
3002   { return this; }
3003 
get_settable_routine_parameter()3004   Settable_routine_parameter *get_settable_routine_parameter() override
3005   { return this; }
3006 
3007   bool append_for_log(THD *thd, String *str) override;
3008 
get_copy(THD *)3009   Item *get_copy(THD *) override { return nullptr; }
3010 
3011   /*
3012     Override the inherited create_field_for_create_select(),
3013     because we want to preserve the exact data type for:
3014       DECLARE a1 INT;
3015       DECLARE a2 TYPE OF t1.a2;
3016       CREATE TABLE t1 AS SELECT a1, a2;
3017     The inherited implementation would create a column
3018     based on result_type(), which is less exact.
3019   */
create_field_for_create_select(MEM_ROOT * root,TABLE * table)3020   Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) override
3021   { return create_table_field_from_handler(root, table); }
3022 
is_valid_limit_clause_variable_with_error()3023   bool is_valid_limit_clause_variable_with_error() const
3024   {
3025     /*
3026       In case if the variable has an anchored data type, e.g.:
3027         DECLARE a TYPE OF t1.a;
3028       type_handler() is set to &type_handler_null and this
3029       function detects such variable as not valid in LIMIT.
3030     */
3031     if (type_handler()->is_limit_clause_valid_type())
3032       return true;
3033     my_error(ER_WRONG_SPVAR_TYPE_IN_LIMIT, MYF(0));
3034     return false;
3035   }
3036 };
3037 
3038 
3039 /**
3040   An Item_splocal variant whose data type becomes known only at
3041   sp_rcontext creation time, e.g. "DECLARE var1 t1.col1%TYPE".
3042 */
3043 class Item_splocal_with_delayed_data_type: public Item_splocal
3044 {
3045 public:
Item_splocal_with_delayed_data_type(THD * thd,const Sp_rcontext_handler * rh,const LEX_CSTRING * sp_var_name,uint sp_var_idx,uint pos_in_q,uint len_in_q)3046   Item_splocal_with_delayed_data_type(THD *thd,
3047                                       const Sp_rcontext_handler *rh,
3048                                       const LEX_CSTRING *sp_var_name,
3049                                       uint sp_var_idx,
3050                                       uint pos_in_q, uint len_in_q)
3051    :Item_splocal(thd, rh, sp_var_name, sp_var_idx, &type_handler_null,
3052                  pos_in_q, len_in_q)
3053   { }
3054 };
3055 
3056 
3057 /**
3058   SP variables that are fields of a ROW.
3059   DELCARE r ROW(a INT,b INT);
3060   SELECT r.a; -- This is handled by Item_splocal_row_field
3061 */
3062 class Item_splocal_row_field :public Item_splocal
3063 {
3064 protected:
3065   LEX_CSTRING m_field_name;
3066   uint m_field_idx;
3067   bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override;
3068 public:
3069   Item_splocal_row_field(THD *thd,
3070                          const Sp_rcontext_handler *rh,
3071                          const LEX_CSTRING *sp_var_name,
3072                          const LEX_CSTRING *sp_field_name,
3073                          uint sp_var_idx, uint sp_field_idx,
3074                          const Type_handler *handler,
3075                          uint pos_in_q= 0, uint len_in_q= 0)
Item_splocal(thd,rh,sp_var_name,sp_var_idx,handler,pos_in_q,len_in_q)3076    :Item_splocal(thd, rh, sp_var_name, sp_var_idx, handler, pos_in_q, len_in_q),
3077     m_field_name(*sp_field_name),
3078     m_field_idx(sp_field_idx)
3079   { }
3080   bool fix_fields(THD *thd, Item **) override;
3081   Item *this_item() override;
3082   const Item *this_item() const override;
3083   Item **this_item_addr(THD *thd, Item **) override;
3084   bool append_for_log(THD *thd, String *str) override;
3085   void print(String *str, enum_query_type query_type) override;
3086 };
3087 
3088 
3089 class Item_splocal_row_field_by_name :public Item_splocal_row_field
3090 {
3091   bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override;
3092 public:
3093   Item_splocal_row_field_by_name(THD *thd,
3094                                  const Sp_rcontext_handler *rh,
3095                                  const LEX_CSTRING *sp_var_name,
3096                                  const LEX_CSTRING *sp_field_name,
3097                                  uint sp_var_idx,
3098                                  const Type_handler *handler,
3099                                  uint pos_in_q= 0, uint len_in_q= 0)
3100    :Item_splocal_row_field(thd, rh, sp_var_name, sp_field_name,
3101                            sp_var_idx, 0 /* field index will be set later */,
3102                            handler, pos_in_q, len_in_q)
3103   { }
3104   bool fix_fields(THD *thd, Item **it) override;
3105   void print(String *str, enum_query_type query_type) override;
3106 };
3107 
3108 
3109 /*****************************************************************************
3110   Item_splocal inline implementation.
3111 *****************************************************************************/
3112 
my_name()3113 inline const LEX_CSTRING *Item_splocal::my_name() const
3114 {
3115   return &m_name;
3116 }
3117 
get_var_idx()3118 inline uint Item_splocal::get_var_idx() const
3119 {
3120   return m_var_idx;
3121 }
3122 
3123 /*****************************************************************************
3124   A reference to case expression in SP, used in runtime.
3125 *****************************************************************************/
3126 
3127 class Item_case_expr :public Item_sp_variable
3128 {
3129 public:
3130   Item_case_expr(THD *thd, uint case_expr_id);
3131 
3132 public:
3133   bool fix_fields(THD *thd, Item **) override;
3134   Item *this_item() override;
3135   const Item *this_item() const override;
3136   Item **this_item_addr(THD *thd, Item **) override;
3137 
3138   Type type() const override;
type_handler()3139   const Type_handler *type_handler() const override
3140   { return this_item()->type_handler(); }
3141 
3142 public:
3143   /*
3144     NOTE: print() is intended to be used from views and for debug.
3145     Item_case_expr can not occur in views, so here it is only for debug
3146     purposes.
3147   */
3148   void print(String *str, enum_query_type query_type) override;
get_copy(THD *)3149   Item *get_copy(THD *) override { return nullptr; }
3150 
3151 private:
3152   uint m_case_expr_id;
3153 };
3154 
3155 /*****************************************************************************
3156   Item_case_expr inline implementation.
3157 *****************************************************************************/
3158 
type()3159 inline enum Item::Type Item_case_expr::type() const
3160 {
3161   return this_item()->type();
3162 }
3163 
3164 /*
3165   NAME_CONST(given_name, const_value).
3166   This 'function' has all properties of the supplied const_value (which is
3167   assumed to be a literal constant), and the name given_name.
3168 
3169   This is used to replace references to SP variables when we write PROCEDURE
3170   statements into the binary log.
3171 
3172   TODO
3173     Together with Item_splocal and Item::this_item() we can actually extract
3174     common a base of this class and Item_splocal. Maybe it is possible to
3175     extract a common base with class Item_ref, too.
3176 */
3177 
3178 class Item_name_const : public Item_fixed_hybrid
3179 {
3180   Item *value_item;
3181   Item *name_item;
3182 public:
3183   Item_name_const(THD *thd, Item *name_arg, Item *val);
3184 
3185   bool fix_fields(THD *, Item **) override;
3186 
3187   Type type() const override;
3188   double val_real() override;
3189   longlong val_int() override;
3190   String *val_str(String *sp) override;
3191   my_decimal *val_decimal(my_decimal *) override;
3192   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
3193   bool val_native(THD *thd, Native *to) override;
3194   bool is_null() override;
3195   void print(String *str, enum_query_type query_type) override;
3196 
type_handler()3197   const Type_handler *type_handler() const override
3198   {
3199     return value_item->type_handler();
3200   }
3201 
const_item()3202   bool const_item() const override { return true; }
3203 
create_tmp_field_ex(MEM_ROOT * root,TABLE * table,Tmp_field_src * src,const Tmp_field_param * param)3204   Field *create_tmp_field_ex(MEM_ROOT *root,
3205                              TABLE *table, Tmp_field_src *src,
3206                              const Tmp_field_param *param) override
3207   {
3208     /*
3209       We can get to here when using a CURSOR for a query with NAME_CONST():
3210         DECLARE c CURSOR FOR SELECT NAME_CONST('x','y') FROM t1;
3211         OPEN c;
3212     */
3213     return tmp_table_field_from_field_type_maybe_null(root, table, src, param,
3214                                               type() == Item::NULL_ITEM);
3215   }
save_in_field(Field * field,bool no_conversions)3216   int save_in_field(Field *field, bool no_conversions) override
3217   {
3218     return  value_item->save_in_field(field, no_conversions);
3219   }
3220 
send(Protocol * protocol,st_value * buffer)3221   bool send(Protocol *protocol, st_value *buffer) override
3222   {
3223     return value_item->send(protocol, buffer);
3224   }
check_vcol_func_processor(void * arg)3225   bool check_vcol_func_processor(void *arg) override
3226   {
3227     return mark_unsupported_function("name_const()", arg, VCOL_IMPOSSIBLE);
3228   }
get_copy(THD * thd)3229   Item *get_copy(THD *thd) override
3230   { return get_item_copy<Item_name_const>(thd, this); }
3231 };
3232 
3233 
3234 class Item_literal: public Item_basic_constant
3235 {
3236 public:
Item_literal(THD * thd)3237   Item_literal(THD *thd): Item_basic_constant(thd)
3238   { }
type()3239   Type type() const override { return CONST_ITEM; }
check_partition_func_processor(void *)3240   bool check_partition_func_processor(void *) override { return false;}
const_item()3241   bool const_item() const override { return true; }
basic_const_item()3242   bool basic_const_item() const override { return true; }
3243 };
3244 
3245 
3246 class Item_num: public Item_literal
3247 {
3248 public:
Item_num(THD * thd)3249   Item_num(THD *thd): Item_literal(thd) { collation= DTCollation_numeric(); }
3250   Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override;
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)3251   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override
3252   {
3253     return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate);
3254   }
3255 };
3256 
3257 #define NO_CACHED_FIELD_INDEX ((uint)(-1))
3258 
3259 class st_select_lex;
3260 
3261 
3262 class Item_result_field :public Item_fixed_hybrid /* Item with result field */
3263 {
3264 protected:
3265   Field *create_tmp_field_ex_from_handler(MEM_ROOT *root, TABLE *table,
3266                                           Tmp_field_src *src,
3267                                           const Tmp_field_param *param,
3268                                           const Type_handler *h);
3269 public:
3270   Field *result_field;				/* Save result here */
Item_result_field(THD * thd)3271   Item_result_field(THD *thd): Item_fixed_hybrid(thd), result_field(0) {}
3272   // Constructor used for Item_sum/Item_cond_and/or (see Item comment)
Item_result_field(THD * thd,Item_result_field * item)3273   Item_result_field(THD *thd, Item_result_field *item):
3274     Item_fixed_hybrid(thd, item), result_field(item->result_field)
3275   {}
~Item_result_field()3276   ~Item_result_field() {}			/* Required with gcc 2.95 */
get_tmp_table_field()3277   Field *get_tmp_table_field() override { return result_field; }
create_tmp_field_ex(MEM_ROOT * root,TABLE * table,Tmp_field_src * src,const Tmp_field_param * param)3278   Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src,
3279                              const Tmp_field_param *param) override
3280   {
3281     DBUG_ASSERT(fixed);
3282     const Type_handler *h= type_handler()->type_handler_for_tmp_table(this);
3283     return create_tmp_field_ex_from_handler(root, table, src, param, h);
3284   }
3285   void get_tmp_field_src(Tmp_field_src *src, const Tmp_field_param *param);
3286   /*
3287     This implementation of used_tables() used by Item_avg_field and
3288     Item_variance_field which work when only temporary table left, so theu
3289     return table map of the temporary table.
3290   */
used_tables()3291   table_map used_tables() const override { return 1; }
is_result_field()3292   bool is_result_field() override { return true; }
save_in_result_field(bool no_conversions)3293   void save_in_result_field(bool no_conversions) override
3294   {
3295     save_in_field(result_field, no_conversions);
3296   }
3297   void cleanup() override;
check_vcol_func_processor(void *)3298   bool check_vcol_func_processor(void *) override { return false; }
3299 };
3300 
3301 
3302 class Item_ident :public Item_result_field
3303 {
3304 protected:
3305   /*
3306     We have to store initial values of db_name, table_name and field_name
3307     to be able to restore them during cleanup() because they can be
3308     updated during fix_fields() to values from Field object and life-time
3309     of those is shorter than life-time of Item_field.
3310   */
3311   LEX_CSTRING orig_db_name;
3312   LEX_CSTRING orig_table_name;
3313   LEX_CSTRING orig_field_name;
3314 
3315   void undeclared_spvar_error() const;
3316 
3317 public:
3318   Name_resolution_context *context;
3319   LEX_CSTRING db_name;
3320   LEX_CSTRING table_name;
3321   LEX_CSTRING field_name;
3322   bool alias_name_used; /* true if item was resolved against alias */
3323   /*
3324     Cached value of index for this field in table->field array, used by prep.
3325     stmts for speeding up their re-execution. Holds NO_CACHED_FIELD_INDEX
3326     if index value is not known.
3327   */
3328   uint cached_field_index;
3329   /*
3330     Cached pointer to table which contains this field, used for the same reason
3331     by prep. stmt. too in case then we have not-fully qualified field.
3332     0 - means no cached value.
3333   */
3334   TABLE_LIST *cached_table;
3335   st_select_lex *depended_from;
3336   /*
3337     Some Items resolved in another select should not be marked as dependency
3338     of the subquery where they are. During normal name resolution, we check
3339     this. Stored procedures and prepared statements first try to resolve an
3340     ident item using a cached table reference and field position from the
3341     previous query execution (cached_table/cached_field_index). If the
3342     tables were not changed, the ident matches the table/field, and we have
3343     faster resolution of the ident without looking through all tables and
3344     fields in the query. But in this case, we can not check all conditions
3345     about this ident item dependency, so we should cache the condition in
3346     this variable.
3347   */
3348   bool can_be_depended;
3349   Item_ident(THD *thd, Name_resolution_context *context_arg,
3350              const LEX_CSTRING &db_name_arg, const LEX_CSTRING &table_name_arg,
3351              const LEX_CSTRING &field_name_arg);
3352   Item_ident(THD *thd, Item_ident *item);
3353   Item_ident(THD *thd, TABLE_LIST *view_arg, const LEX_CSTRING &field_name_arg);
3354   const char *full_name() const override;
3355   void cleanup() override;
3356   st_select_lex *get_depended_from() const;
3357   bool remove_dependence_processor(void * arg) override;
3358   void print(String *str, enum_query_type query_type) override;
change_context_processor(void * cntx)3359   bool change_context_processor(void *cntx) override
3360     { context= (Name_resolution_context *)cntx; return FALSE; }
3361   /**
3362     Collect outer references
3363   */
3364   bool collect_outer_ref_processor(void *arg) override;
3365   friend bool insert_fields(THD *thd, Name_resolution_context *context,
3366                             const char *db_name,
3367                             const char *table_name, List_iterator<Item> *it,
3368                             bool any_privileges, bool returning_field);
3369 };
3370 
3371 
3372 class Item_field :public Item_ident,
3373                   public Load_data_outvar
3374 {
3375 protected:
3376   void set_field(Field *field);
3377 public:
3378   Field *field;
3379   Item_equal *item_equal;
3380   /*
3381     if any_privileges set to TRUE then here real effective privileges will
3382     be stored
3383   */
3384   privilege_t have_privileges;
3385   /* field need any privileges (for VIEW creation) */
3386   bool any_privileges;
3387   Item_field(THD *thd, Name_resolution_context *context_arg,
3388              const LEX_CSTRING &db_arg, const LEX_CSTRING &table_name_arg,
3389 	     const LEX_CSTRING &field_name_arg);
Item_field(THD * thd,Name_resolution_context * context_arg,const LEX_CSTRING & field_name_arg)3390   Item_field(THD *thd, Name_resolution_context *context_arg,
3391              const LEX_CSTRING &field_name_arg)
3392    :Item_field(thd, context_arg, null_clex_str, null_clex_str, field_name_arg)
3393   { }
Item_field(THD * thd,Name_resolution_context * context_arg)3394   Item_field(THD *thd, Name_resolution_context *context_arg)
3395    :Item_field(thd, context_arg, null_clex_str, null_clex_str, null_clex_str)
3396   { }
3397   /*
3398     Constructor needed to process subselect with temporary tables (see Item)
3399   */
3400   Item_field(THD *thd, Item_field *item);
3401   /*
3402     Constructor used inside setup_wild(), ensures that field, table,
3403     and database names will live as long as Item_field (this is important
3404     in prepared statements).
3405   */
3406   Item_field(THD *thd, Name_resolution_context *context_arg, Field *field);
3407   /*
3408     If this constructor is used, fix_fields() won't work, because
3409     db_name, table_name and column_name are unknown. It's necessary to call
3410     reset_field() before fix_fields() for all fields created this way.
3411   */
3412   Item_field(THD *thd, Field *field);
type()3413   Type type() const override { return FIELD_ITEM; }
3414   bool eq(const Item *item, bool binary_cmp) const override;
3415   double val_real() override;
3416   longlong val_int() override;
3417   my_decimal *val_decimal(my_decimal *) override;
3418   String *val_str(String*) override;
3419   void save_result(Field *to) override;
3420   double val_result() override;
3421   longlong val_int_result() override;
3422   bool val_native(THD *thd, Native *to) override;
3423   bool val_native_result(THD *thd, Native *to) override;
3424   String *str_result(String* tmp) override;
3425   my_decimal *val_decimal_result(my_decimal *) override;
3426   bool val_bool_result() override;
3427   bool is_null_result() override;
3428   bool send(Protocol *protocol, st_value *buffer) override;
get_load_data_outvar()3429   Load_data_outvar *get_load_data_outvar() override { return this; }
load_data_set_null(THD * thd,const Load_data_param * param)3430   bool load_data_set_null(THD *thd, const Load_data_param *param) override
3431   {
3432     return field->load_data_set_null(thd);
3433   }
load_data_set_value(THD * thd,const char * pos,uint length,const Load_data_param * param)3434   bool load_data_set_value(THD *thd, const char *pos, uint length,
3435                            const Load_data_param *param) override
3436   {
3437     field->load_data_set_value(pos, length, param->charset());
3438     return false;
3439   }
3440   bool load_data_set_no_data(THD *thd, const Load_data_param *param) override;
3441   void load_data_print_for_log_event(THD *thd, String *to) const override;
load_data_add_outvar(THD * thd,Load_data_param * param)3442   bool load_data_add_outvar(THD *thd, Load_data_param *param) const override
3443   {
3444     return param->add_outvar_field(thd, field);
3445   }
load_data_fixed_length()3446   uint load_data_fixed_length() const override
3447   {
3448     return field->field_length;
3449   }
3450   void reset_field(Field *f);
3451   bool fix_fields(THD *, Item **) override;
3452   void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge)
3453     override;
3454   void make_send_field(THD *thd, Send_field *tmp_field) override;
3455   int save_in_field(Field *field,bool no_conversions) override;
3456   void save_org_in_field(Field *field, fast_field_copier optimizer_data)
3457     override;
3458   fast_field_copier setup_fast_field_copier(Field *field) override;
3459   table_map used_tables() const override;
3460   table_map all_used_tables() const override;
type_handler()3461   const Type_handler *type_handler() const override
3462   {
3463     const Type_handler *handler= field->type_handler();
3464     return handler->type_handler_for_item_field();
3465   }
real_type_handler()3466   const Type_handler *real_type_handler() const override
3467   {
3468     if (field->is_created_from_null_item)
3469       return &type_handler_null;
3470     return field->type_handler();
3471   }
3472   Field *create_tmp_field_from_item_field(MEM_ROOT *root, TABLE *new_table,
3473                                           Item_ref *orig_item,
3474                                           const Tmp_field_param *param);
3475   Field *create_tmp_field_ex(MEM_ROOT *root,
3476                              TABLE *table, Tmp_field_src *src,
3477                              const Tmp_field_param *param) override;
get_typelib()3478   const TYPELIB *get_typelib() const override { return field->get_typelib(); }
get_monotonicity_info()3479   enum_monotonicity_info get_monotonicity_info() const override
3480   {
3481     return MONOTONIC_STRICT_INCREASING;
3482   }
value_depends_on_sql_mode()3483   Sql_mode_dependency value_depends_on_sql_mode() const override
3484   {
3485     return Sql_mode_dependency(0, field->value_depends_on_sql_mode());
3486   }
3487   longlong val_int_endpoint(bool left_endp, bool *incl_endp) override;
3488   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
3489   bool get_date_result(THD *thd, MYSQL_TIME *ltime,date_mode_t fuzzydate)
3490     override;
3491   longlong val_datetime_packed(THD *thd) override;
3492   longlong val_time_packed(THD *thd) override;
is_null()3493   bool is_null() override { return field->is_null(); }
3494   void update_null_value() override;
update_table_bitmaps()3495   void update_table_bitmaps()
3496   {
3497     if (field && field->table)
3498     {
3499       TABLE *tab= field->table;
3500       tab->covering_keys.intersect(field->part_of_key);
3501       if (tab->read_set)
3502         tab->mark_column_with_deps(field);
3503     }
3504   }
update_used_tables()3505   void update_used_tables() override
3506   {
3507     update_table_bitmaps();
3508   }
build_equal_items(THD * thd,COND_EQUAL * inherited,bool link_item_fields,COND_EQUAL ** cond_equal_ref)3509   COND *build_equal_items(THD *thd, COND_EQUAL *inherited,
3510                           bool link_item_fields,
3511                           COND_EQUAL **cond_equal_ref) override
3512   {
3513     /*
3514       normilize_cond() replaced all conditions of type
3515          WHERE/HAVING field
3516       to:
3517         WHERE/HAVING field<>0
3518       By the time of a build_equal_items() call, all such conditions should
3519       already be replaced. No Item_field are possible.
3520       Note, some Item_field derivants are still possible.
3521       Item_insert_value:
3522         SELECT * FROM t1 WHERE VALUES(a);
3523       Item_default_value:
3524         SELECT * FROM t1 WHERE DEFAULT(a);
3525     */
3526     DBUG_ASSERT(type() != FIELD_ITEM);
3527     return Item_ident::build_equal_items(thd, inherited, link_item_fields,
3528                                          cond_equal_ref);
3529   }
is_result_field()3530   bool is_result_field() override { return false; }
3531   void save_in_result_field(bool no_conversions) override;
3532   Item *get_tmp_table_item(THD *thd) override;
3533   bool find_not_null_fields(table_map allowed) override;
3534   bool collect_item_field_processor(void * arg) override;
3535   bool unknown_splocal_processor(void *arg) override;
3536   bool add_field_to_set_processor(void * arg) override;
3537   bool find_item_in_field_list_processor(void *arg) override;
3538   bool register_field_in_read_map(void *arg) override;
3539   bool register_field_in_write_map(void *arg) override;
3540   bool register_field_in_bitmap(void *arg) override;
check_partition_func_processor(void *)3541   bool check_partition_func_processor(void *) override {return false;}
3542   bool post_fix_fields_part_expr_processor(void *bool_arg) override;
3543   bool check_valid_arguments_processor(void *bool_arg) override;
3544   bool check_field_expression_processor(void *arg) override;
3545   bool enumerate_field_refs_processor(void *arg) override;
3546   bool update_table_bitmaps_processor(void *arg) override;
3547   bool switch_to_nullable_fields_processor(void *arg) override;
3548   bool update_vcol_processor(void *arg) override;
3549   bool rename_fields_processor(void *arg) override;
3550   bool check_vcol_func_processor(void *arg) override;
set_fields_as_dependent_processor(void * arg)3551   bool set_fields_as_dependent_processor(void *arg) override
3552   {
3553     if (!(used_tables() & OUTER_REF_TABLE_BIT))
3554     {
3555       depended_from= (st_select_lex *) arg;
3556       item_equal= NULL;
3557     }
3558     return 0;
3559   }
check_table_name_processor(void * arg)3560   bool check_table_name_processor(void *arg) override
3561   {
3562     Check_table_name_prm &p= *static_cast<Check_table_name_prm*>(arg);
3563     if (!field && p.table_name.length && table_name.length)
3564     {
3565       DBUG_ASSERT(p.db.length);
3566       if ((db_name.length &&
3567           my_strcasecmp(table_alias_charset, p.db.str, db_name.str)) ||
3568           my_strcasecmp(table_alias_charset, p.table_name.str, table_name.str))
3569       {
3570         print(&p.field, (enum_query_type) (QT_ITEM_ORIGINAL_FUNC_NULLIF |
3571                                           QT_NO_DATA_EXPANSION |
3572                                           QT_TO_SYSTEM_CHARSET));
3573         return true;
3574       }
3575     }
3576     return false;
3577   }
3578   void cleanup() override;
get_item_equal()3579   Item_equal *get_item_equal() override { return item_equal; }
set_item_equal(Item_equal * item_eq)3580   void set_item_equal(Item_equal *item_eq) override { item_equal= item_eq; }
3581   Item_equal *find_item_equal(COND_EQUAL *cond_equal) override;
3582   Item* propagate_equal_fields(THD *, const Context &, COND_EQUAL *) override;
3583   Item *replace_equal_field(THD *thd, uchar *arg) override;
max_display_length()3584   uint32 max_display_length() const override
3585   { return field->max_display_length(); }
field_for_view_update()3586   Item_field *field_for_view_update() override { return this; }
3587   int fix_outer_field(THD *thd, Field **field, Item **reference);
3588   Item *update_value_transformer(THD *thd, uchar *select_arg) override;
3589   Item *derived_field_transformer_for_having(THD *thd, uchar *arg) override;
3590   Item *derived_field_transformer_for_where(THD *thd, uchar *arg) override;
3591   Item *grouping_field_transformer_for_where(THD *thd, uchar *arg) override;
3592   Item *in_subq_field_transformer_for_where(THD *thd, uchar *arg) override;
3593   Item *in_subq_field_transformer_for_having(THD *thd, uchar *arg) override;
3594   void print(String *str, enum_query_type query_type) override;
3595   bool excl_dep_on_table(table_map tab_map) override;
3596   bool excl_dep_on_grouping_fields(st_select_lex *sel) override;
3597   bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) override;
cleanup_excluding_fields_processor(void * arg)3598   bool cleanup_excluding_fields_processor(void *arg) override
3599   { return field ? 0 : cleanup_processor(arg); }
cleanup_excluding_const_fields_processor(void * arg)3600   bool cleanup_excluding_const_fields_processor(void *arg) override
3601   { return field && const_item() ? 0 : cleanup_processor(arg); }
3602 
get_copy(THD * thd)3603   Item *get_copy(THD *thd) override
3604   { return get_item_copy<Item_field>(thd, this); }
is_outer_field()3605   bool is_outer_field() const override
3606   {
3607     DBUG_ASSERT(fixed);
3608     return field->table->pos_in_table_list->outer_join;
3609   }
3610   bool check_index_dependence(void *arg) override;
3611   friend class Item_default_value;
3612   friend class Item_insert_value;
3613   friend class st_select_lex_unit;
3614 };
3615 
3616 
3617 /**
3618   Item_field for the ROW data type
3619 */
3620 class Item_field_row: public Item_field,
3621                       public Item_args
3622 {
3623 public:
Item_field_row(THD * thd,Field * field)3624   Item_field_row(THD *thd, Field *field)
3625    :Item_field(thd, field),
3626     Item_args()
3627   { }
get_copy(THD * thd)3628   Item *get_copy(THD *thd) override
3629   { return get_item_copy<Item_field_row>(thd, this); }
3630 
type_handler()3631   const Type_handler *type_handler() const override
3632   { return &type_handler_row; }
cols()3633   uint cols() const override { return arg_count; }
element_index(uint i)3634   Item* element_index(uint i) override { return arg_count ? args[i] : this; }
addr(uint i)3635   Item** addr(uint i) override { return arg_count ? args + i : NULL; }
check_cols(uint c)3636   bool check_cols(uint c) override
3637   {
3638     if (cols() != c)
3639     {
3640       my_error(ER_OPERAND_COLUMNS, MYF(0), c);
3641       return true;
3642     }
3643     return false;
3644   }
3645   bool row_create_items(THD *thd, List<Spvar_definition> *list);
3646 };
3647 
3648 
3649 /*
3650   @brief
3651     Item_temptable_field is the same as Item_field, except that print()
3652     continues to work even if the table has been dropped.
3653 
3654   @detail
3655 
3656     We need this item for "ANALYZE statement" feature. Query execution has
3657     these steps:
3658 
3659       1. Run the query.
3660       2. Cleanup starts. Temporary tables are destroyed
3661       3. print "ANALYZE statement" output, if needed
3662       4. Call close_thread_table() for regular tables.
3663 
3664     Step #4 is done after step #3, so "ANALYZE stmt" has no problem printing
3665     Item_field objects that refer to regular tables.
3666 
3667     However, Step #3 is done after Step #2. Attempt to print Item_field objects
3668     that refer to temporary tables will cause access to freed memory.
3669 
3670     To resolve this, we use Item_temptable_field to refer to items in temporary
3671     (work) tables.
3672 */
3673 
3674 class Item_temptable_field :public Item_field
3675 {
3676 public:
Item_temptable_field(THD * thd,Name_resolution_context * context_arg,Field * field)3677   Item_temptable_field(THD *thd, Name_resolution_context *context_arg, Field *field)
3678    : Item_field(thd, context_arg, field) {}
3679 
Item_temptable_field(THD * thd,Field * field)3680   Item_temptable_field(THD *thd, Field *field)
3681    : Item_field(thd, field) {}
3682 
Item_temptable_field(THD * thd,Item_field * item)3683   Item_temptable_field(THD *thd, Item_field *item) : Item_field(thd, item) {};
3684 
3685   void print(String *str, enum_query_type query_type) override;
3686 };
3687 
3688 
3689 class Item_null :public Item_basic_constant
3690 {
3691 public:
3692   Item_null(THD *thd, const char *name_par=0, CHARSET_INFO *cs= &my_charset_bin):
Item_basic_constant(thd)3693     Item_basic_constant(thd)
3694   {
3695     maybe_null= null_value= TRUE;
3696     max_length= 0;
3697     name.str= name_par ? name_par : "NULL";
3698     name.length= strlen(name.str);
3699     collation.set(cs, DERIVATION_IGNORABLE, MY_REPERTOIRE_ASCII);
3700   }
type()3701   Type type() const override { return NULL_ITEM; }
vcol_assignment_allowed_value()3702   bool vcol_assignment_allowed_value() const override { return true; }
3703   double val_real() override;
3704   longlong val_int() override;
3705   String *val_str(String *str) override;
3706   my_decimal *val_decimal(my_decimal *) override;
3707   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
3708   longlong val_datetime_packed(THD *) override;
3709   longlong val_time_packed(THD *) override;
3710   int save_in_field(Field *field, bool no_conversions) override;
3711   int save_safe_in_field(Field *field) override;
3712   bool send(Protocol *protocol, st_value *buffer) override;
type_handler()3713   const Type_handler *type_handler() const override
3714   { return &type_handler_null; }
basic_const_item()3715   bool basic_const_item() const override { return true; }
3716   Item *clone_item(THD *thd) override;
const_is_null()3717   bool const_is_null() const override { return true; }
is_null()3718   bool is_null() override { return true; }
3719 
print(String * str,enum_query_type)3720   void print(String *str, enum_query_type) override
3721   {
3722     str->append(STRING_WITH_LEN("NULL"));
3723   }
3724 
3725   Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override;
check_partition_func_processor(void *)3726   bool check_partition_func_processor(void *) override { return false; }
3727   Item_basic_constant *make_string_literal_concat(THD *thd,
3728                                                   const LEX_CSTRING *)
3729     override;
get_copy(THD * thd)3730   Item *get_copy(THD *thd) override
3731   { return get_item_copy<Item_null>(thd, this); }
3732 };
3733 
3734 class Item_null_result :public Item_null
3735 {
3736 public:
3737   Field *result_field;
Item_null_result(THD * thd)3738   Item_null_result(THD *thd): Item_null(thd), result_field(0) {}
is_result_field()3739   bool is_result_field() override { return result_field != 0; }
type_handler()3740   const Type_handler *type_handler() const override
3741   {
3742     if (result_field)
3743       return result_field->type_handler();
3744     return &type_handler_null;
3745   }
create_tmp_field_ex(MEM_ROOT *,TABLE *,Tmp_field_src *,const Tmp_field_param *)3746   Field *create_tmp_field_ex(MEM_ROOT *, TABLE *, Tmp_field_src *,
3747                              const Tmp_field_param *) override
3748   {
3749     DBUG_ASSERT(0);
3750     return NULL;
3751   }
save_in_result_field(bool no_conversions)3752   void save_in_result_field(bool no_conversions) override
3753   {
3754     save_in_field(result_field, no_conversions);
3755   }
check_partition_func_processor(void *)3756   bool check_partition_func_processor(void *) override { return true; }
check_vcol_func_processor(void * arg)3757   bool check_vcol_func_processor(void *arg) override
3758   {
3759     return mark_unsupported_function(full_name(), arg, VCOL_IMPOSSIBLE);
3760   }
3761 };
3762 
3763 /*
3764   Item represents one placeholder ('?') of prepared statement
3765 
3766   Notes:
3767   Item_param::field_type() is used when this item is in a temporary table.
3768   This is NOT placeholder metadata sent to client, as this value
3769   is assigned after sending metadata (in setup_one_conversion_function).
3770   For example in case of 'SELECT ?' you'll get MYSQL_TYPE_STRING both
3771   in result set and placeholders metadata, no matter what type you will
3772   supply for this placeholder in mysql_stmt_execute.
3773 
3774   Item_param has two Type_handler pointers,
3775   which can point to different handlers:
3776 
3777   1. In the Type_handler_hybrid_field_type member
3778      It's initialized in:
3779      - Item_param::setup_conversion(), for client-server PS protocol,
3780        according to the bind type.
3781      - Item_param::set_from_item(), for EXECUTE and EXECUTE IMMEDIATE,
3782        according to the actual parameter data type.
3783 
3784   2. In the "value" member.
3785      It's initialized in:
3786      - Item_param::set_param_func(), for client-server PS protocol.
3787      - Item_param::set_from_item(), for EXECUTE and EXECUTE IMMEDIATE.
3788 */
3789 
3790 class Item_param :public Item_basic_value,
3791                   private Settable_routine_parameter,
3792                   public Rewritable_query_parameter,
3793                   private Type_handler_hybrid_field_type
3794 {
3795   /*
3796     NO_VALUE is a special value meaning that the parameter has not been
3797     assigned yet. Item_param::state is assigned to NO_VALUE in constructor
3798     and is used at prepare time.
3799 
3800     1. At prepare time
3801       Item_param::fix_fields() sets "fixed" to true,
3802       but as Item_param::state is still NO_VALUE,
3803       Item_param::basic_const_item() returns false. This prevents various
3804       optimizations to happen at prepare time fix_fields().
3805       For example, in this query:
3806         PREPARE stmt FROM 'SELECT FORMAT(10000,2,?)';
3807       Item_param::basic_const_item() is tested from
3808       Item_func_format::fix_length_and_dec().
3809 
3810     2. At execute time:
3811       When Item_param gets a value
3812       (or a pseudo-value like DEFAULT_VALUE or IGNORE_VALUE):
3813       - Item_param::state changes from NO_VALUE to something else
3814       - Item_param::fixed is changed to true
3815       All Item_param::set_xxx() make sure to do so.
3816       In the state with an assigned value:
3817       - Item_param::basic_const_item() returns true
3818       - Item::type() returns NULL_ITEM or CONST_ITEM,
3819         depending on the value assigned.
3820       So in this state Item_param behaves in many cases like a literal.
3821 
3822       When Item_param::cleanup() is called:
3823       - Item_param::state does not change
3824       - Item_param::fixed changes to false
3825       Note, this puts Item_param into an inconsistent state:
3826       - Item_param::basic_const_item() still returns "true"
3827       - Item_param::type() still pretends to be a basic constant Item
3828       Both are not expected in combination with fixed==false.
3829       However, these methods are not really called in this state,
3830       see asserts in Item_param::basic_const_item() and Item_param::type().
3831 
3832       When Item_param::reset() is called:
3833       - Item_param::state changes to NO_VALUE
3834       - Item_param::fixed changes to false
3835   */
3836   enum enum_item_param_state
3837   {
3838     NO_VALUE, NULL_VALUE, SHORT_DATA_VALUE, LONG_DATA_VALUE,
3839     DEFAULT_VALUE, IGNORE_VALUE
3840   } state;
3841 
3842   void fix_temporal(uint32 max_length_arg, uint decimals_arg);
3843 
3844   struct CONVERSION_INFO
3845   {
3846     /*
3847       Character sets conversion info for string values.
3848       Character sets of client and connection defined at bind time are used
3849       for all conversions, even if one of them is later changed (i.e.
3850       between subsequent calls to mysql_stmt_execute).
3851     */
3852     CHARSET_INFO *character_set_client;
3853     CHARSET_INFO *character_set_of_placeholder;
3854     /*
3855       This points at character set of connection if conversion
3856       to it is required (i. e. if placeholder typecode is not BLOB).
3857       Otherwise it's equal to character_set_client (to simplify
3858       check in convert_str_value()).
3859     */
3860     CHARSET_INFO *final_character_set_of_str_value;
3861   private:
needs_conversionCONVERSION_INFO3862     bool needs_conversion() const
3863     {
3864       return final_character_set_of_str_value !=
3865              character_set_of_placeholder;
3866     }
3867     bool convert(THD *thd, String *str);
3868   public:
3869     void set(THD *thd, CHARSET_INFO *cs);
convert_if_neededCONVERSION_INFO3870     bool convert_if_needed(THD *thd, String *str)
3871     {
3872       /*
3873         Check is so simple because all charsets were set up properly
3874         in setup_one_conversion_function, where typecode of
3875         placeholder was also taken into account: the variables are different
3876         here only if conversion is really necessary.
3877       */
3878       if (needs_conversion())
3879         return convert(thd, str);
3880       str->set_charset(final_character_set_of_str_value);
3881       return false;
3882     }
3883   };
3884 
3885   bool m_empty_string_is_null;
3886 
3887   class PValue_simple
3888   {
3889   public:
3890     union
3891     {
3892       longlong integer;
3893       double   real;
3894       CONVERSION_INFO cs_info;
3895       MYSQL_TIME     time;
3896     };
swap(PValue_simple & other)3897     void swap(PValue_simple &other)
3898     {
3899       swap_variables(PValue_simple, *this, other);
3900     }
3901   };
3902 
3903   class PValue: public Type_handler_hybrid_field_type,
3904                 public PValue_simple,
3905                 public Value_source
3906   {
3907   public:
PValue()3908     PValue(): Type_handler_hybrid_field_type(&type_handler_null) {}
3909     my_decimal m_decimal;
3910     String m_string;
3911     /*
3912       A buffer for string and long data values. Historically all allocated
3913       values returned from val_str() were treated as eligible to
3914       modification. I. e. in some cases Item_func_concat can append it's
3915       second argument to return value of the first one. Because of that we
3916       can't return the original buffer holding string data from val_str(),
3917       and have to have one buffer for data and another just pointing to
3918       the data. This is the latter one and it's returned from val_str().
3919       Can not be declared inside the union as it's not a POD type.
3920     */
3921     String m_string_ptr;
3922 
swap(PValue & other)3923     void swap(PValue &other)
3924     {
3925       Type_handler_hybrid_field_type::swap(other);
3926       PValue_simple::swap(other);
3927       m_decimal.swap(other.m_decimal);
3928       m_string.swap(other.m_string);
3929       m_string_ptr.swap(other.m_string_ptr);
3930     }
3931     double val_real(const Type_std_attributes *attr) const;
3932     longlong val_int(const Type_std_attributes *attr) const;
3933     my_decimal *val_decimal(my_decimal *dec, const Type_std_attributes *attr);
3934     String *val_str(String *str, const Type_std_attributes *attr);
3935   };
3936 
3937   PValue value;
3938 
3939   const String *value_query_val_str(THD *thd, String* str) const;
3940   Item *value_clone_item(THD *thd);
3941   bool is_evaluable_expression() const override;
3942   bool can_return_value() const;
3943 
3944 public:
3945   /*
3946     Used for bulk protocol only.
3947   */
3948   enum enum_indicator_type indicator;
3949 
type_handler()3950   const Type_handler *type_handler() const override
3951   { return Type_handler_hybrid_field_type::type_handler(); }
3952 
vcol_assignment_allowed_value()3953   bool vcol_assignment_allowed_value() const override
3954   {
3955     switch (state) {
3956     case NULL_VALUE:
3957     case DEFAULT_VALUE:
3958     case IGNORE_VALUE:
3959       return true;
3960     case NO_VALUE:
3961     case SHORT_DATA_VALUE:
3962     case LONG_DATA_VALUE:
3963       break;
3964     }
3965     return false;
3966   }
3967 
3968   Item_param(THD *thd, const LEX_CSTRING *name_arg,
3969              uint pos_in_query_arg, uint len_in_query_arg);
3970 
type()3971   Type type() const override
3972   {
3973     // Don't pretend to be a constant unless value for this item is set.
3974     switch (state) {
3975     case NO_VALUE:         return PARAM_ITEM;
3976     case NULL_VALUE:       return NULL_ITEM;
3977     case SHORT_DATA_VALUE: return CONST_ITEM;
3978     case LONG_DATA_VALUE:  return CONST_ITEM;
3979     case DEFAULT_VALUE:    return PARAM_ITEM;
3980     case IGNORE_VALUE:     return PARAM_ITEM;
3981     }
3982     DBUG_ASSERT(0);
3983     return PARAM_ITEM;
3984   }
3985 
is_order_clause_position()3986   bool is_order_clause_position() const override
3987   {
3988     return state == SHORT_DATA_VALUE &&
3989            type_handler()->is_order_clause_position_type();
3990   }
3991 
get_item_const()3992   const Item_const *get_item_const() const override
3993   {
3994     switch (state) {
3995     case SHORT_DATA_VALUE:
3996     case LONG_DATA_VALUE:
3997     case NULL_VALUE:
3998       return this;
3999     case IGNORE_VALUE:
4000     case DEFAULT_VALUE:
4001     case NO_VALUE:
4002       break;
4003     }
4004     return NULL;
4005   }
4006 
const_is_null()4007   bool const_is_null() const override { return state == NULL_VALUE; }
can_return_const_value(Item_result type)4008   bool can_return_const_value(Item_result type) const
4009   {
4010     return can_return_value() &&
4011            value.type_handler()->cmp_type() == type &&
4012            type_handler()->cmp_type() == type;
4013   }
const_ptr_longlong()4014   const longlong *const_ptr_longlong() const override
4015   { return can_return_const_value(INT_RESULT) ? &value.integer : NULL; }
const_ptr_double()4016   const double *const_ptr_double() const override
4017   { return can_return_const_value(REAL_RESULT) ? &value.real : NULL; }
const_ptr_my_decimal()4018   const my_decimal *const_ptr_my_decimal() const override
4019   { return can_return_const_value(DECIMAL_RESULT) ? &value.m_decimal : NULL; }
const_ptr_mysql_time()4020   const MYSQL_TIME *const_ptr_mysql_time() const override
4021   { return can_return_const_value(TIME_RESULT) ? &value.time : NULL; }
const_ptr_string()4022   const String *const_ptr_string() const override
4023   { return can_return_const_value(STRING_RESULT) ? &value.m_string : NULL; }
4024 
val_real()4025   double val_real() override
4026   {
4027     return can_return_value() ? value.val_real(this) : 0e0;
4028   }
val_int()4029   longlong val_int() override
4030   {
4031     return can_return_value() ? value.val_int(this) : 0;
4032   }
val_decimal(my_decimal * dec)4033   my_decimal *val_decimal(my_decimal *dec) override
4034   {
4035     return can_return_value() ? value.val_decimal(dec, this) : NULL;
4036   }
val_str(String * str)4037   String *val_str(String *str) override
4038   {
4039     return can_return_value() ? value.val_str(str, this) : NULL;
4040   }
4041   bool get_date(THD *thd, MYSQL_TIME *tm, date_mode_t fuzzydate) override;
val_native(THD * thd,Native * to)4042   bool val_native(THD *thd, Native *to) override
4043   {
4044     return Item_param::type_handler()->Item_param_val_native(thd, this, to);
4045   }
4046 
4047   int save_in_field(Field *field, bool no_conversions) override;
4048 
4049   void set_default();
4050   void set_ignore();
4051   void set_null();
4052   void set_int(longlong i, uint32 max_length_arg);
4053   void set_double(double i);
4054   void set_decimal(const char *str, ulong length);
4055   void set_decimal(const my_decimal *dv, bool unsigned_arg);
4056   bool set_str(const char *str, ulong length,
4057                CHARSET_INFO *fromcs, CHARSET_INFO *tocs);
4058   bool set_longdata(const char *str, ulong length);
4059   void set_time(MYSQL_TIME *tm, timestamp_type type, uint32 max_length_arg);
4060   void set_time(const MYSQL_TIME *tm, uint32 max_length_arg, uint decimals_arg);
4061   bool set_from_item(THD *thd, Item *item);
4062   void reset();
4063 
4064   void set_param_tiny(uchar **pos, ulong len);
4065   void set_param_short(uchar **pos, ulong len);
4066   void set_param_int32(uchar **pos, ulong len);
4067   void set_param_int64(uchar **pos, ulong len);
4068   void set_param_float(uchar **pos, ulong len);
4069   void set_param_double(uchar **pos, ulong len);
4070   void set_param_decimal(uchar **pos, ulong len);
4071   void set_param_time(uchar **pos, ulong len);
4072   void set_param_datetime(uchar **pos, ulong len);
4073   void set_param_date(uchar **pos, ulong len);
4074   void set_param_str(uchar **pos, ulong len);
4075 
4076   void setup_conversion(THD *thd, uchar param_type);
4077   void setup_conversion_blob(THD *thd);
4078   void setup_conversion_string(THD *thd, CHARSET_INFO *fromcs);
4079 
4080   /*
4081     Assign placeholder value from bind data.
4082     Note, that 'len' has different semantics in embedded library (as we
4083     don't need to check that packet is not broken there). See
4084     sql_prepare.cc for details.
4085   */
set_param_func(uchar ** pos,ulong len)4086   void set_param_func(uchar **pos, ulong len)
4087   {
4088     /*
4089       To avoid Item_param::set_xxx() asserting on data type mismatch,
4090       we set the value type handler here:
4091       - It can not be initialized yet after Item_param::setup_conversion().
4092       - Also, for LIMIT clause parameters, the value type handler might have
4093         changed from the real type handler to type_handler_longlong.
4094         So here we'll restore it.
4095     */
4096     const Type_handler *h= Item_param::type_handler();
4097     value.set_handler(h);
4098     h->Item_param_set_param_func(this, pos, len);
4099   }
4100 
set_value(THD * thd,const Type_all_attributes * attr,const st_value * val,const Type_handler * h)4101   bool set_value(THD *thd, const Type_all_attributes *attr,
4102                  const st_value *val, const Type_handler *h)
4103   {
4104     value.set_handler(h); // See comments in set_param_func()
4105     return h->Item_param_set_from_value(thd, this, attr, val);
4106   }
4107 
set_limit_clause_param(longlong nr)4108   bool set_limit_clause_param(longlong nr)
4109   {
4110     value.set_handler(&type_handler_slonglong);
4111     set_int(nr, MY_INT64_NUM_DECIMAL_DIGITS);
4112     return !unsigned_flag && value.integer < 0;
4113   }
4114   const String *query_val_str(THD *thd, String *str) const;
4115 
4116   bool convert_str_value(THD *thd);
4117 
4118   /*
4119     If value for parameter was not set we treat it as non-const
4120     so no one will use parameters value in fix_fields still
4121     parameter is constant during execution.
4122   */
const_item()4123   bool const_item() const override
4124   {
4125     return state != NO_VALUE;
4126   }
used_tables()4127   table_map used_tables() const override
4128   {
4129     return state != NO_VALUE ? (table_map)0 : PARAM_TABLE_BIT;
4130   }
4131   void print(String *str, enum_query_type query_type) override;
is_null()4132   bool is_null() override
4133   { DBUG_ASSERT(state != NO_VALUE); return state == NULL_VALUE; }
4134   bool basic_const_item() const override;
has_no_value()4135   bool has_no_value() const
4136   {
4137     return state == NO_VALUE;
4138   }
has_long_data_value()4139   bool has_long_data_value() const
4140   {
4141     return state == LONG_DATA_VALUE;
4142   }
has_int_value()4143   bool has_int_value() const
4144   {
4145     return state == SHORT_DATA_VALUE &&
4146            value.type_handler()->cmp_type() == INT_RESULT;
4147   }
4148   /*
4149     This method is used to make a copy of a basic constant item when
4150     propagating constants in the optimizer. The reason to create a new
4151     item and not use the existing one is not precisely known (2005/04/16).
4152     Probably we are trying to preserve tree structure of items, in other
4153     words, avoid pointing at one item from two different nodes of the tree.
4154     Return a new basic constant item if parameter value is a basic
4155     constant, assert otherwise. This method is called only if
4156     basic_const_item returned TRUE.
4157   */
4158   Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override;
4159   Item *clone_item(THD *thd) override;
4160   void set_param_type_and_swap_value(Item_param *from);
4161 
get_rewritable_query_parameter()4162   Rewritable_query_parameter *get_rewritable_query_parameter() override
4163   { return this; }
get_settable_routine_parameter()4164   Settable_routine_parameter *get_settable_routine_parameter() override
4165   { return m_is_settable_routine_parameter ? this : nullptr; }
4166 
4167   bool append_for_log(THD *thd, String *str) override;
check_vcol_func_processor(void *)4168   bool check_vcol_func_processor(void *) override { return false; }
get_copy(THD *)4169   Item *get_copy(THD *) override { return nullptr; }
4170 
4171   bool add_as_clone(THD *thd);
4172   void sync_clones();
register_clone(Item_param * i)4173   bool register_clone(Item_param *i) { return m_clones.push_back(i); }
4174 
4175 private:
4176   void invalid_default_param() const;
4177 
4178   bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override;
4179 
4180   void set_out_param_info(Send_field *info) override;
4181 
4182 public:
4183   const Send_field *get_out_param_info() const override;
4184 
get_item_param()4185   Item_param *get_item_param() override { return this; }
4186 
4187   void make_send_field(THD *thd, Send_field *field) override;
4188 
4189 private:
4190   Send_field *m_out_param_info;
4191   bool m_is_settable_routine_parameter;
4192   /*
4193     Array of all references of this parameter marker used in a CTE to its clones
4194     created for copies of this marker used the CTE's copies. It's used to
4195     synchronize the actual value of the parameter with the values of the clones.
4196   */
4197   Mem_root_array<Item_param *, true> m_clones;
4198 };
4199 
4200 
4201 class Item_int :public Item_num
4202 {
4203 public:
4204   longlong value;
4205   Item_int(THD *thd, int32 i,size_t length= MY_INT32_NUM_DECIMAL_DIGITS):
Item_num(thd)4206     Item_num(thd), value((longlong) i)
4207     { max_length=(uint32)length; }
4208   Item_int(THD *thd, longlong i,size_t length= MY_INT64_NUM_DECIMAL_DIGITS):
Item_num(thd)4209     Item_num(thd), value(i)
4210     { max_length=(uint32)length; }
4211   Item_int(THD *thd, ulonglong i, size_t length= MY_INT64_NUM_DECIMAL_DIGITS):
Item_num(thd)4212     Item_num(thd), value((longlong)i)
4213     { max_length=(uint32)length; unsigned_flag= 1; }
Item_int(THD * thd,const char * str_arg,longlong i,size_t length)4214   Item_int(THD *thd, const char *str_arg,longlong i,size_t length):
4215     Item_num(thd), value(i)
4216     {
4217       max_length=(uint32)length;
4218       name.str= str_arg; name.length= safe_strlen(name.str);
4219     }
Item_int(THD * thd,const char * str_arg,longlong i,size_t length,bool flag)4220   Item_int(THD *thd, const char *str_arg,longlong i,size_t length, bool flag):
4221     Item_num(thd), value(i)
4222     {
4223       max_length=(uint32)length;
4224       name.str= str_arg; name.length= safe_strlen(name.str);
4225       unsigned_flag= flag;
4226     }
4227   Item_int(THD *thd, const char *str_arg, size_t length=64);
type_handler()4228   const Type_handler *type_handler() const override
4229   { return type_handler_long_or_longlong(); }
create_field_for_create_select(MEM_ROOT * root,TABLE * table)4230   Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) override
4231   { return tmp_table_field_from_field_type(root, table); }
const_ptr_longlong()4232   const longlong *const_ptr_longlong() const override { return &value; }
val_int()4233   longlong val_int() override { return value; }
val_int_min()4234   longlong val_int_min() const override { return value; }
val_real()4235   double val_real() override { return (double) value; }
4236   my_decimal *val_decimal(my_decimal *) override;
4237   String *val_str(String*) override;
4238   int save_in_field(Field *field, bool no_conversions) override;
is_order_clause_position()4239   bool is_order_clause_position() const override { return true; }
4240   Item *clone_item(THD *thd) override;
4241   void print(String *str, enum_query_type query_type) override;
4242   Item *neg(THD *thd) override;
decimal_precision()4243   uint decimal_precision() const override
4244   { return (uint) (max_length - MY_TEST(value < 0)); }
get_copy(THD * thd)4245   Item *get_copy(THD *thd) override
4246   { return get_item_copy<Item_int>(thd, this); }
4247 };
4248 
4249 
4250 /*
4251   We sometimes need to distinguish a number from a boolean:
4252   a[1] and a[true] are different things in XPath.
4253   Also in JSON boolean values should be treated differently.
4254 */
4255 class Item_bool :public Item_int
4256 {
4257 public:
Item_bool(THD * thd,const char * str_arg,longlong i)4258   Item_bool(THD *thd, const char *str_arg, longlong i):
4259     Item_int(thd, str_arg, i, 1) {}
Item_bool(THD * thd,bool i)4260   Item_bool(THD *thd, bool i) :Item_int(thd, (longlong) i, 1) { }
is_bool_literal()4261   bool is_bool_literal() const override { return true; }
4262   Item *neg_transformer(THD *thd) override;
type_handler()4263   const Type_handler *type_handler() const override
4264   { return &type_handler_bool; }
fixed_type_handler()4265   const Type_handler *fixed_type_handler() const override
4266   { return &type_handler_bool; }
quick_fix_field()4267   void quick_fix_field() override
4268   {
4269     /*
4270       We can get here when Item_bool is created instead of a constant
4271       predicate at various condition optimization stages in sql_select.
4272     */
4273   }
4274 };
4275 
4276 
4277 class Item_uint :public Item_int
4278 {
4279 public:
4280   Item_uint(THD *thd, const char *str_arg, size_t length);
Item_uint(THD * thd,ulonglong i)4281   Item_uint(THD *thd, ulonglong i): Item_int(thd, i, 10) {}
4282   Item_uint(THD *thd, const char *str_arg, longlong i, uint length);
val_real()4283   double val_real() { return ulonglong2double((ulonglong)value); }
4284   Item *clone_item(THD *thd);
4285   Item *neg(THD *thd);
decimal_precision()4286   uint decimal_precision() const { return max_length; }
get_copy(THD * thd)4287   Item *get_copy(THD *thd)
4288   { return get_item_copy<Item_uint>(thd, this); }
4289 };
4290 
4291 
4292 class Item_datetime :public Item_int
4293 {
4294 protected:
4295   MYSQL_TIME ltime;
4296 public:
Item_datetime(THD * thd)4297   Item_datetime(THD *thd): Item_int(thd, 0) { unsigned_flag=0; }
4298   int save_in_field(Field *field, bool no_conversions) override;
4299   longlong val_int() override;
val_real()4300   double val_real() override { return (double)val_int(); }
4301   void set(longlong packed, enum_mysql_timestamp_type ts_type);
get_date(THD * thd,MYSQL_TIME * to,date_mode_t fuzzydate)4302   bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t fuzzydate) override
4303   {
4304     *to= ltime;
4305     return false;
4306   }
4307 };
4308 
4309 
4310 /* decimal (fixed point) constant */
4311 class Item_decimal :public Item_num
4312 {
4313 protected:
4314   my_decimal decimal_value;
4315 public:
4316   Item_decimal(THD *thd, const char *str_arg, size_t length,
4317                CHARSET_INFO *charset);
4318   Item_decimal(THD *thd, const char *str, const my_decimal *val_arg,
4319                uint decimal_par, uint length);
4320   Item_decimal(THD *thd, const my_decimal *value_par);
4321   Item_decimal(THD *thd, longlong val, bool unsig);
4322   Item_decimal(THD *thd, double val, int precision, int scale);
4323   Item_decimal(THD *thd, const uchar *bin, int precision, int scale);
4324 
type_handler()4325   const Type_handler *type_handler() const override
4326   { return &type_handler_newdecimal; }
val_int()4327   longlong val_int() override
4328   { return decimal_value.to_longlong(unsigned_flag); }
val_real()4329   double val_real() override { return decimal_value.to_double(); }
val_str(String * to)4330   String *val_str(String *to) override { return decimal_value.to_string(to); }
val_decimal(my_decimal * val)4331   my_decimal *val_decimal(my_decimal *val) override { return &decimal_value; }
const_ptr_my_decimal()4332   const my_decimal *const_ptr_my_decimal() const override
4333   { return &decimal_value; }
4334   int save_in_field(Field *field, bool no_conversions) override;
4335   Item *clone_item(THD *thd) override;
print(String * str,enum_query_type query_type)4336   void print(String *str, enum_query_type query_type) override
4337   {
4338     decimal_value.to_string(&str_value);
4339     str->append(str_value);
4340   }
4341   Item *neg(THD *thd) override;
decimal_precision()4342   uint decimal_precision() const override { return decimal_value.precision(); }
4343   void set_decimal_value(my_decimal *value_par);
get_copy(THD * thd)4344   Item *get_copy(THD *thd) override
4345   { return get_item_copy<Item_decimal>(thd, this); }
4346 };
4347 
4348 
4349 class Item_float :public Item_num
4350 {
4351   const char *presentation;
4352 public:
4353   double value;
4354   Item_float(THD *thd, const char *str_arg, size_t length);
Item_float(THD * thd,const char * str,double val_arg,uint decimal_par,uint length)4355   Item_float(THD *thd, const char *str, double val_arg, uint decimal_par,
4356              uint length): Item_num(thd), value(val_arg)
4357   {
4358     presentation= name.str= str;
4359     name.length= safe_strlen(str);
4360     decimals=(uint8) decimal_par;
4361     max_length= length;
4362   }
Item_float(THD * thd,double value_par,uint decimal_par)4363   Item_float(THD *thd, double value_par, uint decimal_par):
4364     Item_num(thd), presentation(0), value(value_par)
4365   {
4366     decimals= (uint8) decimal_par;
4367   }
4368   int save_in_field(Field *field, bool no_conversions) override;
type_handler()4369   const Type_handler *type_handler() const override
4370   { return &type_handler_double; }
const_ptr_double()4371   const double *const_ptr_double() const override { return &value; }
val_real()4372   double val_real() override { return value; }
val_int()4373   longlong val_int() override
4374   {
4375     if (value <= (double) LONGLONG_MIN)
4376     {
4377        return LONGLONG_MIN;
4378     }
4379     else if (value >= (double) (ulonglong) LONGLONG_MAX)
4380     {
4381       return LONGLONG_MAX;
4382     }
4383     return (longlong) rint(value);
4384   }
4385   String *val_str(String*) override;
4386   my_decimal *val_decimal(my_decimal *) override;
4387   Item *clone_item(THD *thd) override;
4388   Item *neg(THD *thd) override;
4389   void print(String *str, enum_query_type query_type) override;
get_copy(THD * thd)4390   Item *get_copy(THD *thd) override
4391   { return get_item_copy<Item_float>(thd, this); }
4392 };
4393 
4394 
4395 class Item_static_float_func :public Item_float
4396 {
4397   const char *func_name;
4398 public:
Item_static_float_func(THD * thd,const char * str,double val_arg,uint decimal_par,uint length)4399   Item_static_float_func(THD *thd, const char *str, double val_arg,
4400                          uint decimal_par, uint length):
4401     Item_float(thd, NullS, val_arg, decimal_par, length), func_name(str)
4402   {}
4403 
print(String * str,enum_query_type)4404   void print(String *str, enum_query_type) override
4405   {
4406     str->append(func_name);
4407   }
4408 
safe_charset_converter(THD * thd,CHARSET_INFO * tocs)4409   Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override
4410   {
4411     return const_charset_converter(thd, tocs, true, func_name);
4412   }
4413 };
4414 
4415 
4416 class Item_string :public Item_literal
4417 {
4418 protected:
fix_from_value(Derivation dv,const Metadata metadata)4419   void fix_from_value(Derivation dv, const Metadata metadata)
4420   {
4421     fix_charset_and_length(str_value.charset(), dv, metadata);
4422   }
fix_and_set_name_from_value(THD * thd,Derivation dv,const Metadata metadata)4423   void fix_and_set_name_from_value(THD *thd, Derivation dv,
4424                                    const Metadata metadata)
4425   {
4426     fix_from_value(dv, metadata);
4427     set_name(thd, &str_value);
4428   }
4429 protected:
4430   /* Just create an item and do not fill string representation */
4431   Item_string(THD *thd, CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE):
Item_literal(thd)4432     Item_literal(thd)
4433   {
4434     collation.set(cs, dv);
4435     max_length= 0;
4436     set_name(thd, NULL, 0, system_charset_info);
4437     decimals= NOT_FIXED_DEC;
4438   }
4439 public:
Item_string(THD * thd,CHARSET_INFO * csi,const char * str_arg,uint length_arg)4440   Item_string(THD *thd, CHARSET_INFO *csi, const char *str_arg, uint length_arg)
4441    :Item_literal(thd)
4442   {
4443     collation.set(csi, DERIVATION_COERCIBLE);
4444     set_name(thd, NULL, 0, system_charset_info);
4445     decimals= NOT_FIXED_DEC;
4446     str_value.copy(str_arg, length_arg, csi);
4447     max_length= str_value.numchars() * csi->mbmaxlen;
4448   }
4449   // Constructors with the item name set from its value
Item_string(THD * thd,const char * str,uint length,CHARSET_INFO * cs,Derivation dv,my_repertoire_t repertoire)4450   Item_string(THD *thd, const char *str, uint length, CHARSET_INFO *cs,
4451               Derivation dv, my_repertoire_t repertoire)
4452    :Item_literal(thd)
4453   {
4454     str_value.set_or_copy_aligned(str, length, cs);
4455     fix_and_set_name_from_value(thd, dv, Metadata(&str_value, repertoire));
4456   }
4457   Item_string(THD *thd, const char *str, size_t length,
4458               CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE)
Item_literal(thd)4459    :Item_literal(thd)
4460   {
4461     str_value.set_or_copy_aligned(str, length, cs);
4462     fix_and_set_name_from_value(thd, dv, Metadata(&str_value));
4463   }
Item_string(THD * thd,const String * str,CHARSET_INFO * tocs,uint * conv_errors,Derivation dv,my_repertoire_t repertoire)4464   Item_string(THD *thd, const String *str, CHARSET_INFO *tocs, uint *conv_errors,
4465               Derivation dv, my_repertoire_t repertoire)
4466    :Item_literal(thd)
4467   {
4468     if (str_value.copy(str, tocs, conv_errors))
4469       str_value.set("", 0, tocs); // EOM ?
4470     str_value.mark_as_const();
4471     fix_and_set_name_from_value(thd, dv, Metadata(&str_value, repertoire));
4472   }
4473   // Constructors with an externally provided item name
4474   Item_string(THD *thd, const LEX_CSTRING &name_par, const LEX_CSTRING &str,
4475               CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE)
Item_literal(thd)4476    :Item_literal(thd)
4477   {
4478     str_value.set_or_copy_aligned(str.str, str.length, cs);
4479     fix_from_value(dv, Metadata(&str_value));
4480     set_name(thd, name_par);
4481   }
Item_string(THD * thd,const LEX_CSTRING & name_par,const LEX_CSTRING & str,CHARSET_INFO * cs,Derivation dv,my_repertoire_t repertoire)4482   Item_string(THD *thd, const LEX_CSTRING &name_par, const LEX_CSTRING &str,
4483               CHARSET_INFO *cs, Derivation dv, my_repertoire_t repertoire)
4484    :Item_literal(thd)
4485   {
4486     str_value.set_or_copy_aligned(str.str, str.length, cs);
4487     fix_from_value(dv, Metadata(&str_value, repertoire));
4488     set_name(thd, name_par);
4489   }
print_value(String * to)4490   void print_value(String *to) const
4491   {
4492     str_value.print(to);
4493   }
4494   double val_real() override;
4495   longlong val_int() override;
const_ptr_string()4496   const String *const_ptr_string() const override { return &str_value; }
val_str(String *)4497   String *val_str(String*) override
4498   {
4499     return (String*) &str_value;
4500   }
4501   my_decimal *val_decimal(my_decimal *) override;
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)4502   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override
4503   {
4504     return get_date_from_string(thd, ltime, fuzzydate);
4505   }
4506   int save_in_field(Field *field, bool no_conversions) override;
type_handler()4507   const Type_handler *type_handler() const override
4508   { return &type_handler_varchar; }
4509   Item *clone_item(THD *thd) override;
safe_charset_converter(THD * thd,CHARSET_INFO * tocs)4510   Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override
4511   {
4512     return const_charset_converter(thd, tocs, true);
4513   }
append(const char * str,uint length)4514   inline void append(const char *str, uint length)
4515   {
4516     str_value.append(str, length);
4517     max_length= str_value.numchars() * collation.collation->mbmaxlen;
4518   }
4519   void print(String *str, enum_query_type query_type) override;
4520 
4521   /**
4522     Return TRUE if character-set-introducer was explicitly specified in the
4523     original query for this item (text literal).
4524 
4525     This operation is to be called from Item_string::print(). The idea is
4526     that when a query is generated (re-constructed) from the Item-tree,
4527     character-set-introducers should appear only for those literals, where
4528     they were explicitly specified by the user. Otherwise, that may lead to
4529     loss collation information (character set introducers implies default
4530     collation for the literal).
4531 
4532     Basically, that makes sense only for views and hopefully will be gone
4533     one day when we start using original query as a view definition.
4534 
4535     @return This operation returns the value of m_cs_specified attribute.
4536       @retval TRUE if character set introducer was explicitly specified in
4537       the original query.
4538       @retval FALSE otherwise.
4539   */
is_cs_specified()4540   virtual bool is_cs_specified() const
4541   {
4542     return false;
4543   }
4544 
check_well_formed_result(bool send_error)4545   String *check_well_formed_result(bool send_error)
4546   { return Item::check_well_formed_result(&str_value, send_error); }
4547 
4548   Item_basic_constant *make_string_literal_concat(THD *thd,
4549                                                   const LEX_CSTRING *)
4550     override;
4551   Item *make_odbc_literal(THD *thd, const LEX_CSTRING *typestr) override;
4552 
get_copy(THD * thd)4553   Item *get_copy(THD *thd) override
4554   { return get_item_copy<Item_string>(thd, this); }
4555 
4556 };
4557 
4558 
4559 class Item_string_with_introducer :public Item_string
4560 {
4561 public:
Item_string_with_introducer(THD * thd,const LEX_CSTRING & str,CHARSET_INFO * cs)4562   Item_string_with_introducer(THD *thd, const LEX_CSTRING &str,
4563                               CHARSET_INFO *cs):
4564     Item_string(thd, str.str, str.length, cs)
4565   { }
Item_string_with_introducer(THD * thd,const LEX_CSTRING & name_arg,const LEX_CSTRING & str,CHARSET_INFO * tocs)4566   Item_string_with_introducer(THD *thd, const LEX_CSTRING &name_arg,
4567                               const LEX_CSTRING &str, CHARSET_INFO *tocs):
4568     Item_string(thd, name_arg, str, tocs)
4569   { }
is_cs_specified()4570   virtual bool is_cs_specified() const
4571   {
4572     return true;
4573   }
4574 };
4575 
4576 
4577 class Item_string_sys :public Item_string
4578 {
4579 public:
Item_string_sys(THD * thd,const char * str,uint length)4580   Item_string_sys(THD *thd, const char *str, uint length):
4581     Item_string(thd, str, length, system_charset_info)
4582   { }
Item_string_sys(THD * thd,const char * str)4583   Item_string_sys(THD *thd, const char *str):
4584     Item_string(thd, str, (uint) strlen(str), system_charset_info)
4585   { }
4586 };
4587 
4588 
4589 class Item_string_ascii :public Item_string
4590 {
4591 public:
Item_string_ascii(THD * thd,const char * str,uint length)4592   Item_string_ascii(THD *thd, const char *str, uint length):
4593     Item_string(thd, str, length, &my_charset_latin1,
4594                 DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII)
4595   { }
Item_string_ascii(THD * thd,const char * str)4596   Item_string_ascii(THD *thd, const char *str):
4597     Item_string(thd, str, (uint) strlen(str), &my_charset_latin1,
4598                 DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII)
4599   { }
4600 };
4601 
4602 
4603 class Item_static_string_func :public Item_string
4604 {
4605   const LEX_CSTRING func_name;
4606 public:
4607   Item_static_string_func(THD *thd, const LEX_CSTRING &name_par,
4608                           const LEX_CSTRING &str, CHARSET_INFO *cs,
4609                           Derivation dv= DERIVATION_COERCIBLE):
4610     Item_string(thd, LEX_CSTRING({NullS,0}), str, cs, dv), func_name(name_par)
4611   {}
Item_static_string_func(THD * thd,const LEX_CSTRING & name_par,const String * str,CHARSET_INFO * tocs,uint * conv_errors,Derivation dv,my_repertoire_t repertoire)4612   Item_static_string_func(THD *thd, const LEX_CSTRING &name_par,
4613                           const String *str,
4614                           CHARSET_INFO *tocs, uint *conv_errors,
4615                           Derivation dv, my_repertoire_t repertoire):
4616     Item_string(thd, str, tocs, conv_errors, dv, repertoire),
4617     func_name(name_par)
4618   {}
safe_charset_converter(THD * thd,CHARSET_INFO * tocs)4619   Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override
4620   {
4621     return const_charset_converter(thd, tocs, true, func_name.str);
4622   }
4623 
print(String * str,enum_query_type)4624   void print(String *str, enum_query_type) override
4625   {
4626     str->append(func_name);
4627   }
4628 
check_partition_func_processor(void *)4629   bool check_partition_func_processor(void *) override { return true; }
4630 
check_vcol_func_processor(void * arg)4631   bool check_vcol_func_processor(void *arg) override
4632   { // VCOL_TIME_FUNC because the value is not constant, but does not
4633     // require fix_fields() to be re-run for every statement.
4634     return mark_unsupported_function(func_name.str, arg, VCOL_TIME_FUNC);
4635   }
4636 };
4637 
4638 
4639 /* for show tables */
4640 class Item_partition_func_safe_string: public Item_string
4641 {
4642 public:
Item_partition_func_safe_string(THD * thd,const LEX_CSTRING & name_arg,uint length,CHARSET_INFO * cs)4643   Item_partition_func_safe_string(THD *thd, const LEX_CSTRING &name_arg,
4644                                   uint length, CHARSET_INFO *cs):
4645     Item_string(thd, name_arg, LEX_CSTRING({0,0}), cs)
4646   {
4647     max_length= length;
4648   }
check_vcol_func_processor(void * arg)4649   bool check_vcol_func_processor(void *arg)
4650   {
4651     return mark_unsupported_function("safe_string", arg, VCOL_IMPOSSIBLE);
4652   }
4653 };
4654 
4655 
4656 /**
4657   Item_empty_string -- is a utility class to put an item into List<Item>
4658   which is then used in protocol.send_result_set_metadata() when sending SHOW output to
4659   the client.
4660 */
4661 
4662 class Item_empty_string :public Item_partition_func_safe_string
4663 {
4664 public:
4665   Item_empty_string(THD *thd, const LEX_CSTRING &header, uint length,
4666                     CHARSET_INFO *cs= &my_charset_utf8mb3_general_ci)
4667    :Item_partition_func_safe_string(thd, header, length * cs->mbmaxlen, cs)
4668   { }
4669   Item_empty_string(THD *thd, const char *header, uint length,
4670                     CHARSET_INFO *cs= &my_charset_utf8mb3_general_ci)
4671    :Item_partition_func_safe_string(thd, LEX_CSTRING({header, strlen(header)}),
4672                                     length * cs->mbmaxlen, cs)
4673   { }
4674   void make_send_field(THD *thd, Send_field *field);
4675 };
4676 
4677 
4678 class Item_return_int :public Item_int
4679 {
4680   enum_field_types int_field_type;
4681 public:
4682   Item_return_int(THD *thd, const char *name_arg, uint length,
4683 		  enum_field_types field_type_arg, longlong value_arg= 0):
Item_int(thd,name_arg,value_arg,length)4684     Item_int(thd, name_arg, value_arg, length), int_field_type(field_type_arg)
4685   {
4686     unsigned_flag=1;
4687   }
type_handler()4688   const Type_handler *type_handler() const
4689   {
4690     const Type_handler *h=
4691       Type_handler::get_handler_by_field_type(int_field_type);
4692     return unsigned_flag ? h->type_handler_unsigned() : h;
4693   }
4694 };
4695 
4696 
4697 /**
4698   Item_hex_constant -- a common class for hex literals: X'HHHH' and 0xHHHH
4699 */
4700 class Item_hex_constant: public Item_literal
4701 {
4702 private:
4703   void hex_string_init(THD *thd, const char *str, size_t str_length);
4704 public:
Item_hex_constant(THD * thd)4705   Item_hex_constant(THD *thd): Item_literal(thd)
4706   {
4707     hex_string_init(thd, "", 0);
4708   }
Item_hex_constant(THD * thd,const char * str,size_t str_length)4709   Item_hex_constant(THD *thd, const char *str, size_t str_length):
4710     Item_literal(thd)
4711   {
4712     hex_string_init(thd, str, str_length);
4713   }
type_handler()4714   const Type_handler *type_handler() const { return &type_handler_varchar; }
safe_charset_converter(THD * thd,CHARSET_INFO * tocs)4715   virtual Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs)
4716   {
4717     return const_charset_converter(thd, tocs, true);
4718   }
const_ptr_string()4719   const String *const_ptr_string() const { return &str_value; }
val_str(String *)4720   String *val_str(String*) { return &str_value; }
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)4721   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate)
4722   {
4723     return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate);
4724   }
4725 };
4726 
4727 
4728 /**
4729   Item_hex_hybrid -- is a class implementing 0xHHHH literals, e.g.:
4730     SELECT 0x3132;
4731   They can behave as numbers and as strings depending on context.
4732 */
4733 class Item_hex_hybrid: public Item_hex_constant
4734 {
4735 public:
Item_hex_hybrid(THD * thd)4736   Item_hex_hybrid(THD *thd): Item_hex_constant(thd) {}
Item_hex_hybrid(THD * thd,const char * str,size_t str_length)4737   Item_hex_hybrid(THD *thd, const char *str, size_t str_length):
4738     Item_hex_constant(thd, str, str_length) {}
type_handler()4739   const Type_handler *type_handler() const override
4740   { return &type_handler_hex_hybrid; }
4741   uint decimal_precision() const override;
val_real()4742   double val_real() override
4743   {
4744     return (double) (ulonglong) Item_hex_hybrid::val_int();
4745   }
val_int()4746   longlong val_int() override
4747   {
4748     return longlong_from_hex_hybrid(str_value.ptr(), str_value.length());
4749   }
val_decimal(my_decimal * decimal_value)4750   my_decimal *val_decimal(my_decimal *decimal_value) override
4751   {
4752     longlong value= Item_hex_hybrid::val_int();
4753     int2my_decimal(E_DEC_FATAL_ERROR, value, TRUE, decimal_value);
4754     return decimal_value;
4755   }
save_in_field(Field * field,bool)4756   int save_in_field(Field *field, bool) override
4757   {
4758     field->set_notnull();
4759     return field->store_hex_hybrid(str_value.ptr(), str_value.length());
4760   }
4761   void print(String *str, enum_query_type query_type) override;
get_copy(THD * thd)4762   Item *get_copy(THD *thd) override
4763   { return get_item_copy<Item_hex_hybrid>(thd, this); }
4764 };
4765 
4766 
4767 /**
4768   Item_hex_string -- is a class implementing X'HHHH' literals, e.g.:
4769     SELECT X'3132';
4770   Unlike Item_hex_hybrid, X'HHHH' literals behave as strings in all contexts.
4771   X'HHHH' are also used in replication of string constants in case of
4772   "dangerous" charsets (sjis, cp932, big5, gbk) who can have backslash (0x5C)
4773   as the second byte of a multi-byte character, so using '\' escaping for
4774   these charsets is not desirable.
4775 */
4776 class Item_hex_string: public Item_hex_constant
4777 {
4778 public:
Item_hex_string(THD * thd)4779   Item_hex_string(THD *thd): Item_hex_constant(thd) {}
Item_hex_string(THD * thd,const char * str,size_t str_length)4780   Item_hex_string(THD *thd, const char *str, size_t str_length):
4781     Item_hex_constant(thd, str, str_length) {}
val_int()4782   longlong val_int() override
4783   {
4784     return longlong_from_string_with_check(&str_value);
4785   }
val_real()4786   double val_real() override
4787   {
4788     return double_from_string_with_check(&str_value);
4789   }
val_decimal(my_decimal * decimal_value)4790   my_decimal *val_decimal(my_decimal *decimal_value) override
4791   {
4792     return val_decimal_from_string(decimal_value);
4793   }
save_in_field(Field * field,bool)4794   int save_in_field(Field *field, bool) override
4795   {
4796     field->set_notnull();
4797     return field->store(str_value.ptr(), str_value.length(),
4798                         collation.collation);
4799   }
4800   void print(String *str, enum_query_type query_type) override;
get_copy(THD * thd)4801   Item *get_copy(THD *thd) override
4802   { return get_item_copy<Item_hex_string>(thd, this); }
4803 };
4804 
4805 
4806 class Item_bin_string: public Item_hex_hybrid
4807 {
4808 public:
4809   Item_bin_string(THD *thd, const char *str, size_t str_length);
4810 };
4811 
4812 
4813 class Item_timestamp_literal: public Item_literal
4814 {
4815   Timestamp_or_zero_datetime m_value;
4816 public:
Item_timestamp_literal(THD * thd)4817   Item_timestamp_literal(THD *thd)
4818    :Item_literal(thd)
4819   { }
type_handler()4820   const Type_handler *type_handler() const override
4821   { return &type_handler_timestamp2; }
save_in_field(Field * field,bool)4822   int save_in_field(Field *field, bool) override
4823   {
4824     Timestamp_or_zero_datetime_native native(m_value, decimals);
4825     return native.save_in_field(field, decimals);
4826   }
val_int()4827   longlong val_int() override
4828   {
4829     return m_value.to_datetime(current_thd).to_longlong();
4830   }
val_real()4831   double val_real() override
4832   {
4833     return m_value.to_datetime(current_thd).to_double();
4834   }
val_str(String * to)4835   String *val_str(String *to) override
4836   {
4837     return m_value.to_datetime(current_thd).to_string(to, decimals);
4838   }
val_decimal(my_decimal * to)4839   my_decimal *val_decimal(my_decimal *to) override
4840   {
4841     return m_value.to_datetime(current_thd).to_decimal(to);
4842   }
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)4843   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override
4844   {
4845     bool res= m_value.to_TIME(thd, ltime, fuzzydate);
4846     DBUG_ASSERT(!res);
4847     return res;
4848   }
val_native(THD * thd,Native * to)4849   bool val_native(THD *thd, Native *to) override
4850   {
4851     return m_value.to_native(to, decimals);
4852   }
set_value(const Timestamp_or_zero_datetime & value)4853   void set_value(const Timestamp_or_zero_datetime &value)
4854   {
4855     m_value= value;
4856   }
get_copy(THD * thd)4857   Item *get_copy(THD *thd) override
4858   { return get_item_copy<Item_timestamp_literal>(thd, this); }
4859 };
4860 
4861 
4862 class Item_temporal_literal :public Item_literal
4863 {
4864 public:
Item_temporal_literal(THD * thd)4865   Item_temporal_literal(THD *thd)
4866    :Item_literal(thd)
4867   {
4868     collation= DTCollation_numeric();
4869     decimals= 0;
4870   }
Item_temporal_literal(THD * thd,uint dec_arg)4871   Item_temporal_literal(THD *thd, uint dec_arg):
4872     Item_literal(thd)
4873   {
4874     collation= DTCollation_numeric();
4875     decimals= dec_arg;
4876   }
4877 
save_in_field(Field * field,bool no_conversions)4878   int save_in_field(Field *field, bool no_conversions) override
4879   { return save_date_in_field(field, no_conversions); }
4880 };
4881 
4882 
4883 /**
4884   DATE'2010-01-01'
4885 */
4886 class Item_date_literal: public Item_temporal_literal
4887 {
4888 protected:
4889   Date cached_time;
update_null()4890   bool update_null()
4891   {
4892     return maybe_null &&
4893            (null_value= cached_time.check_date_with_warn(current_thd));
4894   }
4895 public:
Item_date_literal(THD * thd,const Date * ltime)4896   Item_date_literal(THD *thd, const Date *ltime)
4897     :Item_temporal_literal(thd),
4898      cached_time(*ltime)
4899   {
4900     DBUG_ASSERT(cached_time.is_valid_date());
4901     max_length= MAX_DATE_WIDTH;
4902     /*
4903       If date has zero month or day, it can return NULL in case of
4904       NO_ZERO_DATE or NO_ZERO_IN_DATE.
4905       If date is `February 30`, it can return NULL in case if
4906       no ALLOW_INVALID_DATES is set.
4907       We can't set null_value using the current sql_mode here in constructor,
4908       because sql_mode can change in case of prepared statements
4909       between PREPARE and EXECUTE.
4910       Here we only set maybe_null to true if the value has such anomalies.
4911       Later (during execution time), if maybe_null is true, then the value
4912       will be checked per row, according to the execution time sql_mode.
4913       The check_date() below call should cover all cases mentioned.
4914     */
4915     maybe_null= cached_time.check_date(TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE);
4916   }
type_handler()4917   const Type_handler *type_handler() const override
4918   { return &type_handler_newdate; }
4919   void print(String *str, enum_query_type query_type) override;
const_ptr_mysql_time()4920   const MYSQL_TIME *const_ptr_mysql_time() const override
4921   {
4922     return cached_time.get_mysql_time();
4923   }
4924   Item *clone_item(THD *thd) override;
val_int()4925   longlong val_int() override
4926   {
4927     return update_null() ? 0 : cached_time.to_longlong();
4928   }
val_real()4929   double val_real() override
4930   {
4931     return update_null() ? 0 : cached_time.to_double();
4932   }
val_str(String * to)4933   String *val_str(String *to) override
4934   {
4935     return update_null() ? 0 : cached_time.to_string(to);
4936   }
val_decimal(my_decimal * to)4937   my_decimal *val_decimal(my_decimal *to) override
4938   {
4939     return update_null() ? 0 : cached_time.to_decimal(to);
4940   }
val_datetime_packed(THD * thd)4941   longlong val_datetime_packed(THD *thd) override
4942   {
4943     return update_null() ? 0 : cached_time.valid_date_to_packed();
4944   }
4945   bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override;
get_copy(THD * thd)4946   Item *get_copy(THD *thd) override
4947   { return get_item_copy<Item_date_literal>(thd, this); }
4948 };
4949 
4950 
4951 /**
4952   TIME'10:10:10'
4953 */
4954 class Item_time_literal: public Item_temporal_literal
4955 {
4956 protected:
4957   Time cached_time;
4958 public:
Item_time_literal(THD * thd,const Time * ltime,uint dec_arg)4959   Item_time_literal(THD *thd, const Time *ltime, uint dec_arg):
4960     Item_temporal_literal(thd, dec_arg),
4961     cached_time(*ltime)
4962   {
4963     DBUG_ASSERT(cached_time.is_valid_time());
4964     max_length= MIN_TIME_WIDTH + (decimals ? decimals + 1 : 0);
4965   }
type_handler()4966   const Type_handler *type_handler() const override
4967   { return &type_handler_time2; }
4968   void print(String *str, enum_query_type query_type) override;
const_ptr_mysql_time()4969   const MYSQL_TIME *const_ptr_mysql_time() const override
4970   {
4971     return cached_time.get_mysql_time();
4972   }
4973   Item *clone_item(THD *thd) override;
val_int()4974   longlong val_int() override { return cached_time.to_longlong(); }
val_real()4975   double val_real() override { return cached_time.to_double(); }
val_str(String * to)4976   String *val_str(String *to) override
4977   { return cached_time.to_string(to, decimals); }
val_decimal(my_decimal * to)4978   my_decimal *val_decimal(my_decimal *to) override
4979   { return cached_time.to_decimal(to); }
val_time_packed(THD * thd)4980   longlong val_time_packed(THD *thd) override
4981   {
4982     return cached_time.valid_time_to_packed();
4983   }
4984   bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override;
val_native(THD * thd,Native * to)4985   bool val_native(THD *thd, Native *to) override
4986   {
4987     return Time(thd, this).to_native(to, decimals);
4988   }
get_copy(THD * thd)4989   Item *get_copy(THD *thd) override
4990   { return get_item_copy<Item_time_literal>(thd, this); }
4991 };
4992 
4993 
4994 /**
4995   TIMESTAMP'2001-01-01 10:20:30'
4996 */
4997 class Item_datetime_literal: public Item_temporal_literal
4998 {
4999 protected:
5000   Datetime cached_time;
update_null()5001   bool update_null()
5002   {
5003     return maybe_null &&
5004            (null_value= cached_time.check_date_with_warn(current_thd));
5005   }
5006 public:
Item_datetime_literal(THD * thd,const Datetime * ltime,uint dec_arg)5007   Item_datetime_literal(THD *thd, const Datetime *ltime, uint dec_arg):
5008     Item_temporal_literal(thd, dec_arg),
5009     cached_time(*ltime)
5010   {
5011     DBUG_ASSERT(cached_time.is_valid_datetime());
5012     max_length= MAX_DATETIME_WIDTH + (decimals ? decimals + 1 : 0);
5013     // See the comment on maybe_null in Item_date_literal
5014     maybe_null= cached_time.check_date(TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE);
5015   }
type_handler()5016   const Type_handler *type_handler() const override
5017   { return &type_handler_datetime2; }
5018   void print(String *str, enum_query_type query_type) override;
const_ptr_mysql_time()5019   const MYSQL_TIME *const_ptr_mysql_time() const override
5020   {
5021     return cached_time.get_mysql_time();
5022   }
5023   Item *clone_item(THD *thd) override;
val_int()5024   longlong val_int() override
5025   {
5026     return update_null() ? 0 : cached_time.to_longlong();
5027   }
val_real()5028   double val_real() override
5029   {
5030     return update_null() ? 0 : cached_time.to_double();
5031   }
val_str(String * to)5032   String *val_str(String *to) override
5033   {
5034     return update_null() ? NULL : cached_time.to_string(to, decimals);
5035   }
val_decimal(my_decimal * to)5036   my_decimal *val_decimal(my_decimal *to) override
5037   {
5038     return update_null() ? NULL : cached_time.to_decimal(to);
5039   }
val_datetime_packed(THD * thd)5040   longlong val_datetime_packed(THD *thd) override
5041   {
5042     return update_null() ? 0 : cached_time.valid_datetime_to_packed();
5043   }
5044   bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override;
get_copy(THD * thd)5045   Item *get_copy(THD *thd) override
5046   { return get_item_copy<Item_datetime_literal>(thd, this); }
5047 };
5048 
5049 
5050 /**
5051   An error-safe counterpart for Item_date_literal
5052 */
5053 class Item_date_literal_for_invalid_dates: public Item_date_literal
5054 {
5055   /**
5056     During equal field propagation we can replace non-temporal constants
5057     found in equalities to their native temporal equivalents:
5058       WHERE date_column='2001-01-01'      ... ->
5059       WHERE date_column=DATE'2001-01-01'  ...
5060 
5061     This is done to make the eqial field propagation code handle mixtures of
5062     different temporal types in the same expressions easier (MDEV-8706), e.g.
5063       WHERE LENGTH(date_column)=10 AND date_column=TIME'00:00:00'
5064 
5065     Item_date_literal_for_invalid_dates::get_date()
5066     (unlike the regular Item_date_literal::get_date())
5067     does not check the result for NO_ZERO_IN_DATE and NO_ZERO_DATE,
5068     always returns success (false), and does not produce error/warning messages.
5069 
5070     We need these _for_invalid_dates classes to be able to rewrite:
5071       SELECT * FROM t1 WHERE date_column='0000-00-00' ...
5072     to:
5073       SELECT * FROM t1 WHERE date_column=DATE'0000-00-00' ...
5074 
5075     to avoid returning NULL value instead of '0000-00-00' even
5076     in sql_mode=TRADITIONAL.
5077   */
5078 public:
Item_date_literal_for_invalid_dates(THD * thd,const Date * ltime)5079   Item_date_literal_for_invalid_dates(THD *thd, const Date *ltime)
5080    :Item_date_literal(thd, ltime)
5081   {
5082     maybe_null= false;
5083   }
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)5084   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate)
5085   {
5086     cached_time.copy_to_mysql_time(ltime);
5087     return (null_value= false);
5088   }
5089 };
5090 
5091 
5092 /**
5093   An error-safe counterpart for Item_datetime_literal
5094   (see Item_date_literal_for_invalid_dates for comments)
5095 */
5096 class Item_datetime_literal_for_invalid_dates: public Item_datetime_literal
5097 {
5098 public:
Item_datetime_literal_for_invalid_dates(THD * thd,const Datetime * ltime,uint dec_arg)5099   Item_datetime_literal_for_invalid_dates(THD *thd,
5100                                           const Datetime *ltime, uint dec_arg)
5101    :Item_datetime_literal(thd, ltime, dec_arg)
5102   {
5103     maybe_null= false;
5104   }
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)5105   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate)
5106   {
5107     cached_time.copy_to_mysql_time(ltime);
5108     return (null_value= false);
5109   }
5110 };
5111 
5112 
5113 class Used_tables_and_const_cache
5114 {
5115 public:
5116   /*
5117     In some cases used_tables_cache is not what used_tables() return
5118     so the method should be used where one need used tables bit map
5119     (even internally in Item_func_* code).
5120   */
5121   table_map used_tables_cache;
5122   bool const_item_cache;
5123 
Used_tables_and_const_cache()5124   Used_tables_and_const_cache()
5125    :used_tables_cache(0),
5126     const_item_cache(true)
5127   { }
Used_tables_and_const_cache(const Used_tables_and_const_cache * other)5128   Used_tables_and_const_cache(const Used_tables_and_const_cache *other)
5129    :used_tables_cache(other->used_tables_cache),
5130     const_item_cache(other->const_item_cache)
5131   { }
used_tables_and_const_cache_init()5132   void used_tables_and_const_cache_init()
5133   {
5134     used_tables_cache= 0;
5135     const_item_cache= true;
5136   }
used_tables_and_const_cache_join(const Item * item)5137   void used_tables_and_const_cache_join(const Item *item)
5138   {
5139     used_tables_cache|= item->used_tables();
5140     const_item_cache&= item->const_item();
5141   }
used_tables_and_const_cache_update_and_join(Item * item)5142   void used_tables_and_const_cache_update_and_join(Item *item)
5143   {
5144     item->update_used_tables();
5145     used_tables_and_const_cache_join(item);
5146   }
5147   /*
5148     Call update_used_tables() for all "argc" items in the array "argv"
5149     and join with the current cache.
5150     "this" must be initialized with a constructor or
5151     re-initialized with used_tables_and_const_cache_init().
5152   */
used_tables_and_const_cache_update_and_join(uint argc,Item ** argv)5153   void used_tables_and_const_cache_update_and_join(uint argc, Item **argv)
5154   {
5155     for (uint i=0 ; i < argc ; i++)
5156       used_tables_and_const_cache_update_and_join(argv[i]);
5157   }
5158   /*
5159     Call update_used_tables() for all items in the list
5160     and join with the current cache.
5161     "this" must be initialized with a constructor or
5162     re-initialized with used_tables_and_const_cache_init().
5163   */
used_tables_and_const_cache_update_and_join(List<Item> & list)5164   void used_tables_and_const_cache_update_and_join(List<Item> &list)
5165   {
5166     List_iterator_fast<Item> li(list);
5167     Item *item;
5168     while ((item=li++))
5169       used_tables_and_const_cache_update_and_join(item);
5170   }
5171 };
5172 
5173 
5174 /**
5175   An abstract class representing common features of
5176   regular functions and aggregate functions.
5177 */
5178 class Item_func_or_sum: public Item_result_field,
5179                         public Item_args,
5180                         public Used_tables_and_const_cache,
5181                         public With_subquery_cache
5182 {
5183 protected:
agg_arg_charsets(DTCollation & c,Item ** items,uint nitems,uint flags,int item_sep)5184   bool agg_arg_charsets(DTCollation &c, Item **items, uint nitems,
5185                         uint flags, int item_sep)
5186   {
5187     return Type_std_attributes::agg_arg_charsets(c, func_name(),
5188                                                  items, nitems,
5189                                                  flags, item_sep);
5190   }
5191   bool agg_arg_charsets_for_string_result(DTCollation &c,
5192                                           Item **items, uint nitems,
5193                                           int item_sep= 1)
5194   {
5195     return Type_std_attributes::
5196       agg_arg_charsets_for_string_result(c, func_name(),
5197                                          items, nitems, item_sep);
5198   }
5199   bool agg_arg_charsets_for_string_result_with_comparison(DTCollation &c,
5200                                                           Item **items,
5201                                                           uint nitems,
5202                                                           int item_sep= 1)
5203   {
5204     return Type_std_attributes::
5205       agg_arg_charsets_for_string_result_with_comparison(c, func_name(),
5206                                                          items, nitems,
5207                                                          item_sep);
5208   }
5209 
5210   /*
5211     Aggregate arguments for comparison, e.g: a=b, a LIKE b, a RLIKE b
5212     - don't convert to @@character_set_connection if all arguments are numbers
5213     - don't allow DERIVATION_NONE
5214   */
5215   bool agg_arg_charsets_for_comparison(DTCollation &c,
5216                                        Item **items, uint nitems,
5217                                        int item_sep= 1)
5218   {
5219     return Type_std_attributes::
5220       agg_arg_charsets_for_comparison(c, func_name(), items, nitems, item_sep);
5221   }
5222 
5223 public:
5224   // This method is used by Arg_comparator
agg_arg_charsets_for_comparison(CHARSET_INFO ** cs,Item ** a,Item ** b)5225   bool agg_arg_charsets_for_comparison(CHARSET_INFO **cs, Item **a, Item **b)
5226   {
5227     DTCollation tmp;
5228     if (tmp.set((*a)->collation, (*b)->collation, MY_COLL_CMP_CONV) ||
5229         tmp.derivation == DERIVATION_NONE)
5230     {
5231       my_error(ER_CANT_AGGREGATE_2COLLATIONS,MYF(0),
5232                (*a)->collation.collation->name,
5233                (*a)->collation.derivation_name(),
5234                (*b)->collation.collation->name,
5235                (*b)->collation.derivation_name(),
5236                func_name());
5237       return true;
5238     }
5239     if (agg_item_set_converter(tmp, func_name(),
5240                                a, 1, MY_COLL_CMP_CONV, 1) ||
5241         agg_item_set_converter(tmp, func_name(),
5242                                b, 1, MY_COLL_CMP_CONV, 1))
5243       return true;
5244     *cs= tmp.collation;
5245     return false;
5246   }
5247 
5248 public:
Item_func_or_sum(THD * thd)5249   Item_func_or_sum(THD *thd): Item_result_field(thd), Item_args() {}
Item_func_or_sum(THD * thd,Item * a)5250   Item_func_or_sum(THD *thd, Item *a): Item_result_field(thd), Item_args(a) { }
Item_func_or_sum(THD * thd,Item * a,Item * b)5251   Item_func_or_sum(THD *thd, Item *a, Item *b):
5252     Item_result_field(thd), Item_args(a, b) { }
Item_func_or_sum(THD * thd,Item * a,Item * b,Item * c)5253   Item_func_or_sum(THD *thd, Item *a, Item *b, Item *c):
5254     Item_result_field(thd), Item_args(thd, a, b, c) { }
Item_func_or_sum(THD * thd,Item * a,Item * b,Item * c,Item * d)5255   Item_func_or_sum(THD *thd, Item *a, Item *b, Item *c, Item *d):
5256     Item_result_field(thd), Item_args(thd, a, b, c, d) { }
Item_func_or_sum(THD * thd,Item * a,Item * b,Item * c,Item * d,Item * e)5257   Item_func_or_sum(THD *thd, Item *a, Item *b, Item *c, Item *d, Item *e):
5258     Item_result_field(thd), Item_args(thd, a, b, c, d, e) { }
Item_func_or_sum(THD * thd,Item_func_or_sum * item)5259   Item_func_or_sum(THD *thd, Item_func_or_sum *item):
5260     Item_result_field(thd, item), Item_args(thd, item),
5261     Used_tables_and_const_cache(item) { }
Item_func_or_sum(THD * thd,List<Item> & list)5262   Item_func_or_sum(THD *thd, List<Item> &list):
5263     Item_result_field(thd), Item_args(thd, list) { }
with_subquery()5264   bool with_subquery() const override
5265   { DBUG_ASSERT(fixed); return m_with_subquery; }
walk(Item_processor processor,bool walk_subquery,void * arg)5266   bool walk(Item_processor processor, bool walk_subquery, void *arg) override
5267   {
5268     if (walk_args(processor, walk_subquery, arg))
5269       return true;
5270     return (this->*processor)(arg);
5271   }
5272   /*
5273     This method is used for debug purposes to print the name of an
5274     item to the debug log. The second use of this method is as
5275     a helper function of print() and error messages, where it is
5276     applicable. To suit both goals it should return a meaningful,
5277     distinguishable and sintactically correct string. This method
5278     should not be used for runtime type identification, use enum
5279     {Sum}Functype and Item_func::functype()/Item_sum::sum_func()
5280     instead.
5281     Added here, to the parent class of both Item_func and Item_sum.
5282 
5283     NOTE: for Items inherited from Item_sum, func_name() return part of
5284     function name till first argument (including '(') to make difference in
5285     names for functions with 'distinct' clause and without 'distinct' and
5286     also to make printing of items inherited from Item_sum uniform.
5287   */
5288   virtual const char *func_name() const= 0;
5289   virtual bool fix_length_and_dec()= 0;
const_item()5290   bool const_item() const override { return const_item_cache; }
used_tables()5291   table_map used_tables() const override { return used_tables_cache; }
5292   Item* build_clone(THD *thd) override;
value_depends_on_sql_mode()5293   Sql_mode_dependency value_depends_on_sql_mode() const override
5294   {
5295     return Item_args::value_depends_on_sql_mode_bit_or().soft_to_hard();
5296   }
5297 };
5298 
5299 class sp_head;
5300 class sp_name;
5301 struct st_sp_security_context;
5302 
5303 class Item_sp
5304 {
5305 protected:
5306   // Can be NULL in some non-SELECT queries
5307   Name_resolution_context *context;
5308 public:
5309   sp_name *m_name;
5310   sp_head *m_sp;
5311   TABLE *dummy_table;
5312   uchar result_buf[64];
5313   sp_rcontext *func_ctx;
5314   MEM_ROOT sp_mem_root;
5315   Query_arena *sp_query_arena;
5316 
5317   /*
5318      The result field of the stored function.
5319   */
5320   Field *sp_result_field;
5321   Item_sp(THD *thd, Name_resolution_context *context_arg, sp_name *name_arg);
5322   Item_sp(THD *thd, Item_sp *item);
5323   const char *func_name(THD *thd) const;
5324   void cleanup();
5325   bool sp_check_access(THD *thd);
5326   bool execute(THD *thd, bool *null_value, Item **args, uint arg_count);
5327   bool execute_impl(THD *thd, Item **args, uint arg_count);
5328   bool init_result_field(THD *thd, uint max_length, uint maybe_null,
5329                          bool *null_value, LEX_CSTRING *name);
process_error(THD * thd)5330   void process_error(THD *thd)
5331   {
5332     if (context)
5333       context->process_error(thd);
5334   }
5335 };
5336 
5337 class Item_ref :public Item_ident,
5338                 protected With_sum_func_cache
5339 {
5340 protected:
5341   void set_properties();
5342   bool set_properties_only; // the item doesn't need full fix_fields
5343 public:
5344   enum Ref_Type { REF, DIRECT_REF, VIEW_REF, OUTER_REF, AGGREGATE_REF };
5345   Item **ref;
5346   bool reference_trough_name;
Item_ref(THD * thd,Name_resolution_context * context_arg,const LEX_CSTRING & db_arg,const LEX_CSTRING & table_name_arg,const LEX_CSTRING & field_name_arg)5347   Item_ref(THD *thd, Name_resolution_context *context_arg,
5348            const LEX_CSTRING &db_arg, const LEX_CSTRING &table_name_arg,
5349            const LEX_CSTRING &field_name_arg):
5350     Item_ident(thd, context_arg, db_arg, table_name_arg, field_name_arg),
5351     set_properties_only(0), ref(0), reference_trough_name(1) {}
Item_ref(THD * thd,Name_resolution_context * context_arg,const LEX_CSTRING & field_name_arg)5352   Item_ref(THD *thd, Name_resolution_context *context_arg,
5353            const LEX_CSTRING &field_name_arg)
5354    :Item_ref(thd, context_arg, null_clex_str, null_clex_str, field_name_arg)
5355   { }
5356   /*
5357     This constructor is used in two scenarios:
5358     A) *item = NULL
5359       No initialization is performed, fix_fields() call will be necessary.
5360 
5361     B) *item points to an Item this Item_ref will refer to. This is
5362       used for GROUP BY. fix_fields() will not be called in this case,
5363       so we call set_properties to make this item "fixed". set_properties
5364       performs a subset of action Item_ref::fix_fields does, and this subset
5365       is enough for Item_ref's used in GROUP BY.
5366 
5367     TODO we probably fix a superset of problems like in BUG#6658. Check this
5368          with Bar, and if we have a more broader set of problems like this.
5369   */
5370   Item_ref(THD *thd, Name_resolution_context *context_arg, Item **item,
5371            const LEX_CSTRING &table_name_arg, const LEX_CSTRING &field_name_arg,
5372            bool alias_name_used_arg= FALSE);
5373   Item_ref(THD *thd, TABLE_LIST *view_arg, Item **item,
5374            const LEX_CSTRING &field_name_arg, bool alias_name_used_arg= FALSE);
5375 
5376   /* Constructor need to process subselect with temporary tables (see Item) */
Item_ref(THD * thd,Item_ref * item)5377   Item_ref(THD *thd, Item_ref *item)
5378     :Item_ident(thd, item), With_sum_func_cache(*item),
5379      set_properties_only(0), ref(item->ref) {}
type()5380   Type type() const override { return REF_ITEM; }
real_type()5381   Type real_type() const override
5382   { return ref ? (*ref)->type() : REF_ITEM; }
eq(const Item * item,bool binary_cmp)5383   bool eq(const Item *item, bool binary_cmp) const override
5384   {
5385     Item *it= ((Item *) item)->real_item();
5386     return ref && (*ref)->eq(it, binary_cmp);
5387   }
5388   void save_val(Field *to) override;
5389   void save_result(Field *to) override;
5390   double val_real() override;
5391   longlong val_int() override;
5392   my_decimal *val_decimal(my_decimal *) override;
5393   bool val_bool() override;
5394   String *val_str(String* tmp) override;
5395   bool val_native(THD *thd, Native *to) override;
5396   bool is_null() override;
5397   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
5398   longlong val_datetime_packed(THD *) override;
5399   longlong val_time_packed(THD *) override;
5400   double val_result() override;
5401   longlong val_int_result() override;
5402   String *str_result(String* tmp) override;
5403   bool val_native_result(THD *thd, Native *to) override;
5404   my_decimal *val_decimal_result(my_decimal *) override;
5405   bool val_bool_result() override;
5406   bool is_null_result() override;
5407   bool send(Protocol *prot, st_value *buffer) override;
5408   void make_send_field(THD *thd, Send_field *field) override;
5409   bool fix_fields(THD *, Item **) override;
5410   void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge)
5411     override;
5412   int save_in_field(Field *field, bool no_conversions) override;
5413   void save_org_in_field(Field *field, fast_field_copier optimizer_data)
5414     override;
setup_fast_field_copier(Field * field)5415   fast_field_copier setup_fast_field_copier(Field *field) override
5416   { return (*ref)->setup_fast_field_copier(field); }
type_handler()5417   const Type_handler *type_handler() const override
5418   { return (*ref)->type_handler(); }
real_type_handler()5419   const Type_handler *real_type_handler() const override
5420   { return (*ref)->real_type_handler(); }
get_tmp_table_field()5421   Field *get_tmp_table_field() override
5422   { return result_field ? result_field : (*ref)->get_tmp_table_field(); }
5423   Item *get_tmp_table_item(THD *thd) override;
5424   Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src,
5425                              const Tmp_field_param *param) override;
5426   Item* propagate_equal_fields(THD *, const Context &, COND_EQUAL *) override;
5427   table_map used_tables() const override;
5428   void update_used_tables() override;
build_equal_items(THD * thd,COND_EQUAL * inherited,bool link_item_fields,COND_EQUAL ** cond_equal_ref)5429   COND *build_equal_items(THD *thd, COND_EQUAL *inherited,
5430                           bool link_item_fields,
5431                           COND_EQUAL **cond_equal_ref) override
5432   {
5433     /*
5434       normilize_cond() replaced all conditions of type
5435          WHERE/HAVING field
5436       to:
5437         WHERE/HAVING field<>0
5438       By the time of a build_equal_items() call, all such conditions should
5439       already be replaced. No Item_ref referencing to Item_field are possible.
5440     */
5441     DBUG_ASSERT(real_type() != FIELD_ITEM);
5442     return Item_ident::build_equal_items(thd, inherited, link_item_fields,
5443                                          cond_equal_ref);
5444   }
const_item()5445   bool const_item() const override { return (*ref)->const_item(); }
not_null_tables()5446   table_map not_null_tables() const override
5447   {
5448     return depended_from ? 0 : (*ref)->not_null_tables();
5449   }
find_not_null_fields(table_map allowed)5450   bool find_not_null_fields(table_map allowed) override
5451   {
5452     return depended_from ? false : (*ref)->find_not_null_fields(allowed);
5453   }
save_in_result_field(bool no_conversions)5454   void save_in_result_field(bool no_conversions) override
5455   {
5456     (*ref)->save_in_field(result_field, no_conversions);
5457   }
real_item()5458   Item *real_item() override { return ref ? (*ref)->real_item() : this; }
get_typelib()5459   const TYPELIB *get_typelib() const override
5460   {
5461     return ref ? (*ref)->get_typelib() : NULL;
5462   }
5463 
walk(Item_processor processor,bool walk_subquery,void * arg)5464   bool walk(Item_processor processor, bool walk_subquery, void *arg) override
5465   {
5466     if (ref && *ref)
5467       return (*ref)->walk(processor, walk_subquery, arg) ||
5468              (this->*processor)(arg);
5469     else
5470       return FALSE;
5471   }
5472   Item* transform(THD *thd, Item_transformer, uchar *arg) override;
5473   Item* compile(THD *thd, Item_analyzer analyzer, uchar **arg_p,
5474                 Item_transformer transformer, uchar *arg_t) override;
enumerate_field_refs_processor(void * arg)5475   bool enumerate_field_refs_processor(void *arg) override
5476   { return (*ref)->enumerate_field_refs_processor(arg); }
no_rows_in_result()5477   void no_rows_in_result() override
5478   {
5479     (*ref)->no_rows_in_result();
5480   }
restore_to_before_no_rows_in_result()5481   void restore_to_before_no_rows_in_result() override
5482   {
5483     (*ref)->restore_to_before_no_rows_in_result();
5484   }
5485   void print(String *str, enum_query_type query_type) override;
precedence()5486   enum precedence precedence() const override
5487   {
5488     return ref ? (*ref)->precedence() : DEFAULT_PRECEDENCE;
5489   }
5490   void cleanup() override;
field_for_view_update()5491   Item_field *field_for_view_update() override
5492     { return (*ref)->field_for_view_update(); }
get_load_data_outvar()5493   Load_data_outvar *get_load_data_outvar() override
5494   {
5495     return (*ref)->get_load_data_outvar();
5496   }
ref_type()5497   virtual Ref_Type ref_type() { return REF; }
5498 
5499   // Row emulation: forwarding of ROW-related calls to ref
cols()5500   uint cols() const override
5501   {
5502     return ref && result_type() == ROW_RESULT ? (*ref)->cols() : 1;
5503   }
element_index(uint i)5504   Item* element_index(uint i) override
5505   {
5506     return ref && result_type() == ROW_RESULT ? (*ref)->element_index(i) : this;
5507   }
addr(uint i)5508   Item** addr(uint i) override
5509   {
5510     return ref && result_type() == ROW_RESULT ? (*ref)->addr(i) : 0;
5511   }
check_cols(uint c)5512   bool check_cols(uint c) override
5513   {
5514     return ref && result_type() == ROW_RESULT ? (*ref)->check_cols(c)
5515                                               : Item::check_cols(c);
5516   }
null_inside()5517   bool null_inside() override
5518   {
5519     return ref && result_type() == ROW_RESULT ? (*ref)->null_inside() : 0;
5520   }
bring_value()5521   void bring_value() override
5522   {
5523     if (ref && result_type() == ROW_RESULT)
5524       (*ref)->bring_value();
5525   }
check_vcol_func_processor(void * arg)5526   bool check_vcol_func_processor(void *arg) override
5527   {
5528     return mark_unsupported_function("ref", arg, VCOL_IMPOSSIBLE);
5529   }
basic_const_item()5530   bool basic_const_item() const override
5531   { return ref && (*ref)->basic_const_item(); }
is_outer_field()5532   bool is_outer_field() const override
5533   {
5534     DBUG_ASSERT(fixed);
5535     DBUG_ASSERT(ref);
5536     return (*ref)->is_outer_field();
5537   }
5538 
5539   Item* build_clone(THD *thd) override;
5540 
5541   /**
5542     Checks if the item tree that ref points to contains a subquery.
5543   */
with_subquery()5544   bool with_subquery() const override { return (*ref)->with_subquery(); }
get_copy(THD * thd)5545   Item *get_copy(THD *thd) override
5546   { return get_item_copy<Item_ref>(thd, this); }
excl_dep_on_table(table_map tab_map)5547   bool excl_dep_on_table(table_map tab_map) override
5548   {
5549     table_map used= used_tables();
5550     if (used & OUTER_REF_TABLE_BIT)
5551       return false;
5552     return (used == tab_map) || (*ref)->excl_dep_on_table(tab_map);
5553   }
excl_dep_on_grouping_fields(st_select_lex * sel)5554   bool excl_dep_on_grouping_fields(st_select_lex *sel) override
5555   { return (*ref)->excl_dep_on_grouping_fields(sel); }
excl_dep_on_in_subq_left_part(Item_in_subselect * subq_pred)5556   bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) override
5557   { return (*ref)->excl_dep_on_in_subq_left_part(subq_pred); }
cleanup_excluding_fields_processor(void * arg)5558   bool cleanup_excluding_fields_processor(void *arg) override
5559   {
5560     Item *item= real_item();
5561     if (item && item->type() == FIELD_ITEM &&
5562         ((Item_field *)item)->field)
5563       return 0;
5564     return cleanup_processor(arg);
5565   }
cleanup_excluding_const_fields_processor(void * arg)5566   bool cleanup_excluding_const_fields_processor(void *arg) override
5567   {
5568     Item *item= real_item();
5569     if (item && item->type() == FIELD_ITEM &&
5570         ((Item_field *) item)->field && item->const_item())
5571       return 0;
5572     return cleanup_processor(arg);
5573   }
with_sum_func()5574   bool with_sum_func() const override { return m_with_sum_func; }
get_with_sum_func_cache()5575   With_sum_func_cache* get_with_sum_func_cache() override { return this; }
field_transformer_for_having_pushdown(THD * thd,uchar * arg)5576   Item *field_transformer_for_having_pushdown(THD *thd, uchar *arg) override
5577   { return (*ref)->field_transformer_for_having_pushdown(thd, arg); }
remove_item_direct_ref()5578   Item *remove_item_direct_ref() override
5579   {
5580     *ref= (*ref)->remove_item_direct_ref();
5581     return this;
5582   }
5583 };
5584 
5585 
5586 /*
5587   The same as Item_ref, but get value from val_* family of method to get
5588   value of item on which it referred instead of result* family.
5589 */
5590 class Item_direct_ref :public Item_ref
5591 {
5592 public:
5593   Item_direct_ref(THD *thd, Name_resolution_context *context_arg, Item **item,
5594                   const LEX_CSTRING &table_name_arg,
5595                   const LEX_CSTRING &field_name_arg,
5596                   bool alias_name_used_arg= FALSE):
Item_ref(thd,context_arg,item,table_name_arg,field_name_arg,alias_name_used_arg)5597     Item_ref(thd, context_arg, item, table_name_arg,
5598              field_name_arg, alias_name_used_arg)
5599   {}
5600   /* Constructor need to process subselect with temporary tables (see Item) */
Item_direct_ref(THD * thd,Item_direct_ref * item)5601   Item_direct_ref(THD *thd, Item_direct_ref *item) : Item_ref(thd, item) {}
5602   Item_direct_ref(THD *thd, TABLE_LIST *view_arg, Item **item,
5603                   const LEX_CSTRING &field_name_arg,
5604                   bool alias_name_used_arg= FALSE):
Item_ref(thd,view_arg,item,field_name_arg,alias_name_used_arg)5605     Item_ref(thd, view_arg, item, field_name_arg,
5606              alias_name_used_arg)
5607   {}
5608 
fix_fields(THD * thd,Item ** it)5609   bool fix_fields(THD *thd, Item **it) override
5610   {
5611     if ((*ref)->fix_fields_if_needed_for_scalar(thd, ref))
5612       return TRUE;
5613     return Item_ref::fix_fields(thd, it);
5614   }
5615   void save_val(Field *to) override;
5616   /* Below we should have all val() methods as in Item_ref */
5617   double val_real() override;
5618   longlong val_int() override;
5619   my_decimal *val_decimal(my_decimal *) override;
5620   bool val_bool() override;
5621   String *val_str(String* tmp) override;
5622   bool val_native(THD *thd, Native *to) override;
5623   bool is_null() override;
5624   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
5625   longlong val_datetime_packed(THD *) override;
5626   longlong val_time_packed(THD *) override;
ref_type()5627   Ref_Type ref_type() override { return DIRECT_REF; }
get_copy(THD * thd)5628   Item *get_copy(THD *thd) override
5629   { return get_item_copy<Item_direct_ref>(thd, this); }
remove_item_direct_ref()5630   Item *remove_item_direct_ref() override
5631   { return (*ref)->remove_item_direct_ref(); }
5632 };
5633 
5634 
5635 /**
5636   This class is the same as Item_direct_ref but created to wrap Item_ident
5637   before fix_fields() call
5638 */
5639 
5640 class Item_direct_ref_to_ident :public Item_direct_ref
5641 {
5642   Item_ident *ident;
5643 public:
Item_direct_ref_to_ident(THD * thd,Item_ident * item)5644   Item_direct_ref_to_ident(THD *thd, Item_ident *item):
5645     Item_direct_ref(thd, item->context, (Item**)&item, item->table_name,
5646                     item->field_name, FALSE)
5647   {
5648     ident= item;
5649     ref= (Item**)&ident;
5650   }
5651 
fix_fields(THD * thd,Item ** it)5652   bool fix_fields(THD *thd, Item **it) override
5653   {
5654     DBUG_ASSERT(ident->type() == FIELD_ITEM || ident->type() == REF_ITEM);
5655     if (ident->fix_fields_if_needed_for_scalar(thd, ref))
5656       return TRUE;
5657     set_properties();
5658     return FALSE;
5659   }
5660 
print(String * str,enum_query_type query_type)5661   void print(String *str, enum_query_type query_type) override
5662   { ident->print(str, query_type); }
5663 
5664 };
5665 
5666 
5667 class Item_cache;
5668 class Expression_cache;
5669 class Expression_cache_tracker;
5670 
5671 /**
5672   The objects of this class can store its values in an expression cache.
5673 */
5674 
5675 class Item_cache_wrapper :public Item_result_field,
5676                           public With_subquery_cache,
5677                           protected With_sum_func_cache
5678 {
5679 private:
5680   /* Pointer on the cached expression */
5681   Item *orig_item;
5682   Expression_cache *expr_cache;
5683   /*
5684     In order to put the expression into the expression cache and return
5685     value of val_*() method, we will need to get the expression value twice
5686     (probably in different types).  In order to avoid making two
5687     (potentially costly) orig_item->val_*() calls, we store expression value
5688     in this Item_cache object.
5689   */
5690   Item_cache *expr_value;
5691 
5692   List<Item> parameters;
5693 
5694   Item *check_cache();
5695   void cache();
5696   void init_on_demand();
5697 
5698 public:
5699   Item_cache_wrapper(THD *thd, Item *item_arg);
5700   ~Item_cache_wrapper();
5701 
type()5702   Type type() const override { return EXPR_CACHE_ITEM; }
real_type()5703   Type real_type() const override { return orig_item->type(); }
with_subquery()5704   bool with_subquery() const override
5705   { DBUG_ASSERT(fixed); return m_with_subquery; }
with_sum_func()5706   bool with_sum_func() const override { return m_with_sum_func; }
get_with_sum_func_cache()5707   With_sum_func_cache* get_with_sum_func_cache() override { return this; }
5708 
5709   bool set_cache(THD *thd);
5710   Expression_cache_tracker* init_tracker(MEM_ROOT *mem_root);
5711 
5712   bool fix_fields(THD *thd, Item **it) override;
5713   void cleanup() override;
5714 
get_orig_item()5715   Item *get_orig_item() const { return orig_item; }
5716 
5717   /* Methods of getting value which should be cached in the cache */
5718   void save_val(Field *to) override;
5719   double val_real() override;
5720   longlong val_int() override;
5721   String *val_str(String* tmp) override;
5722   bool val_native(THD *thd, Native *to) override;
5723   my_decimal *val_decimal(my_decimal *) override;
5724   bool val_bool() override;
5725   bool is_null() override;
5726   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
5727   bool send(Protocol *protocol, st_value *buffer) override;
save_org_in_field(Field * field,fast_field_copier)5728   void save_org_in_field(Field *field, fast_field_copier) override
5729   {
5730     save_val(field);
5731   }
save_in_result_field(bool)5732   void save_in_result_field(bool) override { save_val(result_field); }
5733   Item* get_tmp_table_item(THD *thd_arg) override;
5734 
5735   /* Following methods make this item transparent as much as possible */
5736 
5737   void print(String *str, enum_query_type query_type) override;
full_name()5738   const char *full_name() const override { return orig_item->full_name(); }
make_send_field(THD * thd,Send_field * field)5739   void make_send_field(THD *thd, Send_field *field) override
5740   { orig_item->make_send_field(thd, field); }
eq(const Item * item,bool binary_cmp)5741   bool eq(const Item *item, bool binary_cmp) const override
5742   {
5743     Item *it= const_cast<Item*>(item)->real_item();
5744     return orig_item->eq(it, binary_cmp);
5745   }
fix_after_pullout(st_select_lex * new_parent,Item ** refptr,bool merge)5746   void fix_after_pullout(st_select_lex *new_parent, Item **refptr, bool merge)
5747     override
5748   {
5749     orig_item->fix_after_pullout(new_parent, &orig_item, merge);
5750   }
5751   int save_in_field(Field *to, bool no_conversions) override;
type_handler()5752   const Type_handler *type_handler() const override
5753   { return orig_item->type_handler(); }
used_tables()5754   table_map used_tables() const override { return orig_item->used_tables(); }
update_used_tables()5755   void update_used_tables() override { orig_item->update_used_tables(); }
const_item()5756   bool const_item() const override { return orig_item->const_item(); }
not_null_tables()5757   table_map not_null_tables() const override
5758   { return orig_item->not_null_tables(); }
walk(Item_processor processor,bool walk_subquery,void * arg)5759   bool walk(Item_processor processor, bool walk_subquery, void *arg) override
5760   {
5761     return orig_item->walk(processor, walk_subquery, arg) ||
5762       (this->*processor)(arg);
5763   }
enumerate_field_refs_processor(void * arg)5764   bool enumerate_field_refs_processor(void *arg) override
5765   { return orig_item->enumerate_field_refs_processor(arg); }
field_for_view_update()5766   Item_field *field_for_view_update() override
5767   { return orig_item->field_for_view_update(); }
5768 
5769   /* Row emulation: forwarding of ROW-related calls to orig_item */
cols()5770   uint cols() const override
5771   { return result_type() == ROW_RESULT ? orig_item->cols() : 1; }
element_index(uint i)5772   Item* element_index(uint i) override
5773   { return result_type() == ROW_RESULT ? orig_item->element_index(i) : this; }
addr(uint i)5774   Item** addr(uint i) override
5775   { return result_type() == ROW_RESULT ? orig_item->addr(i) : 0; }
check_cols(uint c)5776   bool check_cols(uint c) override
5777   {
5778     return (result_type() == ROW_RESULT ?
5779             orig_item->check_cols(c) :
5780             Item::check_cols(c));
5781   }
null_inside()5782   bool null_inside() override
5783   { return result_type() == ROW_RESULT ? orig_item->null_inside() : 0; }
bring_value()5784   void bring_value() override
5785   {
5786     if (result_type() == ROW_RESULT)
5787       orig_item->bring_value();
5788   }
is_expensive()5789   bool is_expensive() override { return orig_item->is_expensive(); }
is_expensive_processor(void * arg)5790   bool is_expensive_processor(void *arg) override
5791   { return orig_item->is_expensive_processor(arg); }
check_vcol_func_processor(void * arg)5792   bool check_vcol_func_processor(void *arg) override
5793   {
5794     return mark_unsupported_function("cache", arg, VCOL_IMPOSSIBLE);
5795   }
get_copy(THD * thd)5796   Item *get_copy(THD *thd) override
5797   { return get_item_copy<Item_cache_wrapper>(thd, this); }
build_clone(THD *)5798   Item *build_clone(THD *) override { return nullptr; }
5799 };
5800 
5801 
5802 /*
5803   Class for view fields, the same as Item_direct_ref, but call fix_fields
5804   of reference if it is not called yet
5805 */
5806 class Item_direct_view_ref :public Item_direct_ref
5807 {
5808   Item_equal *item_equal;
5809   TABLE_LIST *view;
5810   TABLE *null_ref_table;
5811 
5812 #define NO_NULL_TABLE (reinterpret_cast<TABLE *>(0x1))
5813 
set_null_ref_table()5814   void set_null_ref_table()
5815   {
5816     if (!view->is_inner_table_of_outer_join() ||
5817         !(null_ref_table= view->get_real_join_table()))
5818       null_ref_table= NO_NULL_TABLE;
5819   }
5820 
check_null_ref()5821   bool check_null_ref()
5822   {
5823     DBUG_ASSERT(null_ref_table);
5824     if (null_ref_table != NO_NULL_TABLE && null_ref_table->null_row)
5825     {
5826       null_value= 1;
5827       return TRUE;
5828     }
5829     return FALSE;
5830   }
5831 
5832 public:
Item_direct_view_ref(THD * thd,Name_resolution_context * context_arg,Item ** item,LEX_CSTRING & table_name_arg,LEX_CSTRING & field_name_arg,TABLE_LIST * view_arg)5833   Item_direct_view_ref(THD *thd, Name_resolution_context *context_arg,
5834                        Item **item,
5835                        LEX_CSTRING &table_name_arg,
5836                        LEX_CSTRING &field_name_arg,
5837                        TABLE_LIST *view_arg):
5838     Item_direct_ref(thd, context_arg, item, table_name_arg, field_name_arg),
5839     item_equal(0), view(view_arg),
5840     null_ref_table(NULL)
5841   {
5842     if (fixed)
5843       set_null_ref_table();
5844   }
5845 
5846   bool fix_fields(THD *, Item **) override;
5847   bool eq(const Item *item, bool binary_cmp) const override;
get_tmp_table_item(THD * thd)5848   Item *get_tmp_table_item(THD *thd) override
5849   {
5850     if (const_item())
5851       return copy_or_same(thd);
5852     Item *item= Item_ref::get_tmp_table_item(thd);
5853     item->name= name;
5854     return item;
5855   }
ref_type()5856   Ref_Type ref_type() override { return VIEW_REF; }
get_item_equal()5857   Item_equal *get_item_equal() override { return item_equal; }
set_item_equal(Item_equal * item_eq)5858   void set_item_equal(Item_equal *item_eq) override { item_equal= item_eq; }
5859   Item_equal *find_item_equal(COND_EQUAL *cond_equal) override;
5860   Item* propagate_equal_fields(THD *, const Context &, COND_EQUAL *) override;
5861   Item *replace_equal_field(THD *thd, uchar *arg) override;
5862   table_map used_tables() const override;
5863   void update_used_tables() override;
5864   table_map not_null_tables() const override;
const_item()5865   bool const_item() const override
5866   {
5867     return (*ref)->const_item() && (null_ref_table == NO_NULL_TABLE);
5868   }
get_null_ref_table()5869   TABLE *get_null_ref_table() const { return null_ref_table; }
walk(Item_processor processor,bool walk_subquery,void * arg)5870   bool walk(Item_processor processor, bool walk_subquery, void *arg) override
5871   {
5872     return (*ref)->walk(processor, walk_subquery, arg) ||
5873            (this->*processor)(arg);
5874   }
view_used_tables_processor(void * arg)5875   bool view_used_tables_processor(void *arg) override
5876   {
5877     TABLE_LIST *view_arg= (TABLE_LIST *) arg;
5878     if (view_arg == view)
5879       view_arg->view_used_tables|= (*ref)->used_tables();
5880     return 0;
5881   }
5882   bool excl_dep_on_table(table_map tab_map) override;
5883   bool excl_dep_on_grouping_fields(st_select_lex *sel) override;
5884   bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) override;
5885   Item *derived_field_transformer_for_having(THD *thd, uchar *arg) override;
5886   Item *derived_field_transformer_for_where(THD *thd, uchar *arg) override;
5887   Item *grouping_field_transformer_for_where(THD *thd, uchar *arg) override;
5888   Item *in_subq_field_transformer_for_where(THD *thd, uchar *arg) override;
5889   Item *in_subq_field_transformer_for_having(THD *thd, uchar *arg) override;
5890 
save_val(Field * to)5891   void save_val(Field *to) override
5892   {
5893     if (check_null_ref())
5894       to->set_null();
5895     else
5896       Item_direct_ref::save_val(to);
5897   }
val_real()5898   double val_real() override
5899   {
5900     if (check_null_ref())
5901       return 0;
5902     else
5903       return Item_direct_ref::val_real();
5904   }
val_int()5905   longlong val_int() override
5906   {
5907     if (check_null_ref())
5908       return 0;
5909     else
5910       return Item_direct_ref::val_int();
5911   }
val_str(String * tmp)5912   String *val_str(String* tmp) override
5913   {
5914     if (check_null_ref())
5915       return NULL;
5916     else
5917       return Item_direct_ref::val_str(tmp);
5918   }
val_native(THD * thd,Native * to)5919   bool val_native(THD *thd, Native *to) override
5920   {
5921     if (check_null_ref())
5922       return true;
5923     return Item_direct_ref::val_native(thd, to);
5924   }
val_decimal(my_decimal * tmp)5925   my_decimal *val_decimal(my_decimal *tmp) override
5926   {
5927     if (check_null_ref())
5928       return NULL;
5929     else
5930       return Item_direct_ref::val_decimal(tmp);
5931   }
val_bool()5932   bool val_bool() override
5933   {
5934     if (check_null_ref())
5935       return 0;
5936     else
5937       return Item_direct_ref::val_bool();
5938   }
is_null()5939   bool is_null() override
5940   {
5941     if (check_null_ref())
5942       return 1;
5943     else
5944       return Item_direct_ref::is_null();
5945   }
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)5946   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override
5947   {
5948     if (check_null_ref())
5949     {
5950       bzero((char*) ltime,sizeof(*ltime));
5951       return 1;
5952     }
5953     return Item_direct_ref::get_date(thd, ltime, fuzzydate);
5954   }
val_time_packed(THD * thd)5955   longlong val_time_packed(THD *thd) override
5956   {
5957     if (check_null_ref())
5958       return 0;
5959     else
5960       return Item_direct_ref::val_time_packed(thd);
5961   }
val_datetime_packed(THD * thd)5962   longlong val_datetime_packed(THD *thd) override
5963   {
5964     if (check_null_ref())
5965       return 0;
5966     else
5967       return Item_direct_ref::val_datetime_packed(thd);
5968   }
5969   bool send(Protocol *protocol, st_value *buffer) override;
save_org_in_field(Field * field,fast_field_copier)5970   void save_org_in_field(Field *field, fast_field_copier) override
5971   {
5972     if (check_null_ref())
5973       field->set_null();
5974     else
5975       Item_direct_ref::save_val(field);
5976   }
save_in_result_field(bool no_conversions)5977   void save_in_result_field(bool no_conversions) override
5978   {
5979     if (check_null_ref())
5980       result_field->set_null();
5981     else
5982       Item_direct_ref::save_in_result_field(no_conversions);
5983   }
5984 
cleanup()5985   void cleanup() override
5986   {
5987     null_ref_table= NULL;
5988     item_equal= NULL;
5989     Item_direct_ref::cleanup();
5990   }
5991   /*
5992     TODO move these val_*_result function to Item_direct_ref (maybe)
5993   */
5994   double val_result() override;
5995   longlong val_int_result() override;
5996   String *str_result(String* tmp) override;
5997   my_decimal *val_decimal_result(my_decimal *val) override;
5998   bool val_bool_result() override;
5999 
get_copy(THD * thd)6000   Item *get_copy(THD *thd) override
6001   { return get_item_copy<Item_direct_view_ref>(thd, this); }
field_transformer_for_having_pushdown(THD *,uchar *)6002   Item *field_transformer_for_having_pushdown(THD *, uchar *) override
6003   { return this; }
remove_item_direct_ref()6004   Item *remove_item_direct_ref() override { return this; }
6005 };
6006 
6007 
6008 /*
6009   Class for outer fields.
6010   An object of this class is created when the select where the outer field was
6011   resolved is a grouping one. After it has been fixed the ref field will point
6012   to either an Item_ref or an Item_direct_ref object which will be used to
6013   access the field.
6014   See also comments for the fix_inner_refs() and the
6015   Item_field::fix_outer_field() functions.
6016 */
6017 
6018 class Item_sum;
6019 class Item_outer_ref :public Item_direct_ref
6020 {
6021 public:
6022   Item *outer_ref;
6023   /* The aggregate function under which this outer ref is used, if any. */
6024   Item_sum *in_sum_func;
6025   /*
6026     TRUE <=> that the outer_ref is already present in the select list
6027     of the outer select.
6028   */
6029   bool found_in_select_list;
6030   bool found_in_group_by;
Item_outer_ref(THD * thd,Name_resolution_context * context_arg,Item_field * outer_field_arg)6031   Item_outer_ref(THD *thd, Name_resolution_context *context_arg,
6032                  Item_field *outer_field_arg):
6033     Item_direct_ref(thd, context_arg, 0, outer_field_arg->table_name,
6034                     outer_field_arg->field_name),
6035     outer_ref(outer_field_arg), in_sum_func(0),
6036     found_in_select_list(0), found_in_group_by(0)
6037   {
6038     ref= &outer_ref;
6039     set_properties();
6040     fixed= 0;                     /* reset flag set in set_properties() */
6041   }
Item_outer_ref(THD * thd,Name_resolution_context * context_arg,Item ** item,const LEX_CSTRING & table_name_arg,LEX_CSTRING & field_name_arg,bool alias_name_used_arg)6042   Item_outer_ref(THD *thd, Name_resolution_context *context_arg, Item **item,
6043                  const LEX_CSTRING &table_name_arg, LEX_CSTRING &field_name_arg,
6044                  bool alias_name_used_arg):
6045     Item_direct_ref(thd, context_arg, item, table_name_arg, field_name_arg,
6046                     alias_name_used_arg),
6047     outer_ref(0), in_sum_func(0), found_in_select_list(1), found_in_group_by(0)
6048   {}
save_in_result_field(bool no_conversions)6049   void save_in_result_field(bool no_conversions) override
6050   {
6051     outer_ref->save_org_in_field(result_field, NULL);
6052   }
6053   bool fix_fields(THD *, Item **) override;
6054   void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge)
6055     override;
used_tables()6056   table_map used_tables() const override
6057   {
6058     return (*ref)->const_item() ? 0 : OUTER_REF_TABLE_BIT;
6059   }
not_null_tables()6060   table_map not_null_tables() const override { return 0; }
ref_type()6061   Ref_Type ref_type() override { return OUTER_REF; }
6062   bool check_inner_refs_processor(void * arg) override;
6063 };
6064 
6065 
6066 class Item_in_subselect;
6067 
6068 
6069 /*
6070   An object of this class:
6071    - Converts val_XXX() calls to ref->val_XXX_result() calls, like Item_ref.
6072    - Sets owner->was_null=TRUE if it has returned a NULL value from any
6073      val_XXX() function. This allows to inject an Item_ref_null_helper
6074      object into subquery and then check if the subquery has produced a row
6075      with NULL value.
6076 */
6077 
6078 class Item_ref_null_helper: public Item_ref
6079 {
6080 protected:
6081   Item_in_subselect* owner;
6082 public:
Item_ref_null_helper(THD * thd,Name_resolution_context * context_arg,Item_in_subselect * master,Item ** item,const LEX_CSTRING & table_name_arg,const LEX_CSTRING & field_name_arg)6083   Item_ref_null_helper(THD *thd, Name_resolution_context *context_arg,
6084                        Item_in_subselect* master, Item **item,
6085 		       const LEX_CSTRING &table_name_arg,
6086                        const LEX_CSTRING &field_name_arg):
6087     Item_ref(thd, context_arg, item, table_name_arg, field_name_arg),
6088     owner(master) {}
6089   void save_val(Field *to) override;
6090   double val_real() override;
6091   longlong val_int() override;
6092   String* val_str(String* s) override;
6093   my_decimal *val_decimal(my_decimal *) override;
6094   bool val_bool() override;
6095   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
6096   bool val_native(THD *thd, Native *to) override;
6097   void print(String *str, enum_query_type query_type) override;
6098   table_map used_tables() const override;
get_copy(THD * thd)6099   Item *get_copy(THD *thd) override
6100   { return get_item_copy<Item_ref_null_helper>(thd, this); }
6101 };
6102 
6103 /*
6104   The following class is used to optimize comparing of date and bigint columns
6105   We need to save the original item ('ref') to be able to call
6106   ref->save_in_field(). This is used to create index search keys.
6107 
6108   An instance of Item_int_with_ref may have signed or unsigned integer value.
6109 
6110 */
6111 
6112 class Item_int_with_ref :public Item_int
6113 {
6114   Item *ref;
6115 public:
Item_int_with_ref(THD * thd,longlong i,Item * ref_arg,bool unsigned_arg)6116   Item_int_with_ref(THD *thd, longlong i, Item *ref_arg, bool unsigned_arg):
6117     Item_int(thd, i), ref(ref_arg)
6118   {
6119     unsigned_flag= unsigned_arg;
6120   }
save_in_field(Field * field,bool no_conversions)6121   int save_in_field(Field *field, bool no_conversions) override
6122   {
6123     return ref->save_in_field(field, no_conversions);
6124   }
6125   Item *clone_item(THD *thd) override;
real_item()6126   Item *real_item() override { return ref; }
6127 };
6128 
6129 #ifdef MYSQL_SERVER
6130 #include "item_sum.h"
6131 #include "item_func.h"
6132 #include "item_row.h"
6133 #include "item_cmpfunc.h"
6134 #include "item_strfunc.h"
6135 #include "item_timefunc.h"
6136 #include "item_subselect.h"
6137 #include "item_xmlfunc.h"
6138 #include "item_jsonfunc.h"
6139 #include "item_create.h"
6140 #include "item_vers.h"
6141 #endif
6142 
6143 /**
6144   Base class to implement typed value caching Item classes
6145 
6146   Item_copy_ classes are very similar to the corresponding Item_
6147   classes (e.g. Item_copy_string is similar to Item_string) but they add
6148   the following additional functionality to Item_ :
6149     1. Nullability
6150     2. Possibility to store the value not only on instantiation time,
6151        but also later.
6152   Item_copy_ classes are a functionality subset of Item_cache_
6153   classes, as e.g. they don't support comparisons with the original Item
6154   as Item_cache_ classes do.
6155   Item_copy_ classes are used in GROUP BY calculation.
6156   TODO: Item_copy should be made an abstract interface and Item_copy_
6157   classes should inherit both the respective Item_ class and the interface.
6158   Ideally we should drop Item_copy_ classes altogether and merge
6159   their functionality to Item_cache_ (and these should be made to inherit
6160   from Item_).
6161 */
6162 
6163 class Item_copy :public Item,
6164                  public Type_handler_hybrid_field_type
6165 {
6166 protected:
6167 
6168   /**
6169     Type_handler_hybrid_field_type is used to
6170     store the type of the resulting field that would be used to store the data
6171     in the cache. This is to avoid calls to the original item.
6172   */
6173 
6174   /** The original item that is copied */
6175   Item *item;
6176 
6177   /**
6178     Constructor of the Item_copy class
6179 
6180     stores metadata information about the original class as well as a
6181     pointer to it.
6182   */
Item_copy(THD * thd,Item * i)6183   Item_copy(THD *thd, Item *i): Item(thd)
6184   {
6185     DBUG_ASSERT(i->is_fixed());
6186     item= i;
6187     null_value=maybe_null=item->maybe_null;
6188     Type_std_attributes::set(item);
6189     name= item->name;
6190     set_handler(item->type_handler());
6191   }
6192 
6193 public:
6194 
6195   /**
6196     Update the cache with the value of the original item
6197 
6198     This is the method that updates the cached value.
6199     It must be explicitly called by the user of this class to store the value
6200     of the original item in the cache.
6201   */
6202   virtual void copy() = 0;
6203 
get_item()6204   Item *get_item() { return item; }
6205   /** All of the subclasses should have the same type tag */
type()6206   Type type() const override { return COPY_STR_ITEM; }
6207 
type_handler()6208   const Type_handler *type_handler() const override
6209   { return Type_handler_hybrid_field_type::type_handler(); }
6210 
create_tmp_field_ex(MEM_ROOT * root,TABLE * table,Tmp_field_src * src,const Tmp_field_param * param)6211   Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src,
6212                              const Tmp_field_param *param) override
6213   {
6214     DBUG_ASSERT(0);
6215     return NULL;
6216   }
make_send_field(THD * thd,Send_field * field)6217   void make_send_field(THD *thd, Send_field *field) override
6218   { item->make_send_field(thd, field); }
used_tables()6219   table_map used_tables() const override { return (table_map) 1L; }
const_item()6220   bool const_item() const override { return false; }
is_null()6221   bool is_null() override { return null_value; }
check_vcol_func_processor(void * arg)6222   bool check_vcol_func_processor(void *arg) override
6223   {
6224     return mark_unsupported_function("copy", arg, VCOL_IMPOSSIBLE);
6225   }
6226 
6227   /*
6228     Override the methods below as pure virtual to make sure all the
6229     sub-classes implement them.
6230   */
6231 
6232   String *val_str(String*) override = 0;
6233   my_decimal *val_decimal(my_decimal *) override = 0;
6234   double val_real() override = 0;
6235   longlong val_int() override = 0;
6236   int save_in_field(Field *field, bool no_conversions) override = 0;
walk(Item_processor processor,bool walk_subquery,void * args)6237   bool walk(Item_processor processor, bool walk_subquery, void *args) override
6238   {
6239     return (item->walk(processor, walk_subquery, args)) ||
6240       (this->*processor)(args);
6241   }
6242 };
6243 
6244 /**
6245  Implementation of a string cache.
6246 
6247  Uses Item::str_value for storage
6248 */
6249 class Item_copy_string : public Item_copy
6250 {
6251 public:
Item_copy_string(THD * thd,Item * item_arg)6252   Item_copy_string(THD *thd, Item *item_arg): Item_copy(thd, item_arg) {}
6253 
6254   String *val_str(String*) override;
6255   my_decimal *val_decimal(my_decimal *) override;
6256   double val_real() override;
6257   longlong val_int() override;
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)6258   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override
6259   { return get_date_from_string(thd, ltime, fuzzydate); }
6260   void copy() override;
6261   int save_in_field(Field *field, bool no_conversions) override;
get_copy(THD * thd)6262   Item *get_copy(THD *thd) override
6263   { return get_item_copy<Item_copy_string>(thd, this); }
6264 };
6265 
6266 
6267 /**
6268   We need a separate class Item_copy_timestamp because
6269   TIMESTAMP->string->TIMESTAMP conversion is not round trip safe
6270   near the DST change, e.g. '2010-10-31 02:25:26' can mean:
6271    - my_time_t(1288477526) - summer time in Moscow
6272    - my_time_t(1288481126) - winter time in Moscow, one hour later
6273 */
6274 class Item_copy_timestamp: public Item_copy
6275 {
6276   Timestamp_or_zero_datetime m_value;
sane()6277   bool sane() const { return !null_value || m_value.is_zero_datetime(); }
6278 public:
Item_copy_timestamp(THD * thd,Item * arg)6279   Item_copy_timestamp(THD *thd, Item *arg): Item_copy(thd, arg) { }
type_handler()6280   const Type_handler *type_handler() const override
6281   { return &type_handler_timestamp2; }
copy()6282   void copy() override
6283   {
6284     Timestamp_or_zero_datetime_native_null tmp(current_thd, item, false);
6285     null_value= tmp.is_null();
6286     m_value= tmp.is_null() ? Timestamp_or_zero_datetime() :
6287                              Timestamp_or_zero_datetime(tmp);
6288   }
save_in_field(Field * field,bool)6289   int save_in_field(Field *field, bool) override
6290   {
6291     DBUG_ASSERT(sane());
6292     if (null_value)
6293       return set_field_to_null(field);
6294     Timestamp_or_zero_datetime_native native(m_value, decimals);
6295     return native.save_in_field(field, decimals);
6296   }
val_int()6297   longlong val_int() override
6298   {
6299     DBUG_ASSERT(sane());
6300     return null_value ? 0 :
6301            m_value.to_datetime(current_thd).to_longlong();
6302   }
val_real()6303   double val_real() override
6304   {
6305     DBUG_ASSERT(sane());
6306     return null_value ? 0e0 :
6307            m_value.to_datetime(current_thd).to_double();
6308   }
val_str(String * to)6309   String *val_str(String *to) override
6310   {
6311     DBUG_ASSERT(sane());
6312     return null_value ? NULL :
6313            m_value.to_datetime(current_thd).to_string(to, decimals);
6314   }
val_decimal(my_decimal * to)6315   my_decimal *val_decimal(my_decimal *to) override
6316   {
6317     DBUG_ASSERT(sane());
6318     return null_value ? NULL :
6319            m_value.to_datetime(current_thd).to_decimal(to);
6320   }
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)6321   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override
6322   {
6323     DBUG_ASSERT(sane());
6324     bool res= m_value.to_TIME(thd, ltime, fuzzydate);
6325     DBUG_ASSERT(!res);
6326     return null_value || res;
6327   }
val_native(THD * thd,Native * to)6328   bool val_native(THD *thd, Native *to) override
6329   {
6330     DBUG_ASSERT(sane());
6331     return null_value || m_value.to_native(to, decimals);
6332   }
get_copy(THD * thd)6333   Item *get_copy(THD *thd) override
6334   { return get_item_copy<Item_copy_timestamp>(thd, this); }
6335 };
6336 
6337 
6338 /*
6339   Cached_item_XXX objects are not exactly caches. They do the following:
6340 
6341   Each Cached_item_XXX object has
6342    - its source item
6343    - saved value of the source item
6344    - cmp() method that compares the saved value with the current value of the
6345      source item, and if they were not equal saves item's value into the saved
6346      value.
6347 
6348   TODO: add here:
6349    - a way to save the new value w/o comparison
6350    - a way to do less/equal/greater comparison
6351 */
6352 
6353 class Cached_item :public Sql_alloc
6354 {
6355 public:
6356   bool null_value;
Cached_item()6357   Cached_item() :null_value(0) {}
6358   /*
6359     Compare the cached value with the source value. If not equal, copy
6360     the source value to the cache.
6361     @return
6362       true  - Not equal
6363       false - Equal
6364   */
6365   virtual bool cmp(void)=0;
6366 
6367   /* Compare the cached value with the source value, without copying */
6368   virtual int  cmp_read_only()=0;
6369 
6370   virtual ~Cached_item(); /*line -e1509 */
6371 };
6372 
6373 class Cached_item_item : public Cached_item
6374 {
6375 protected:
6376   Item *item;
6377 
Cached_item_item(Item * arg)6378   Cached_item_item(Item *arg) : item(arg) {}
6379 public:
fetch_value_from(Item * new_item)6380   void fetch_value_from(Item *new_item)
6381   {
6382     Item *save= item;
6383     item= new_item;
6384     cmp();
6385     item= save;
6386   }
6387 };
6388 
6389 class Cached_item_str :public Cached_item_item
6390 {
6391   uint32 value_max_length;
6392   String value,tmp_value;
6393 public:
6394   Cached_item_str(THD *thd, Item *arg);
6395   bool cmp() override;
6396   int cmp_read_only() override;
6397   ~Cached_item_str();                           // Deallocate String:s
6398 };
6399 
6400 
6401 class Cached_item_real :public Cached_item_item
6402 {
6403   double value;
6404 public:
Cached_item_real(Item * item_par)6405   Cached_item_real(Item *item_par) :Cached_item_item(item_par),value(0.0) {}
6406   bool cmp() override;
6407   int cmp_read_only() override;
6408 };
6409 
6410 class Cached_item_int :public Cached_item_item
6411 {
6412   longlong value;
6413 public:
Cached_item_int(Item * item_par)6414   Cached_item_int(Item *item_par) :Cached_item_item(item_par),value(0) {}
6415   bool cmp() override;
6416   int cmp_read_only() override;
6417 };
6418 
6419 
6420 class Cached_item_decimal :public Cached_item_item
6421 {
6422   my_decimal value;
6423 public:
6424   Cached_item_decimal(Item *item_par);
6425   bool cmp() override;
6426   int cmp_read_only() override;
6427 };
6428 
6429 class Cached_item_field :public Cached_item
6430 {
6431   uchar *buff;
6432   Field *field;
6433   uint length;
6434 
6435 public:
Cached_item_field(THD * thd,Field * arg_field)6436   Cached_item_field(THD *thd, Field *arg_field): field(arg_field)
6437   {
6438     field= arg_field;
6439     /* TODO: take the memory allocation below out of the constructor. */
6440     buff= (uchar*) thd_calloc(thd, length= field->pack_length());
6441   }
6442   bool cmp() override;
6443   int cmp_read_only() override;
6444 };
6445 
6446 class Item_default_value : public Item_field
6447 {
6448   bool vcol_assignment_ok;
6449   void calculate();
6450 public:
6451   Item *arg= nullptr;
6452   Field *cached_field= nullptr;
Item_default_value(THD * thd,Name_resolution_context * context_arg,Item * a,bool vcol_assignment_arg)6453   Item_default_value(THD *thd, Name_resolution_context *context_arg, Item *a,
6454                      bool vcol_assignment_arg)
6455     : Item_field(thd, context_arg),
6456       vcol_assignment_ok(vcol_assignment_arg), arg(a) {}
type()6457   Type type() const override { return DEFAULT_VALUE_ITEM; }
6458   bool eq(const Item *item, bool binary_cmp) const override;
6459   bool fix_fields(THD *, Item **) override;
6460   void cleanup() override;
6461   void print(String *str, enum_query_type query_type) override;
6462   String *val_str(String *str) override;
6463   double val_real() override;
6464   longlong val_int() override;
6465   my_decimal *val_decimal(my_decimal *decimal_value) override;
6466   bool get_date(THD *thd, MYSQL_TIME *ltime,date_mode_t fuzzydate) override;
6467   bool val_native(THD *thd, Native *to) override;
6468   bool val_native_result(THD *thd, Native *to) override;
6469 
6470   /* Result variants */
6471   double val_result() override;
6472   longlong val_int_result() override;
6473   String *str_result(String* tmp) override;
6474   my_decimal *val_decimal_result(my_decimal *val) override;
6475   bool val_bool_result() override;
6476   bool is_null_result() override;
6477   bool get_date_result(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate)
6478     override;
6479 
6480   bool send(Protocol *protocol, st_value *buffer) override;
6481   int save_in_field(Field *field_arg, bool no_conversions) override;
save_in_param(THD *,Item_param * param)6482   bool save_in_param(THD *, Item_param *param) override
6483   {
6484     // It should not be possible to have "EXECUTE .. USING DEFAULT(a)"
6485     DBUG_ASSERT(0);
6486     param->set_default();
6487     return false;
6488   }
6489   table_map used_tables() const override;
update_used_tables()6490   void update_used_tables() override
6491   {
6492     if (field && field->default_value)
6493       field->default_value->expr->update_used_tables();
6494   }
vcol_assignment_allowed_value()6495   bool vcol_assignment_allowed_value() const override
6496   { return vcol_assignment_ok; }
get_tmp_table_field()6497   Field *get_tmp_table_field() override { return nullptr; }
get_tmp_table_item(THD *)6498   Item *get_tmp_table_item(THD *) override { return this; }
field_for_view_update()6499   Item_field *field_for_view_update() override { return nullptr; }
update_vcol_processor(void *)6500   bool update_vcol_processor(void *) override { return false; }
check_func_default_processor(void *)6501   bool check_func_default_processor(void *) override { return true; }
6502 
walk(Item_processor processor,bool walk_subquery,void * args)6503   bool walk(Item_processor processor, bool walk_subquery, void *args) override
6504   {
6505     return (arg && arg->walk(processor, walk_subquery, args)) ||
6506       (this->*processor)(args);
6507   }
6508 
6509   Item *transform(THD *thd, Item_transformer transformer, uchar *args)
6510     override;
6511   Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src,
6512                              const Tmp_field_param *param) override;
6513 };
6514 
6515 
6516 class Item_contextually_typed_value_specification: public Item
6517 {
6518 public:
Item_contextually_typed_value_specification(THD * thd)6519   Item_contextually_typed_value_specification(THD *thd) :Item(thd)
6520   { }
type()6521   Type type() const override { return CONTEXTUALLY_TYPED_VALUE_ITEM; }
vcol_assignment_allowed_value()6522   bool vcol_assignment_allowed_value() const override { return true; }
eq(const Item * item,bool binary_cmp)6523   bool eq(const Item *item, bool binary_cmp) const override { return false; }
is_evaluable_expression()6524   bool is_evaluable_expression() const override { return false; }
create_tmp_field_ex(MEM_ROOT *,TABLE *,Tmp_field_src *,const Tmp_field_param *)6525   Field *create_tmp_field_ex(MEM_ROOT *,
6526                              TABLE *, Tmp_field_src *,
6527                              const Tmp_field_param *) override
6528   {
6529     DBUG_ASSERT(0);
6530     return NULL;
6531   }
val_str(String * str)6532   String *val_str(String *str) override
6533   {
6534     DBUG_ASSERT(0); // never should be called
6535     null_value= true;
6536     return 0;
6537   }
val_real()6538   double val_real() override
6539   {
6540     DBUG_ASSERT(0); // never should be called
6541     null_value= true;
6542     return 0.0;
6543   }
val_int()6544   longlong val_int() override
6545   {
6546     DBUG_ASSERT(0); // never should be called
6547     null_value= true;
6548     return 0;
6549   }
val_decimal(my_decimal *)6550   my_decimal *val_decimal(my_decimal *) override
6551   {
6552     DBUG_ASSERT(0); // never should be called
6553     null_value= true;
6554     return 0;
6555   }
get_date(THD *,MYSQL_TIME *,date_mode_t)6556   bool get_date(THD *, MYSQL_TIME *, date_mode_t) override
6557   {
6558     DBUG_ASSERT(0); // never should be called
6559     return null_value= true;
6560   }
send(Protocol *,st_value *)6561   bool send(Protocol *, st_value *) override
6562   {
6563     DBUG_ASSERT(0);
6564     return true;
6565   }
type_handler()6566   const Type_handler *type_handler() const override
6567   {
6568     DBUG_ASSERT(0);
6569     return &type_handler_null;
6570   }
6571 };
6572 
6573 
6574 /*
6575   <default specification> ::= DEFAULT
6576 */
6577 class Item_default_specification:
6578         public Item_contextually_typed_value_specification
6579 {
6580 public:
Item_default_specification(THD * thd)6581   Item_default_specification(THD *thd)
6582    :Item_contextually_typed_value_specification(thd)
6583   { }
print(String * str,enum_query_type)6584   void print(String *str, enum_query_type) override
6585   {
6586     str->append(STRING_WITH_LEN("default"));
6587   }
save_in_field(Field * field_arg,bool)6588   int save_in_field(Field *field_arg, bool) override
6589   {
6590     return field_arg->save_in_field_default_value(false);
6591   }
save_in_param(THD *,Item_param * param)6592   bool save_in_param(THD *, Item_param *param) override
6593   {
6594     param->set_default();
6595     return false;
6596   }
get_copy(THD * thd)6597   Item *get_copy(THD *thd) override
6598   { return get_item_copy<Item_default_specification>(thd, this); }
6599 };
6600 
6601 
6602 /**
6603   This class is used as bulk parameter INGNORE representation.
6604 
6605   It just do nothing when assigned to a field
6606 
6607   This is a non-standard MariaDB extension.
6608 */
6609 
6610 class Item_ignore_specification:
6611         public Item_contextually_typed_value_specification
6612 {
6613 public:
Item_ignore_specification(THD * thd)6614   Item_ignore_specification(THD *thd)
6615    :Item_contextually_typed_value_specification(thd)
6616   { }
print(String * str,enum_query_type)6617   void print(String *str, enum_query_type) override
6618   {
6619     str->append(STRING_WITH_LEN("ignore"));
6620   }
save_in_field(Field * field_arg,bool)6621   int save_in_field(Field *field_arg, bool) override
6622   {
6623     return field_arg->save_in_field_ignore_value(false);
6624   }
save_in_param(THD *,Item_param * param)6625   bool save_in_param(THD *, Item_param *param) override
6626   {
6627     param->set_ignore();
6628     return false;
6629   }
6630 
get_copy(THD * thd)6631   Item *get_copy(THD *thd) override
6632   { return get_item_copy<Item_ignore_specification>(thd, this); }
6633 };
6634 
6635 
6636 /*
6637   Item_insert_value -- an implementation of VALUES() function.
6638   You can use the VALUES(col_name) function in the UPDATE clause
6639   to refer to column values from the INSERT portion of the INSERT
6640   ... UPDATE statement. In other words, VALUES(col_name) in the
6641   UPDATE clause refers to the value of col_name that would be
6642   inserted, had no duplicate-key conflict occurred.
6643   In all other places this function returns NULL.
6644 */
6645 
6646 class Item_insert_value : public Item_field
6647 {
6648 public:
6649   Item *arg;
Item_insert_value(THD * thd,Name_resolution_context * context_arg,Item * a)6650   Item_insert_value(THD *thd, Name_resolution_context *context_arg, Item *a)
6651     :Item_field(thd, context_arg),
6652      arg(a) {}
6653   bool eq(const Item *item, bool binary_cmp) const override;
6654   bool fix_fields(THD *, Item **) override;
6655   void print(String *str, enum_query_type query_type) override;
save_in_field(Field * field_arg,bool no_conversions)6656   int save_in_field(Field *field_arg, bool no_conversions) override
6657   {
6658     return Item_field::save_in_field(field_arg, no_conversions);
6659   }
type()6660   Type type() const override { return INSERT_VALUE_ITEM; }
6661   /*
6662    We use RAND_TABLE_BIT to prevent Item_insert_value from
6663    being treated as a constant and precalculated before execution
6664   */
used_tables()6665   table_map used_tables() const override { return RAND_TABLE_BIT; }
6666 
field_for_view_update()6667   Item_field *field_for_view_update() override { return nullptr; }
6668 
walk(Item_processor processor,bool walk_subquery,void * args)6669   bool walk(Item_processor processor, bool walk_subquery, void *args) override
6670   {
6671     return arg->walk(processor, walk_subquery, args) ||
6672 	    (this->*processor)(args);
6673   }
check_partition_func_processor(void *)6674   bool check_partition_func_processor(void *) override { return true; }
update_vcol_processor(void *)6675   bool update_vcol_processor(void *) override { return false; }
check_vcol_func_processor(void * arg)6676   bool check_vcol_func_processor(void *arg) override
6677   {
6678     return mark_unsupported_function("value()", arg, VCOL_IMPOSSIBLE);
6679   }
6680 };
6681 
6682 
6683 class Table_triggers_list;
6684 
6685 /*
6686   Represents NEW/OLD version of field of row which is
6687   changed/read in trigger.
6688 
6689   Note: For this item main part of actual binding to Field object happens
6690         not during fix_fields() call (like for Item_field) but right after
6691         parsing of trigger definition, when table is opened, with special
6692         setup_field() call. On fix_fields() stage we simply choose one of
6693         two Field instances representing either OLD or NEW version of this
6694         field.
6695 */
6696 class Item_trigger_field : public Item_field,
6697                            private Settable_routine_parameter
6698 {
6699 public:
6700   /* Is this item represents row from NEW or OLD row ? */
6701   enum row_version_type {OLD_ROW, NEW_ROW};
6702   row_version_type row_version;
6703   /* Next in list of all Item_trigger_field's in trigger */
6704   Item_trigger_field *next_trg_field;
6705   /* Index of the field in the TABLE::field array */
6706   uint field_idx;
6707   /* Pointer to Table_trigger_list object for table of this trigger */
6708   Table_triggers_list *triggers;
6709 
Item_trigger_field(THD * thd,Name_resolution_context * context_arg,row_version_type row_ver_arg,const LEX_CSTRING & field_name_arg,privilege_t priv,const bool ro)6710   Item_trigger_field(THD *thd, Name_resolution_context *context_arg,
6711                      row_version_type row_ver_arg,
6712                      const LEX_CSTRING &field_name_arg,
6713                      privilege_t priv, const bool ro)
6714     :Item_field(thd, context_arg, field_name_arg),
6715      row_version(row_ver_arg), field_idx((uint)-1), original_privilege(priv),
6716      want_privilege(priv), table_grants(NULL), read_only (ro)
6717   {}
6718   void setup_field(THD *thd, TABLE *table, GRANT_INFO *table_grant_info);
type()6719   Type type() const override { return TRIGGER_FIELD_ITEM; }
6720   bool eq(const Item *item, bool binary_cmp) const override;
6721   bool fix_fields(THD *, Item **) override;
6722   void print(String *str, enum_query_type query_type) override;
used_tables()6723   table_map used_tables() const override { return (table_map)0L; }
get_tmp_table_field()6724   Field *get_tmp_table_field() override { return nullptr; }
copy_or_same(THD *)6725   Item *copy_or_same(THD *) override { return this; }
get_tmp_table_item(THD * thd)6726   Item *get_tmp_table_item(THD *thd) override { return copy_or_same(thd); }
6727   void cleanup() override;
6728 
6729 private:
6730   void set_required_privilege(bool rw) override;
6731   bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override;
6732 
6733 public:
get_settable_routine_parameter()6734   Settable_routine_parameter *get_settable_routine_parameter() override
6735   {
6736     return read_only ? nullptr : this;
6737   }
6738 
set_value(THD * thd,Item ** it)6739   bool set_value(THD *thd, Item **it)
6740   {
6741     return set_value(thd, NULL, it);
6742   }
6743 
6744 private:
6745   /*
6746     'want_privilege' holds privileges required to perform operation on
6747     this trigger field (SELECT_ACL if we are going to read it and
6748     UPDATE_ACL if we are going to update it).  It is initialized at
6749     parse time but can be updated later if this trigger field is used
6750     as OUT or INOUT parameter of stored routine (in this case
6751     set_required_privilege() is called to appropriately update
6752     want_privilege and cleanup() is responsible for restoring of
6753     original want_privilege once parameter's value is updated).
6754   */
6755   privilege_t original_privilege;
6756   privilege_t want_privilege;
6757   GRANT_INFO *table_grants;
6758   /*
6759     Trigger field is read-only unless it belongs to the NEW row in a
6760     BEFORE INSERT of BEFORE UPDATE trigger.
6761   */
6762   bool read_only;
6763 public:
unknown_splocal_processor(void *)6764   bool unknown_splocal_processor(void *) override { return false; }
6765   bool check_vcol_func_processor(void *arg) override;
6766 };
6767 
6768 
6769 /**
6770   @todo
6771   Implement the is_null() method for this class. Currently calling is_null()
6772   on any Item_cache object resolves to Item::is_null(), which returns FALSE
6773   for any value.
6774 */
6775 
6776 class Item_cache: public Item,
6777                   public Type_handler_hybrid_field_type
6778 {
6779 protected:
6780   Item *example;
6781   /**
6782     Field that this object will get value from. This is used by
6783     index-based subquery engines to detect and remove the equality injected
6784     by IN->EXISTS transformation.
6785   */
6786   Field *cached_field;
6787   /*
6788     TRUE <=> cache holds value of the last stored item (i.e actual value).
6789     store() stores item to be cached and sets this flag to FALSE.
6790     On the first call of val_xxx function if this flag is set to FALSE the
6791     cache_value() will be called to actually cache value of saved item.
6792     cache_value() will set this flag to TRUE.
6793   */
6794   bool value_cached;
6795 
6796   table_map used_table_map;
6797 public:
6798   /*
6799     This is set if at least one of the values of a sub query is NULL
6800     Item_cache_row returns this with null_inside().
6801     For not row items, it's set to the value of null_value
6802     It is set after cache_value() is called.
6803   */
6804   bool null_value_inside;
6805 
Item_cache(THD * thd)6806   Item_cache(THD *thd):
6807     Item(thd),
6808     Type_handler_hybrid_field_type(&type_handler_string),
6809     example(0), cached_field(0),
6810     value_cached(0),
6811     used_table_map(0)
6812   {
6813     maybe_null= 1;
6814     null_value= 1;
6815     null_value_inside= true;
6816   }
6817 protected:
Item_cache(THD * thd,const Type_handler * handler)6818   Item_cache(THD *thd, const Type_handler *handler):
6819     Item(thd),
6820     Type_handler_hybrid_field_type(handler),
6821     example(0), cached_field(0),
6822     value_cached(0),
6823     used_table_map(0)
6824   {
6825     maybe_null= 1;
6826     null_value= 1;
6827     null_value_inside= true;
6828   }
6829 
6830 public:
allocate(THD * thd,uint i)6831   virtual bool allocate(THD *thd, uint i) { return 0; }
setup(THD * thd,Item * item)6832   virtual bool setup(THD *thd, Item *item)
6833   {
6834     example= item;
6835     Type_std_attributes::set(item);
6836     if (item->type() == FIELD_ITEM)
6837       cached_field= ((Item_field *)item)->field;
6838     return 0;
6839   };
6840 
set_used_tables(table_map map)6841   void set_used_tables(table_map map) { used_table_map= map; }
used_tables()6842   table_map used_tables() const override { return used_table_map; }
type()6843   Type type() const override { return CACHE_ITEM; }
6844 
type_handler()6845   const Type_handler *type_handler() const override
6846   { return Type_handler_hybrid_field_type::type_handler(); }
create_tmp_field_ex(MEM_ROOT * root,TABLE * table,Tmp_field_src * src,const Tmp_field_param * param)6847   Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src,
6848                              const Tmp_field_param *param) override
6849   {
6850     return create_tmp_field_ex_simple(root, table, src, param);
6851   }
6852 
keep_array()6853   virtual void keep_array() {}
6854   void print(String *str, enum_query_type query_type) override;
eq_def(const Field * field)6855   bool eq_def(const Field *field)
6856   {
6857     return cached_field ? cached_field->eq_def (field) : FALSE;
6858   }
eq(const Item * item,bool binary_cmp)6859   bool eq(const Item *item, bool binary_cmp) const override
6860   {
6861     return this == item;
6862   }
check_vcol_func_processor(void * arg)6863   bool check_vcol_func_processor(void *arg) override
6864   {
6865     if (example)
6866     {
6867       Item::vcol_func_processor_result *res= (Item::vcol_func_processor_result*)arg;
6868       example->check_vcol_func_processor(arg);
6869       /*
6870         Item_cache of a non-deterministic function requires re-fixing
6871         even if the function itself doesn't (e.g. CURRENT_TIMESTAMP)
6872       */
6873       if (res->errors & VCOL_NOT_STRICTLY_DETERMINISTIC)
6874         res->errors|= VCOL_SESSION_FUNC;
6875       return false;
6876     }
6877     return mark_unsupported_function("cache", arg, VCOL_IMPOSSIBLE);
6878   }
cleanup()6879   void cleanup() override
6880   {
6881     clear();
6882     Item::cleanup();
6883   }
6884   /**
6885      Check if saved item has a non-NULL value.
6886      Will cache value of saved item if not already done.
6887      @return TRUE if cached value is non-NULL.
6888    */
has_value()6889   bool has_value()
6890   {
6891     return (value_cached || cache_value()) && !null_value;
6892   }
6893 
6894   virtual void store(Item *item);
get_item()6895   virtual Item *get_item() { return example; }
6896   virtual bool cache_value()= 0;
basic_const_item()6897   bool basic_const_item() const override
6898   { return example && example->basic_const_item(); }
clear()6899   virtual void clear() { null_value= TRUE; value_cached= FALSE; }
is_null()6900   bool is_null() override { return !has_value(); }
is_expensive()6901   bool is_expensive() override
6902   {
6903     if (value_cached)
6904       return false;
6905     return example->is_expensive();
6906   }
is_expensive_processor(void * arg)6907   bool is_expensive_processor(void *arg) override
6908   {
6909     DBUG_ASSERT(example);
6910     if (value_cached)
6911       return false;
6912     return example->is_expensive_processor(arg);
6913   }
6914   virtual void set_null();
walk(Item_processor processor,bool walk_subquery,void * arg)6915   bool walk(Item_processor processor, bool walk_subquery, void *arg) override
6916   {
6917     if (arg == STOP_PTR)
6918       return FALSE;
6919     if (example && example->walk(processor, walk_subquery, arg))
6920       return TRUE;
6921     return (this->*processor)(arg);
6922   }
6923   Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override;
split_sum_func2_example(THD * thd,Ref_ptr_array ref_pointer_array,List<Item> & fields,uint flags)6924   void split_sum_func2_example(THD *thd,  Ref_ptr_array ref_pointer_array,
6925                                List<Item> &fields, uint flags)
6926   {
6927     example->split_sum_func2(thd, ref_pointer_array, fields, &example, flags);
6928   }
get_example()6929   Item *get_example() const { return example; }
6930 
convert_to_basic_const_item(THD * thd)6931   virtual Item *convert_to_basic_const_item(THD *thd) { return 0; };
derived_field_transformer_for_having(THD * thd,uchar *)6932   Item *derived_field_transformer_for_having(THD *thd, uchar *) override
6933   { return convert_to_basic_const_item(thd); }
derived_field_transformer_for_where(THD * thd,uchar *)6934   Item *derived_field_transformer_for_where(THD *thd, uchar *) override
6935   { return convert_to_basic_const_item(thd); }
grouping_field_transformer_for_where(THD * thd,uchar *)6936   Item *grouping_field_transformer_for_where(THD *thd, uchar *) override
6937   { return convert_to_basic_const_item(thd); }
in_subq_field_transformer_for_where(THD * thd,uchar *)6938   Item *in_subq_field_transformer_for_where(THD *thd, uchar *) override
6939   { return convert_to_basic_const_item(thd); }
in_subq_field_transformer_for_having(THD * thd,uchar *)6940   Item *in_subq_field_transformer_for_having(THD *thd, uchar *) override
6941   { return convert_to_basic_const_item(thd); }
6942 };
6943 
6944 
6945 class Item_cache_int: public Item_cache
6946 {
6947 protected:
6948   longlong value;
6949 public:
Item_cache_int(THD * thd,const Type_handler * handler)6950   Item_cache_int(THD *thd, const Type_handler *handler):
6951     Item_cache(thd, handler), value(0) {}
6952 
6953   double val_real() override;
6954   longlong val_int() override;
6955   String* val_str(String *str) override;
6956   my_decimal *val_decimal(my_decimal *) override;
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)6957   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override
6958   { return get_date_from_int(thd, ltime, fuzzydate); }
6959   bool cache_value() override;
6960   int save_in_field(Field *field, bool no_conversions) override;
6961   Item *convert_to_basic_const_item(THD *thd) override;
get_copy(THD * thd)6962   Item *get_copy(THD *thd) override
6963   { return get_item_copy<Item_cache_int>(thd, this); }
6964 };
6965 
6966 
6967 class Item_cache_year: public Item_cache_int
6968 {
6969 public:
Item_cache_year(THD * thd,const Type_handler * handler)6970   Item_cache_year(THD *thd, const Type_handler *handler)
6971    :Item_cache_int(thd, handler) { }
get_date(THD * thd,MYSQL_TIME * to,date_mode_t mode)6972   bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t mode)
6973   {
6974     return type_handler_year.Item_get_date_with_warn(thd, this, to, mode);
6975   }
6976 };
6977 
6978 
6979 class Item_cache_temporal: public Item_cache_int
6980 {
6981 protected:
6982   Item_cache_temporal(THD *thd, const Type_handler *handler);
6983 public:
6984   bool cache_value() override;
6985   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
6986   int save_in_field(Field *field, bool no_conversions) override;
setup(THD * thd,Item * item)6987   bool setup(THD *thd, Item *item) override
6988   {
6989     if (Item_cache_int::setup(thd, item))
6990       return true;
6991     set_if_smaller(decimals, TIME_SECOND_PART_DIGITS);
6992     return false;
6993   }
6994   void store_packed(longlong val_arg, Item *example);
6995   /*
6996     Having a clone_item method tells optimizer that this object
6997     is a constant and need not be optimized further.
6998     Important when storing packed datetime values.
6999   */
7000   Item *clone_item(THD *thd) override;
7001   Item *convert_to_basic_const_item(THD *thd) override;
7002   virtual Item *make_literal(THD *) =0;
7003 };
7004 
7005 
7006 class Item_cache_time: public Item_cache_temporal
7007 {
7008 public:
Item_cache_time(THD * thd)7009   Item_cache_time(THD *thd)
7010    :Item_cache_temporal(thd, &type_handler_time2) { }
7011   bool cache_value() override;
get_copy(THD * thd)7012   Item *get_copy(THD *thd) override
7013   { return get_item_copy<Item_cache_time>(thd, this); }
7014   Item *make_literal(THD *) override;
val_datetime_packed(THD * thd)7015   longlong val_datetime_packed(THD *thd) override
7016   {
7017     Datetime::Options_cmp opt(thd);
7018     return has_value() ? Datetime(thd, this, opt).to_packed() : 0;
7019   }
val_time_packed(THD *)7020   longlong val_time_packed(THD *) override
7021   {
7022     return has_value() ? value : 0;
7023   }
val_int()7024   longlong val_int() override
7025   {
7026     return has_value() ? Time(this).to_longlong() : 0;
7027   }
val_real()7028   double val_real() override
7029   {
7030     return has_value() ? Time(this).to_double() : 0;
7031   }
val_str(String * to)7032   String *val_str(String *to) override
7033   {
7034     return has_value() ? Time(this).to_string(to, decimals) : NULL;
7035   }
val_decimal(my_decimal * to)7036   my_decimal *val_decimal(my_decimal *to) override
7037   {
7038     return has_value() ? Time(this).to_decimal(to) : NULL;
7039   }
val_native(THD * thd,Native * to)7040   bool val_native(THD *thd, Native *to) override
7041   {
7042     return has_value() ? Time(thd, this).to_native(to, decimals) : true;
7043   }
7044 };
7045 
7046 
7047 class Item_cache_datetime: public Item_cache_temporal
7048 {
7049 public:
Item_cache_datetime(THD * thd)7050   Item_cache_datetime(THD *thd)
7051    :Item_cache_temporal(thd, &type_handler_datetime2) { }
get_copy(THD * thd)7052   Item *get_copy(THD *thd) override
7053   { return get_item_copy<Item_cache_datetime>(thd, this); }
7054   Item *make_literal(THD *) override;
val_datetime_packed(THD *)7055   longlong val_datetime_packed(THD *) override
7056   {
7057     return has_value() ? value : 0;
7058   }
val_time_packed(THD * thd)7059   longlong val_time_packed(THD *thd) override
7060   {
7061     return Time(thd, this, Time::Options_cmp(thd)).to_packed();
7062   }
val_int()7063   longlong val_int() override
7064   {
7065     return has_value() ? Datetime(this).to_longlong() : 0;
7066   }
val_real()7067   double val_real() override
7068   {
7069     return has_value() ? Datetime(this).to_double() : 0;
7070   }
val_str(String * to)7071   String *val_str(String *to) override
7072   {
7073     return has_value() ? Datetime(this).to_string(to, decimals) : NULL;
7074   }
val_decimal(my_decimal * to)7075   my_decimal *val_decimal(my_decimal *to) override
7076   {
7077     return has_value() ? Datetime(this).to_decimal(to) : NULL;
7078   }
7079 };
7080 
7081 
7082 class Item_cache_date: public Item_cache_temporal
7083 {
7084 public:
Item_cache_date(THD * thd)7085   Item_cache_date(THD *thd)
7086    :Item_cache_temporal(thd, &type_handler_newdate) { }
get_copy(THD * thd)7087   Item *get_copy(THD *thd) override
7088   { return get_item_copy<Item_cache_date>(thd, this); }
7089   Item *make_literal(THD *) override;
val_datetime_packed(THD *)7090   longlong val_datetime_packed(THD *) override
7091   {
7092     return has_value() ? value : 0;
7093   }
val_time_packed(THD * thd)7094   longlong val_time_packed(THD *thd) override
7095   {
7096     return Time(thd, this, Time::Options_cmp(thd)).to_packed();
7097   }
val_int()7098   longlong val_int() override
7099   { return has_value() ? Date(this).to_longlong() : 0; }
val_real()7100   double val_real() override
7101   { return has_value() ? Date(this).to_double() : 0; }
val_str(String * to)7102   String *val_str(String *to) override
7103   {
7104     return has_value() ? Date(this).to_string(to) : NULL;
7105   }
val_decimal(my_decimal * to)7106   my_decimal *val_decimal(my_decimal *to) override
7107   {
7108     return has_value() ? Date(this).to_decimal(to) : NULL;
7109   }
7110 };
7111 
7112 
7113 class Item_cache_timestamp: public Item_cache
7114 {
7115   Timestamp_or_zero_datetime_native m_native;
7116   Datetime to_datetime(THD *thd);
7117 public:
Item_cache_timestamp(THD * thd)7118   Item_cache_timestamp(THD *thd)
7119    :Item_cache(thd, &type_handler_timestamp2) { }
get_copy(THD * thd)7120   Item *get_copy(THD *thd) override
7121   { return get_item_copy<Item_cache_timestamp>(thd, this); }
7122   bool cache_value() override;
val_str(String * to)7123   String* val_str(String *to) override
7124   {
7125     return to_datetime(current_thd).to_string(to, decimals);
7126   }
val_decimal(my_decimal * to)7127   my_decimal *val_decimal(my_decimal *to) override
7128   {
7129     return to_datetime(current_thd).to_decimal(to);
7130   }
val_int()7131   longlong val_int() override
7132   {
7133     return to_datetime(current_thd).to_longlong();
7134   }
val_real()7135   double val_real() override
7136   {
7137     return to_datetime(current_thd).to_double();
7138   }
val_datetime_packed(THD * thd)7139   longlong val_datetime_packed(THD *thd) override
7140   {
7141     return to_datetime(thd).to_packed();
7142   }
val_time_packed(THD *)7143   longlong val_time_packed(THD *) override
7144   {
7145     DBUG_ASSERT(0);
7146     return 0;
7147   }
7148   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
7149   int save_in_field(Field *field, bool no_conversions) override;
7150   bool val_native(THD *thd, Native *to) override;
7151 };
7152 
7153 
7154 class Item_cache_real: public Item_cache
7155 {
7156 protected:
7157   double value;
7158 public:
Item_cache_real(THD * thd,const Type_handler * h)7159   Item_cache_real(THD *thd, const Type_handler *h)
7160    :Item_cache(thd, h),
7161     value(0)
7162   {}
7163   double val_real() override;
7164   longlong val_int() override;
7165   my_decimal *val_decimal(my_decimal *) override;
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)7166   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override
7167   { return get_date_from_real(thd, ltime, fuzzydate); }
7168   bool cache_value() override;
7169   Item *convert_to_basic_const_item(THD *thd) override;
7170 };
7171 
7172 
7173 class Item_cache_double: public Item_cache_real
7174 {
7175 public:
Item_cache_double(THD * thd)7176   Item_cache_double(THD *thd)
7177    :Item_cache_real(thd, &type_handler_double)
7178   { }
7179   String* val_str(String *str);
get_copy(THD * thd)7180   Item *get_copy(THD *thd)
7181   { return get_item_copy<Item_cache_double>(thd, this); }
7182 };
7183 
7184 
7185 class Item_cache_float: public Item_cache_real
7186 {
7187 public:
Item_cache_float(THD * thd)7188   Item_cache_float(THD *thd)
7189    :Item_cache_real(thd, &type_handler_float)
7190   { }
7191   String* val_str(String *str);
get_copy(THD * thd)7192   Item *get_copy(THD *thd)
7193   { return get_item_copy<Item_cache_float>(thd, this); }
7194 };
7195 
7196 
7197 class Item_cache_decimal: public Item_cache
7198 {
7199 protected:
7200   my_decimal decimal_value;
7201 public:
Item_cache_decimal(THD * thd)7202   Item_cache_decimal(THD *thd): Item_cache(thd, &type_handler_newdecimal) {}
7203 
7204   double val_real() override;
7205   longlong val_int() override;
7206   String* val_str(String *str) override;
7207   my_decimal *val_decimal(my_decimal *) override;
get_date(THD * thd,MYSQL_TIME * to,date_mode_t mode)7208   bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t mode) override
7209   {
7210     return decimal_to_datetime_with_warn(thd, VDec(this).ptr(), to, mode,
7211                                          NULL, NULL);
7212   }
7213   bool cache_value() override;
7214   Item *convert_to_basic_const_item(THD *thd) override;
get_copy(THD * thd)7215   Item *get_copy(THD *thd) override
7216   { return get_item_copy<Item_cache_decimal>(thd, this); }
7217 };
7218 
7219 
7220 class Item_cache_str: public Item_cache
7221 {
7222   char buffer[STRING_BUFFER_USUAL_SIZE];
7223   String *value, value_buff;
7224   bool is_varbinary;
7225 
7226 public:
Item_cache_str(THD * thd,const Item * item)7227   Item_cache_str(THD *thd, const Item *item):
7228     Item_cache(thd, item->type_handler()), value(0),
7229     is_varbinary(item->type() == FIELD_ITEM &&
7230                  Item_cache_str::field_type() == MYSQL_TYPE_VARCHAR &&
7231                  !((const Item_field *) item)->field->has_charset())
7232   {
7233     collation.set(const_cast<DTCollation&>(item->collation));
7234   }
7235   double val_real() override;
7236   longlong val_int() override;
7237   String* val_str(String *) override;
7238   my_decimal *val_decimal(my_decimal *) override;
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)7239   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override
7240   { return get_date_from_string(thd, ltime, fuzzydate); }
charset()7241   CHARSET_INFO *charset() const { return value->charset(); };
7242   int save_in_field(Field *field, bool no_conversions) override;
7243   bool cache_value() override;
7244   Item *convert_to_basic_const_item(THD *thd) override;
get_copy(THD * thd)7245   Item *get_copy(THD *thd) override
7246   { return get_item_copy<Item_cache_str>(thd, this); }
7247 };
7248 
7249 
7250 class Item_cache_str_for_nullif: public Item_cache_str
7251 {
7252 public:
Item_cache_str_for_nullif(THD * thd,const Item * item)7253   Item_cache_str_for_nullif(THD *thd, const Item *item)
7254    :Item_cache_str(thd, item)
7255   { }
safe_charset_converter(THD * thd,CHARSET_INFO * tocs)7256   Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs)
7257   {
7258     /**
7259       Item_cache_str::safe_charset_converter() returns a new Item_cache
7260       with Item_func_conv_charset installed on "example". The original
7261       Item_cache is not referenced (neither directly nor recursively)
7262       from the result of Item_cache_str::safe_charset_converter().
7263 
7264       For NULLIF() purposes we need a different behavior:
7265       we need a new instance of Item_func_conv_charset,
7266       with the original Item_cache referenced in args[0]. See MDEV-9181.
7267     */
7268     return Item::safe_charset_converter(thd, tocs);
7269   }
get_copy(THD * thd)7270   Item *get_copy(THD *thd)
7271   { return get_item_copy<Item_cache_str_for_nullif>(thd, this); }
7272 };
7273 
7274 
7275 class Item_cache_row: public Item_cache
7276 {
7277   Item_cache  **values;
7278   uint item_count;
7279   bool save_array;
7280 public:
Item_cache_row(THD * thd)7281   Item_cache_row(THD *thd):
7282     Item_cache(thd), values(0), item_count(2),
7283     save_array(0) {}
7284 
7285   /*
7286     'allocate' used only in row transformer, to preallocate space for row
7287     cache.
7288   */
7289   bool allocate(THD *thd, uint num) override;
7290   /*
7291     'setup' is needed only by row => it not called by simple row subselect
7292     (only by IN subselect (in subselect optimizer))
7293   */
7294   bool setup(THD *thd, Item *item) override;
7295   void store(Item *item) override;
7296   void illegal_method_call(const char *);
make_send_field(THD *,Send_field *)7297   void make_send_field(THD *, Send_field *) override
7298   {
7299     illegal_method_call("make_send_field");
7300   };
val_real()7301   double val_real() override
7302   {
7303     illegal_method_call("val");
7304     return 0;
7305   };
val_int()7306   longlong val_int() override
7307   {
7308     illegal_method_call("val_int");
7309     return 0;
7310   };
val_str(String *)7311   String *val_str(String *) override
7312   {
7313     illegal_method_call("val_str");
7314     return nullptr;
7315   };
val_decimal(my_decimal *)7316   my_decimal *val_decimal(my_decimal *) override
7317   {
7318     illegal_method_call("val_decimal");
7319     return nullptr;
7320   };
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)7321   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override
7322   {
7323     illegal_method_call("val_decimal");
7324     return true;
7325   }
7326 
cols()7327   uint cols() const override { return item_count; }
element_index(uint i)7328   Item *element_index(uint i) override { return values[i]; }
addr(uint i)7329   Item **addr(uint i) override { return (Item **) (values + i); }
7330   bool check_cols(uint c) override;
7331   bool null_inside() override;
7332   void bring_value() override;
keep_array()7333   void keep_array() override { save_array= 1; }
cleanup()7334   void cleanup() override
7335   {
7336     DBUG_ENTER("Item_cache_row::cleanup");
7337     Item_cache::cleanup();
7338     if (save_array)
7339       bzero(values, item_count*sizeof(Item**));
7340     else
7341       values= 0;
7342     DBUG_VOID_RETURN;
7343   }
7344   bool cache_value() override;
7345   void set_null() override;
get_copy(THD * thd)7346   Item *get_copy(THD *thd) override
7347   { return get_item_copy<Item_cache_row>(thd, this); }
7348 };
7349 
7350 
7351 /*
7352   Item_type_holder used to store type. name, length of Item for UNIONS &
7353   derived tables.
7354 
7355   Item_type_holder do not need cleanup() because its time of live limited by
7356   single SP/PS execution.
7357 */
7358 class Item_type_holder: public Item,
7359                         public Type_handler_hybrid_field_type
7360 {
7361 protected:
7362   const TYPELIB *enum_set_typelib;
7363 public:
Item_type_holder(THD * thd,Item * item)7364   Item_type_holder(THD *thd, Item *item)
7365    :Item(thd, item),
7366     Type_handler_hybrid_field_type(item->real_type_handler()),
7367     enum_set_typelib(0)
7368   {
7369     DBUG_ASSERT(item->is_fixed());
7370     maybe_null= item->maybe_null;
7371   }
Item_type_holder(THD * thd,Item * item,const Type_handler * handler,const Type_all_attributes * attr,bool maybe_null_arg)7372   Item_type_holder(THD *thd,
7373                    Item *item,
7374                    const Type_handler *handler,
7375                    const Type_all_attributes *attr,
7376                    bool maybe_null_arg)
7377    :Item(thd),
7378     Type_handler_hybrid_field_type(handler),
7379     enum_set_typelib(attr->get_typelib())
7380   {
7381     name= item->name;
7382     Type_std_attributes::set(*attr);
7383     maybe_null= maybe_null_arg;
7384     common_flags= item->common_flags;
7385   }
7386 
type_handler()7387   const Type_handler *type_handler() const override
7388   {
7389     return Type_handler_hybrid_field_type::type_handler()->
7390              type_handler_for_item_field();
7391   }
real_type_handler()7392   const Type_handler *real_type_handler() const override
7393   {
7394     return Type_handler_hybrid_field_type::type_handler();
7395   }
7396 
type()7397   Type type() const override { return TYPE_HOLDER; }
get_typelib()7398   const TYPELIB *get_typelib() const override { return enum_set_typelib; }
7399   /*
7400     When handling a query like this:
7401       VALUES ('') UNION VALUES( _utf16 0x0020 COLLATE utf16_bin);
7402     Item_type_holder can be passed to
7403       Type_handler_xxx::Item_hybrid_func_fix_attributes()
7404     We don't want the latter to perform character set conversion of a
7405     Item_type_holder by calling its val_str(), which calls DBUG_ASSERT(0).
7406     Let's override const_item() and is_expensive() to avoid this.
7407     Note, Item_hybrid_func_fix_attributes() could probably
7408     have a new argument to distinguish what we need:
7409     - (a) aggregate data type attributes only
7410     - (b) install converters after attribute aggregation
7411     So st_select_lex_unit::join_union_type_attributes() could
7412     ask it to do (a) only, without (b).
7413   */
const_item()7414   bool const_item() const override { return false; }
is_expensive()7415   bool is_expensive() override { return true; }
7416   double val_real() override;
7417   longlong val_int() override;
7418   my_decimal *val_decimal(my_decimal *) override;
7419   String *val_str(String*) override;
7420   bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
create_tmp_field_ex(MEM_ROOT * root,TABLE * table,Tmp_field_src * src,const Tmp_field_param * param)7421   Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src,
7422                              const Tmp_field_param *param) override
7423   {
7424     return Item_type_holder::real_type_handler()->
7425            make_and_init_table_field(root, &name, Record_addr(maybe_null),
7426                                      *this, table);
7427   }
get_copy(THD *)7428   Item* get_copy(THD *) override { return nullptr; }
7429 
7430 };
7431 
7432 
7433 class st_select_lex;
7434 void mark_select_range_as_dependent(THD *thd,
7435                                     st_select_lex *last_select,
7436                                     st_select_lex *current_sel,
7437                                     Field *found_field, Item *found_item,
7438                                     Item_ident *resolved_item,
7439                                     bool suppress_warning_output);
7440 
7441 extern Cached_item *new_Cached_item(THD *thd, Item *item,
7442                                     bool pass_through_ref);
7443 extern Item_result item_cmp_type(Item_result a,Item_result b);
7444 extern void resolve_const_item(THD *thd, Item **ref, Item *cmp_item);
7445 extern int stored_field_cmp_to_item(THD *thd, Field *field, Item *item);
7446 
7447 extern const String my_null_string;
7448 
7449 /**
7450   Interface for Item iterator
7451 */
7452 
7453 class Item_iterator
7454 {
7455 public:
7456   /**
7457     Shall set this iterator to the position before the first item
7458 
7459     @note
7460     This method also may perform some other initialization actions like
7461     allocation of certain resources.
7462   */
7463   virtual void open()= 0;
7464   /**
7465     Shall return the next Item (or NULL if there is no next item) and
7466     move pointer to position after it.
7467   */
7468   virtual Item *next()= 0;
7469   /**
7470     Shall force iterator to free resources (if it holds them)
7471 
7472     @note
7473     One should not use the iterator without open() call after close()
7474   */
7475   virtual void close()= 0;
7476 
~Item_iterator()7477   virtual ~Item_iterator() {}
7478 };
7479 
7480 
7481 /**
7482   Item iterator over List_iterator_fast for Item references
7483 */
7484 
7485 class Item_iterator_ref_list: public Item_iterator
7486 {
7487   List_iterator<Item*> list;
7488 public:
Item_iterator_ref_list(List_iterator<Item * > & arg_list)7489   Item_iterator_ref_list(List_iterator<Item*> &arg_list):
7490     list(arg_list) {}
open()7491   void open() { list.rewind(); }
next()7492   Item *next() { return *(list++); }
close()7493   void close() {}
7494 };
7495 
7496 
7497 /**
7498   Item iterator over List_iterator_fast for Items
7499 */
7500 
7501 class Item_iterator_list: public Item_iterator
7502 {
7503   List_iterator<Item> list;
7504 public:
Item_iterator_list(List_iterator<Item> & arg_list)7505   Item_iterator_list(List_iterator<Item> &arg_list):
7506     list(arg_list) {}
open()7507   void open() { list.rewind(); }
next()7508   Item *next() { return (list++); }
close()7509   void close() {}
7510 };
7511 
7512 
7513 /**
7514   Item iterator over Item interface for rows
7515 */
7516 
7517 class Item_iterator_row: public Item_iterator
7518 {
7519   Item *base_item;
7520   uint current;
7521 public:
Item_iterator_row(Item * base)7522   Item_iterator_row(Item *base) : base_item(base), current(0) {}
open()7523   void open() { current= 0; }
next()7524   Item *next()
7525   {
7526     if (current >= base_item->cols())
7527       return NULL;
7528     return base_item->element_index(current++);
7529   }
close()7530   void close() {}
7531 };
7532 
7533 
7534 /*
7535   fix_escape_item() sets the out "escape" parameter to:
7536   - native code in case of an 8bit character set
7537   - Unicode code point in case of a multi-byte character set
7538 
7539   The value meaning a not-initialized ESCAPE character must not be equal to
7540   any valid value, so must be outside of these ranges:
7541   - -128..+127, not to conflict with a valid 8bit charcter
7542   - 0..0x10FFFF, not to conflict with a valid Unicode code point
7543   The exact value does not matter.
7544 */
7545 #define ESCAPE_NOT_INITIALIZED -1000
7546 
7547 /*
7548   It's used in ::fix_fields() methods of LIKE and JSON_SEARCH
7549   functions to handle the ESCAPE parameter.
7550   This parameter is quite non-standard so the specific function.
7551 */
7552 bool fix_escape_item(THD *thd, Item *escape_item, String *tmp_str,
7553                      bool escape_used_in_parsing, CHARSET_INFO *cmp_cs,
7554                      int *escape);
7555 
is_equal(const Virtual_column_info * vcol)7556 inline bool Virtual_column_info::is_equal(const Virtual_column_info* vcol) const
7557 {
7558   return type_handler()  == vcol->type_handler()
7559       && stored_in_db == vcol->is_stored()
7560       && expr->eq(vcol->expr, true);
7561 }
7562 
print(String * str)7563 inline void Virtual_column_info::print(String* str)
7564 {
7565   expr->print_for_table_def(str);
7566 }
7567 
mark_column_with_deps(Field * field)7568 inline bool TABLE::mark_column_with_deps(Field *field)
7569 {
7570   bool res;
7571   if (!(res= bitmap_fast_test_and_set(read_set, field->field_index)))
7572   {
7573     if (field->vcol_info)
7574       mark_virtual_column_deps(field);
7575   }
7576   return res;
7577 }
7578 
mark_virtual_column_with_deps(Field * field)7579 inline bool TABLE::mark_virtual_column_with_deps(Field *field)
7580 {
7581   bool res;
7582   DBUG_ASSERT(field->vcol_info);
7583   if (!(res= bitmap_fast_test_and_set(read_set, field->field_index)))
7584     mark_virtual_column_deps(field);
7585   return res;
7586 }
7587 
mark_virtual_column_deps(Field * field)7588 inline void TABLE::mark_virtual_column_deps(Field *field)
7589 {
7590   DBUG_ASSERT(field->vcol_info);
7591   DBUG_ASSERT(field->vcol_info->expr);
7592   field->vcol_info->expr->walk(&Item::register_field_in_read_map, 1, 0);
7593 }
7594 
use_all_stored_columns()7595 inline void TABLE::use_all_stored_columns()
7596 {
7597   bitmap_set_all(read_set);
7598   if (Field **vf= vfield)
7599     for (; *vf; vf++)
7600       bitmap_clear_bit(read_set, (*vf)->field_index);
7601 }
7602 
7603 #endif /* SQL_ITEM_INCLUDED */
7604