1 #ifndef ITEM_INCLUDED
2 #define ITEM_INCLUDED
3 
4 /* Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
5 
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License, version 2.0,
8    as published by the Free Software Foundation.
9 
10    This program is also distributed with certain software (including
11    but not limited to OpenSSL) that is licensed under separate terms,
12    as designated in a particular file or component or in included license
13    documentation.  The authors of MySQL hereby grant you an additional
14    permission to link the program and your derivative works with the
15    separately licensed software that they have included with MySQL.
16 
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License, version 2.0, for more details.
21 
22    You should have received a copy of the GNU General Public License
23    along with this program; if not, write to the Free Software
24    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
25 
26 
27 #include "sql_priv.h"                /* STRING_BUFFER_USUAL_SIZE */
28 #include "unireg.h"
29 #include "sql_const.h"                 /* RAND_TABLE_BIT, MAX_FIELD_NAME */
30 #include "unireg.h"                    // REQUIRED: for other includes
31 #include "thr_malloc.h"                         /* sql_calloc */
32 #include "field.h"                              /* Derivation */
33 #include "sql_array.h"
34 
35 class Protocol;
36 struct TABLE_LIST;
37 void item_init(void);			/* Init item functions */
38 class Item_field;
39 class user_var_entry;
40 
41 typedef Bounds_checked_array<Item*> Ref_ptr_array;
42 
43 static inline uint32
char_to_byte_length_safe(uint32 char_length_arg,uint32 mbmaxlen_arg)44 char_to_byte_length_safe(uint32 char_length_arg, uint32 mbmaxlen_arg)
45 {
46    ulonglong tmp= ((ulonglong) char_length_arg) * mbmaxlen_arg;
47    return (tmp > UINT_MAX32) ? (uint32) UINT_MAX32 : (uint32) tmp;
48 }
49 
50 
51 /*
52    "Declared Type Collation"
53    A combination of collation and its derivation.
54 
55   Flags for collation aggregation modes:
56   MY_COLL_ALLOW_SUPERSET_CONV  - allow conversion to a superset
57   MY_COLL_ALLOW_COERCIBLE_CONV - allow conversion of a coercible value
58                                  (i.e. constant).
59   MY_COLL_ALLOW_CONV           - allow any kind of conversion
60                                  (combination of the above two)
61   MY_COLL_ALLOW_NUMERIC_CONV   - if all items were numbers, convert to
62                                  @@character_set_connection
63   MY_COLL_DISALLOW_NONE        - don't allow return DERIVATION_NONE
64                                  (e.g. when aggregating for comparison)
65   MY_COLL_CMP_CONV             - combination of MY_COLL_ALLOW_CONV
66                                  and MY_COLL_DISALLOW_NONE
67 */
68 
69 #define MY_COLL_ALLOW_SUPERSET_CONV   1
70 #define MY_COLL_ALLOW_COERCIBLE_CONV  2
71 #define MY_COLL_DISALLOW_NONE         4
72 #define MY_COLL_ALLOW_NUMERIC_CONV    8
73 
74 #define MY_COLL_ALLOW_CONV (MY_COLL_ALLOW_SUPERSET_CONV | MY_COLL_ALLOW_COERCIBLE_CONV)
75 #define MY_COLL_CMP_CONV   (MY_COLL_ALLOW_CONV | MY_COLL_DISALLOW_NONE)
76 
77 class DTCollation {
78 public:
79   const CHARSET_INFO *collation;
80   enum Derivation derivation;
81   uint repertoire;
82 
set_repertoire_from_charset(const CHARSET_INFO * cs)83   void set_repertoire_from_charset(const CHARSET_INFO *cs)
84   {
85     repertoire= cs->state & MY_CS_PUREASCII ?
86                 MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30;
87   }
DTCollation()88   DTCollation()
89   {
90     collation= &my_charset_bin;
91     derivation= DERIVATION_NONE;
92     repertoire= MY_REPERTOIRE_UNICODE30;
93   }
DTCollation(const CHARSET_INFO * collation_arg,Derivation derivation_arg)94   DTCollation(const CHARSET_INFO *collation_arg, Derivation derivation_arg)
95   {
96     collation= collation_arg;
97     derivation= derivation_arg;
98     set_repertoire_from_charset(collation_arg);
99   }
set(DTCollation & dt)100   void set(DTCollation &dt)
101   {
102     collation= dt.collation;
103     derivation= dt.derivation;
104     repertoire= dt.repertoire;
105   }
set(const CHARSET_INFO * collation_arg,Derivation derivation_arg)106   void set(const CHARSET_INFO *collation_arg, Derivation derivation_arg)
107   {
108     collation= collation_arg;
109     derivation= derivation_arg;
110     set_repertoire_from_charset(collation_arg);
111   }
set(const CHARSET_INFO * collation_arg,Derivation derivation_arg,uint repertoire_arg)112   void set(const CHARSET_INFO *collation_arg,
113            Derivation derivation_arg,
114            uint repertoire_arg)
115   {
116     collation= collation_arg;
117     derivation= derivation_arg;
118     repertoire= repertoire_arg;
119   }
set_numeric()120   void set_numeric()
121   {
122     collation= &my_charset_numeric;
123     derivation= DERIVATION_NUMERIC;
124     repertoire= MY_REPERTOIRE_NUMERIC;
125   }
set(const CHARSET_INFO * collation_arg)126   void set(const CHARSET_INFO *collation_arg)
127   {
128     collation= collation_arg;
129     set_repertoire_from_charset(collation_arg);
130   }
set(Derivation derivation_arg)131   void set(Derivation derivation_arg)
132   { derivation= derivation_arg; }
set_repertoire(uint repertoire_arg)133   void set_repertoire(uint repertoire_arg)
134   { repertoire= repertoire_arg; }
135   bool aggregate(DTCollation &dt, uint flags= 0);
136   bool set(DTCollation &dt1, DTCollation &dt2, uint flags= 0)
137   { set(dt1); return aggregate(dt2, flags); }
derivation_name()138   const char *derivation_name() const
139   {
140     switch(derivation)
141     {
142       case DERIVATION_NUMERIC:   return "NUMERIC";
143       case DERIVATION_IGNORABLE: return "IGNORABLE";
144       case DERIVATION_COERCIBLE: return "COERCIBLE";
145       case DERIVATION_IMPLICIT:  return "IMPLICIT";
146       case DERIVATION_SYSCONST:  return "SYSCONST";
147       case DERIVATION_EXPLICIT:  return "EXPLICIT";
148       case DERIVATION_NONE:      return "NONE";
149       default: return "UNKNOWN";
150     }
151   }
152 };
153 /**
154   Class used as argument to Item::walk() together with used_tables_for_level()
155 */
156 class Used_tables
157 {
158 public:
Used_tables(st_select_lex * select)159   explicit Used_tables(st_select_lex *select) :
160   select(select), used_tables(0)
161   {}
162 
163   st_select_lex *const select;           ///< Level for which data is accumulated
164   table_map used_tables;              ///< Accumulated used tables data
165 };
166 
167 /*************************************************************************/
168 
169 /**
170   Storage for name strings.
171   Enpowers Simple_cstring with allocation routines from the sql_strmake family.
172 
173   This class must stay as small as possible as we often
174   pass it into functions using call-by-value evaluation.
175 
176   Don't add new members or virual methods into this class!
177 */
178 class Name_string: public Simple_cstring
179 {
180 private:
set_or_copy(const char * str,size_t length,bool is_null_terminated)181   void set_or_copy(const char *str, size_t length, bool is_null_terminated)
182   {
183     if (is_null_terminated)
184       set(str, length);
185     else
186       copy(str, length);
187   }
188 public:
Name_string()189   Name_string(): Simple_cstring() {}
190   /*
191     Please do NOT add constructor Name_string(const char *str) !
192     It will involve hidden strlen() call, which can affect
193     performance negatively. Use Name_string(str, len) instead.
194   */
Name_string(const char * str,size_t length)195   Name_string(const char *str, size_t length):
196     Simple_cstring(str, length) {}
Name_string(const LEX_STRING str)197   Name_string(const LEX_STRING str): Simple_cstring(str) {}
Name_string(const char * str,size_t length,bool is_null_terminated)198   Name_string(const char *str, size_t length, bool is_null_terminated):
199     Simple_cstring()
200   {
201     set_or_copy(str, length, is_null_terminated);
202   }
Name_string(const LEX_STRING str,bool is_null_terminated)203   Name_string(const LEX_STRING str, bool is_null_terminated):
204     Simple_cstring()
205   {
206     set_or_copy(str.str, str.length, is_null_terminated);
207   }
208   /**
209     Allocate space using sql_strmake() or sql_strmake_with_convert().
210   */
211   void copy(const char *str, size_t length, const CHARSET_INFO *cs);
212   /**
213     Variants for copy(), for various argument combinations.
214   */
copy(const char * str,size_t length)215   void copy(const char *str, size_t length)
216   {
217     copy(str, length, system_charset_info);
218   }
copy(const char * str)219   void copy(const char *str)
220   {
221     copy(str, (str ? strlen(str) : 0), system_charset_info);
222   }
copy(const LEX_STRING lex)223   void copy(const LEX_STRING lex)
224   {
225     copy(lex.str, lex.length);
226   }
copy(const LEX_STRING * lex)227   void copy(const LEX_STRING *lex)
228   {
229     copy(lex->str, lex->length);
230   }
copy(const Name_string str)231   void copy(const Name_string str)
232   {
233     copy(str.ptr(), str.length());
234   }
235   /**
236     Compare name to another name in C string, case insensitively.
237   */
eq(const char * str)238   bool eq(const char *str) const
239   {
240     DBUG_ASSERT(str && ptr());
241     return my_strcasecmp(system_charset_info, ptr(), str) == 0;
242   }
eq_safe(const char * str)243   bool eq_safe(const char *str) const
244   {
245     return is_set() && str && eq(str);
246   }
247   /**
248     Compare name to another name in Name_string, case insensitively.
249   */
eq(const Name_string name)250   bool eq(const Name_string name) const
251   {
252     return eq(name.ptr());
253   }
eq_safe(const Name_string name)254   bool eq_safe(const Name_string name) const
255   {
256     return is_set() && name.is_set() && eq(name);
257   }
258 };
259 
260 
261 #define NAME_STRING(x)  Name_string(C_STRING_WITH_LEN(x))
262 
263 
264 extern const Name_string null_name_string;
265 
266 
267 /**
268   Storage for Item names.
269   Adds "autogenerated" flag and warning functionality to Name_string.
270 */
271 class Item_name_string: public Name_string
272 {
273 private:
274   bool m_is_autogenerated; /* indicates if name of this Item
275                               was autogenerated or set by user */
276 public:
Item_name_string()277   Item_name_string(): Name_string(), m_is_autogenerated(true)
278   { }
Item_name_string(const Name_string name)279   Item_name_string(const Name_string name)
280     :Name_string(name), m_is_autogenerated(true)
281   { }
282   /**
283     Set m_is_autogenerated flag to the given value.
284   */
set_autogenerated(bool is_autogenerated)285   void set_autogenerated(bool is_autogenerated)
286   {
287     m_is_autogenerated= is_autogenerated;
288   }
289   /**
290     Return the auto-generated flag.
291   */
is_autogenerated()292   bool is_autogenerated() const { return m_is_autogenerated; }
293   using Name_string::copy;
294   /**
295     Copy name together with autogenerated flag.
296     Produce a warning if name was cut.
297   */
298   void copy(const char *str_arg, size_t length_arg, const CHARSET_INFO *cs_arg,
299            bool is_autogenerated_arg);
300 };
301 
302 
303 
304 /*************************************************************************/
305 /*
306   A framework to easily handle different return types for hybrid items
307   (hybrid item is an item whose operand can be of any type, e.g. integer,
308   real, decimal).
309 */
310 
311 struct Hybrid_type_traits;
312 
313 struct Hybrid_type
314 {
315   longlong integer;
316 
317   double real;
318   /*
319     Use two decimal buffers interchangeably to speed up += operation
320     which has no native support in decimal library.
321     Hybrid_type+= arg is implemented as dec_buf[1]= dec_buf[0] + arg.
322     The third decimal is used as a handy temporary storage.
323   */
324   my_decimal dec_buf[3];
325   int used_dec_buf_no;
326 
327   /*
328     Traits moved to a separate class to
329       a) be able to easily change object traits in runtime
330       b) they work as a differentiator for the union above
331   */
332   const Hybrid_type_traits *traits;
333 
Hybrid_typeHybrid_type334   Hybrid_type() {}
335   /* XXX: add traits->copy() when needed */
Hybrid_typeHybrid_type336   Hybrid_type(const Hybrid_type &rhs) :traits(rhs.traits) {}
337 };
338 
339 
340 /* Hybryd_type_traits interface + default implementation for REAL_RESULT */
341 
342 struct Hybrid_type_traits
343 {
typeHybrid_type_traits344   virtual Item_result type() const { return REAL_RESULT; }
345 
346   virtual void
347   fix_length_and_dec(Item *item, Item *arg) const;
348 
349   /* Hybrid_type operations. */
set_zeroHybrid_type_traits350   virtual void set_zero(Hybrid_type *val) const { val->real= 0.0; }
addHybrid_type_traits351   virtual void add(Hybrid_type *val, Field *f) const
352   { val->real+= f->val_real(); }
divHybrid_type_traits353   virtual void div(Hybrid_type *val, ulonglong u) const
354   { val->real/= ulonglong2double(u); }
355 
val_intHybrid_type_traits356   virtual longlong val_int(Hybrid_type *val, bool unsigned_flag) const
357   { return (longlong) rint(val->real); }
val_realHybrid_type_traits358   virtual double val_real(Hybrid_type *val) const { return val->real; }
359   virtual my_decimal *val_decimal(Hybrid_type *val, my_decimal *buf) const;
360   virtual String *val_str(Hybrid_type *val, String *buf, uint8 decimals) const;
361   static const Hybrid_type_traits *instance();
Hybrid_type_traitsHybrid_type_traits362   Hybrid_type_traits() {}
~Hybrid_type_traitsHybrid_type_traits363   virtual ~Hybrid_type_traits() {}
364 };
365 
366 
367 struct Hybrid_type_traits_decimal: public Hybrid_type_traits
368 {
typeHybrid_type_traits_decimal369   virtual Item_result type() const { return DECIMAL_RESULT; }
370 
371   virtual void
372   fix_length_and_dec(Item *arg, Item *item) const;
373 
374   /* Hybrid_type operations. */
375   virtual void set_zero(Hybrid_type *val) const;
376   virtual void add(Hybrid_type *val, Field *f) const;
377   virtual void div(Hybrid_type *val, ulonglong u) const;
378 
379   virtual longlong val_int(Hybrid_type *val, bool unsigned_flag) const;
380   virtual double val_real(Hybrid_type *val) const;
val_decimalHybrid_type_traits_decimal381   virtual my_decimal *val_decimal(Hybrid_type *val, my_decimal *buf) const
382   { return &val->dec_buf[val->used_dec_buf_no]; }
383   virtual String *val_str(Hybrid_type *val, String *buf, uint8 decimals) const;
384   static const Hybrid_type_traits_decimal *instance();
Hybrid_type_traits_decimalHybrid_type_traits_decimal385   Hybrid_type_traits_decimal() {};
386 };
387 
388 
389 struct Hybrid_type_traits_integer: public Hybrid_type_traits
390 {
typeHybrid_type_traits_integer391   virtual Item_result type() const { return INT_RESULT; }
392 
393   virtual void
394   fix_length_and_dec(Item *arg, Item *item) const;
395 
396   /* Hybrid_type operations. */
set_zeroHybrid_type_traits_integer397   virtual void set_zero(Hybrid_type *val) const
398   { val->integer= 0; }
addHybrid_type_traits_integer399   virtual void add(Hybrid_type *val, Field *f) const
400   { val->integer+= f->val_int(); }
divHybrid_type_traits_integer401   virtual void div(Hybrid_type *val, ulonglong u) const
402   { val->integer/= (longlong) u; }
403 
val_intHybrid_type_traits_integer404   virtual longlong val_int(Hybrid_type *val, bool unsigned_flag) const
405   { return val->integer; }
val_realHybrid_type_traits_integer406   virtual double val_real(Hybrid_type *val) const
407   { return (double) val->integer; }
val_decimalHybrid_type_traits_integer408   virtual my_decimal *val_decimal(Hybrid_type *val, my_decimal *buf) const
409   {
410     int2my_decimal(E_DEC_FATAL_ERROR, val->integer, 0, &val->dec_buf[2]);
411     return &val->dec_buf[2];
412   }
val_strHybrid_type_traits_integer413   virtual String *val_str(Hybrid_type *val, String *buf, uint8 decimals) const
414   { buf->set(val->integer, &my_charset_bin); return buf;}
415   static const Hybrid_type_traits_integer *instance();
Hybrid_type_traits_integerHybrid_type_traits_integer416   Hybrid_type_traits_integer() {};
417 };
418 
419 
420 void dummy_error_processor(THD *thd, void *data);
421 
422 void view_error_processor(THD *thd, void *data);
423 
424 /*
425   Instances of Name_resolution_context store the information necesary for
426   name resolution of Items and other context analysis of a query made in
427   fix_fields().
428 
429   This structure is a part of SELECT_LEX, a pointer to this structure is
430   assigned when an item is created (which happens mostly during  parsing
431   (sql_yacc.yy)), but the structure itself will be initialized after parsing
432   is complete
433 
434   TODO: move subquery of INSERT ... SELECT and CREATE ... SELECT to
435   separate SELECT_LEX which allow to remove tricks of changing this
436   structure before and after INSERT/CREATE and its SELECT to make correct
437   field name resolution.
438 */
439 struct Name_resolution_context: Sql_alloc
440 {
441   /*
442     The name resolution context to search in when an Item cannot be
443     resolved in this context (the context of an outer select)
444   */
445   Name_resolution_context *outer_context;
446 
447   /*
448     List of tables used to resolve the items of this context.  Usually these
449     are tables from the FROM clause of SELECT statement.  The exceptions are
450     INSERT ... SELECT and CREATE ... SELECT statements, where SELECT
451     subquery is not moved to a separate SELECT_LEX.  For these types of
452     statements we have to change this member dynamically to ensure correct
453     name resolution of different parts of the statement.
454   */
455   TABLE_LIST *table_list;
456   /*
457     In most cases the two table references below replace 'table_list' above
458     for the purpose of name resolution. The first and last name resolution
459     table references allow us to search only in a sub-tree of the nested
460     join tree in a FROM clause. This is needed for NATURAL JOIN, JOIN ... USING
461     and JOIN ... ON.
462   */
463   TABLE_LIST *first_name_resolution_table;
464   /*
465     Last table to search in the list of leaf table references that begins
466     with first_name_resolution_table.
467   */
468   TABLE_LIST *last_name_resolution_table;
469 
470   /*
471     SELECT_LEX item belong to, in case of merged VIEW it can differ from
472     SELECT_LEX where item was created, so we can't use table_list/field_list
473     from there
474   */
475   st_select_lex *select_lex;
476 
477   /*
478     Processor of errors caused during Item name resolving, now used only to
479     hide underlying tables in errors about views (i.e. it substitute some
480     errors for views)
481   */
482   void (*error_processor)(THD *, void *);
483   void *error_processor_data;
484 
485   /**
486     When TRUE, items are resolved in this context against
487     SELECT_LEX::item_list, SELECT_lex::group_list and
488     this->table_list. If FALSE, items are resolved only against
489     this->table_list.
490 
491     @see st_select_lex::item_list, st_select_lex::group_list
492   */
493   bool resolve_in_select_list;
494 
495   /*
496     Security context of this name resolution context. It's used for views
497     and is non-zero only if the view is defined with SQL SECURITY DEFINER.
498   */
499   Security_context *security_ctx;
500 
Name_resolution_contextName_resolution_context501   Name_resolution_context()
502     :outer_context(0), table_list(0), select_lex(0),
503     error_processor_data(0),
504     security_ctx(0)
505     {}
506 
initName_resolution_context507   void init()
508   {
509     resolve_in_select_list= FALSE;
510     error_processor= &dummy_error_processor;
511     first_name_resolution_table= NULL;
512     last_name_resolution_table= NULL;
513   }
514 
resolve_in_table_list_onlyName_resolution_context515   void resolve_in_table_list_only(TABLE_LIST *tables)
516   {
517     table_list= first_name_resolution_table= tables;
518     resolve_in_select_list= FALSE;
519   }
520 
process_errorName_resolution_context521   void process_error(THD *thd)
522   {
523     (*error_processor)(thd, error_processor_data);
524   }
525 };
526 
527 
528 /*
529   Store and restore the current state of a name resolution context.
530 */
531 
532 class Name_resolution_context_state
533 {
534 private:
535   TABLE_LIST *save_table_list;
536   TABLE_LIST *save_first_name_resolution_table;
537   TABLE_LIST *save_next_name_resolution_table;
538   bool        save_resolve_in_select_list;
539   TABLE_LIST *save_next_local;
540 
541 public:
Name_resolution_context_state()542   Name_resolution_context_state() {}          /* Remove gcc warning */
543 
544 public:
545   /* Save the state of a name resolution context. */
save_state(Name_resolution_context * context,TABLE_LIST * table_list)546   void save_state(Name_resolution_context *context, TABLE_LIST *table_list)
547   {
548     save_table_list=                  context->table_list;
549     save_first_name_resolution_table= context->first_name_resolution_table;
550     save_resolve_in_select_list=      context->resolve_in_select_list;
551     save_next_local=                  table_list->next_local;
552     save_next_name_resolution_table=  table_list->next_name_resolution_table;
553   }
554 
555   /* Restore a name resolution context from saved state. */
restore_state(Name_resolution_context * context,TABLE_LIST * table_list)556   void restore_state(Name_resolution_context *context, TABLE_LIST *table_list)
557   {
558     table_list->next_local=                save_next_local;
559     table_list->next_name_resolution_table= save_next_name_resolution_table;
560     context->table_list=                   save_table_list;
561     context->first_name_resolution_table=  save_first_name_resolution_table;
562     context->resolve_in_select_list=       save_resolve_in_select_list;
563   }
564 
get_first_name_resolution_table()565   TABLE_LIST *get_first_name_resolution_table()
566   {
567     return save_first_name_resolution_table;
568   }
569 };
570 
571 
572 /*
573   This enum is used to report information about monotonicity of function
574   represented by Item* tree.
575   Monotonicity is defined only for Item* trees that represent table
576   partitioning expressions (i.e. have no subselects/user vars/PS parameters
577   etc etc). An Item* tree is assumed to have the same monotonicity properties
578   as its correspoinding function F:
579 
580   [signed] longlong F(field1, field2, ...) {
581     put values of field_i into table record buffer;
582     return item->val_int();
583   }
584 
585   NOTE
586   At the moment function monotonicity is not well defined (and so may be
587   incorrect) for Item trees with parameters/return types that are different
588   from INT_RESULT, may be NULL, or are unsigned.
589   It will be possible to address this issue once the related partitioning bugs
590   (BUG#16002, BUG#15447, BUG#13436) are fixed.
591 
592   The NOT_NULL enums are used in TO_DAYS, since TO_DAYS('2001-00-00') returns
593   NULL which puts those rows into the NULL partition, but
594   '2000-12-31' < '2001-00-00' < '2001-01-01'. So special handling is needed
595   for this (see Bug#20577).
596 */
597 
598 typedef enum monotonicity_info
599 {
600    NON_MONOTONIC,              /* none of the below holds */
601    MONOTONIC_INCREASING,       /* F() is unary and (x < y) => (F(x) <= F(y)) */
602    MONOTONIC_INCREASING_NOT_NULL,  /* But only for valid/real x and y */
603    MONOTONIC_STRICT_INCREASING,/* F() is unary and (x < y) => (F(x) <  F(y)) */
604    MONOTONIC_STRICT_INCREASING_NOT_NULL  /* But only for valid/real x and y */
605 } enum_monotonicity_info;
606 
607 /*************************************************************************/
608 
609 class sp_rcontext;
610 
611 
612 class Settable_routine_parameter
613 {
614 public:
615   /*
616     Set required privileges for accessing the parameter.
617 
618     SYNOPSIS
619       set_required_privilege()
620         rw        if 'rw' is true then we are going to read and set the
621                   parameter, so SELECT and UPDATE privileges might be
622                   required, otherwise we only reading it and SELECT
623                   privilege might be required.
624   */
Settable_routine_parameter()625   Settable_routine_parameter() {}
~Settable_routine_parameter()626   virtual ~Settable_routine_parameter() {}
set_required_privilege(bool rw)627   virtual void set_required_privilege(bool rw) {};
628 
629   /*
630     Set parameter value.
631 
632     SYNOPSIS
633       set_value()
634         thd       thread handle
635         ctx       context to which parameter belongs (if it is local
636                   variable).
637         it        item which represents new value
638 
639     RETURN
640       FALSE if parameter value has been set,
641       TRUE if error has occured.
642   */
643   virtual bool set_value(THD *thd, sp_rcontext *ctx, Item **it)= 0;
644 
set_out_param_info(Send_field * info)645   virtual void set_out_param_info(Send_field *info) {}
646 
get_out_param_info()647   virtual const Send_field *get_out_param_info() const
648   { return NULL; }
649 };
650 
651 
652 typedef bool (Item::*Item_processor) (uchar *arg);
653 /*
654   Analyzer function
655     SYNOPSIS
656       argp   in/out IN:  Analysis parameter
657                     OUT: Parameter to be passed to the transformer
658 
659     RETURN
660       TRUE   Invoke the transformer
661       FALSE  Don't do it
662 
663 */
664 typedef bool (Item::*Item_analyzer) (uchar **argp);
665 typedef Item* (Item::*Item_transformer) (uchar *arg);
666 typedef void (*Cond_traverser) (const Item *item, void *arg);
667 
668 
669 class Item
670 {
671   Item(const Item &);			/* Prevent use of these */
672   void operator=(Item &);
673   /* Cache of the result of is_expensive(). */
674   int8 is_expensive_cache;
is_expensive_processor(uchar * arg)675   virtual bool is_expensive_processor(uchar *arg) { return 0; }
676 
677 public:
new(size_t size)678   static void *operator new(size_t size) throw ()
679   { return sql_alloc(size); }
new(size_t size,MEM_ROOT * mem_root)680   static void *operator new(size_t size, MEM_ROOT *mem_root) throw ()
681   { return alloc_root(mem_root, size); }
delete(void * ptr,size_t size)682   static void operator delete(void *ptr,size_t size) { TRASH(ptr, size); }
delete(void * ptr,MEM_ROOT * mem_root)683   static void operator delete(void *ptr, MEM_ROOT *mem_root) {}
684 
685   enum Type {FIELD_ITEM= 0, FUNC_ITEM, SUM_FUNC_ITEM, STRING_ITEM,
686 	     INT_ITEM, REAL_ITEM, NULL_ITEM, VARBIN_ITEM,
687 	     COPY_STR_ITEM, FIELD_AVG_ITEM, DEFAULT_VALUE_ITEM,
688 	     PROC_ITEM,COND_ITEM, REF_ITEM, FIELD_STD_ITEM,
689 	     FIELD_VARIANCE_ITEM, INSERT_VALUE_ITEM,
690              SUBSELECT_ITEM, ROW_ITEM, CACHE_ITEM, TYPE_HOLDER,
691              PARAM_ITEM, TRIGGER_FIELD_ITEM, DECIMAL_ITEM,
692              XPATH_NODESET, XPATH_NODESET_CMP,
693              VIEW_FIXER_ITEM};
694 
695   enum cond_result { COND_UNDEF,COND_OK,COND_TRUE,COND_FALSE };
696 
697   enum traverse_order { POSTFIX, PREFIX };
698 
699   /* Reuse size, only used by SP local variable assignment, otherwize 0 */
700   uint rsize;
701 
702   /*
703     str_values's main purpose is to be used to cache the value in
704     save_in_field
705   */
706   String str_value;
707 
708   Item_name_string item_name;  /* Name from select */
709   Item_name_string orig_name;  /* Original item name (if it was renamed)*/
710 
711   /**
712      Intrusive list pointer for free list. If not null, points to the next
713      Item on some Query_arena's free list. For instance, stored procedures
714      have their own Query_arena's.
715 
716      @see Query_arena::free_list
717    */
718   Item *next;
719   uint32 max_length;                    /* Maximum length, in bytes */
720   /**
721      This member has several successive meanings, depending on the phase we're
722      in:
723      - during field resolution: it contains the index, in the "all_fields"
724      list, of the expression to which this field belongs; or a special
725      constant UNDEF_POS; see st_select_lex::cur_pos_in_all_fields and
726      match_exprs_for_only_full_group_by().
727      - when attaching conditions to tables: it says whether some condition
728      needs to be attached or can be omitted (for example because it is already
729      implemented by 'ref' access)
730      - when pushing index conditions: it says whether a condition uses only
731      indexed columns
732      - when creating an internal temporary table: it says how to store BIT
733      fields
734      - when we change DISTINCT to GROUP BY: it is used for book-keeping of
735      fields.
736   */
737   int marker;
738   uint8 decimals;
739   my_bool maybe_null;			/* If item may be null */
740   my_bool null_value;			/* if item is null */
741   my_bool unsigned_flag;
742   my_bool with_sum_func;
743   my_bool fixed;                        /* If item fixed with fix_fields */
744   DTCollation collation;
745   Item_result cmp_context;              /* Comparison context */
746   /*
747     If this item was created in runtime memroot,it cannot be used for
748     substitution in subquery transformation process
749    */
750   bool runtime_item;
751  protected:
752   my_bool with_subselect;               /* If this item is a subselect or some
753                                            of its arguments is or contains a
754                                            subselect. Computed by fix_fields
755                                            and updated by update_used_tables. */
756   my_bool with_stored_program;          /* If this item is a stored program
757                                            or some of its arguments is or
758                                            contains a stored program.
759                                            Computed by fix_fields and updated
760                                            by update_used_tables. */
761 
762   /**
763     This variable is a cache of 'Needed tables are locked'. True if either
764     'No tables locks is needed' or 'Needed tables are locked'.
765     If tables are used, then it will be set to
766     current_thd->lex->is_query_tables_locked().
767 
768     It is used when checking const_item()/can_be_evaluated_now().
769   */
770   bool tables_locked_cache;
771  public:
772   // alloc & destruct is done as start of select using sql_alloc
773   Item();
774   /*
775      Constructor used by Item_field, Item_ref & aggregate (sum) functions.
776      Used for duplicating lists in processing queries with temporary
777      tables
778      Also it used for Item_cond_and/Item_cond_or for creating
779      top AND/OR structure of WHERE clause to protect it of
780      optimisation changes in prepared statements
781   */
782   Item(THD *thd, Item *item);
~Item()783   virtual ~Item()
784   {
785 #ifdef EXTRA_DEBUG
786     item_name.set(0);
787 #endif
788   }		/*lint -e1509 */
789   void rename(char *new_name);
790   void init_make_field(Send_field *tmp_field,enum enum_field_types type);
791   virtual void cleanup();
792   virtual void make_field(Send_field *field);
793   virtual Field *make_string_field(TABLE *table);
794   virtual bool fix_fields(THD *, Item **);
795   /**
796     Fix after tables have been moved from one select_lex level to the parent
797     level, e.g by semijoin conversion.
798     Basically re-calculate all attributes dependent on the tables.
799 
800     @param parent_select  select_lex that tables are moved to.
801     @param removed_select select_lex that tables are moved away from,
802                           child of parent_select.
803   */
fix_after_pullout(st_select_lex * parent_select,st_select_lex * removed_select)804   virtual void fix_after_pullout(st_select_lex *parent_select,
805                                  st_select_lex *removed_select)
806   {};
807   /*
808     should be used in case where we are sure that we do not need
809     complete fix_fields() procedure.
810   */
quick_fix_field()811   inline void quick_fix_field() { fixed= 1; }
812   /* Function returns 1 on overflow and -1 on fatal errors */
813   type_conversion_status save_in_field_no_warnings(Field *field,
814                                                    bool no_conversions);
815   /**
816     Save a temporal value in packed longlong format into a Field.
817     Used in optimizer.
818     @param OUT field  The field to set the value to.
819     @retval 0         On success.
820     @retval >0        In error.
821   */
822   virtual type_conversion_status save_in_field(Field *field,
823                                                bool no_conversions);
save_org_in_field(Field * field)824   virtual void save_org_in_field(Field *field)
825   { (void) save_in_field(field, 1); }
save_safe_in_field(Field * field)826   virtual type_conversion_status save_safe_in_field(Field *field)
827   { return save_in_field(field, 1); }
828   virtual bool send(Protocol *protocol, String *str);
829   virtual bool eq(const Item *, bool binary_cmp) const;
result_type()830   virtual Item_result result_type() const { return REAL_RESULT; }
831   /**
832     Result type when an item appear in a numeric context.
833     See Field::numeric_context_result_type() for more comments.
834   */
numeric_context_result_type()835   virtual enum Item_result numeric_context_result_type() const
836   {
837     if (is_temporal())
838       return decimals ? DECIMAL_RESULT : INT_RESULT;
839     if (result_type() == STRING_RESULT)
840       return REAL_RESULT;
841     return result_type();
842   }
843   /**
844     Similar to result_type() but makes DATE, DATETIME, TIMESTAMP
845     pretend to be numbers rather than strings.
846   */
temporal_with_date_as_number_result_type()847   inline enum Item_result temporal_with_date_as_number_result_type() const
848   {
849     return is_temporal_with_date() ?
850            (decimals ? DECIMAL_RESULT : INT_RESULT) : result_type();
851   }
cast_to_int_type()852   virtual Item_result cast_to_int_type() const { return result_type(); }
853   virtual enum_field_types string_field_type() const;
854   virtual enum_field_types field_type() const;
855   virtual enum Type type() const =0;
856 
857   /*
858     Return information about function monotonicity. See comment for
859     enum_monotonicity_info for details. This function can only be called
860     after fix_fields() call.
861   */
get_monotonicity_info()862   virtual enum_monotonicity_info get_monotonicity_info() const
863   { return NON_MONOTONIC; }
864 
865   /*
866     Convert "func_arg $CMP$ const" half-interval into "FUNC(func_arg) $CMP2$ const2"
867 
868     SYNOPSIS
869       val_int_endpoint()
870         left_endp  FALSE  <=> The interval is "x < const" or "x <= const"
871                    TRUE   <=> The interval is "x > const" or "x >= const"
872 
873         incl_endp  IN   FALSE <=> the comparison is '<' or '>'
874                         TRUE  <=> the comparison is '<=' or '>='
875                    OUT  The same but for the "F(x) $CMP$ F(const)" comparison
876 
877     DESCRIPTION
878       This function is defined only for unary monotonic functions. The caller
879       supplies the source half-interval
880 
881          x $CMP$ const
882 
883       The value of const is supplied implicitly as the value this item's
884       argument, the form of $CMP$ comparison is specified through the
885       function's arguments. The calle returns the result interval
886 
887          F(x) $CMP2$ F(const)
888 
889       passing back F(const) as the return value, and the form of $CMP2$
890       through the out parameter. NULL values are assumed to be comparable and
891       be less than any non-NULL values.
892 
893     RETURN
894       The output range bound, which equal to the value of val_int()
895         - If the value of the function is NULL then the bound is the
896           smallest possible value of LONGLONG_MIN
897   */
val_int_endpoint(bool left_endp,bool * incl_endp)898   virtual longlong val_int_endpoint(bool left_endp, bool *incl_endp)
899   { DBUG_ASSERT(0); return 0; }
900 
901 
902   /* valXXX methods must return NULL or 0 or 0.0 if null_value is set. */
903   /*
904     Return double precision floating point representation of item.
905 
906     SYNOPSIS
907       val_real()
908 
909     RETURN
910       In case of NULL value return 0.0 and set null_value flag to TRUE.
911       If value is not null null_value flag will be reset to FALSE.
912   */
913   virtual double val_real()=0;
914   /*
915     Return integer representation of item.
916 
917     SYNOPSIS
918       val_int()
919 
920     RETURN
921       In case of NULL value return 0 and set null_value flag to TRUE.
922       If value is not null null_value flag will be reset to FALSE.
923   */
924   virtual longlong val_int()=0;
925   /**
926     Return date value of item in packed longlong format.
927   */
928   virtual longlong val_date_temporal();
929   /**
930     Return time value of item in packed longlong format.
931   */
932   virtual longlong val_time_temporal();
933   /**
934     Return date or time value of item in packed longlong format,
935     depending on item field type.
936   */
val_temporal_by_field_type()937   longlong val_temporal_by_field_type()
938   {
939     if (field_type() == MYSQL_TYPE_TIME)
940       return val_time_temporal();
941     DBUG_ASSERT(is_temporal_with_date());
942     return val_date_temporal();
943   }
944   /**
945     Get date or time value in packed longlong format.
946     Before conversion from MYSQL_TIME to packed format,
947     the MYSQL_TIME value is rounded to "dec" fractional digits.
948   */
949   longlong val_temporal_with_round(enum_field_types type, uint8 dec);
950 
951   /*
952     This is just a shortcut to avoid the cast. You should still use
953     unsigned_flag to check the sign of the item.
954   */
val_uint()955   inline ulonglong val_uint() { return (ulonglong) val_int(); }
956   /*
957     Return string representation of this item object.
958 
959     SYNOPSIS
960       val_str()
961       str   an allocated buffer this or any nested Item object can use to
962             store return value of this method.
963 
964     NOTE
965       Buffer passed via argument  should only be used if the item itself
966       doesn't have an own String buffer. In case when the item maintains
967       it's own string buffer, it's preferable to return it instead to
968       minimize number of mallocs/memcpys.
969       The caller of this method can modify returned string, but only in case
970       when it was allocated on heap, (is_alloced() is true).  This allows
971       the caller to efficiently use a buffer allocated by a child without
972       having to allocate a buffer of it's own. The buffer, given to
973       val_str() as argument, belongs to the caller and is later used by the
974       caller at it's own choosing.
975       A few implications from the above:
976       - unless you return a string object which only points to your buffer
977         but doesn't manages it you should be ready that it will be
978         modified.
979       - even for not allocated strings (is_alloced() == false) the caller
980         can change charset (see Item_func_{typecast/binary}. XXX: is this
981         a bug?
982       - still you should try to minimize data copying and return internal
983         object whenever possible.
984 
985     RETURN
986       In case of NULL value return 0 (NULL pointer) and set null_value flag
987       to TRUE.
988       If value is not null null_value flag will be reset to FALSE.
989   */
990   virtual String *val_str(String *str)=0;
991 
992   /*
993     Returns string representation of this item in ASCII format.
994 
995     SYNOPSIS
996       val_str_ascii()
997       str - similar to val_str();
998 
999     NOTE
1000       This method is introduced for performance optimization purposes.
1001 
1002       1. val_str() result of some Items in string context
1003       depends on @@character_set_results.
1004       @@character_set_results can be set to a "real multibyte" character
1005       set like UCS2, UTF16, UTF32. (We'll use only UTF32 in the examples
1006       below for convenience.)
1007 
1008       So the default string result of such functions
1009       in these circumstances is real multi-byte character set, like UTF32.
1010 
1011       For example, all numbers in string context
1012       return result in @@character_set_results:
1013 
1014       SELECT CONCAT(20010101); -> UTF32
1015 
1016       We do sprintf() first (to get ASCII representation)
1017       and then convert to UTF32;
1018 
1019       So these kind "data sources" can use ASCII representation
1020       internally, but return multi-byte data only because
1021       @@character_set_results wants so.
1022       Therefore, conversion from ASCII to UTF32 is applied internally.
1023 
1024 
1025       2. Some other functions need in fact ASCII input.
1026 
1027       For example,
1028         inet_aton(), GeometryFromText(), Convert_TZ(), GET_FORMAT().
1029 
1030       Similar, fields of certain type, like DATE, TIME,
1031       when you insert string data into them, expect in fact ASCII input.
1032       If they get non-ASCII input, for example UTF32, they
1033       convert input from UTF32 to ASCII, and then use ASCII
1034       representation to do further processing.
1035 
1036 
1037       3. Now imagine we pass result of a data source of the first type
1038          to a data destination of the second type.
1039 
1040       What happens:
1041         a. data source converts data from ASCII to UTF32, because
1042            @@character_set_results wants so and passes the result to
1043            data destination.
1044         b. data destination gets UTF32 string.
1045         c. data destination converts UTF32 string to ASCII,
1046            because it needs ASCII representation to be able to handle data
1047            correctly.
1048 
1049       As a result we get two steps of unnecessary conversion:
1050       From ASCII to UTF32, then from UTF32 to ASCII.
1051 
1052       A better way to handle these situations is to pass ASCII
1053       representation directly from the source to the destination.
1054 
1055       This is why val_str_ascii() introduced.
1056 
1057     RETURN
1058       Similar to val_str()
1059   */
1060   virtual String *val_str_ascii(String *str);
1061 
1062   /*
1063     Return decimal representation of item with fixed point.
1064 
1065     SYNOPSIS
1066       val_decimal()
1067       decimal_buffer  buffer which can be used by Item for returning value
1068                       (but can be not)
1069 
1070     NOTE
1071       Returned value should not be changed if it is not the same which was
1072       passed via argument.
1073 
1074     RETURN
1075       Return pointer on my_decimal (it can be other then passed via argument)
1076         if value is not NULL (null_value flag will be reset to FALSE).
1077       In case of NULL value it return 0 pointer and set null_value flag
1078         to TRUE.
1079   */
1080   virtual my_decimal *val_decimal(my_decimal *decimal_buffer)= 0;
1081   /*
1082     Return boolean value of item.
1083 
1084     RETURN
1085       FALSE value is false or NULL
1086       TRUE value is true (not equal to 0)
1087   */
1088   virtual bool val_bool();
val_nodeset(String *)1089   virtual String *val_nodeset(String*) { return 0; }
1090 
1091 protected:
1092   /* Helper functions, see item_sum.cc */
1093   String *val_string_from_real(String *str);
1094   String *val_string_from_int(String *str);
1095   String *val_string_from_decimal(String *str);
1096   String *val_string_from_date(String *str);
1097   String *val_string_from_datetime(String *str);
1098   String *val_string_from_time(String *str);
1099   my_decimal *val_decimal_from_real(my_decimal *decimal_value);
1100   my_decimal *val_decimal_from_int(my_decimal *decimal_value);
1101   my_decimal *val_decimal_from_string(my_decimal *decimal_value);
1102   my_decimal *val_decimal_from_date(my_decimal *decimal_value);
1103   my_decimal *val_decimal_from_time(my_decimal *decimal_value);
1104   longlong val_int_from_decimal();
1105   longlong val_int_from_date();
1106   longlong val_int_from_time();
1107   longlong val_int_from_datetime();
1108   double val_real_from_decimal();
1109 
1110   /**
1111     Convert val_str() to date in MYSQL_TIME
1112   */
1113   bool get_date_from_string(MYSQL_TIME *ltime, uint flags);
1114   /**
1115     Convert val_real() to date in MYSQL_TIME
1116   */
1117   bool get_date_from_real(MYSQL_TIME *ltime, uint flags);
1118   /**
1119     Convert val_decimal() to date in MYSQL_TIME
1120   */
1121   bool get_date_from_decimal(MYSQL_TIME *ltime, uint flags);
1122   /**
1123     Convert val_int() to date in MYSQL_TIME
1124   */
1125   bool get_date_from_int(MYSQL_TIME *ltime, uint flags);
1126   /**
1127     Convert get_time() from time to date in MYSQL_TIME
1128   */
1129   bool get_date_from_time(MYSQL_TIME *ltime);
1130 
1131   /**
1132     Convert a numeric type to date
1133   */
1134   bool get_date_from_numeric(MYSQL_TIME *ltime, uint fuzzydate);
1135 
1136   /**
1137     Convert a non-temporal type to date
1138   */
1139   bool get_date_from_non_temporal(MYSQL_TIME *ltime, uint fuzzydate);
1140 
1141   /**
1142     Convert val_str() to time in MYSQL_TIME
1143   */
1144   bool get_time_from_string(MYSQL_TIME *ltime);
1145   /**
1146     Convert val_real() to time in MYSQL_TIME
1147   */
1148   bool get_time_from_real(MYSQL_TIME *ltime);
1149   /**
1150     Convert val_decimal() to time in MYSQL_TIME
1151   */
1152   bool get_time_from_decimal(MYSQL_TIME *ltime);
1153   /**
1154     Convert val_int() to time in MYSQL_TIME
1155   */
1156   bool get_time_from_int(MYSQL_TIME *ltime);
1157   /**
1158     Convert date to time
1159   */
1160   bool get_time_from_date(MYSQL_TIME *ltime);
1161   /**
1162     Convert datetime to time
1163   */
1164   bool get_time_from_datetime(MYSQL_TIME *ltime);
1165 
1166   /**
1167     Convert a numeric type to time
1168   */
1169   bool get_time_from_numeric(MYSQL_TIME *ltime);
1170 
1171   /**
1172     Convert a non-temporal type to time
1173   */
1174   bool get_time_from_non_temporal(MYSQL_TIME *ltime);
1175 
1176 
1177 public:
1178 
1179   type_conversion_status save_time_in_field(Field *field);
1180   type_conversion_status save_date_in_field(Field *field);
1181   type_conversion_status save_str_value_in_field(Field *field, String *result);
1182 
get_tmp_table_field()1183   virtual Field *get_tmp_table_field() { return 0; }
1184   /* This is also used to create fields in CREATE ... SELECT: */
tmp_table_field(TABLE * t_arg)1185   virtual Field *tmp_table_field(TABLE *t_arg) { return 0; }
full_name()1186   virtual const char *full_name() const
1187   {
1188     return item_name.is_set() ? item_name.ptr() : "???";
1189   }
1190 
1191   /*
1192     *result* family of methods is analog of *val* family (see above) but
1193     return value of result_field of item if it is present. If Item have not
1194     result field, it return val(). This methods set null_value flag in same
1195     way as *val* methods do it.
1196   */
val_result()1197   virtual double  val_result() { return val_real(); }
val_int_result()1198   virtual longlong val_int_result() { return val_int(); }
1199   /**
1200     Get time value in packed longlong format. NULL is converted to 0.
1201   */
val_time_temporal_result()1202   virtual longlong val_time_temporal_result() { return val_time_temporal(); }
1203   /**
1204     Get date value in packed longlong format. NULL is converted to 0.
1205   */
val_date_temporal_result()1206   virtual longlong val_date_temporal_result() { return val_date_temporal(); }
str_result(String * tmp)1207   virtual String *str_result(String* tmp) { return val_str(tmp); }
val_decimal_result(my_decimal * val)1208   virtual my_decimal *val_decimal_result(my_decimal *val)
1209   { return val_decimal(val); }
val_bool_result()1210   virtual bool val_bool_result() { return val_bool(); }
is_null_result()1211   virtual bool is_null_result() { return is_null(); }
1212 
1213   /* bit map of tables used by item */
used_tables()1214   virtual table_map used_tables() const { return (table_map) 0L; }
1215   /*
1216     Return table map of tables that can't be NULL tables (tables that are
1217     used in a context where if they would contain a NULL row generated
1218     by a LEFT or RIGHT join, the item would not be true).
1219     This expression is used on WHERE item to determinate if a LEFT JOIN can be
1220     converted to a normal join.
1221     Generally this function should return used_tables() if the function
1222     would return null if any of the arguments are null
1223     As this is only used in the beginning of optimization, the value don't
1224     have to be updated in update_used_tables()
1225   */
not_null_tables()1226   virtual table_map not_null_tables() const { return used_tables(); }
1227   /*
1228     Returns true if this is a simple constant item like an integer, not
1229     a constant expression. Used in the optimizer to propagate basic constants.
1230   */
basic_const_item()1231   virtual bool basic_const_item() const { return 0; }
1232   /* cloning of constant items (0 if it is not const) */
clone_item()1233   virtual Item *clone_item() { return 0; }
eq_cmp_result()1234   virtual cond_result eq_cmp_result() const { return COND_OK; }
float_length(uint decimals_par)1235   inline uint float_length(uint decimals_par) const
1236   { return decimals != NOT_FIXED_DEC ? (DBL_DIG+2+decimals_par) : DBL_DIG+8;}
1237   virtual uint decimal_precision() const;
decimal_int_part()1238   inline int decimal_int_part() const
1239   { return my_decimal_int_part(decimal_precision(), decimals); }
1240   /**
1241     TIME precision of the item: 0..6
1242   */
1243   virtual uint time_precision();
1244   /**
1245     DATETIME precision of the item: 0..6
1246   */
1247   virtual uint datetime_precision();
1248   /*
1249     Returns true if this is constant (during query execution, i.e. its value
1250     will not change until next fix_fields) and its value is known.
1251     When the default implementation of used_tables() is effective, this
1252     function will always return true (because used_tables() is empty).
1253   */
const_item()1254   virtual bool const_item() const
1255   {
1256     if (used_tables() == 0)
1257       return can_be_evaluated_now();
1258     return false;
1259   }
1260   /*
1261     Returns true if this is constant but its value may be not known yet.
1262     (Can be used for parameters of prep. stmts or of stored procedures.)
1263   */
const_during_execution()1264   virtual bool const_during_execution() const
1265   { return (used_tables() & ~PARAM_TABLE_BIT) == 0; }
1266 
1267   /**
1268     This method is used for to:
1269       - to generate a view definition query (SELECT-statement);
1270       - to generate a SQL-query for EXPLAIN EXTENDED;
1271       - to generate a SQL-query to be shown in INFORMATION_SCHEMA;
1272       - debug.
1273 
1274     For more information about view definition query, INFORMATION_SCHEMA
1275     query and why they should be generated from the Item-tree, @see
1276     mysql_register_view().
1277   */
print(String * str,enum_query_type query_type)1278   virtual inline void print(String *str, enum_query_type query_type)
1279   {
1280     str->append(full_name());
1281   }
1282 
1283   void print_item_w_name(String *, enum_query_type query_type);
1284   /**
1285      Prints the item when it's part of ORDER BY and GROUP BY.
1286      @param  str            String to print to
1287      @param  query_type     How to format the item
1288      @param  used_alias     Whether item was referenced with alias.
1289   */
1290   void print_for_order(String *str, enum_query_type query_type,
1291                        bool used_alias);
1292 
update_used_tables()1293   virtual void update_used_tables() {}
split_sum_func(THD * thd,Ref_ptr_array ref_pointer_array,List<Item> & fields)1294   virtual void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array,
1295                               List<Item> &fields) {}
1296   /* Called for items that really have to be split */
1297   void split_sum_func2(THD *thd, Ref_ptr_array ref_pointer_array,
1298                        List<Item> &fields,
1299                        Item **ref, bool skip_registered);
1300   virtual bool get_date(MYSQL_TIME *ltime,uint fuzzydate)= 0;
1301   virtual bool get_time(MYSQL_TIME *ltime)= 0;
1302   /**
1303     Get timestamp in "struct timeval" format.
1304     @retval  false on success
1305     @retval  true  on error
1306   */
1307   virtual bool get_timeval(struct timeval *tm, int *warnings);
get_date_result(MYSQL_TIME * ltime,uint fuzzydate)1308   virtual bool get_date_result(MYSQL_TIME *ltime,uint fuzzydate)
1309   { return get_date(ltime,fuzzydate); }
1310   /*
1311     The method allows to determine nullness of a complex expression
1312     without fully evaluating it, instead of calling val/result*() then
1313     checking null_value. Used in Item_func_isnull/Item_func_isnotnull
1314     and Item_sum_count/Item_sum_count_distinct.
1315     Any new item which can be NULL must implement this method.
1316   */
is_null()1317   virtual bool is_null() { return 0; }
1318 
1319   /*
1320    Make sure the null_value member has a correct value.
1321   */
update_null_value()1322   virtual void update_null_value () { (void) val_int(); }
1323 
1324   /*
1325     Inform the item that there will be no distinction between its result
1326     being FALSE or NULL.
1327 
1328     NOTE
1329       This function will be called for eg. Items that are top-level AND-parts
1330       of the WHERE clause. Items implementing this function (currently
1331       Item_cond_and and subquery-related item) enable special optimizations
1332       when they are "top level".
1333   */
top_level_item()1334   virtual void top_level_item() {}
1335   /*
1336     set field of temporary table for Item which can be switched on temporary
1337     table during query processing (grouping and so on)
1338   */
set_result_field(Field * field)1339   virtual void set_result_field(Field *field) {}
is_result_field()1340   virtual bool is_result_field() { return 0; }
is_bool_func()1341   virtual bool is_bool_func() { return 0; }
save_in_result_field(bool no_conversions)1342   virtual void save_in_result_field(bool no_conversions) {}
1343   /*
1344     Set value of aggregate function in case of no rows for grouping were found.
1345     Also used for subqueries with outer references in SELECT list.
1346   */
no_rows_in_result()1347   virtual void no_rows_in_result() {}
copy_or_same(THD * thd)1348   virtual Item *copy_or_same(THD *thd) { return this; }
1349   /**
1350      @param real_items  True <=> in the copy, replace any Item_ref with its
1351      real_item()
1352      @todo this argument should be always false and removed in WL#7082.
1353   */
1354   virtual Item *copy_andor_structure(THD *thd, bool real_items= false)
1355   { return real_items ? real_item() : this; }
real_item()1356   virtual Item *real_item() { return this; }
substitutional_item()1357   virtual Item *substitutional_item()
1358   {
1359     return  runtime_item ? real_item() : this;
1360   }
set_runtime_created()1361   virtual void set_runtime_created() { runtime_item= true; }
get_tmp_table_item(THD * thd)1362   virtual Item *get_tmp_table_item(THD *thd) { return copy_or_same(thd); }
1363 
1364   static const CHARSET_INFO *default_charset();
compare_collation()1365   virtual const CHARSET_INFO *compare_collation() { return NULL; }
1366 
1367   /*
1368     For backward compatibility, to make numeric
1369     data types return "binary" charset in client-side metadata.
1370   */
charset_for_protocol(void)1371   virtual const CHARSET_INFO *charset_for_protocol(void) const
1372   {
1373     return result_type() == STRING_RESULT ? collation.collation :
1374                                             &my_charset_bin;
1375   };
1376 
walk(Item_processor processor,bool walk_subquery,uchar * arg)1377   virtual bool walk(Item_processor processor, bool walk_subquery, uchar *arg)
1378   {
1379     return (this->*processor)(arg);
1380   }
1381 
1382   virtual Item* transform(Item_transformer transformer, uchar *arg);
1383 
1384   /*
1385     This function performs a generic "compilation" of the Item tree.
1386     The process of compilation is assumed to go as follows:
1387 
1388     compile()
1389     {
1390       if (this->*some_analyzer(...))
1391       {
1392         compile children if any;
1393         return this->*some_transformer(...);
1394       }
1395       else
1396         return this;
1397     }
1398 
1399     i.e. analysis is performed top-down while transformation is done
1400     bottom-up. If no transformation is applied, the item is returned unchanged.
1401     A transformation error is indicated by returning a NULL pointer. Notice
1402     that the analyzer function should never cause an error.
1403   */
compile(Item_analyzer analyzer,uchar ** arg_p,Item_transformer transformer,uchar * arg_t)1404   virtual Item* compile(Item_analyzer analyzer, uchar **arg_p,
1405                         Item_transformer transformer, uchar *arg_t)
1406   {
1407     if ((this->*analyzer) (arg_p))
1408       return ((this->*transformer) (arg_t));
1409     return this;
1410   }
1411 
traverse_cond(Cond_traverser traverser,void * arg,traverse_order order)1412    virtual void traverse_cond(Cond_traverser traverser,
1413                               void *arg, traverse_order order)
1414    {
1415      (*traverser)(this, arg);
1416    }
1417 
1418   /*
1419     This is used to get the most recent version of any function in
1420     an item tree. The version is the version where a MySQL function
1421     was introduced in. So any function which is added should use
1422     this function and set the int_arg to maximum of the input data
1423     and their own version info.
1424   */
intro_version(uchar * int_arg)1425   virtual bool intro_version(uchar *int_arg) { return 0; }
1426 
remove_dependence_processor(uchar * arg)1427   virtual bool remove_dependence_processor(uchar * arg) { return 0; }
remove_fixed(uchar * arg)1428   virtual bool remove_fixed(uchar * arg) { fixed= 0; return 0; }
1429   virtual bool cleanup_processor(uchar *arg);
collect_item_field_processor(uchar * arg)1430   virtual bool collect_item_field_processor(uchar * arg) { return 0; }
add_field_to_set_processor(uchar * arg)1431   virtual bool add_field_to_set_processor(uchar * arg) { return 0; }
1432 
1433   /**
1434      Visitor interface for removing all column expressions (Item_field) in
1435      this expression tree from a bitmap. @See walk()
1436 
1437      @param arg  A MY_BITMAP* cast to unsigned char*, where the bits represent
1438                  Field::field_index values.
1439    */
remove_column_from_bitmap(uchar * arg)1440   virtual bool remove_column_from_bitmap(uchar *arg) { return false; }
find_item_in_field_list_processor(uchar * arg)1441   virtual bool find_item_in_field_list_processor(uchar *arg) { return 0; }
change_context_processor(uchar * context)1442   virtual bool change_context_processor(uchar *context) { return 0; }
reset_query_id_processor(uchar * query_id_arg)1443   virtual bool reset_query_id_processor(uchar *query_id_arg) { return 0; }
find_item_processor(uchar * arg)1444   virtual bool find_item_processor(uchar *arg) { return this == (void *) arg; }
register_field_in_read_map(uchar * arg)1445   virtual bool register_field_in_read_map(uchar *arg) { return 0; }
1446 /**
1447     Return used table information for the specified query block (level).
1448     For a field that is resolved from this query block, return the table number.
1449     For a field that is resolved from a query block outer to the specified one,
1450     return OUTER_REF_TABLE_BIT
1451 
1452     @param[in,out] arg pointer to an instance of class Used_tables, which is
1453                        constructed with the query block as argument.
1454                        The used tables information is accumulated in the field
1455                        used_tables in this class.
1456 
1457     @note This function is used to update used tables information after
1458           merging a query block (a subquery) with its parent.
1459   */
used_tables_for_level(uchar * arg)1460   virtual bool used_tables_for_level(uchar *arg) { return false; }
inform_item_in_cond_of_tab(uchar * join_tab_index)1461   virtual bool inform_item_in_cond_of_tab(uchar *join_tab_index) { return false; }
1462   /**
1463      Clean up after removing the item from the item tree.
1464 
1465      @param arg Pointer to the st_select_lex from which the walk started, i.e.,
1466                 the st_select_lex that contained the clause that was removed.
1467   */
clean_up_after_removal(uchar * arg)1468   virtual bool clean_up_after_removal(uchar *arg) { return false; }
1469 
1470   virtual bool cache_const_expr_analyzer(uchar **arg);
1471   virtual Item* cache_const_expr_transformer(uchar *arg);
1472 
1473   /**
1474      Analyzer for finding Item_field by name
1475 
1476      @param arg  Field name to search for
1477 
1478      @return TRUE Go deeper in item tree.  (Found Item or not an Item_field)
1479      @return FALSE Don't go deeper in item tree. (Item_field with other name)
1480   */
item_field_by_name_analyzer(uchar ** arg)1481   virtual bool item_field_by_name_analyzer(uchar **arg) { return true; };
1482 
1483   /**
1484      Simple transformer that returns the argument if this is an Item_field.
1485      The new item will inherit it's name to maintain aliases.
1486 
1487      @param arg Item to replace Item_field
1488 
1489      @return argument if this is an Item_field
1490      @return this otherwise.
1491   */
item_field_by_name_transformer(uchar * arg)1492   virtual Item* item_field_by_name_transformer(uchar *arg) { return this; }
1493 
equality_substitution_analyzer(uchar ** arg)1494   virtual bool equality_substitution_analyzer(uchar **arg) { return false; }
1495 
equality_substitution_transformer(uchar * arg)1496   virtual Item* equality_substitution_transformer(uchar *arg) { return this; }
1497 
1498   /*
1499     Check if a partition function is allowed
1500     SYNOPSIS
1501       check_partition_func_processor()
1502       int_arg                        Ignored
1503     RETURN VALUE
1504       TRUE                           Partition function not accepted
1505       FALSE                          Partition function accepted
1506 
1507     DESCRIPTION
1508     check_partition_func_processor is used to check if a partition function
1509     uses an allowed function. An allowed function will always ensure that
1510     X=Y guarantees that also part_function(X)=part_function(Y) where X is
1511     a set of partition fields and so is Y. The problems comes mainly from
1512     character sets where two equal strings can be quite unequal. E.g. the
1513     german character for double s is equal to 2 s.
1514 
1515     The default is that an item is not allowed
1516     in a partition function. Allowed functions
1517     can never depend on server version, they cannot depend on anything
1518     related to the environment. They can also only depend on a set of
1519     fields in the table itself. They cannot depend on other tables and
1520     cannot contain any queries and cannot contain udf's or similar.
1521     If a new Item class is defined and it inherits from a class that is
1522     allowed in a partition function then it is very important to consider
1523     whether this should be inherited to the new class. If not the function
1524     below should be defined in the new Item class.
1525 
1526     The general behaviour is that most integer functions are allowed.
1527     If the partition function contains any multi-byte collations then
1528     the function check_part_func_fields will report an error on the
1529     partition function independent of what functions are used. So the
1530     only character sets allowed are single character collation and
1531     even for those only a limited set of functions are allowed. The
1532     problem with multi-byte collations is that almost every string
1533     function has the ability to change things such that two strings
1534     that are equal will not be equal after manipulated by a string
1535     function. E.g. two strings one contains a double s, there is a
1536     special german character that is equal to two s. Now assume a
1537     string function removes one character at this place, then in
1538     one the double s will be removed and in the other there will
1539     still be one s remaining and the strings are no longer equal
1540     and thus the partition function will not sort equal strings into
1541     the same partitions.
1542 
1543     So the check if a partition function is valid is two steps. First
1544     check that the field types are valid, next check that the partition
1545     function is valid. The current set of partition functions valid
1546     assumes that there are no multi-byte collations amongst the partition
1547     fields.
1548   */
check_partition_func_processor(uchar * bool_arg)1549   virtual bool check_partition_func_processor(uchar *bool_arg) { return TRUE;}
subst_argument_checker(uchar ** arg)1550   virtual bool subst_argument_checker(uchar **arg)
1551   {
1552     if (*arg)
1553       *arg= NULL;
1554     return TRUE;
1555   }
explain_subquery_checker(uchar ** arg)1556   virtual bool explain_subquery_checker(uchar **arg) { return true; }
explain_subquery_propagator(uchar * arg)1557   virtual Item *explain_subquery_propagator(uchar *arg) { return this; }
1558 
equal_fields_propagator(uchar * arg)1559   virtual Item *equal_fields_propagator(uchar * arg) { return this; }
set_no_const_sub(uchar * arg)1560   virtual bool set_no_const_sub(uchar *arg) { return FALSE; }
replace_equal_field(uchar * arg)1561   virtual Item *replace_equal_field(uchar * arg) { return this; }
1562   /*
1563     Check if an expression value has allowed arguments, like DATE/DATETIME
1564     for date functions. Also used by partitioning code to reject
1565     timezone-dependent expressions in a (sub)partitioning function.
1566   */
check_valid_arguments_processor(uchar * bool_arg)1567   virtual bool check_valid_arguments_processor(uchar *bool_arg)
1568   {
1569     return FALSE;
1570   }
1571 
1572   /**
1573     Find a function of a given type
1574 
1575     @param   arg     the function type to search (enum Item_func::Functype)
1576     @return
1577       @retval TRUE   the function type we're searching for is found
1578       @retval FALSE  the function type wasn't found
1579 
1580     @description
1581       This function can be used (together with Item::walk()) to find functions
1582       in an item tree fragment.
1583   */
find_function_processor(uchar * arg)1584   virtual bool find_function_processor (uchar *arg)
1585   {
1586     return FALSE;
1587   }
1588 
1589   /*
1590     For SP local variable returns pointer to Item representing its
1591     current value and pointer to current Item otherwise.
1592   */
this_item()1593   virtual Item *this_item() { return this; }
this_item()1594   virtual const Item *this_item() const { return this; }
1595 
1596   /*
1597     For SP local variable returns address of pointer to Item representing its
1598     current value and pointer passed via parameter otherwise.
1599   */
this_item_addr(THD * thd,Item ** addr_arg)1600   virtual Item **this_item_addr(THD *thd, Item **addr_arg) { return addr_arg; }
1601 
1602   // Row emulation
cols()1603   virtual uint cols() { return 1; }
element_index(uint i)1604   virtual Item* element_index(uint i) { return this; }
addr(uint i)1605   virtual Item** addr(uint i) { return 0; }
1606   virtual bool check_cols(uint c);
1607   // It is not row => null inside is impossible
null_inside()1608   virtual bool null_inside() { return 0; }
1609   // used in row subselects to get value of elements
bring_value()1610   virtual void bring_value() {}
1611 
1612   Field *tmp_table_field_from_field_type(TABLE *table, bool fixed_length);
field_for_view_update()1613   virtual Item_field *field_for_view_update() { return 0; }
1614 
neg_transformer(THD * thd)1615   virtual Item *neg_transformer(THD *thd) { return NULL; }
update_value_transformer(uchar * select_arg)1616   virtual Item *update_value_transformer(uchar *select_arg) { return this; }
1617   virtual Item *safe_charset_converter(const CHARSET_INFO *tocs);
delete_self()1618   void delete_self()
1619   {
1620     cleanup();
1621     delete this;
1622   }
1623 
is_splocal()1624   virtual bool is_splocal() { return 0; } /* Needed for error checking */
1625 
1626   /*
1627     Return Settable_routine_parameter interface of the Item.  Return 0
1628     if this Item is not Settable_routine_parameter.
1629   */
get_settable_routine_parameter()1630   virtual Settable_routine_parameter *get_settable_routine_parameter()
1631   {
1632     return 0;
1633   }
is_temporal_with_date()1634   inline bool is_temporal_with_date() const
1635   {
1636     return is_temporal_type_with_date(field_type());
1637   }
is_temporal_with_date_and_time()1638   inline bool is_temporal_with_date_and_time() const
1639   {
1640     return is_temporal_type_with_date_and_time(field_type());
1641   }
is_temporal_with_time()1642   inline bool is_temporal_with_time() const
1643   {
1644     return is_temporal_type_with_time(field_type());
1645   }
is_temporal()1646   inline bool is_temporal() const
1647   {
1648     return is_temporal_type(field_type());
1649   }
1650   /**
1651     Check whether this and the given item has compatible comparison context.
1652     Used by the equality propagation. See Item_field::equal_fields_propagator.
1653 
1654     @return
1655       TRUE  if the context is the same or if fields could be
1656             compared as DATETIME values by the Arg_comparator.
1657       FALSE otherwise.
1658   */
has_compatible_context(Item * item)1659   inline bool has_compatible_context(Item *item) const
1660   {
1661     /* Same context. */
1662     if (cmp_context == (Item_result)-1 || item->cmp_context == cmp_context)
1663       return TRUE;
1664     /* DATETIME comparison context. */
1665     if (is_temporal_with_date())
1666       return item->is_temporal_with_date() ||
1667              item->cmp_context == STRING_RESULT;
1668     if (item->is_temporal_with_date())
1669       return is_temporal_with_date() || cmp_context == STRING_RESULT;
1670     return FALSE;
1671   }
get_geometry_type()1672   virtual Field::geometry_type get_geometry_type() const
1673     { return Field::GEOM_GEOMETRY; };
1674   String *check_well_formed_result(String *str,
1675                                    bool send_error,
1676                                    bool truncate);
1677   bool eq_by_collation(Item *item, bool binary_cmp, const CHARSET_INFO *cs);
1678 
1679   /*
1680     Test whether an expression is expensive to compute. Used during
1681     optimization to avoid computing expensive expressions during this
1682     phase. Also used to force temp tables when sorting on expensive
1683     functions.
1684     TODO:
1685     Normally we should have a method:
1686       cost Item::execution_cost(),
1687     where 'cost' is either 'double' or some structure of various cost
1688     parameters.
1689   */
is_expensive()1690   virtual bool is_expensive()
1691   {
1692     if (is_expensive_cache < 0)
1693       is_expensive_cache= walk(&Item::is_expensive_processor, 0, (uchar*)0);
1694     return MY_TEST(is_expensive_cache);
1695   }
1696   virtual bool can_be_evaluated_now() const;
max_char_length()1697   uint32 max_char_length() const
1698   { return max_length / collation.collation->mbmaxlen; }
fix_length_and_charset(uint32 max_char_length_arg,const CHARSET_INFO * cs)1699   void fix_length_and_charset(uint32 max_char_length_arg,
1700                               const CHARSET_INFO *cs)
1701   {
1702     max_length= char_to_byte_length_safe(max_char_length_arg, cs->mbmaxlen);
1703     collation.collation= cs;
1704   }
fix_char_length(uint32 max_char_length_arg)1705   void fix_char_length(uint32 max_char_length_arg)
1706   {
1707     max_length= char_to_byte_length_safe(max_char_length_arg,
1708                                          collation.collation->mbmaxlen);
1709   }
fix_char_length_ulonglong(ulonglong max_char_length_arg)1710   void fix_char_length_ulonglong(ulonglong max_char_length_arg)
1711   {
1712     ulonglong max_result_length= max_char_length_arg *
1713                                  collation.collation->mbmaxlen;
1714     if (max_result_length >= MAX_BLOB_WIDTH)
1715     {
1716       max_length= MAX_BLOB_WIDTH;
1717       maybe_null= 1;
1718     }
1719     else
1720       max_length= (uint32) max_result_length;
1721   }
fix_length_and_charset_datetime(uint32 max_char_length_arg)1722   void fix_length_and_charset_datetime(uint32 max_char_length_arg)
1723   {
1724     collation.set(&my_charset_numeric, DERIVATION_NUMERIC, MY_REPERTOIRE_ASCII);
1725     fix_char_length(max_char_length_arg);
1726   }
fix_length_and_dec_and_charset_datetime(uint32 max_char_length_arg,uint8 dec_arg)1727   void fix_length_and_dec_and_charset_datetime(uint32 max_char_length_arg,
1728                                                uint8 dec_arg)
1729   {
1730     decimals= dec_arg;
1731     fix_length_and_charset_datetime(max_char_length_arg +
1732                                     (dec_arg ? dec_arg + 1 : 0));
1733   }
1734   /*
1735     Return TRUE if the item points to a column of an outer-joined table.
1736   */
is_outer_field()1737   virtual bool is_outer_field() const { DBUG_ASSERT(fixed); return FALSE; }
1738 
1739   /**
1740      Check if an item either is a blob field, or will be represented as a BLOB
1741      field if a field is created based on this item.
1742 
1743      @retval TRUE  If a field based on this item will be a BLOB field,
1744      @retval FALSE Otherwise.
1745   */
1746   bool is_blob_field() const;
1747 
1748   /**
1749     Checks if this item or any of its decendents contains a subquery.
1750   */
has_subquery()1751   virtual bool has_subquery() const { return with_subselect; }
has_stored_program()1752   virtual bool has_stored_program() const { return with_stored_program; }
1753   /// Whether this Item was created by the IN->EXISTS subquery transformation
created_by_in2exists()1754   virtual bool created_by_in2exists() const { return false; }
1755 };
1756 
1757 
1758 class sp_head;
1759 
1760 
1761 class Item_basic_constant :public Item
1762 {
1763   table_map used_table_map;
1764 public:
Item_basic_constant()1765   Item_basic_constant(): Item(), used_table_map(0) {};
set_used_tables(table_map map)1766   void set_used_tables(table_map map) { used_table_map= map; }
used_tables()1767   table_map used_tables() const { return used_table_map; }
1768   /* to prevent drop fixed flag (no need parent cleanup call) */
cleanup()1769   void cleanup()
1770   {
1771     /*
1772       Restore the original field name as it might not have been allocated
1773       in the statement memory. If the name is auto generated, it must be
1774       done again between subsequent executions of a prepared statement.
1775     */
1776     if (orig_name.is_set())
1777       item_name= orig_name;
1778   }
1779 };
1780 
1781 
1782 /*****************************************************************************
1783   The class is a base class for representation of stored routine variables in
1784   the Item-hierarchy. There are the following kinds of SP-vars:
1785     - local variables (Item_splocal);
1786     - CASE expression (Item_case_expr);
1787 *****************************************************************************/
1788 
1789 class Item_sp_variable :public Item
1790 {
1791 protected:
1792   /*
1793     THD, which is stored in fix_fields() and is used in this_item() to avoid
1794     current_thd use.
1795   */
1796   THD *m_thd;
1797 
1798 public:
1799   Name_string m_name;
1800 
1801 public:
1802 #ifndef DBUG_OFF
1803   /*
1804     Routine to which this Item_splocal belongs. Used for checking if correct
1805     runtime context is used for variable handling.
1806   */
1807   sp_head *m_sp;
1808 #endif
1809 
1810 public:
1811   Item_sp_variable(const Name_string sp_var_name);
1812 
1813 public:
1814   bool fix_fields(THD *thd, Item **);
1815 
1816   double val_real();
1817   longlong val_int();
1818   String *val_str(String *sp);
1819   my_decimal *val_decimal(my_decimal *decimal_value);
1820   bool get_date(MYSQL_TIME *ltime, uint fuzzydate);
1821   bool get_time(MYSQL_TIME *ltime);
1822   bool is_null();
1823 
1824 public:
1825   inline void make_field(Send_field *field);
1826   inline type_conversion_status save_in_field(Field *field,
1827                                               bool no_conversions);
1828   inline bool send(Protocol *protocol, String *str);
1829 };
1830 
1831 /*****************************************************************************
1832   Item_sp_variable inline implementation.
1833 *****************************************************************************/
1834 
make_field(Send_field * field)1835 inline void Item_sp_variable::make_field(Send_field *field)
1836 {
1837   Item *it= this_item();
1838   it->item_name.copy(item_name.is_set() ? item_name : m_name);
1839   it->make_field(field);
1840 }
1841 
1842 inline type_conversion_status
save_in_field(Field * field,bool no_conversions)1843 Item_sp_variable::save_in_field(Field *field, bool no_conversions)
1844 {
1845   return this_item()->save_in_field(field, no_conversions);
1846 }
1847 
send(Protocol * protocol,String * str)1848 inline bool Item_sp_variable::send(Protocol *protocol, String *str)
1849 {
1850   return this_item()->send(protocol, str);
1851 }
1852 
1853 
1854 /*****************************************************************************
1855   A reference to local SP variable (incl. reference to SP parameter), used in
1856   runtime.
1857 *****************************************************************************/
1858 
1859 class Item_splocal :public Item_sp_variable,
1860                     private Settable_routine_parameter
1861 {
1862   uint m_var_idx;
1863 
1864   Type m_type;
1865   Item_result m_result_type;
1866   enum_field_types m_field_type;
1867 public:
1868   /*
1869     If this variable is a parameter in LIMIT clause.
1870     Used only during NAME_CONST substitution, to not append
1871     NAME_CONST to the resulting query and thus not break
1872     the slave.
1873   */
1874   bool limit_clause_param;
1875   /*
1876     Position of this reference to SP variable in the statement (the
1877     statement itself is in sp_instr_stmt::m_query).
1878     This is valid only for references to SP variables in statements,
1879     excluding DECLARE CURSOR statement. It is used to replace references to SP
1880     variables with NAME_CONST calls when putting statements into the binary
1881     log.
1882     Value of 0 means that this object doesn't corresponding to reference to
1883     SP variable in query text.
1884   */
1885   uint pos_in_query;
1886   /*
1887     Byte length of SP variable name in the statement (see pos_in_query).
1888     The value of this field may differ from the name_length value because
1889     name_length contains byte length of UTF8-encoded item name, but
1890     the query string (see sp_instr_stmt::m_query) is currently stored with
1891     a charset from the SET NAMES statement.
1892   */
1893   uint len_in_query;
1894 
1895   Item_splocal(const Name_string sp_var_name, uint sp_var_idx,
1896                enum_field_types sp_var_type,
1897                uint pos_in_q= 0, uint len_in_q= 0);
1898 
is_splocal()1899   bool is_splocal() { return 1; } /* Needed for error checking */
1900 
1901   Item *this_item();
1902   const Item *this_item() const;
1903   Item **this_item_addr(THD *thd, Item **);
1904 
1905   virtual void print(String *str, enum_query_type query_type);
1906 
1907 public:
1908   inline uint get_var_idx() const;
1909 
1910   inline enum Type type() const;
1911   inline Item_result result_type() const;
field_type()1912   inline enum_field_types field_type() const { return m_field_type; }
1913 
1914 private:
1915   bool set_value(THD *thd, sp_rcontext *ctx, Item **it);
1916 
1917 public:
get_settable_routine_parameter()1918   Settable_routine_parameter *get_settable_routine_parameter()
1919   {
1920     return this;
1921   }
1922 };
1923 
1924 /*****************************************************************************
1925   Item_splocal inline implementation.
1926 *****************************************************************************/
1927 
get_var_idx()1928 inline uint Item_splocal::get_var_idx() const
1929 {
1930   return m_var_idx;
1931 }
1932 
type()1933 inline enum Item::Type Item_splocal::type() const
1934 {
1935   return m_type;
1936 }
1937 
result_type()1938 inline Item_result Item_splocal::result_type() const
1939 {
1940   return m_result_type;
1941 }
1942 
1943 
1944 /*****************************************************************************
1945   A reference to case expression in SP, used in runtime.
1946 *****************************************************************************/
1947 
1948 class Item_case_expr :public Item_sp_variable
1949 {
1950 public:
1951   Item_case_expr(uint case_expr_id);
1952 
1953 public:
1954   Item *this_item();
1955   const Item *this_item() const;
1956   Item **this_item_addr(THD *thd, Item **);
1957 
1958   inline enum Type type() const;
1959   inline Item_result result_type() const;
1960 
1961 public:
1962   /*
1963     NOTE: print() is intended to be used from views and for debug.
1964     Item_case_expr can not occur in views, so here it is only for debug
1965     purposes.
1966   */
1967   virtual void print(String *str, enum_query_type query_type);
1968 
1969 private:
1970   uint m_case_expr_id;
1971 };
1972 
1973 /*****************************************************************************
1974   Item_case_expr inline implementation.
1975 *****************************************************************************/
1976 
type()1977 inline enum Item::Type Item_case_expr::type() const
1978 {
1979   return this_item()->type();
1980 }
1981 
result_type()1982 inline Item_result Item_case_expr::result_type() const
1983 {
1984   return this_item()->result_type();
1985 }
1986 
1987 
1988 /*
1989   NAME_CONST(given_name, const_value).
1990   This 'function' has all properties of the supplied const_value (which is
1991   assumed to be a literal constant), and the name given_name.
1992 
1993   This is used to replace references to SP variables when we write PROCEDURE
1994   statements into the binary log.
1995 
1996   TODO
1997     Together with Item_splocal and Item::this_item() we can actually extract
1998     common a base of this class and Item_splocal. Maybe it is possible to
1999     extract a common base with class Item_ref, too.
2000 */
2001 
2002 class Item_name_const : public Item
2003 {
2004   Item *value_item;
2005   Item *name_item;
2006   bool valid_args;
2007 public:
2008   Item_name_const(Item *name_arg, Item *val);
2009 
2010   bool fix_fields(THD *, Item **);
2011 
2012   enum Type type() const;
2013   double val_real();
2014   longlong val_int();
2015   String *val_str(String *sp);
2016   my_decimal *val_decimal(my_decimal *);
2017   bool get_date(MYSQL_TIME *ltime, uint fuzzydate);
2018   bool get_time(MYSQL_TIME *ltime);
2019   bool is_null();
2020   virtual void print(String *str, enum_query_type query_type);
2021 
result_type()2022   Item_result result_type() const
2023   {
2024     return value_item->result_type();
2025   }
2026 
cache_const_expr_analyzer(uchar ** arg)2027   virtual bool cache_const_expr_analyzer(uchar **arg)
2028   {
2029     // Item_name_const always wraps a literal, so there is no need to cache it.
2030     return false;
2031   }
2032 
save_in_field(Field * field,bool no_conversions)2033   type_conversion_status save_in_field(Field *field, bool no_conversions)
2034   {
2035     return  value_item->save_in_field(field, no_conversions);
2036   }
2037 
send(Protocol * protocol,String * str)2038   bool send(Protocol *protocol, String *str)
2039   {
2040     return value_item->send(protocol, str);
2041   }
2042 };
2043 
2044 bool agg_item_collations(DTCollation &c, const char *name,
2045                          Item **items, uint nitems, uint flags, int item_sep);
2046 bool agg_item_collations_for_comparison(DTCollation &c, const char *name,
2047                                         Item **items, uint nitems, uint flags);
2048 bool agg_item_set_converter(DTCollation &coll, const char *fname,
2049                             Item **args, uint nargs, uint flags, int item_sep);
2050 bool agg_item_charsets(DTCollation &c, const char *name,
2051                        Item **items, uint nitems, uint flags, int item_sep);
2052 inline bool
2053 agg_item_charsets_for_string_result(DTCollation &c, const char *name,
2054                                     Item **items, uint nitems,
2055                                     int item_sep= 1)
2056 {
2057   uint flags= MY_COLL_ALLOW_SUPERSET_CONV |
2058               MY_COLL_ALLOW_COERCIBLE_CONV |
2059               MY_COLL_ALLOW_NUMERIC_CONV;
2060   return agg_item_charsets(c, name, items, nitems, flags, item_sep);
2061 }
2062 inline bool
2063 agg_item_charsets_for_comparison(DTCollation &c, const char *name,
2064                                  Item **items, uint nitems,
2065                                  int item_sep= 1)
2066 {
2067   uint flags= MY_COLL_ALLOW_SUPERSET_CONV |
2068               MY_COLL_ALLOW_COERCIBLE_CONV |
2069               MY_COLL_DISALLOW_NONE;
2070   return agg_item_charsets(c, name, items, nitems, flags, item_sep);
2071 }
2072 inline bool
2073 agg_item_charsets_for_string_result_with_comparison(DTCollation &c,
2074                                                     const char *name,
2075                                                     Item **items, uint nitems,
2076                                                     int item_sep= 1)
2077 {
2078   uint flags= MY_COLL_ALLOW_SUPERSET_CONV |
2079               MY_COLL_ALLOW_COERCIBLE_CONV |
2080               MY_COLL_ALLOW_NUMERIC_CONV |
2081               MY_COLL_DISALLOW_NONE;
2082   return agg_item_charsets(c, name, items, nitems, flags, item_sep);
2083 }
2084 
2085 
2086 class Item_num: public Item_basic_constant
2087 {
2088 public:
Item_num()2089   Item_num() { collation.set_numeric(); } /* Remove gcc warning */
2090   virtual Item_num *neg()= 0;
2091   Item *safe_charset_converter(const CHARSET_INFO *tocs);
check_partition_func_processor(uchar * int_arg)2092   bool check_partition_func_processor(uchar *int_arg) { return FALSE;}
2093 };
2094 
2095 #define NO_CACHED_FIELD_INDEX ((uint)(-1))
2096 
2097 class st_select_lex;
2098 class Item_ident :public Item
2099 {
2100 protected:
2101   /*
2102     We have to store initial values of db_name, table_name and field_name
2103     to be able to restore them during cleanup() because they can be
2104     updated during fix_fields() to values from Field object and life-time
2105     of those is shorter than life-time of Item_field.
2106   */
2107   const char *orig_db_name;
2108   const char *orig_table_name;
2109   const char *orig_field_name;
2110 
2111 public:
2112   Name_resolution_context *context;
2113   const char *db_name;
2114   const char *table_name;
2115   const char *field_name;
2116   bool alias_name_used; /* true if item was resolved against alias */
2117   /*
2118     Cached value of index for this field in table->field array, used by prep.
2119     stmts for speeding up their re-execution. Holds NO_CACHED_FIELD_INDEX
2120     if index value is not known.
2121   */
2122   uint cached_field_index;
2123   /*
2124     Cached pointer to table which contains this field, used for the same reason
2125     by prep. stmt. too in case then we have not-fully qualified field.
2126     0 - means no cached value.
2127   */
2128   TABLE_LIST *cached_table;
2129   st_select_lex *depended_from;
2130   Item_ident(Name_resolution_context *context_arg,
2131              const char *db_name_arg, const char *table_name_arg,
2132              const char *field_name_arg);
2133   Item_ident(THD *thd, Item_ident *item);
2134   const char *full_name() const;
2135   virtual void fix_after_pullout(st_select_lex *parent_select,
2136                                  st_select_lex *removed_select);
2137   void cleanup();
2138   bool remove_dependence_processor(uchar * arg);
print(String * str,enum_query_type query_type)2139   virtual void print(String *str, enum_query_type query_type)
2140   {
2141     print(str, query_type, db_name, table_name);
2142   }
2143 protected:
2144   /**
2145     Function to print column name for a table
2146 
2147     To print a column for a permanent table (picks up database and table from
2148     Item_ident object):
2149 
2150        item->print(str, qt)
2151 
2152     To print a column for a temporary table:
2153 
2154        item->print(str, qt, specific_db, specific_table)
2155 
2156     Items of temporary table fields have empty/NULL values of table_name and
2157     db_name. To print column names in a 3D form (`database`.`table`.`column`),
2158     this function prints db_name_arg and table_name_arg parameters instead of
2159     this->db_name and this->table_name respectively.
2160 
2161     @param [out] str            Output string buffer.
2162     @param       query_type     Bitmap to control printing details.
2163     @param       db_name_arg    String to output as a column database name.
2164     @param       table_name_arg String to output as a column table name.
2165   */
2166   void print(String *str, enum_query_type query_type,
2167              const char *db_name_arg,
2168              const char *table_name_arg) const;
2169 public:
change_context_processor(uchar * cntx)2170   virtual bool change_context_processor(uchar *cntx)
2171     { context= (Name_resolution_context *)cntx; return FALSE; }
2172   friend bool insert_fields(THD *thd, Name_resolution_context *context,
2173                             const char *db_name,
2174                             const char *table_name, List_iterator<Item> *it,
2175                             bool any_privileges);
2176 };
2177 
2178 
2179 class Item_ident_for_show :public Item
2180 {
2181 public:
2182   Field *field;
2183   const char *db_name;
2184   const char *table_name;
2185 
Item_ident_for_show(Field * par_field,const char * db_arg,const char * table_name_arg)2186   Item_ident_for_show(Field *par_field, const char *db_arg,
2187                       const char *table_name_arg)
2188     :field(par_field), db_name(db_arg), table_name(table_name_arg)
2189   {}
2190 
type()2191   enum Type type() const { return FIELD_ITEM; }
val_real()2192   double val_real() { return field->val_real(); }
val_int()2193   longlong val_int() { return field->val_int(); }
val_str(String * str)2194   String *val_str(String *str) { return field->val_str(str); }
val_decimal(my_decimal * dec)2195   my_decimal *val_decimal(my_decimal *dec) { return field->val_decimal(dec); }
get_date(MYSQL_TIME * ltime,uint fuzzydate)2196   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
2197   {
2198     return field->get_date(ltime, fuzzydate);
2199   }
get_time(MYSQL_TIME * ltime)2200   bool get_time(MYSQL_TIME *ltime)
2201   {
2202     return field->get_time(ltime);
2203   }
2204   void make_field(Send_field *tmp_field);
charset_for_protocol(void)2205   CHARSET_INFO *charset_for_protocol(void) const
2206   { return (CHARSET_INFO *)field->charset_for_protocol(); }
2207 };
2208 
2209 
2210 class Item_equal;
2211 class COND_EQUAL;
2212 
2213 class Item_field :public Item_ident
2214 {
2215 protected:
2216   void set_field(Field *field);
2217 public:
2218   Field *field,*result_field;
2219   Item_equal *item_equal;
2220   bool no_const_subst;
2221   /*
2222     if any_privileges set to TRUE then here real effective privileges will
2223     be stored
2224   */
2225   uint have_privileges;
2226   /* field need any privileges (for VIEW creation) */
2227   bool any_privileges;
2228   Item_field(Name_resolution_context *context_arg,
2229              const char *db_arg,const char *table_name_arg,
2230 	     const char *field_name_arg);
2231   /*
2232     Constructor needed to process subquery with temporary tables (see Item).
2233     Notice that it will have no name resolution context.
2234   */
2235   Item_field(THD *thd, Item_field *item);
2236   /*
2237     Ensures that field, table, and database names will live as long as
2238     Item_field (this is important in prepared statements).
2239   */
2240   Item_field(THD *thd, Name_resolution_context *context_arg, Field *field);
2241   /*
2242     If this constructor is used, fix_fields() won't work, because
2243     db_name, table_name and column_name are unknown. It's necessary to call
2244     reset_field() before fix_fields() for all fields created this way.
2245   */
2246   Item_field(Field *field);
type()2247   enum Type type() const { return FIELD_ITEM; }
2248   bool eq(const Item *item, bool binary_cmp) const;
2249   double val_real();
2250   longlong val_int();
2251   longlong val_time_temporal();
2252   longlong val_date_temporal();
2253   my_decimal *val_decimal(my_decimal *);
2254   String *val_str(String*);
2255   double val_result();
2256   longlong val_int_result();
2257   longlong val_time_temporal_result();
2258   longlong val_date_temporal_result();
2259   String *str_result(String* tmp);
2260   my_decimal *val_decimal_result(my_decimal *);
2261   bool val_bool_result();
2262   bool is_null_result();
2263   bool send(Protocol *protocol, String *str_arg);
2264   void reset_field(Field *f);
2265   bool fix_fields(THD *, Item **);
2266   void make_field(Send_field *tmp_field);
2267   type_conversion_status save_in_field(Field *field,bool no_conversions);
2268   void save_org_in_field(Field *field);
2269   table_map used_tables() const;
result_type()2270   enum Item_result result_type () const
2271   {
2272     return field->result_type();
2273   }
numeric_context_result_type()2274   enum Item_result numeric_context_result_type() const
2275   {
2276     return field->numeric_context_result_type();
2277   }
cast_to_int_type()2278   Item_result cast_to_int_type() const
2279   {
2280     return field->cast_to_int_type();
2281   }
field_type()2282   enum_field_types field_type() const
2283   {
2284     return field->type();
2285   }
get_monotonicity_info()2286   enum_monotonicity_info get_monotonicity_info() const
2287   {
2288     return MONOTONIC_STRICT_INCREASING;
2289   }
2290   longlong val_int_endpoint(bool left_endp, bool *incl_endp);
get_tmp_table_field()2291   Field *get_tmp_table_field() { return result_field; }
tmp_table_field(TABLE * t_arg)2292   Field *tmp_table_field(TABLE *t_arg) { return result_field; }
2293   bool get_date(MYSQL_TIME *ltime,uint fuzzydate);
2294   bool get_date_result(MYSQL_TIME *ltime,uint fuzzydate);
2295   bool get_time(MYSQL_TIME *ltime);
2296   bool get_timeval(struct timeval *tm, int *warnings);
is_null()2297   bool is_null() { return field->is_null(); }
2298   void update_null_value();
2299   Item *get_tmp_table_item(THD *thd);
2300   bool collect_item_field_processor(uchar * arg);
2301   bool add_field_to_set_processor(uchar * arg);
2302   bool remove_column_from_bitmap(uchar * arg);
2303   bool find_item_in_field_list_processor(uchar *arg);
2304   bool used_tables_for_level(uchar *arg);
2305   bool register_field_in_read_map(uchar *arg);
check_partition_func_processor(uchar * int_arg)2306   bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
2307   void cleanup();
2308   Item_equal *find_item_equal(COND_EQUAL *cond_equal);
2309   bool subst_argument_checker(uchar **arg);
2310   Item *equal_fields_propagator(uchar *arg);
2311   bool set_no_const_sub(uchar *arg);
2312   Item *replace_equal_field(uchar *arg);
max_disp_length()2313   inline uint32 max_disp_length() { return field->max_display_length(); }
field_for_view_update()2314   Item_field *field_for_view_update() { return this; }
2315   Item *safe_charset_converter(const CHARSET_INFO *tocs);
2316   int fix_outer_field(THD *thd, Field **field, Item **reference);
2317   virtual Item *update_value_transformer(uchar *select_arg);
2318   virtual bool item_field_by_name_analyzer(uchar **arg);
2319   virtual Item* item_field_by_name_transformer(uchar *arg);
2320   virtual void print(String *str, enum_query_type query_type);
is_outer_field()2321   bool is_outer_field() const
2322   {
2323     DBUG_ASSERT(fixed);
2324     return field->table->pos_in_table_list->outer_join ||
2325            field->table->pos_in_table_list->outer_join_nest();
2326   }
get_geometry_type()2327   Field::geometry_type get_geometry_type() const
2328   {
2329     DBUG_ASSERT(field_type() == MYSQL_TYPE_GEOMETRY);
2330     return field->get_geometry_type();
2331   }
charset_for_protocol(void)2332   const CHARSET_INFO *charset_for_protocol(void) const
2333   { return field->charset_for_protocol(); }
2334 
2335 #ifndef DBUG_OFF
dbug_print()2336   void dbug_print()
2337   {
2338     fprintf(DBUG_FILE, "<field ");
2339     if (field)
2340     {
2341       fprintf(DBUG_FILE, "'%s.%s': ", field->table->alias, field->field_name);
2342       field->dbug_print();
2343     }
2344     else
2345       fprintf(DBUG_FILE, "NULL");
2346 
2347     fprintf(DBUG_FILE, ", result_field: ");
2348     if (result_field)
2349     {
2350       fprintf(DBUG_FILE, "'%s.%s': ",
2351               result_field->table->alias, result_field->field_name);
2352       result_field->dbug_print();
2353     }
2354     else
2355       fprintf(DBUG_FILE, "NULL");
2356     fprintf(DBUG_FILE, ">\n");
2357   }
2358 #endif
2359 
2360   /// Pushes the item to select_lex.non_agg_fields() and updates its marker.
2361   bool push_to_non_agg_fields(st_select_lex *select_lex);
2362 
2363   friend class Item_default_value;
2364   friend class Item_insert_value;
2365   friend class st_select_lex_unit;
2366 };
2367 
2368 class Item_null :public Item_basic_constant
2369 {
init()2370   void init()
2371   {
2372     maybe_null= null_value= TRUE;
2373     max_length= 0;
2374     fixed= 1;
2375     collation.set(&my_charset_bin, DERIVATION_IGNORABLE);
2376   }
2377 public:
Item_null()2378   Item_null()
2379   {
2380     init();
2381     item_name= NAME_STRING("NULL");
2382   }
Item_null(const Name_string & name_par)2383   Item_null(const Name_string &name_par)
2384   {
2385     init();
2386     item_name= name_par;
2387   }
type()2388   enum Type type() const { return NULL_ITEM; }
2389   bool eq(const Item *item, bool binary_cmp) const;
2390   double val_real();
2391   longlong val_int();
val_time_temporal()2392   longlong val_time_temporal() { return val_int(); }
val_date_temporal()2393   longlong val_date_temporal() { return val_int(); }
2394   String *val_str(String *str);
2395   my_decimal *val_decimal(my_decimal *);
get_date(MYSQL_TIME * ltime,uint fuzzydate)2396   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
2397   {
2398     return true;
2399   }
get_time(MYSQL_TIME * ltime)2400   bool get_time(MYSQL_TIME *ltime)
2401   {
2402     return true;
2403   }
2404   type_conversion_status save_in_field(Field *field, bool no_conversions);
2405   type_conversion_status save_safe_in_field(Field *field);
2406   bool send(Protocol *protocol, String *str);
result_type()2407   enum Item_result result_type () const { return STRING_RESULT; }
field_type()2408   enum_field_types field_type() const   { return MYSQL_TYPE_NULL; }
basic_const_item()2409   bool basic_const_item() const { return 1; }
clone_item()2410   Item *clone_item() { return new Item_null(item_name); }
is_null()2411   bool is_null() { return 1; }
2412 
print(String * str,enum_query_type query_type)2413   virtual inline void print(String *str, enum_query_type query_type)
2414   {
2415     str->append(STRING_WITH_LEN("NULL"));
2416   }
2417 
2418   Item *safe_charset_converter(const CHARSET_INFO *tocs);
check_partition_func_processor(uchar * int_arg)2419   bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
2420 };
2421 
2422 /**
2423   An item representing NULL values for use with ROLLUP.
2424 
2425   When grouping WITH ROLLUP, Item_null_result items are created to
2426   represent NULL values in the grouping columns of the ROLLUP rows. To
2427   avoid type problems during execution, these objects are created with
2428   the same field and result types as the fields of the columns they
2429   belong to.
2430  */
2431 class Item_null_result :public Item_null
2432 {
2433   /** Field type for this NULL value */
2434   enum_field_types fld_type;
2435   /** Result type for this NULL value */
2436   Item_result res_type;
2437 
2438 public:
2439   Field *result_field;
Item_null_result(enum_field_types fld_type,Item_result res_type)2440   Item_null_result(enum_field_types fld_type, Item_result res_type)
2441     : Item_null(), fld_type(fld_type), res_type(res_type), result_field(0) {}
is_result_field()2442   bool is_result_field() { return result_field != 0; }
save_in_result_field(bool no_conversions)2443   void save_in_result_field(bool no_conversions)
2444   {
2445     save_in_field(result_field, no_conversions);
2446   }
check_partition_func_processor(uchar * int_arg)2447   bool check_partition_func_processor(uchar *int_arg) {return TRUE;}
field_type()2448   enum_field_types field_type() const { return fld_type; }
result_type()2449   Item_result result_type() const { return res_type; }
2450 };
2451 
2452 /* Item represents one placeholder ('?') of prepared statement */
2453 
2454 class Item_param :public Item,
2455                   private Settable_routine_parameter
2456 {
2457 public:
2458   enum enum_item_param_state
2459   {
2460     NO_VALUE, NULL_VALUE, INT_VALUE, REAL_VALUE,
2461     STRING_VALUE, TIME_VALUE, LONG_DATA_VALUE,
2462     DECIMAL_VALUE
2463   } state;
2464 
2465   /*
2466     A buffer for string and long data values. Historically all allocated
2467     values returned from val_str() were treated as eligible to
2468     modification. I. e. in some cases Item_func_concat can append it's
2469     second argument to return value of the first one. Because of that we
2470     can't return the original buffer holding string data from val_str(),
2471     and have to have one buffer for data and another just pointing to
2472     the data. This is the latter one and it's returned from val_str().
2473     Can not be declared inside the union as it's not a POD type.
2474   */
2475   String str_value_ptr;
2476   my_decimal decimal_value;
2477   union
2478   {
2479     longlong integer;
2480     double   real;
2481     /*
2482       Character sets conversion info for string values.
2483       Character sets of client and connection defined at bind time are used
2484       for all conversions, even if one of them is later changed (i.e.
2485       between subsequent calls to mysql_stmt_execute).
2486     */
2487     struct CONVERSION_INFO
2488     {
2489       const CHARSET_INFO *character_set_client;
2490       const CHARSET_INFO *character_set_of_placeholder;
2491       /*
2492         This points at character set of connection if conversion
2493         to it is required (i. e. if placeholder typecode is not BLOB).
2494         Otherwise it's equal to character_set_client (to simplify
2495         check in convert_str_value()).
2496       */
2497       const CHARSET_INFO *final_character_set_of_str_value;
2498     } cs_info;
2499     MYSQL_TIME     time;
2500   } value;
2501 
2502   /* Cached values for virtual methods to save us one switch.  */
2503   enum Item_result item_result_type;
2504   enum Type item_type;
2505 
2506   /*
2507     Used when this item is used in a temporary table.
2508     This is NOT placeholder metadata sent to client, as this value
2509     is assigned after sending metadata (in setup_one_conversion_function).
2510     For example in case of 'SELECT ?' you'll get MYSQL_TYPE_STRING both
2511     in result set and placeholders metadata, no matter what type you will
2512     supply for this placeholder in mysql_stmt_execute.
2513   */
2514   enum enum_field_types param_type;
2515   /*
2516     Offset of placeholder inside statement text. Used to create
2517     no-placeholders version of this statement for the binary log.
2518   */
2519   uint pos_in_query;
2520 
2521   Item_param(uint pos_in_query_arg);
2522 
result_type()2523   enum Item_result result_type () const { return item_result_type; }
type()2524   enum Type type() const { return item_type; }
field_type()2525   enum_field_types field_type() const { return param_type; }
2526 
2527   double val_real();
2528   longlong val_int();
2529   my_decimal *val_decimal(my_decimal*);
2530   String *val_str(String*);
2531   bool get_time(MYSQL_TIME *tm);
2532   bool get_date(MYSQL_TIME *tm, uint fuzzydate);
2533   type_conversion_status save_in_field(Field *field, bool no_conversions);
2534 
2535   void set_null();
2536   void set_int(longlong i, uint32 max_length_arg);
2537   void set_double(double i);
2538   void set_decimal(const char *str, ulong length);
2539   void set_decimal(const my_decimal *dv);
2540   bool set_str(const char *str, ulong length);
2541   bool set_longdata(const char *str, ulong length);
2542   void set_time(MYSQL_TIME *tm, timestamp_type type, uint32 max_length_arg);
2543   bool set_from_user_var(THD *thd, const user_var_entry *entry);
2544   void reset();
2545   /*
2546     Assign placeholder value from bind data.
2547     Note, that 'len' has different semantics in embedded library (as we
2548     don't need to check that packet is not broken there). See
2549     sql_prepare.cc for details.
2550   */
2551   void (*set_param_func)(Item_param *param, uchar **pos, ulong len);
2552 
2553   const String *query_val_str(THD *thd, String *str) const;
2554 
2555   bool convert_str_value(THD *thd);
2556 
2557   /*
2558     If value for parameter was not set we treat it as non-const
2559     so noone will use parameters value in fix_fields still
2560     parameter is constant during execution.
2561   */
used_tables()2562   virtual table_map used_tables() const
2563   { return state != NO_VALUE ? (table_map)0 : PARAM_TABLE_BIT; }
2564   virtual void print(String *str, enum_query_type query_type);
is_null()2565   bool is_null()
2566   { DBUG_ASSERT(state != NO_VALUE); return state == NULL_VALUE; }
2567   bool basic_const_item() const;
2568   /*
2569     This method is used to make a copy of a basic constant item when
2570     propagating constants in the optimizer. The reason to create a new
2571     item and not use the existing one is not precisely known (2005/04/16).
2572     Probably we are trying to preserve tree structure of items, in other
2573     words, avoid pointing at one item from two different nodes of the tree.
2574     Return a new basic constant item if parameter value is a basic
2575     constant, assert otherwise. This method is called only if
2576     basic_const_item returned TRUE.
2577   */
2578   Item *safe_charset_converter(const CHARSET_INFO *tocs);
2579   Item *clone_item();
2580   /*
2581     Implement by-value equality evaluation if parameter value
2582     is set and is a basic constant (integer, real or string).
2583     Otherwise return FALSE.
2584   */
2585   bool eq(const Item *item, bool binary_cmp) const;
2586   /** Item is a argument to a limit clause. */
2587   bool limit_clause_param;
2588   void set_param_type_and_swap_value(Item_param *from);
2589 
2590 private:
2591   virtual inline Settable_routine_parameter *
get_settable_routine_parameter()2592     get_settable_routine_parameter()
2593   {
2594     return this;
2595   }
2596 
2597   virtual bool set_value(THD *thd, sp_rcontext *ctx, Item **it);
2598 
2599   virtual void set_out_param_info(Send_field *info);
2600 
2601 public:
2602   virtual const Send_field *get_out_param_info() const;
2603 
2604   virtual void make_field(Send_field *field);
2605 
2606 private:
2607   Send_field *m_out_param_info;
2608 };
2609 
2610 
2611 class Item_int :public Item_num
2612 {
2613 public:
2614   longlong value;
2615   Item_int(int32 i,uint length= MY_INT32_NUM_DECIMAL_DIGITS)
2616     :value((longlong) i)
2617     { max_length=length; fixed= 1; }
2618   Item_int(longlong i,uint length= MY_INT64_NUM_DECIMAL_DIGITS)
value(i)2619     :value(i)
2620     { max_length=length; fixed= 1; }
2621   Item_int(ulonglong i, uint length= MY_INT64_NUM_DECIMAL_DIGITS)
2622     :value((longlong)i)
2623     { max_length=length; fixed= 1; unsigned_flag= 1; }
Item_int(Item_int * item_arg)2624   Item_int(Item_int *item_arg)
2625   {
2626     value= item_arg->value;
2627     item_name= item_arg->item_name;
2628     max_length= item_arg->max_length;
2629     fixed= 1;
2630   }
Item_int(const Name_string & name_arg,longlong i,uint length)2631   Item_int(const Name_string &name_arg, longlong i, uint length) :value(i)
2632   {
2633     max_length= length;
2634     item_name= name_arg;
2635     fixed= 1;
2636   }
2637   Item_int(const char *str_arg, uint length);
type()2638   enum Type type() const { return INT_ITEM; }
result_type()2639   enum Item_result result_type () const { return INT_RESULT; }
field_type()2640   enum_field_types field_type() const { return MYSQL_TYPE_LONGLONG; }
val_int()2641   longlong val_int() { DBUG_ASSERT(fixed == 1); return value; }
val_real()2642   double val_real() { DBUG_ASSERT(fixed == 1); return (double) value; }
2643   my_decimal *val_decimal(my_decimal *);
2644   String *val_str(String*);
get_date(MYSQL_TIME * ltime,uint fuzzydate)2645   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
2646   {
2647     return get_date_from_int(ltime, fuzzydate);
2648   }
get_time(MYSQL_TIME * ltime)2649   bool get_time(MYSQL_TIME *ltime)
2650   {
2651     return get_time_from_int(ltime);
2652   }
2653   type_conversion_status save_in_field(Field *field, bool no_conversions);
basic_const_item()2654   bool basic_const_item() const { return 1; }
clone_item()2655   Item *clone_item() { return new Item_int(this); }
2656   virtual void print(String *str, enum_query_type query_type);
neg()2657   Item_num *neg() { value= -value; return this; }
decimal_precision()2658   uint decimal_precision() const
2659   { return (uint)(max_length - MY_TEST(value < 0)); }
2660   bool eq(const Item *, bool binary_cmp) const;
check_partition_func_processor(uchar * bool_arg)2661   bool check_partition_func_processor(uchar *bool_arg) { return FALSE;}
2662 };
2663 
2664 
2665 /**
2666   Item_int with value==0 and length==1
2667 */
2668 class Item_int_0 :public Item_int
2669 {
2670 public:
Item_int_0()2671   Item_int_0() :Item_int(NAME_STRING("0"), 0, 1) {}
2672 };
2673 
2674 
2675 /*
2676   Item_temporal is used to store numeric representation
2677   of time/date/datetime values for queries like:
2678 
2679      WHERE datetime_column NOT IN
2680      ('2006-04-25 10:00:00','2006-04-25 10:02:00', ...);
2681 
2682   and for SHOW/INFORMATION_SCHEMA purposes (see sql_show.cc)
2683 
2684   TS-TODO: Can't we use Item_time_literal, Item_date_literal,
2685   TS-TODO: and Item_datetime_literal for this purpose?
2686 */
2687 class Item_temporal :public Item_int
2688 {
2689   enum_field_types cached_field_type;
2690 public:
Item_temporal(enum_field_types field_type_arg,longlong i)2691   Item_temporal(enum_field_types field_type_arg, longlong i): Item_int(i),
2692     cached_field_type(field_type_arg)
2693   {
2694     DBUG_ASSERT(is_temporal_type(field_type_arg));
2695   }
Item_temporal(enum_field_types field_type_arg,const Name_string & name_arg,longlong i,uint length)2696   Item_temporal(enum_field_types field_type_arg, const Name_string &name_arg,
2697                 longlong i, uint length): Item_int(i),
2698     cached_field_type(field_type_arg)
2699   {
2700     DBUG_ASSERT(is_temporal_type(field_type_arg));
2701     max_length= length;
2702     item_name= name_arg;
2703     fixed= 1;
2704   }
clone_item()2705   Item *clone_item() { return new Item_temporal(field_type(), value); }
2706   type_conversion_status save_in_field(Field *field, bool no_conversions);
val_time_temporal()2707   longlong val_time_temporal() { return val_int(); }
val_date_temporal()2708   longlong val_date_temporal() { return val_int(); }
get_date(MYSQL_TIME * ltime,uint fuzzydate)2709   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
2710   {
2711     DBUG_ASSERT(0);
2712     return false;
2713   }
get_time(MYSQL_TIME * ltime)2714   bool get_time(MYSQL_TIME *ltime)
2715   {
2716     DBUG_ASSERT(0);
2717     return false;
2718   }
field_type()2719   enum_field_types field_type() const
2720   {
2721     return cached_field_type;
2722   }
2723 };
2724 
2725 
2726 class Item_uint :public Item_int
2727 {
2728 public:
Item_uint(const char * str_arg,uint length)2729   Item_uint(const char *str_arg, uint length)
2730     :Item_int(str_arg, length) { unsigned_flag= 1; }
Item_uint(ulonglong i)2731   Item_uint(ulonglong i) :Item_int((ulonglong) i, 10) {}
Item_uint(const Name_string & name_arg,longlong i,uint length)2732   Item_uint(const Name_string &name_arg, longlong i, uint length)
2733     :Item_int(name_arg, i, length) { unsigned_flag= 1; }
val_real()2734   double val_real()
2735     { DBUG_ASSERT(fixed == 1); return ulonglong2double((ulonglong)value); }
2736   String *val_str(String*);
2737 
clone_item()2738   Item *clone_item() { return new Item_uint(item_name, value, max_length); }
2739   type_conversion_status save_in_field(Field *field, bool no_conversions);
2740   virtual void print(String *str, enum_query_type query_type);
2741   Item_num *neg ();
decimal_precision()2742   uint decimal_precision() const { return max_length; }
check_partition_func_processor(uchar * bool_arg)2743   bool check_partition_func_processor(uchar *bool_arg) { return FALSE;}
2744 };
2745 
2746 
2747 /* decimal (fixed point) constant */
2748 class Item_decimal :public Item_num
2749 {
2750 protected:
2751   my_decimal decimal_value;
2752 public:
2753   Item_decimal(const char *str_arg, uint length, const CHARSET_INFO *charset);
2754   Item_decimal(const Name_string &name_arg,
2755                const my_decimal *val_arg, uint decimal_par, uint length);
2756   Item_decimal(my_decimal *value_par);
2757   Item_decimal(longlong val, bool unsig);
2758   Item_decimal(double val, int precision, int scale);
2759   Item_decimal(const uchar *bin, int precision, int scale);
2760 
type()2761   enum Type type() const { return DECIMAL_ITEM; }
result_type()2762   enum Item_result result_type () const { return DECIMAL_RESULT; }
field_type()2763   enum_field_types field_type() const { return MYSQL_TYPE_NEWDECIMAL; }
2764   longlong val_int();
2765   double val_real();
2766   String *val_str(String*);
val_decimal(my_decimal * val)2767   my_decimal *val_decimal(my_decimal *val) { return &decimal_value; }
get_date(MYSQL_TIME * ltime,uint fuzzydate)2768   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
2769   {
2770     return get_date_from_decimal(ltime, fuzzydate);
2771   }
get_time(MYSQL_TIME * ltime)2772   bool get_time(MYSQL_TIME *ltime)
2773   {
2774     return get_time_from_decimal(ltime);
2775   }
2776   type_conversion_status save_in_field(Field *field, bool no_conversions);
basic_const_item()2777   bool basic_const_item() const { return 1; }
clone_item()2778   Item *clone_item()
2779   {
2780     return new Item_decimal(item_name, &decimal_value, decimals, max_length);
2781   }
2782   virtual void print(String *str, enum_query_type query_type);
neg()2783   Item_num *neg()
2784   {
2785     my_decimal_neg(&decimal_value);
2786     unsigned_flag= !decimal_value.sign();
2787     return this;
2788   }
decimal_precision()2789   uint decimal_precision() const { return decimal_value.precision(); }
2790   bool eq(const Item *, bool binary_cmp) const;
2791   void set_decimal_value(my_decimal *value_par);
check_partition_func_processor(uchar * bool_arg)2792   bool check_partition_func_processor(uchar *bool_arg) { return FALSE;}
2793 };
2794 
2795 
2796 class Item_float :public Item_num
2797 {
2798   Name_string presentation;
2799 public:
2800   double value;
2801   // Item_real() :value(0) {}
2802   Item_float(const char *str_arg, uint length);
Item_float(const Name_string name_arg,double val_arg,uint decimal_par,uint length)2803   Item_float(const Name_string name_arg,
2804              double val_arg, uint decimal_par, uint length)
2805     :value(val_arg)
2806   {
2807     presentation= name_arg;
2808     item_name= name_arg;
2809     decimals= (uint8) decimal_par;
2810     max_length= length;
2811     fixed= 1;
2812   }
Item_float(double value_par,uint decimal_par)2813   Item_float(double value_par, uint decimal_par) :value(value_par)
2814   {
2815     decimals= (uint8) decimal_par;
2816     fixed= 1;
2817   }
2818   type_conversion_status save_in_field(Field *field, bool no_conversions);
type()2819   enum Type type() const { return REAL_ITEM; }
field_type()2820   enum_field_types field_type() const { return MYSQL_TYPE_DOUBLE; }
val_real()2821   double val_real() { DBUG_ASSERT(fixed == 1); return value; }
val_int()2822   longlong val_int()
2823   {
2824     DBUG_ASSERT(fixed == 1);
2825     if (value <= (double) LONGLONG_MIN)
2826     {
2827        return LONGLONG_MIN;
2828     }
2829     else if (value >= (double) (ulonglong) LONGLONG_MAX)
2830     {
2831       return LONGLONG_MAX;
2832     }
2833     return (longlong) rint(value);
2834   }
2835   String *val_str(String*);
2836   my_decimal *val_decimal(my_decimal *);
get_date(MYSQL_TIME * ltime,uint fuzzydate)2837   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
2838   {
2839     return get_date_from_real(ltime, fuzzydate);
2840   }
get_time(MYSQL_TIME * ltime)2841   bool get_time(MYSQL_TIME *ltime)
2842   {
2843     return get_time_from_real(ltime);
2844   }
basic_const_item()2845   bool basic_const_item() const { return 1; }
clone_item()2846   Item *clone_item()
2847   { return new Item_float(item_name, value, decimals, max_length); }
neg()2848   Item_num *neg() { value= -value; return this; }
2849   virtual void print(String *str, enum_query_type query_type);
2850   bool eq(const Item *, bool binary_cmp) const;
2851 };
2852 
2853 
2854 class Item_static_float_func :public Item_float
2855 {
2856   const Name_string func_name;
2857 public:
Item_static_float_func(const Name_string & name_arg,double val_arg,uint decimal_par,uint length)2858   Item_static_float_func(const Name_string &name_arg,
2859                          double val_arg, uint decimal_par, uint length)
2860     :Item_float(null_name_string,
2861                 val_arg, decimal_par, length), func_name(name_arg)
2862   {}
2863 
print(String * str,enum_query_type query_type)2864   virtual inline void print(String *str, enum_query_type query_type)
2865   {
2866     str->append(func_name);
2867   }
2868 
2869   Item *safe_charset_converter(const CHARSET_INFO *tocs);
2870 };
2871 
2872 
2873 class Item_string :public Item_basic_constant
2874 {
2875 public:
2876   /* Create from a string, set name from the string itself. */
2877   Item_string(const char *str,uint length,
2878               const CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE,
2879               uint repertoire= MY_REPERTOIRE_UNICODE30)
m_cs_specified(FALSE)2880     : m_cs_specified(FALSE)
2881   {
2882     str_value.set_or_copy_aligned(str, length, cs);
2883     collation.set(cs, dv, repertoire);
2884     /*
2885       We have to have a different max_length than 'length' here to
2886       ensure that we get the right length if we do use the item
2887       to create a new table. In this case max_length must be the maximum
2888       number of chars for a string of this type because we in Create_field::
2889       divide the max_length with mbmaxlen).
2890     */
2891     max_length= str_value.numchars()*cs->mbmaxlen;
2892     item_name.copy(str, length, cs);
2893     decimals=NOT_FIXED_DEC;
2894     // it is constant => can be used without fix_fields (and frequently used)
2895     fixed= 1;
2896     /*
2897       Check if the string has any character that can't be
2898       interpreted using the relevant charset.
2899     */
2900     check_well_formed_result(&str_value, false, false);
2901   }
2902   /* Just create an item and do not fill string representation */
2903   Item_string(const CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE)
m_cs_specified(FALSE)2904     : m_cs_specified(FALSE)
2905   {
2906     collation.set(cs, dv);
2907     max_length= 0;
2908     decimals= NOT_FIXED_DEC;
2909     fixed= 1;
2910   }
2911   /* Create from the given name and string. */
2912   Item_string(const Name_string name_par, const char *str, uint length,
2913               const CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE,
2914               uint repertoire= MY_REPERTOIRE_UNICODE30)
m_cs_specified(FALSE)2915     : m_cs_specified(FALSE)
2916   {
2917     str_value.set_or_copy_aligned(str, length, cs);
2918     collation.set(cs, dv, repertoire);
2919     max_length= str_value.numchars()*cs->mbmaxlen;
2920     item_name= name_par;
2921     decimals=NOT_FIXED_DEC;
2922     // it is constant => can be used without fix_fields (and frequently used)
2923     fixed= 1;
2924   }
2925   /*
2926     This is used in stored procedures to avoid memory leaks and
2927     does a deep copy of its argument.
2928   */
set_str_with_copy(const char * str_arg,uint length_arg)2929   void set_str_with_copy(const char *str_arg, uint length_arg)
2930   {
2931     str_value.copy(str_arg, length_arg, collation.collation);
2932     max_length= str_value.numchars() * collation.collation->mbmaxlen;
2933   }
set_repertoire_from_value()2934   void set_repertoire_from_value()
2935   {
2936     collation.repertoire= my_string_repertoire(str_value.charset(),
2937                                                str_value.ptr(),
2938                                                str_value.length());
2939   }
type()2940   enum Type type() const { return STRING_ITEM; }
2941   double val_real();
2942   longlong val_int();
val_str(String *)2943   String *val_str(String*)
2944   {
2945     DBUG_ASSERT(fixed == 1);
2946     return (String*) &str_value;
2947   }
2948   my_decimal *val_decimal(my_decimal *);
get_date(MYSQL_TIME * ltime,uint fuzzydate)2949   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
2950   {
2951     return get_date_from_string(ltime, fuzzydate);
2952   }
get_time(MYSQL_TIME * ltime)2953   bool get_time(MYSQL_TIME *ltime)
2954   {
2955     return get_time_from_string(ltime);
2956   }
2957   type_conversion_status save_in_field(Field *field, bool no_conversions);
result_type()2958   enum Item_result result_type () const { return STRING_RESULT; }
field_type()2959   enum_field_types field_type() const { return MYSQL_TYPE_VARCHAR; }
basic_const_item()2960   bool basic_const_item() const { return 1; }
2961   bool eq(const Item *item, bool binary_cmp) const;
clone_item()2962   Item *clone_item()
2963   {
2964     return new Item_string(static_cast<Name_string>(item_name), str_value.ptr(),
2965     			   str_value.length(), collation.collation);
2966   }
2967   Item *safe_charset_converter(const CHARSET_INFO *tocs);
2968   Item *charset_converter(const CHARSET_INFO *tocs, bool lossless);
append(char * str,uint length)2969   inline void append(char *str, uint length)
2970   {
2971     str_value.append(str, length);
2972     max_length= str_value.numchars() * collation.collation->mbmaxlen;
2973   }
2974   virtual void print(String *str, enum_query_type query_type);
check_partition_func_processor(uchar * int_arg)2975   bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
2976 
2977   /**
2978     Return TRUE if character-set-introducer was explicitly specified in the
2979     original query for this item (text literal).
2980 
2981     This operation is to be called from Item_string::print(). The idea is
2982     that when a query is generated (re-constructed) from the Item-tree,
2983     character-set-introducers should appear only for those literals, where
2984     they were explicitly specified by the user. Otherwise, that may lead to
2985     loss collation information (character set introducers implies default
2986     collation for the literal).
2987 
2988     Basically, that makes sense only for views and hopefully will be gone
2989     one day when we start using original query as a view definition.
2990 
2991     @return This operation returns the value of m_cs_specified attribute.
2992       @retval TRUE if character set introducer was explicitly specified in
2993       the original query.
2994       @retval FALSE otherwise.
2995   */
is_cs_specified()2996   inline bool is_cs_specified() const
2997   {
2998     return m_cs_specified;
2999   }
3000 
3001   /**
3002     Set the value of m_cs_specified attribute.
3003 
3004     m_cs_specified attribute shows whether character-set-introducer was
3005     explicitly specified in the original query for this text literal or
3006     not. The attribute makes sense (is used) only for views.
3007 
3008     This operation is to be called from the parser during parsing an input
3009     query.
3010   */
set_cs_specified(bool cs_specified)3011   inline void set_cs_specified(bool cs_specified)
3012   {
3013     m_cs_specified= cs_specified;
3014   }
3015 
3016 private:
3017   bool m_cs_specified;
3018 };
3019 
3020 
3021 longlong
3022 longlong_from_string_with_check (const CHARSET_INFO *cs,
3023                                  const char *cptr, char *end);
3024 double
3025 double_from_string_with_check (const CHARSET_INFO *cs,
3026                                const char *cptr, char *end);
3027 
3028 class Item_static_string_func :public Item_string
3029 {
3030   const Name_string func_name;
3031 public:
3032   Item_static_string_func(const Name_string &name_par,
3033                           const char *str, uint length, const CHARSET_INFO *cs,
3034                           Derivation dv= DERIVATION_COERCIBLE)
Item_string(null_name_string,str,length,cs,dv)3035     :Item_string(null_name_string, str, length, cs, dv), func_name(name_par)
3036   {}
3037   Item *safe_charset_converter(const CHARSET_INFO *tocs);
3038 
print(String * str,enum_query_type query_type)3039   virtual inline void print(String *str, enum_query_type query_type)
3040   {
3041     str->append(func_name);
3042   }
3043 
check_partition_func_processor(uchar * int_arg)3044   bool check_partition_func_processor(uchar *int_arg) {return TRUE;}
3045 };
3046 
3047 
3048 /* for show tables */
3049 class Item_partition_func_safe_string: public Item_string
3050 {
3051 public:
3052   Item_partition_func_safe_string(const Name_string name, uint length,
3053                                   const CHARSET_INFO *cs= NULL):
3054     Item_string(name, NullS, 0, cs)
3055   {
3056     max_length= length;
3057   }
3058 };
3059 
3060 
3061 class Item_blob :public Item_partition_func_safe_string
3062 {
3063 public:
Item_blob(const char * name,uint length)3064   Item_blob(const char *name, uint length) :
3065     Item_partition_func_safe_string(Name_string(name, strlen(name)),
3066                                     length, &my_charset_bin)
3067   { }
type()3068   enum Type type() const { return TYPE_HOLDER; }
field_type()3069   enum_field_types field_type() const { return MYSQL_TYPE_BLOB; }
3070 };
3071 
3072 
3073 /**
3074   Item_empty_string -- is a utility class to put an item into List<Item>
3075   which is then used in protocol.send_result_set_metadata() when sending SHOW output to
3076   the client.
3077 */
3078 
3079 class Item_empty_string :public Item_partition_func_safe_string
3080 {
3081 public:
3082   Item_empty_string(const char *header, uint length,
3083                     const CHARSET_INFO *cs= NULL) :
Name_string(header,strlen (header))3084     Item_partition_func_safe_string(Name_string(header, strlen(header)),
3085                                     0, cs ? cs : &my_charset_utf8_general_ci)
3086     {
3087       max_length= length * collation.collation->mbmaxlen;
3088     }
3089   void make_field(Send_field *field);
3090 };
3091 
3092 
3093 class Item_return_int :public Item_int
3094 {
3095   enum_field_types int_field_type;
3096 public:
3097   Item_return_int(const char *name_arg, uint length,
3098 		  enum_field_types field_type_arg, longlong value= 0)
3099     :Item_int(Name_string(name_arg, name_arg ? strlen(name_arg) : 0),
3100               value, length), int_field_type(field_type_arg)
3101   {
3102     unsigned_flag=1;
3103   }
field_type()3104   enum_field_types field_type() const { return int_field_type; }
3105 };
3106 
3107 
3108 class Item_hex_string: public Item_basic_constant
3109 {
3110 public:
3111   Item_hex_string();
3112   Item_hex_string(const char *str,uint str_length);
type()3113   enum Type type() const { return VARBIN_ITEM; }
val_real()3114   double val_real()
3115   {
3116     DBUG_ASSERT(fixed == 1);
3117     return (double) (ulonglong) Item_hex_string::val_int();
3118   }
3119   longlong val_int();
basic_const_item()3120   bool basic_const_item() const { return 1; }
val_str(String *)3121   String *val_str(String*) { DBUG_ASSERT(fixed == 1); return &str_value; }
3122   my_decimal *val_decimal(my_decimal *);
get_date(MYSQL_TIME * ltime,uint fuzzydate)3123   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
3124   {
3125     return get_date_from_string(ltime, fuzzydate);
3126   }
get_time(MYSQL_TIME * ltime)3127   bool get_time(MYSQL_TIME *ltime)
3128   {
3129     return get_time_from_string(ltime);
3130   }
3131   type_conversion_status save_in_field(Field *field, bool no_conversions);
result_type()3132   enum Item_result result_type () const { return STRING_RESULT; }
cast_to_int_type()3133   enum Item_result cast_to_int_type() const { return INT_RESULT; }
field_type()3134   enum_field_types field_type() const { return MYSQL_TYPE_VARCHAR; }
3135   virtual void print(String *str, enum_query_type query_type);
3136   bool eq(const Item *item, bool binary_cmp) const;
3137   virtual Item *safe_charset_converter(const CHARSET_INFO *tocs);
check_partition_func_processor(uchar * int_arg)3138   bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
3139 private:
3140   void hex_string_init(const char *str, uint str_length);
3141 };
3142 
3143 
3144 class Item_bin_string: public Item_hex_string
3145 {
3146 public:
3147   Item_bin_string(const char *str,uint str_length);
3148 };
3149 
3150 class Item_result_field :public Item	/* Item with result field */
3151 {
3152 public:
3153   Field *result_field;				/* Save result here */
Item_result_field()3154   Item_result_field() :result_field(0) {}
3155   // Constructor used for Item_sum/Item_cond_and/or (see Item comment)
Item_result_field(THD * thd,Item_result_field * item)3156   Item_result_field(THD *thd, Item_result_field *item):
3157     Item(thd, item), result_field(item->result_field)
3158   {}
~Item_result_field()3159   ~Item_result_field() {}			/* Required with gcc 2.95 */
get_tmp_table_field()3160   Field *get_tmp_table_field() { return result_field; }
tmp_table_field(TABLE * t_arg)3161   Field *tmp_table_field(TABLE *t_arg) { return result_field; }
used_tables()3162   table_map used_tables() const { return 1; }
3163   virtual void fix_length_and_dec()=0;
set_result_field(Field * field)3164   void set_result_field(Field *field) { result_field= field; }
is_result_field()3165   bool is_result_field() { return 1; }
save_in_result_field(bool no_conversions)3166   void save_in_result_field(bool no_conversions)
3167   {
3168     save_in_field(result_field, no_conversions);
3169   }
3170   void cleanup();
3171   /*
3172     This method is used for debug purposes to print the name of an
3173     item to the debug log. The second use of this method is as
3174     a helper function of print() and error messages, where it is
3175     applicable. To suit both goals it should return a meaningful,
3176     distinguishable and sintactically correct string. This method
3177     should not be used for runtime type identification, use enum
3178     {Sum}Functype and Item_func::functype()/Item_sum::sum_func()
3179     instead.
3180     Added here, to the parent class of both Item_func and Item_sum_func.
3181 
3182     NOTE: for Items inherited from Item_sum, func_name() return part of
3183     function name till first argument (including '(') to make difference in
3184     names for functions with 'distinct' clause and without 'distinct' and
3185     also to make printing of items inherited from Item_sum uniform.
3186   */
3187   virtual const char *func_name() const= 0;
3188 };
3189 
3190 
3191 class Item_ref :public Item_ident
3192 {
3193 protected:
3194   void set_properties();
3195 public:
3196   enum Ref_Type { REF, DIRECT_REF, VIEW_REF, OUTER_REF, AGGREGATE_REF };
3197   Field *result_field;			 /* Save result here */
3198   Item **ref;
Item_ref(Name_resolution_context * context_arg,const char * db_arg,const char * table_name_arg,const char * field_name_arg)3199   Item_ref(Name_resolution_context *context_arg,
3200            const char *db_arg, const char *table_name_arg,
3201            const char *field_name_arg)
3202     :Item_ident(context_arg, db_arg, table_name_arg, field_name_arg),
3203      result_field(0), ref(0) {}
3204   /*
3205     This constructor is used in two scenarios:
3206     A) *item = NULL
3207       No initialization is performed, fix_fields() call will be necessary.
3208 
3209     B) *item points to an Item this Item_ref will refer to. This is
3210       used for GROUP BY. fix_fields() will not be called in this case,
3211       so we call set_properties to make this item "fixed". set_properties
3212       performs a subset of action Item_ref::fix_fields does, and this subset
3213       is enough for Item_ref's used in GROUP BY.
3214 
3215     TODO we probably fix a superset of problems like in BUG#6658. Check this
3216          with Bar, and if we have a more broader set of problems like this.
3217   */
3218   Item_ref(Name_resolution_context *context_arg, Item **item,
3219            const char *table_name_arg, const char *field_name_arg,
3220            bool alias_name_used_arg= FALSE);
3221 
3222   /* Constructor need to process subselect with temporary tables (see Item) */
Item_ref(THD * thd,Item_ref * item)3223   Item_ref(THD *thd, Item_ref *item)
3224     :Item_ident(thd, item), result_field(item->result_field), ref(item->ref) {}
type()3225   enum Type type() const		{ return REF_ITEM; }
eq(const Item * item,bool binary_cmp)3226   bool eq(const Item *item, bool binary_cmp) const
3227   {
3228     Item *it= ((Item *) item)->real_item();
3229     return ref && (*ref)->eq(it, binary_cmp);
3230   }
3231   double val_real();
3232   longlong val_int();
3233   longlong val_time_temporal();
3234   longlong val_date_temporal();
3235   my_decimal *val_decimal(my_decimal *);
3236   bool val_bool();
3237   String *val_str(String* tmp);
3238   bool is_null();
3239   bool get_date(MYSQL_TIME *ltime,uint fuzzydate);
3240   double val_result();
3241   longlong val_int_result();
3242   String *str_result(String* tmp);
3243   my_decimal *val_decimal_result(my_decimal *);
3244   bool val_bool_result();
3245   bool is_null_result();
3246   bool send(Protocol *prot, String *tmp);
3247   void make_field(Send_field *field);
3248   bool fix_fields(THD *, Item **);
3249   void fix_after_pullout(st_select_lex *parent_select,
3250                          st_select_lex *removed_select);
3251   type_conversion_status save_in_field(Field *field, bool no_conversions);
3252   void save_org_in_field(Field *field);
result_type()3253   enum Item_result result_type () const { return (*ref)->result_type(); }
field_type()3254   enum_field_types field_type() const   { return (*ref)->field_type(); }
get_tmp_table_field()3255   Field *get_tmp_table_field()
3256   { return result_field ? result_field : (*ref)->get_tmp_table_field(); }
3257   Item *get_tmp_table_item(THD *thd);
const_item()3258   bool const_item() const
3259   {
3260     return (*ref)->const_item() && (used_tables() == 0);
3261   }
used_tables()3262   table_map used_tables() const
3263   {
3264     return depended_from ? OUTER_REF_TABLE_BIT : (*ref)->used_tables();
3265   }
update_used_tables()3266   void update_used_tables()
3267   {
3268     if (!depended_from)
3269       (*ref)->update_used_tables();
3270   }
3271 
not_null_tables()3272   table_map not_null_tables() const
3273   {
3274     /*
3275       It can happen that our 'depended_from' member is set but the
3276       'depended_from' member of the referenced item is not (example: if a
3277       field in a subquery belongs to an outer merged view), so we first test
3278       ours:
3279     */
3280     return depended_from ? OUTER_REF_TABLE_BIT : (*ref)->not_null_tables();
3281   }
set_result_field(Field * field)3282   void set_result_field(Field *field)	{ result_field= field; }
is_result_field()3283   bool is_result_field() { return 1; }
save_in_result_field(bool no_conversions)3284   void save_in_result_field(bool no_conversions)
3285   {
3286     (*ref)->save_in_field(result_field, no_conversions);
3287   }
real_item()3288   Item *real_item()
3289   {
3290     return ref ? (*ref)->real_item() : this;
3291   }
walk(Item_processor processor,bool walk_subquery,uchar * arg)3292   bool walk(Item_processor processor, bool walk_subquery, uchar *arg)
3293   {
3294     return (*ref)->walk(processor, walk_subquery, arg) ||
3295            (this->*processor)(arg);
3296   }
3297   virtual Item* transform(Item_transformer, uchar *arg);
3298   virtual Item* compile(Item_analyzer analyzer, uchar **arg_p,
3299                         Item_transformer transformer, uchar *arg_t);
explain_subquery_checker(uchar ** arg)3300   virtual bool explain_subquery_checker(uchar **arg)
3301   {
3302     /*
3303       Always return false: we don't need to go deeper into referenced
3304       expression tree since we have to mark aliased subqueries at
3305       their original places (select list, derived tables), not by
3306       references from other expression (order by etc).
3307     */
3308     return false;
3309   }
3310   virtual void print(String *str, enum_query_type query_type);
3311   void cleanup();
field_for_view_update()3312   Item_field *field_for_view_update()
3313     { return (*ref)->field_for_view_update(); }
ref_type()3314   virtual Ref_Type ref_type() { return REF; }
3315 
3316   // Row emulation: forwarding of ROW-related calls to ref
cols()3317   uint cols()
3318   {
3319     return ref && result_type() == ROW_RESULT ? (*ref)->cols() : 1;
3320   }
element_index(uint i)3321   Item* element_index(uint i)
3322   {
3323     return ref && result_type() == ROW_RESULT ? (*ref)->element_index(i) : this;
3324   }
addr(uint i)3325   Item** addr(uint i)
3326   {
3327     return ref && result_type() == ROW_RESULT ? (*ref)->addr(i) : 0;
3328   }
check_cols(uint c)3329   bool check_cols(uint c)
3330   {
3331     return ref && result_type() == ROW_RESULT ? (*ref)->check_cols(c)
3332                                               : Item::check_cols(c);
3333   }
null_inside()3334   bool null_inside()
3335   {
3336     return ref && result_type() == ROW_RESULT ? (*ref)->null_inside() : 0;
3337   }
bring_value()3338   void bring_value()
3339   {
3340     if (ref && result_type() == ROW_RESULT)
3341       (*ref)->bring_value();
3342   }
get_time(MYSQL_TIME * ltime)3343   bool get_time(MYSQL_TIME *ltime)
3344   {
3345     DBUG_ASSERT(fixed);
3346     return (*ref)->get_time(ltime);
3347   }
basic_const_item()3348   virtual bool basic_const_item() const { return ref && (*ref)->basic_const_item(); }
is_outer_field()3349   bool is_outer_field() const
3350   {
3351     DBUG_ASSERT(fixed);
3352     DBUG_ASSERT(ref);
3353     return (*ref)->is_outer_field();
3354   }
3355 
3356   /**
3357     Checks if the item tree that ref points to contains a subquery.
3358   */
has_subquery()3359   virtual bool has_subquery() const
3360   {
3361     DBUG_ASSERT(ref);
3362     return (*ref)->has_subquery();
3363   }
3364 
3365   /**
3366     Checks if the item tree that ref points to contains a stored program.
3367   */
has_stored_program()3368   virtual bool has_stored_program() const
3369   {
3370     DBUG_ASSERT(ref);
3371     return (*ref)->has_stored_program();
3372   }
3373 
created_by_in2exists()3374   virtual bool created_by_in2exists() const
3375   {
3376     return (*ref)->created_by_in2exists();
3377   }
3378 };
3379 
3380 
3381 /*
3382   The same as Item_ref, but get value from val_* family of method to get
3383   value of item on which it referred instead of result* family.
3384 */
3385 class Item_direct_ref :public Item_ref
3386 {
3387 public:
3388   Item_direct_ref(Name_resolution_context *context_arg, Item **item,
3389                   const char *table_name_arg,
3390                   const char *field_name_arg,
3391                   bool alias_name_used_arg= FALSE)
Item_ref(context_arg,item,table_name_arg,field_name_arg,alias_name_used_arg)3392     :Item_ref(context_arg, item, table_name_arg,
3393               field_name_arg, alias_name_used_arg)
3394   {}
3395   /* Constructor need to process subselect with temporary tables (see Item) */
Item_direct_ref(THD * thd,Item_direct_ref * item)3396   Item_direct_ref(THD *thd, Item_direct_ref *item) : Item_ref(thd, item) {}
3397 
3398   double val_real();
3399   longlong val_int();
3400   longlong val_time_temporal();
3401   longlong val_date_temporal();
3402   String *val_str(String* tmp);
3403   my_decimal *val_decimal(my_decimal *);
3404   bool val_bool();
3405   bool is_null();
3406   bool get_date(MYSQL_TIME *ltime,uint fuzzydate);
ref_type()3407   virtual Ref_Type ref_type() { return DIRECT_REF; }
3408 };
3409 
3410 /*
3411   Class for view fields, the same as Item_direct_ref, but call fix_fields
3412   of reference if it is not called yet
3413 */
3414 class Item_direct_view_ref :public Item_direct_ref
3415 {
3416 public:
Item_direct_view_ref(Name_resolution_context * context_arg,Item ** item,const char * alias_name_arg,const char * table_name_arg,const char * field_name_arg)3417   Item_direct_view_ref(Name_resolution_context *context_arg,
3418                        Item **item,
3419                        const char *alias_name_arg,
3420                        const char *table_name_arg,
3421                        const char *field_name_arg)
3422     : Item_direct_ref(context_arg, item, alias_name_arg, field_name_arg)
3423   {
3424     orig_table_name= table_name_arg;
3425   }
3426 
3427   /* Constructor need to process subselect with temporary tables (see Item) */
Item_direct_view_ref(THD * thd,Item_direct_ref * item)3428   Item_direct_view_ref(THD *thd, Item_direct_ref *item)
3429     :Item_direct_ref(thd, item) {}
3430 
3431   /*
3432     We share one underlying Item_field, so we have to disable
3433     build_equal_items_for_cond().
3434     TODO: Implement multiple equality optimization for views.
3435   */
subst_argument_checker(uchar ** arg)3436   virtual bool subst_argument_checker(uchar **arg)
3437   {
3438     return false;
3439   }
3440 
3441   bool fix_fields(THD *, Item **);
3442   bool eq(const Item *item, bool binary_cmp) const;
get_tmp_table_item(THD * thd)3443   Item *get_tmp_table_item(THD *thd)
3444   {
3445     Item *item= Item_ref::get_tmp_table_item(thd);
3446     item->item_name= item_name;
3447     return item;
3448   }
ref_type()3449   virtual Ref_Type ref_type() { return VIEW_REF; }
3450 };
3451 
3452 
3453 /*
3454   Class for outer fields.
3455   An object of this class is created when the select where the outer field was
3456   resolved is a grouping one. After it has been fixed the ref field will point
3457   to either an Item_ref or an Item_direct_ref object which will be used to
3458   access the field.
3459   The ref field may also point to an Item_field instance.
3460   See also comments for the fix_inner_refs() and the
3461   Item_field::fix_outer_field() functions.
3462 */
3463 
3464 class Item_sum;
3465 class Item_outer_ref :public Item_direct_ref
3466 {
3467 public:
3468   Item *outer_ref;
3469   /* The aggregate function under which this outer ref is used, if any. */
3470   Item_sum *in_sum_func;
3471   /*
3472     TRUE <=> that the outer_ref is already present in the select list
3473     of the outer select.
3474   */
3475   bool found_in_select_list;
Item_outer_ref(Name_resolution_context * context_arg,Item_field * outer_field_arg)3476   Item_outer_ref(Name_resolution_context *context_arg,
3477                  Item_field *outer_field_arg)
3478     :Item_direct_ref(context_arg, 0, outer_field_arg->table_name,
3479                      outer_field_arg->field_name),
3480     outer_ref(outer_field_arg), in_sum_func(0),
3481     found_in_select_list(0)
3482   {
3483     ref= &outer_ref;
3484     set_properties();
3485     fixed= 0;
3486   }
Item_outer_ref(Name_resolution_context * context_arg,Item ** item,const char * table_name_arg,const char * field_name_arg,bool alias_name_used_arg)3487   Item_outer_ref(Name_resolution_context *context_arg, Item **item,
3488                  const char *table_name_arg, const char *field_name_arg,
3489                  bool alias_name_used_arg)
3490     :Item_direct_ref(context_arg, item, table_name_arg, field_name_arg,
3491                      alias_name_used_arg),
3492     outer_ref(0), in_sum_func(0), found_in_select_list(1)
3493   {}
save_in_result_field(bool no_conversions)3494   void save_in_result_field(bool no_conversions)
3495   {
3496     outer_ref->save_org_in_field(result_field);
3497   }
3498   bool fix_fields(THD *, Item **);
3499   void fix_after_pullout(st_select_lex *parent_select,
3500                          st_select_lex *removed_select);
used_tables()3501   table_map used_tables() const
3502   {
3503     return (*ref)->const_item() ? 0 : OUTER_REF_TABLE_BIT;
3504   }
not_null_tables()3505   table_map not_null_tables() const { return 0; }
3506 
ref_type()3507   virtual Ref_Type ref_type() { return OUTER_REF; }
3508 };
3509 
3510 
3511 class Item_in_subselect;
3512 
3513 
3514 /*
3515   An object of this class:
3516    - Converts val_XXX() calls to ref->val_XXX_result() calls, like Item_ref.
3517    - Sets owner->was_null=TRUE if it has returned a NULL value from any
3518      val_XXX() function. This allows to inject an Item_ref_null_helper
3519      object into subquery and then check if the subquery has produced a row
3520      with NULL value.
3521 */
3522 
3523 class Item_ref_null_helper: public Item_ref
3524 {
3525 protected:
3526   Item_in_subselect* owner;
3527 public:
Item_ref_null_helper(Name_resolution_context * context_arg,Item_in_subselect * master,Item ** item,const char * table_name_arg,const char * field_name_arg)3528   Item_ref_null_helper(Name_resolution_context *context_arg,
3529                        Item_in_subselect* master, Item **item,
3530 		       const char *table_name_arg, const char *field_name_arg)
3531     :Item_ref(context_arg, item, table_name_arg, field_name_arg),
3532      owner(master) {}
3533   double val_real();
3534   longlong val_int();
3535   longlong val_time_temporal();
3536   longlong val_date_temporal();
3537   String* val_str(String* s);
3538   my_decimal *val_decimal(my_decimal *);
3539   bool val_bool();
3540   bool get_date(MYSQL_TIME *ltime, uint fuzzydate);
3541   virtual void print(String *str, enum_query_type query_type);
3542   /*
3543     we add RAND_TABLE_BIT to prevent moving this item from HAVING to WHERE
3544   */
used_tables()3545   table_map used_tables() const
3546   {
3547     return (depended_from ?
3548             OUTER_REF_TABLE_BIT :
3549             (*ref)->used_tables() | RAND_TABLE_BIT);
3550   }
3551 };
3552 
3553 /*
3554   The following class is used to optimize comparing of bigint columns.
3555   We need to save the original item ('ref') to be able to call
3556   ref->save_in_field(). This is used to create index search keys.
3557 
3558   An instance of Item_int_with_ref may have signed or unsigned integer value.
3559 
3560 */
3561 
3562 class Item_int_with_ref :public Item_int
3563 {
3564 protected:
3565   Item *ref;
3566 public:
Item_int_with_ref(longlong i,Item * ref_arg,my_bool unsigned_arg)3567   Item_int_with_ref(longlong i, Item *ref_arg, my_bool unsigned_arg) :
3568     Item_int(i), ref(ref_arg)
3569   {
3570     unsigned_flag= unsigned_arg;
3571   }
save_in_field(Field * field,bool no_conversions)3572   type_conversion_status save_in_field(Field *field, bool no_conversions)
3573   {
3574     return ref->save_in_field(field, no_conversions);
3575   }
3576   Item *clone_item();
real_item()3577   virtual Item *real_item() { return ref; }
3578 };
3579 
3580 
3581 /*
3582   Similar to Item_int_with_ref, but to optimize comparing of temporal columns.
3583 */
3584 class Item_temporal_with_ref :public Item_int_with_ref
3585 {
3586 private:
3587   enum_field_types cached_field_type;
3588 public:
Item_temporal_with_ref(enum_field_types field_type_arg,uint8 decimals_arg,longlong i,Item * ref_arg,bool unsigned_flag)3589   Item_temporal_with_ref(enum_field_types field_type_arg,
3590                          uint8 decimals_arg, longlong i, Item *ref_arg,
3591                          bool unsigned_flag):
3592     Item_int_with_ref(i, ref_arg, unsigned_flag),
3593     cached_field_type(field_type_arg)
3594   {
3595     decimals= decimals_arg;
3596   }
field_type()3597   enum_field_types field_type() const { return cached_field_type; }
3598   void print(String *str, enum_query_type query_type);
get_date(MYSQL_TIME * ltime,uint fuzzydate)3599   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
3600   {
3601     DBUG_ASSERT(0);
3602     return true;
3603   }
get_time(MYSQL_TIME * ltime)3604   bool get_time(MYSQL_TIME *ltime)
3605   {
3606     DBUG_ASSERT(0);
3607     return true;
3608   }
3609 
3610 };
3611 
3612 
3613 /*
3614   Item_datetime_with_ref is used to optimize queries like:
3615     SELECT ... FROM t1 WHERE date_or_datetime_column = 20110101101010;
3616   The numeric constant is replaced to Item_datetime_with_ref
3617   by convert_constant_item().
3618 */
3619 class Item_datetime_with_ref :public Item_temporal_with_ref
3620 {
3621 private:
3622   enum_field_types cached_field_type;
3623 public:
3624   /**
3625     Constructor for Item_datetime_with_ref.
3626     @param    field_type_arg Data type: MYSQL_TYPE_DATE or MYSQL_TYPE_DATETIME
3627     @param    decimals_arg   Number of fractional digits.
3628     @param    i              Temporal value in packed format.
3629     @param    ref_arg        Pointer to the original numeric Item.
3630   */
Item_datetime_with_ref(enum_field_types field_type_arg,uint8 decimals_arg,longlong i,Item * ref_arg)3631   Item_datetime_with_ref(enum_field_types field_type_arg,
3632                          uint8 decimals_arg, longlong i, Item *ref_arg):
3633     Item_temporal_with_ref(field_type_arg, decimals_arg, i, ref_arg, true),
3634     cached_field_type(field_type_arg)
3635   {
3636   }
3637   Item *clone_item();
val_date_temporal()3638   longlong val_date_temporal() { return val_int(); }
val_time_temporal()3639   longlong val_time_temporal()
3640   {
3641     DBUG_ASSERT(0);
3642     return val_int();
3643   }
3644 };
3645 
3646 
3647 /*
3648   Item_time_with_ref is used to optimize queries like:
3649     SELECT ... FROM t1 WHERE time_column = 20110101101010;
3650   The numeric constant is replaced to Item_time_with_ref
3651   by convert_constant_item().
3652 */
3653 class Item_time_with_ref :public Item_temporal_with_ref
3654 {
3655 public:
3656   /**
3657     Constructor for Item_time_with_ref.
3658     @param    decimals_arg   Number of fractional digits.
3659     @param    i              Temporal value in packed format.
3660     @param    ref_arg        Pointer to the original numeric Item.
3661   */
Item_time_with_ref(uint8 decimals_arg,longlong i,Item * ref_arg)3662   Item_time_with_ref(uint8 decimals_arg, longlong i, Item *ref_arg):
3663     Item_temporal_with_ref(MYSQL_TYPE_TIME, decimals_arg, i, ref_arg, 0)
3664   {
3665   }
3666   Item *clone_item();
val_time_temporal()3667   longlong val_time_temporal() { return val_int(); }
val_date_temporal()3668   longlong val_date_temporal()
3669   {
3670     DBUG_ASSERT(0);
3671     return val_int();
3672   }
3673 };
3674 
3675 
3676 #ifdef MYSQL_SERVER
3677 #include "gstream.h"
3678 #include "spatial.h"
3679 #include "item_sum.h"
3680 #include "item_func.h"
3681 #include "item_row.h"
3682 #include "item_cmpfunc.h"
3683 #include "item_strfunc.h"
3684 #include "item_geofunc.h"
3685 #include "item_timefunc.h"
3686 #include "item_subselect.h"
3687 #include "item_xmlfunc.h"
3688 #include "item_create.h"
3689 #endif
3690 
3691 /**
3692   Base class to implement typed value caching Item classes
3693 
3694   Item_copy_ classes are very similar to the corresponding Item_
3695   classes (e.g. Item_copy_int is similar to Item_int) but they add
3696   the following additional functionality to Item_ :
3697     1. Nullability
3698     2. Possibility to store the value not only on instantiation time,
3699        but also later.
3700   Item_copy_ classes are a functionality subset of Item_cache_
3701   classes, as e.g. they don't support comparisons with the original Item
3702   as Item_cache_ classes do.
3703   Item_copy_ classes are used in GROUP BY calculation.
3704   TODO: Item_copy should be made an abstract interface and Item_copy_
3705   classes should inherit both the respective Item_ class and the interface.
3706   Ideally we should drop Item_copy_ classes altogether and merge
3707   their functionality to Item_cache_ (and these should be made to inherit
3708   from Item_).
3709 */
3710 
3711 class Item_copy :public Item
3712 {
3713 protected:
3714 
3715   /**
3716     Stores the type of the resulting field that would be used to store the data
3717     in the cache. This is to avoid calls to the original item.
3718   */
3719   enum enum_field_types cached_field_type;
3720 
3721   /** The original item that is copied */
3722   Item *item;
3723 
3724   /**
3725     Stores the result type of the original item, so it can be returned
3726     without calling the original item's method
3727   */
3728   Item_result cached_result_type;
3729 
3730   /**
3731     Constructor of the Item_copy class
3732 
3733     stores metadata information about the original class as well as a
3734     pointer to it.
3735   */
Item_copy(Item * i)3736   Item_copy(Item *i)
3737   {
3738     item= i;
3739     null_value=maybe_null=item->maybe_null;
3740     decimals=item->decimals;
3741     max_length=item->max_length;
3742     item_name= item->item_name;
3743     cached_field_type= item->field_type();
3744     cached_result_type= item->result_type();
3745     unsigned_flag= item->unsigned_flag;
3746     fixed= item->fixed;
3747     collation.set(item->collation);
3748   }
3749 
3750 public:
3751   /**
3752     Factory method to create the appropriate subclass dependent on the type of
3753     the original item.
3754 
3755     @param item      the original item.
3756   */
3757   static Item_copy *create (Item *item);
3758 
3759   /**
3760     Update the cache with the value of the original item
3761 
3762     This is the method that updates the cached value.
3763     It must be explicitly called by the user of this class to store the value
3764     of the orginal item in the cache.
3765   */
3766   virtual void copy() = 0;
3767 
get_item()3768   Item *get_item() { return item; }
3769   /** All of the subclasses should have the same type tag */
type()3770   enum Type type() const { return COPY_STR_ITEM; }
field_type()3771   enum_field_types field_type() const { return cached_field_type; }
result_type()3772   enum Item_result result_type () const { return cached_result_type; }
3773 
make_field(Send_field * field)3774   void make_field(Send_field *field) { item->make_field(field); }
used_tables()3775   table_map used_tables() const { return (table_map) 1L; }
const_item()3776   bool const_item() const { return 0; }
is_null()3777   bool is_null() { return null_value; }
3778 
no_rows_in_result()3779   virtual void no_rows_in_result()
3780   {
3781     item->no_rows_in_result();
3782   }
3783 
3784   /*
3785     Override the methods below as pure virtual to make sure all the
3786     sub-classes implement them.
3787   */
3788 
3789   virtual String *val_str(String*) = 0;
3790   virtual my_decimal *val_decimal(my_decimal *) = 0;
3791   virtual double val_real() = 0;
3792   virtual longlong val_int() = 0;
3793   virtual bool get_date(MYSQL_TIME *ltime, uint fuzzydate)= 0;
3794   virtual bool get_time(MYSQL_TIME *ltime)= 0;
3795   virtual type_conversion_status save_in_field(Field *field,
3796                                                bool no_conversions) = 0;
3797 };
3798 
3799 /**
3800  Implementation of a string cache.
3801 
3802  Uses Item::str_value for storage
3803 */
3804 class Item_copy_string : public Item_copy
3805 {
3806 public:
Item_copy_string(Item * item)3807   Item_copy_string (Item *item) : Item_copy(item) {}
3808 
3809   String *val_str(String*);
3810   my_decimal *val_decimal(my_decimal *);
3811   double val_real();
3812   longlong val_int();
3813   bool get_date(MYSQL_TIME *ltime, uint fuzzydate);
3814   bool get_time(MYSQL_TIME *ltime);
3815   void copy();
3816   type_conversion_status save_in_field(Field *field, bool no_conversions);
3817 };
3818 
3819 
3820 class Item_copy_int : public Item_copy
3821 {
3822 protected:
3823   longlong cached_value;
3824 public:
Item_copy_int(Item * i)3825   Item_copy_int (Item *i) : Item_copy(i) {}
3826   type_conversion_status save_in_field(Field *field, bool no_conversions);
3827 
3828   virtual String *val_str(String*);
3829   virtual my_decimal *val_decimal(my_decimal *);
val_real()3830   virtual double val_real()
3831   {
3832     return null_value ? 0.0 : (double) cached_value;
3833   }
val_int()3834   virtual longlong val_int()
3835   {
3836     return null_value ? LL(0) : cached_value;
3837   }
get_date(MYSQL_TIME * ltime,uint fuzzydate)3838   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
3839   {
3840     return get_date_from_int(ltime, fuzzydate);
3841   }
get_time(MYSQL_TIME * ltime)3842   bool get_time(MYSQL_TIME *ltime)
3843   {
3844     return get_time_from_int(ltime);
3845   }
3846   virtual void copy();
3847 };
3848 
3849 
3850 class Item_copy_uint : public Item_copy_int
3851 {
3852 public:
Item_copy_uint(Item * item)3853   Item_copy_uint (Item *item) : Item_copy_int(item)
3854   {
3855     unsigned_flag= 1;
3856   }
3857 
3858   String *val_str(String*);
val_real()3859   double val_real()
3860   {
3861     return null_value ? 0.0 : (double) (ulonglong) cached_value;
3862   }
3863 };
3864 
3865 
3866 class Item_copy_float : public Item_copy
3867 {
3868 protected:
3869   double cached_value;
3870 public:
Item_copy_float(Item * i)3871   Item_copy_float (Item *i) : Item_copy(i) {}
3872   type_conversion_status save_in_field(Field *field, bool no_conversions);
3873 
3874   String *val_str(String*);
3875   my_decimal *val_decimal(my_decimal *);
val_real()3876   double val_real()
3877   {
3878     return null_value ? 0.0 : cached_value;
3879   }
val_int()3880   longlong val_int()
3881   {
3882     return (longlong) rint(val_real());
3883   }
get_date(MYSQL_TIME * ltime,uint fuzzydate)3884   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
3885   {
3886     return get_date_from_real(ltime, fuzzydate);
3887   }
get_time(MYSQL_TIME * ltime)3888   bool get_time(MYSQL_TIME *ltime)
3889   {
3890     return get_time_from_real(ltime);
3891   }
copy()3892   void copy()
3893   {
3894     cached_value= item->val_real();
3895     null_value= item->null_value;
3896   }
3897 };
3898 
3899 
3900 class Item_copy_decimal : public Item_copy
3901 {
3902 protected:
3903   my_decimal cached_value;
3904 public:
Item_copy_decimal(Item * i)3905   Item_copy_decimal (Item *i) : Item_copy(i) {}
3906   type_conversion_status save_in_field(Field *field, bool no_conversions);
3907 
3908   String *val_str(String*);
val_decimal(my_decimal *)3909   my_decimal *val_decimal(my_decimal *)
3910   {
3911     return null_value ? NULL: &cached_value;
3912   }
3913   double val_real();
3914   longlong val_int();
get_date(MYSQL_TIME * ltime,uint fuzzydate)3915   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
3916   {
3917     return get_date_from_decimal(ltime, fuzzydate);
3918   }
get_time(MYSQL_TIME * ltime)3919   bool get_time(MYSQL_TIME *ltime)
3920   {
3921     return get_time_from_decimal(ltime);
3922   }
3923   void copy();
3924 };
3925 
3926 
3927 class Cached_item :public Sql_alloc
3928 {
3929 public:
3930   my_bool null_value;
Cached_item()3931   Cached_item() :null_value(0) {}
3932   virtual bool cmp(void)=0;
3933   virtual ~Cached_item(); /*line -e1509 */
3934 };
3935 
3936 class Cached_item_str :public Cached_item
3937 {
3938   Item *item;
3939   uint32 value_max_length;
3940   String value,tmp_value;
3941 public:
3942   Cached_item_str(THD *thd, Item *arg);
3943   bool cmp(void);
3944   ~Cached_item_str();                           // Deallocate String:s
3945 };
3946 
3947 
3948 class Cached_item_real :public Cached_item
3949 {
3950   Item *item;
3951   double value;
3952 public:
Cached_item_real(Item * item_par)3953   Cached_item_real(Item *item_par) :item(item_par),value(0.0) {}
3954   bool cmp(void);
3955 };
3956 
3957 class Cached_item_int :public Cached_item
3958 {
3959   Item *item;
3960   longlong value;
3961 public:
Cached_item_int(Item * item_par)3962   Cached_item_int(Item *item_par) :item(item_par),value(0) {}
3963   bool cmp(void);
3964 };
3965 
3966 class Cached_item_temporal :public Cached_item
3967 {
3968   Item *item;
3969   longlong value;
3970 public:
Cached_item_temporal(Item * item_par)3971   Cached_item_temporal(Item *item_par) :item(item_par), value(0) {}
3972   bool cmp(void);
3973 };
3974 
3975 
3976 class Cached_item_decimal :public Cached_item
3977 {
3978   Item *item;
3979   my_decimal value;
3980 public:
3981   Cached_item_decimal(Item *item_par);
3982   bool cmp(void);
3983 };
3984 
3985 class Cached_item_field :public Cached_item
3986 {
3987   uchar *buff;
3988   Field *field;
3989   uint length;
3990 
3991 public:
3992 #ifndef DBUG_OFF
dbug_print()3993   void dbug_print()
3994   {
3995     uchar *org_ptr;
3996     org_ptr= field->ptr;
3997     fprintf(DBUG_FILE, "new: ");
3998     field->dbug_print();
3999     field->ptr= buff;
4000     fprintf(DBUG_FILE, ", old: ");
4001     field->dbug_print();
4002     field->ptr= org_ptr;
4003     fprintf(DBUG_FILE, "\n");
4004   }
4005 #endif
Cached_item_field(Field * arg_field)4006   Cached_item_field(Field *arg_field) : field(arg_field)
4007   {
4008     field= arg_field;
4009     /* TODO: take the memory allocation below out of the constructor. */
4010     buff= (uchar*) sql_calloc(length=field->pack_length());
4011   }
4012   bool cmp(void);
4013 };
4014 
4015 class Item_default_value : public Item_field
4016 {
4017 public:
4018   Item *arg;
Item_default_value(Name_resolution_context * context_arg)4019   Item_default_value(Name_resolution_context *context_arg)
4020     :Item_field(context_arg, (const char *)NULL, (const char *)NULL,
4021                (const char *)NULL),
4022      arg(NULL) {}
Item_default_value(Name_resolution_context * context_arg,Item * a)4023   Item_default_value(Name_resolution_context *context_arg, Item *a)
4024     :Item_field(context_arg, (const char *)NULL, (const char *)NULL,
4025                 (const char *)NULL),
4026      arg(a) {}
type()4027   enum Type type() const { return DEFAULT_VALUE_ITEM; }
4028   bool eq(const Item *item, bool binary_cmp) const;
4029   bool fix_fields(THD *, Item **);
4030   virtual void print(String *str, enum_query_type query_type);
4031   type_conversion_status save_in_field(Field *field_arg, bool no_conversions);
used_tables()4032   table_map used_tables() const { return (table_map)0L; }
get_tmp_table_item(THD * thd)4033   Item *get_tmp_table_item(THD *thd) { return copy_or_same(thd); }
4034 
walk(Item_processor processor,bool walk_subquery,uchar * args)4035   bool walk(Item_processor processor, bool walk_subquery, uchar *args)
4036   {
4037     if (arg && arg->walk(processor, walk_subquery, args))
4038       return true;
4039 
4040     return (this->*processor)(args);
4041   }
4042 
4043   Item *transform(Item_transformer transformer, uchar *args);
4044 };
4045 
4046 /*
4047   Item_insert_value -- an implementation of VALUES() function.
4048   You can use the VALUES(col_name) function in the UPDATE clause
4049   to refer to column values from the INSERT portion of the INSERT
4050   ... UPDATE statement. In other words, VALUES(col_name) in the
4051   UPDATE clause refers to the value of col_name that would be
4052   inserted, had no duplicate-key conflict occurred.
4053   In all other places this function returns NULL.
4054 */
4055 
4056 class Item_insert_value : public Item_field
4057 {
4058 public:
4059   Item *arg;
Item_insert_value(Name_resolution_context * context_arg,Item * a)4060   Item_insert_value(Name_resolution_context *context_arg, Item *a)
4061     :Item_field(context_arg, (const char *)NULL, (const char *)NULL,
4062                (const char *)NULL),
4063      arg(a) {}
4064   bool eq(const Item *item, bool binary_cmp) const;
4065   bool fix_fields(THD *, Item **);
4066   virtual void print(String *str, enum_query_type query_type);
save_in_field(Field * field_arg,bool no_conversions)4067   type_conversion_status save_in_field(Field *field_arg, bool no_conversions)
4068   {
4069     return Item_field::save_in_field(field_arg, no_conversions);
4070   }
4071 
type()4072   enum Type type() const { return INSERT_VALUE_ITEM; }
4073   /*
4074    We use RAND_TABLE_BIT to prevent Item_insert_value from
4075    being treated as a constant and precalculated before execution
4076   */
used_tables()4077   table_map used_tables() const { return RAND_TABLE_BIT; }
4078 
walk(Item_processor processor,bool walk_subquery,uchar * args)4079   bool walk(Item_processor processor, bool walk_subquery, uchar *args)
4080   {
4081     return arg->walk(processor, walk_subquery, args) ||
4082 	    (this->*processor)(args);
4083   }
4084 };
4085 
4086 
4087 class Table_triggers_list;
4088 
4089 /*
4090   Represents NEW/OLD version of field of row which is
4091   changed/read in trigger.
4092 
4093   Note: For this item main part of actual binding to Field object happens
4094         not during fix_fields() call (like for Item_field) but right after
4095         parsing of trigger definition, when table is opened, with special
4096         setup_field() call. On fix_fields() stage we simply choose one of
4097         two Field instances representing either OLD or NEW version of this
4098         field.
4099 */
4100 class Item_trigger_field : public Item_field,
4101                            private Settable_routine_parameter
4102 {
4103 public:
4104   /* Is this item represents row from NEW or OLD row ? */
4105   enum row_version_type {OLD_ROW, NEW_ROW};
4106   row_version_type row_version;
4107   /* Next in list of all Item_trigger_field's in trigger */
4108   Item_trigger_field *next_trg_field;
4109   /*
4110     Next list of Item_trigger_field's in "sp_head::
4111     m_list_of_trig_fields_item_lists".
4112   */
4113   SQL_I_List<Item_trigger_field> *next_trig_field_list;
4114   /* Index of the field in the TABLE::field array */
4115   uint field_idx;
4116   /* Pointer to Table_trigger_list object for table of this trigger */
4117   Table_triggers_list *triggers;
4118 
Item_trigger_field(Name_resolution_context * context_arg,row_version_type row_ver_arg,const char * field_name_arg,ulong priv,const bool ro)4119   Item_trigger_field(Name_resolution_context *context_arg,
4120                      row_version_type row_ver_arg,
4121                      const char *field_name_arg,
4122                      ulong priv, const bool ro)
4123     :Item_field(context_arg,
4124                (const char *)NULL, (const char *)NULL, field_name_arg),
4125      row_version(row_ver_arg), next_trig_field_list(NULL), field_idx((uint)-1),
4126      original_privilege(priv), want_privilege(priv), table_grants(NULL),
4127      read_only (ro)
4128   {}
4129   void setup_field(THD *thd, TABLE *table, GRANT_INFO *table_grant_info);
type()4130   enum Type type() const { return TRIGGER_FIELD_ITEM; }
4131   bool eq(const Item *item, bool binary_cmp) const;
4132   bool fix_fields(THD *, Item **);
4133   virtual void print(String *str, enum_query_type query_type);
used_tables()4134   table_map used_tables() const { return (table_map)0L; }
get_tmp_table_field()4135   Field *get_tmp_table_field() { return 0; }
copy_or_same(THD * thd)4136   Item *copy_or_same(THD *thd) { return this; }
get_tmp_table_item(THD * thd)4137   Item *get_tmp_table_item(THD *thd) { return copy_or_same(thd); }
4138   void cleanup();
4139 
4140 private:
4141   void set_required_privilege(bool rw);
4142   bool set_value(THD *thd, sp_rcontext *ctx, Item **it);
4143 
4144 public:
get_settable_routine_parameter()4145   Settable_routine_parameter *get_settable_routine_parameter()
4146   {
4147     return (read_only ? 0 : this);
4148   }
4149 
set_value(THD * thd,Item ** it)4150   bool set_value(THD *thd, Item **it)
4151   {
4152     return set_value(thd, NULL, it);
4153   }
4154 
4155 private:
4156   /*
4157     'want_privilege' holds privileges required to perform operation on
4158     this trigger field (SELECT_ACL if we are going to read it and
4159     UPDATE_ACL if we are going to update it).  It is initialized at
4160     parse time but can be updated later if this trigger field is used
4161     as OUT or INOUT parameter of stored routine (in this case
4162     set_required_privilege() is called to appropriately update
4163     want_privilege and cleanup() is responsible for restoring of
4164     original want_privilege once parameter's value is updated).
4165   */
4166   ulong original_privilege;
4167   ulong want_privilege;
4168   GRANT_INFO *table_grants;
4169   /*
4170     Trigger field is read-only unless it belongs to the NEW row in a
4171     BEFORE INSERT of BEFORE UPDATE trigger.
4172   */
4173   bool read_only;
4174 };
4175 
4176 
4177 class Item_cache: public Item_basic_constant
4178 {
4179 protected:
4180   Item *example;
4181   table_map used_table_map;
4182   /**
4183     Field that this object will get value from. This is used by
4184     index-based subquery engines to detect and remove the equality injected
4185     by IN->EXISTS transformation.
4186   */
4187   Field *cached_field;
4188   enum enum_field_types cached_field_type;
4189   /*
4190     TRUE <=> cache holds value of the last stored item (i.e actual value).
4191     store() stores item to be cached and sets this flag to FALSE.
4192     On the first call of val_xxx function if this flag is set to FALSE the
4193     cache_value() will be called to actually cache value of saved item.
4194     cache_value() will set this flag to TRUE.
4195   */
4196   bool value_cached;
4197 public:
Item_cache()4198   Item_cache():
4199     example(0), used_table_map(0), cached_field(0),
4200     cached_field_type(MYSQL_TYPE_STRING),
4201     value_cached(0)
4202   {
4203     fixed= 1;
4204     null_value= 1;
4205   }
Item_cache(enum_field_types field_type_arg)4206   Item_cache(enum_field_types field_type_arg):
4207     example(0), used_table_map(0), cached_field(0),
4208     cached_field_type(field_type_arg),
4209     value_cached(0)
4210   {
4211     fixed= 1;
4212     null_value= 1;
4213   }
4214 
set_used_tables(table_map map)4215   void set_used_tables(table_map map) { used_table_map= map; }
4216 
allocate(uint i)4217   virtual bool allocate(uint i) { return 0; }
setup(Item * item)4218   virtual bool setup(Item *item)
4219   {
4220     example= item;
4221     max_length= item->max_length;
4222     decimals= item->decimals;
4223     collation.set(item->collation);
4224     unsigned_flag= item->unsigned_flag;
4225     if (item->type() == FIELD_ITEM)
4226     {
4227       cached_field= ((Item_field *)item)->field;
4228       if (cached_field->table)
4229         used_table_map= cached_field->table->map;
4230     }
4231     return 0;
4232   };
type()4233   enum Type type() const { return CACHE_ITEM; }
field_type()4234   enum_field_types field_type() const { return cached_field_type; }
4235   static Item_cache* get_cache(const Item *item);
4236   static Item_cache* get_cache(const Item* item, const Item_result type);
used_tables()4237   table_map used_tables() const { return used_table_map; }
keep_array()4238   virtual void keep_array() {}
4239   virtual void print(String *str, enum_query_type query_type);
eq_def(Field * field)4240   bool eq_def(Field *field)
4241   {
4242     return cached_field ? cached_field->eq_def (field) : FALSE;
4243   }
eq(const Item * item,bool binary_cmp)4244   bool eq(const Item *item, bool binary_cmp) const
4245   {
4246     return this == item;
4247   }
4248   /**
4249      Check if saved item has a non-NULL value.
4250      Will cache value of saved item if not already done.
4251      @return TRUE if cached value is non-NULL.
4252    */
has_value()4253   bool has_value()
4254   {
4255     return (value_cached || cache_value()) && !null_value;
4256   }
4257 
4258   /**
4259     If this item caches a field value, return pointer to underlying field.
4260 
4261     @return Pointer to field, or NULL if this is not a cache for a field value.
4262   */
field()4263   Field* field() { return cached_field; }
4264 
4265   virtual void store(Item *item);
4266   virtual bool cache_value()= 0;
basic_const_item()4267   bool basic_const_item() const
4268   { return MY_TEST(example && example->basic_const_item());}
4269   bool walk (Item_processor processor, bool walk_subquery, uchar *argument);
clear()4270   virtual void clear() { null_value= TRUE; value_cached= FALSE; }
is_null()4271   bool is_null() { return value_cached ? null_value : example->is_null(); }
result_type()4272   Item_result result_type() const
4273   {
4274     if (!example)
4275       return INT_RESULT;
4276     return Field::result_merge_type(example->field_type());
4277   }
4278 };
4279 
4280 
4281 class Item_cache_int: public Item_cache
4282 {
4283 protected:
4284   longlong value;
4285 public:
Item_cache_int()4286   Item_cache_int(): Item_cache(),
4287     value(0) {}
Item_cache_int(enum_field_types field_type_arg)4288   Item_cache_int(enum_field_types field_type_arg):
4289     Item_cache(field_type_arg), value(0) {}
4290 
store(Item * item)4291   virtual void store(Item *item){ Item_cache::store(item); }
4292   void store(Item *item, longlong val_arg);
4293   double val_real();
4294   longlong val_int();
val_time_temporal()4295   longlong val_time_temporal() { return val_int(); }
val_date_temporal()4296   longlong val_date_temporal() { return val_int(); }
4297   String* val_str(String *str);
4298   my_decimal *val_decimal(my_decimal *);
get_date(MYSQL_TIME * ltime,uint fuzzydate)4299   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
4300   {
4301     return get_date_from_int(ltime, fuzzydate);
4302   }
get_time(MYSQL_TIME * ltime)4303   bool get_time(MYSQL_TIME *ltime)
4304   {
4305     return get_time_from_int(ltime);
4306   }
result_type()4307   enum Item_result result_type() const { return INT_RESULT; }
4308   bool cache_value();
4309 };
4310 
4311 
4312 class Item_cache_real: public Item_cache
4313 {
4314   double value;
4315 public:
Item_cache_real()4316   Item_cache_real(): Item_cache(),
4317     value(0) {}
4318 
4319   double val_real();
4320   longlong val_int();
4321   String* val_str(String *str);
4322   my_decimal *val_decimal(my_decimal *);
get_date(MYSQL_TIME * ltime,uint fuzzydate)4323   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
4324   {
4325     return get_date_from_real(ltime, fuzzydate);
4326   }
get_time(MYSQL_TIME * ltime)4327   bool get_time(MYSQL_TIME *ltime)
4328   {
4329     return get_time_from_real(ltime);
4330   }
result_type()4331   enum Item_result result_type() const { return REAL_RESULT; }
4332   bool cache_value();
4333 };
4334 
4335 
4336 class Item_cache_decimal: public Item_cache
4337 {
4338 protected:
4339   my_decimal decimal_value;
4340 public:
Item_cache_decimal()4341   Item_cache_decimal(): Item_cache() {}
4342 
4343   double val_real();
4344   longlong val_int();
4345   String* val_str(String *str);
4346   my_decimal *val_decimal(my_decimal *);
get_date(MYSQL_TIME * ltime,uint fuzzydate)4347   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
4348   {
4349     return get_date_from_decimal(ltime, fuzzydate);
4350   }
get_time(MYSQL_TIME * ltime)4351   bool get_time(MYSQL_TIME *ltime)
4352   {
4353     return get_time_from_decimal(ltime);
4354   }
result_type()4355   enum Item_result result_type() const { return DECIMAL_RESULT; }
4356   bool cache_value();
4357 };
4358 
4359 
4360 class Item_cache_str: public Item_cache
4361 {
4362   char buffer[STRING_BUFFER_USUAL_SIZE];
4363   String *value, value_buff;
4364   bool is_varbinary;
4365 
4366 public:
Item_cache_str(const Item * item)4367   Item_cache_str(const Item *item) :
4368     Item_cache(item->field_type()), value(0),
4369     is_varbinary(item->type() == FIELD_ITEM &&
4370                  cached_field_type == MYSQL_TYPE_VARCHAR &&
4371                  !((const Item_field *) item)->field->has_charset())
4372   {
4373     collation.set(const_cast<DTCollation&>(item->collation));
4374   }
4375   double val_real();
4376   longlong val_int();
4377   String* val_str(String *);
4378   my_decimal *val_decimal(my_decimal *);
get_date(MYSQL_TIME * ltime,uint fuzzydate)4379   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
4380   {
4381     return get_date_from_string(ltime, fuzzydate);
4382   }
get_time(MYSQL_TIME * ltime)4383   bool get_time(MYSQL_TIME *ltime)
4384   {
4385     return get_time_from_string(ltime);
4386   }
result_type()4387   enum Item_result result_type() const { return STRING_RESULT; }
charset()4388   const CHARSET_INFO *charset() const { return value->charset(); };
4389   type_conversion_status save_in_field(Field *field, bool no_conversions);
4390   bool cache_value();
4391 };
4392 
4393 class Item_cache_row: public Item_cache
4394 {
4395   Item_cache  **values;
4396   uint item_count;
4397   bool save_array;
4398 public:
Item_cache_row()4399   Item_cache_row()
4400     :Item_cache(), values(0), item_count(2),
4401     save_array(0) {}
4402 
4403   /*
4404     'allocate' used only in row transformer, to preallocate space for row
4405     cache.
4406   */
4407   bool allocate(uint num);
4408   /*
4409     'setup' is needed only by row => it not called by simple row subselect
4410     (only by IN subselect (in subselect optimizer))
4411   */
4412   bool setup(Item *item);
4413   void store(Item *item);
4414   void illegal_method_call(const char *);
make_field(Send_field *)4415   void make_field(Send_field *)
4416   {
4417     illegal_method_call((const char*)"make_field");
4418   };
val_real()4419   double val_real()
4420   {
4421     illegal_method_call((const char*)"val");
4422     return 0;
4423   };
val_int()4424   longlong val_int()
4425   {
4426     illegal_method_call((const char*)"val_int");
4427     return 0;
4428   };
val_str(String *)4429   String *val_str(String *)
4430   {
4431     illegal_method_call((const char*)"val_str");
4432     return 0;
4433   };
val_decimal(my_decimal * val)4434   my_decimal *val_decimal(my_decimal *val)
4435   {
4436     illegal_method_call((const char*)"val_decimal");
4437     return 0;
4438   };
get_date(MYSQL_TIME * ltime,uint fuzzydate)4439   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
4440   {
4441     illegal_method_call((const char *) "get_date");
4442     return true;
4443   }
get_time(MYSQL_TIME * ltime)4444   bool get_time(MYSQL_TIME *ltime)
4445   {
4446     illegal_method_call((const char *) "get_time");
4447     return true;
4448   }
4449 
result_type()4450   enum Item_result result_type() const { return ROW_RESULT; }
4451 
cols()4452   uint cols() { return item_count; }
element_index(uint i)4453   Item *element_index(uint i) { return values[i]; }
addr(uint i)4454   Item **addr(uint i) { return (Item **) (values + i); }
4455   bool check_cols(uint c);
4456   bool null_inside();
4457   void bring_value();
keep_array()4458   void keep_array() { save_array= 1; }
cleanup()4459   void cleanup()
4460   {
4461     DBUG_ENTER("Item_cache_row::cleanup");
4462     Item_cache::cleanup();
4463     if (save_array)
4464       memset(values, 0, item_count*sizeof(Item**));
4465     else
4466       values= 0;
4467     DBUG_VOID_RETURN;
4468   }
4469   bool cache_value();
4470 };
4471 
4472 
4473 class Item_cache_datetime: public Item_cache
4474 {
4475 protected:
4476   String str_value;
4477   longlong int_value;
4478   bool str_value_cached;
4479 public:
Item_cache_datetime(enum_field_types field_type_arg)4480   Item_cache_datetime(enum_field_types field_type_arg):
4481     Item_cache(field_type_arg), int_value(0), str_value_cached(0)
4482   {
4483     cmp_context= STRING_RESULT;
4484   }
4485 
4486   void store(Item *item, longlong val_arg);
4487   void store(Item *item);
4488   double val_real();
4489   longlong val_int();
4490   longlong val_time_temporal();
4491   longlong val_date_temporal();
4492   String* val_str(String *str);
4493   my_decimal *val_decimal(my_decimal *);
4494   bool get_date(MYSQL_TIME *ltime, uint fuzzydate);
4495   bool get_time(MYSQL_TIME *ltime);
result_type()4496   enum Item_result result_type() const { return STRING_RESULT; }
4497   /*
4498     In order to avoid INT <-> STRING conversion of a DATETIME value
4499     two cache_value functions are introduced. One (cache_value) caches STRING
4500     value, another (cache_value_int) - INT value. Thus this cache item
4501     completely relies on the ability of the underlying item to do the
4502     correct conversion.
4503   */
4504   bool cache_value_int();
4505   bool cache_value();
clear()4506   void clear() { Item_cache::clear(); str_value_cached= FALSE; }
4507 };
4508 
4509 
4510 /*
4511   Item_type_holder used to store type. name, length of Item for UNIONS &
4512   derived tables.
4513 
4514   Item_type_holder do not need cleanup() because its time of live limited by
4515   single SP/PS execution.
4516 */
4517 class Item_type_holder: public Item
4518 {
4519 protected:
4520   TYPELIB *enum_set_typelib;
4521   enum_field_types fld_type;
4522   Field::geometry_type geometry_type;
4523 
4524   void get_full_info(Item *item);
4525 
4526   /* It is used to count decimal precision in join_types */
4527   int prev_decimal_int_part;
4528 public:
4529   Item_type_holder(THD*, Item*);
4530 
4531   Item_result result_type() const;
field_type()4532   enum_field_types field_type() const { return fld_type; };
type()4533   enum Type type() const { return TYPE_HOLDER; }
4534   double val_real();
4535   longlong val_int();
4536   my_decimal *val_decimal(my_decimal *);
4537   String *val_str(String*);
get_date(MYSQL_TIME * ltime,uint fuzzydate)4538   bool get_date(MYSQL_TIME *ltime, uint fuzzydate)
4539   {
4540     DBUG_ASSERT(0);
4541     return true;
4542   }
get_time(MYSQL_TIME * ltime)4543   bool get_time(MYSQL_TIME *ltime)
4544   {
4545     DBUG_ASSERT(0);
4546     return true;
4547   }
4548   bool join_types(THD *thd, Item *);
4549   Field *make_field_by_type(TABLE *table);
4550   static uint32 display_length(Item *item);
4551   static enum_field_types get_real_type(Item *);
get_geometry_type()4552   Field::geometry_type get_geometry_type() const { return geometry_type; };
4553 };
4554 
4555 
4556 class st_select_lex;
4557 void mark_select_range_as_dependent(THD *thd,
4558                                     st_select_lex *last_select,
4559                                     st_select_lex *current_sel,
4560                                     Field *found_field, Item *found_item,
4561                                     Item_ident *resolved_item);
4562 
4563 extern Cached_item *new_Cached_item(THD *thd, Item *item,
4564                                     bool use_result_field);
4565 extern Item_result item_cmp_type(Item_result a,Item_result b);
4566 extern void resolve_const_item(THD *thd, Item **ref, Item *cmp_item);
4567 extern int stored_field_cmp_to_item(THD *thd, Field *field, Item *item);
4568 
4569 extern const String my_null_string;
4570 
4571 #endif /* ITEM_INCLUDED */
4572