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