1 #ifndef FIELD_INCLUDED
2 #define FIELD_INCLUDED
3 /* Copyright (c) 2000, 2015, Oracle and/or its affiliates.
4    Copyright (c) 2008, 2021, MariaDB Corporation.
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 as published by
8    the Free Software Foundation; version 2 of the License.
9 
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14 
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335  USA */
18 
19 /*
20   Because of the function make_new_field() all field classes that have static
21   variables must declare the size_of() member function.
22 */
23 
24 #ifdef USE_PRAGMA_INTERFACE
25 #pragma interface			/* gcc class implementation */
26 #endif
27 
28 #include "mysqld.h"                             /* system_charset_info */
29 #include "table.h"                              /* TABLE */
30 #include "sql_string.h"                         /* String */
31 #include "my_decimal.h"                         /* my_decimal */
32 #include "sql_error.h"                          /* Sql_condition */
33 #include "compat56.h"
34 #include "sql_type.h"                           /* Type_std_attributes */
35 #include "field_comp.h"
36 
37 class Send_field;
38 class Copy_field;
39 class Protocol;
40 class Protocol_text;
41 class Create_field;
42 class Relay_log_info;
43 class Field;
44 class Column_statistics;
45 class Column_statistics_collected;
46 class Item_func;
47 class Item_bool_func;
48 class Item_equal;
49 class Virtual_tmp_table;
50 class Qualified_column_ident;
51 class Table_ident;
52 class SEL_ARG;
53 class RANGE_OPT_PARAM;
54 struct KEY_PART;
55 struct SORT_FIELD;
56 struct SORT_FIELD_ATTR;
57 
58 enum enum_check_fields
59 {
60   CHECK_FIELD_IGNORE,
61   CHECK_FIELD_EXPRESSION,
62   CHECK_FIELD_WARN,
63   CHECK_FIELD_ERROR_FOR_NULL,
64 };
65 
66 
67 enum enum_conv_type
68 {
69   CONV_TYPE_PRECISE,
70   CONV_TYPE_VARIANT,
71   CONV_TYPE_SUBSET_TO_SUPERSET,
72   CONV_TYPE_SUPERSET_TO_SUBSET,
73   CONV_TYPE_IMPOSSIBLE
74 };
75 
76 
77 class Conv_param
78 {
79   uint16 m_table_def_flags;
80 public:
Conv_param(uint16 table_def_flags)81   Conv_param(uint16 table_def_flags)
82    :m_table_def_flags(table_def_flags)
83   { }
table_def_flags()84   uint16 table_def_flags() const { return m_table_def_flags; }
85 };
86 
87 
88 class Conv_source: public Type_handler_hybrid_field_type
89 {
90   uint16 m_metadata;
91   CHARSET_INFO *m_cs;
92 public:
Conv_source(const Type_handler * h,uint16 metadata,CHARSET_INFO * cs)93   Conv_source(const Type_handler *h, uint16 metadata, CHARSET_INFO *cs)
94    :Type_handler_hybrid_field_type(h),
95     m_metadata(metadata),
96     m_cs(cs)
97   {
98     DBUG_ASSERT(cs);
99   }
metadata()100   uint16 metadata() const { return m_metadata; }
mbmaxlen()101   uint mbmaxlen() const { return m_cs->mbmaxlen; }
102 };
103 
104 
105 /*
106   Common declarations for Field and Item
107 */
108 class Value_source
109 {
110 protected:
111 
112   // Parameters for warning and note generation
113   class Warn_filter
114   {
115     bool m_want_warning_edom;
116     bool m_want_note_truncated_spaces;
117   public:
Warn_filter(bool want_warning_edom,bool want_note_truncated_spaces)118     Warn_filter(bool want_warning_edom, bool want_note_truncated_spaces) :
119      m_want_warning_edom(want_warning_edom),
120      m_want_note_truncated_spaces(want_note_truncated_spaces)
121     { }
122     Warn_filter(const THD *thd);
want_warning_edom()123     bool want_warning_edom() const
124     { return m_want_warning_edom; }
want_note_truncated_spaces()125     bool want_note_truncated_spaces() const
126     { return m_want_note_truncated_spaces; }
127   };
128   class Warn_filter_all: public Warn_filter
129   {
130   public:
Warn_filter_all()131     Warn_filter_all() :Warn_filter(true, true) { }
132   };
133 
134   class Converter_double_to_longlong
135   {
136   protected:
137     bool m_error;
138     longlong m_result;
139   public:
140     Converter_double_to_longlong(double nr, bool unsigned_flag);
result()141     longlong result() const { return m_result; }
error()142     bool error() const { return m_error; }
143     void push_warning(THD *thd, double nr, bool unsigned_flag);
144   };
145   class Converter_double_to_longlong_with_warn:
146     public Converter_double_to_longlong
147   {
148   public:
Converter_double_to_longlong_with_warn(THD * thd,double nr,bool unsigned_flag)149     Converter_double_to_longlong_with_warn(THD *thd, double nr,
150                                            bool unsigned_flag)
151       :Converter_double_to_longlong(nr, unsigned_flag)
152     {
153       if (m_error)
154         push_warning(thd, nr, unsigned_flag);
155     }
Converter_double_to_longlong_with_warn(double nr,bool unsigned_flag)156     Converter_double_to_longlong_with_warn(double nr, bool unsigned_flag)
157       :Converter_double_to_longlong(nr, unsigned_flag)
158     {
159       if (m_error)
160         push_warning(current_thd, nr, unsigned_flag);
161     }
162   };
163 
164   // String-to-number converters
165   class Converter_string_to_number
166   {
167   protected:
168     char *m_end_of_num; // Where the low-level conversion routine stopped
169     int m_error;        // The error code returned by the low-level routine
170     bool m_edom;        // If EDOM-alike error happened during conversion
171     /**
172       Check string-to-number conversion and produce a warning if
173       - could not convert any digits (EDOM-alike error)
174       - found garbage at the end of the string
175       - found extra spaces at the end (a note)
176       See also Field_num::check_edom_and_truncation() for a similar function.
177 
178       @param thd         - the thread that will be used to generate warnings.
179                            Can be NULL (which means current_thd will be used
180                            if a warning is really necessary).
181       @param type        - name of the data type
182                            (e.g. "INTEGER", "DECIMAL", "DOUBLE")
183       @param cs          - character set of the original string
184       @param str         - the original string
185       @param end         - the end of the string
186       @param allow_notes - tells if trailing space notes should be displayed
187                            or suppressed.
188 
189       Unlike Field_num::check_edom_and_truncation(), this function does not
190       distinguish between EDOM and truncation and reports the same warning for
191       both cases. Perhaps we should eventually print different warnings,
192       to make the explicit CAST work closer to the implicit cast in
193       Field_xxx::store().
194     */
195     void check_edom_and_truncation(THD *thd, Warn_filter filter,
196                                    const char *type,
197                                    CHARSET_INFO *cs,
198                                    const char *str,
199                                    size_t length) const;
200   public:
error()201     int error() const { return m_error; }
202   };
203 
204   class Converter_strntod: public Converter_string_to_number
205   {
206     double m_result;
207   public:
Converter_strntod(CHARSET_INFO * cs,const char * str,size_t length)208     Converter_strntod(CHARSET_INFO *cs, const char *str, size_t length)
209     {
210       m_result= cs->strntod((char *) str, length, &m_end_of_num, &m_error);
211       // strntod() does not set an error if the input string was empty
212       m_edom= m_error !=0 || str == m_end_of_num;
213     }
result()214     double result() const { return m_result; }
215   };
216 
217   class Converter_string_to_longlong: public Converter_string_to_number
218   {
219   protected:
220     longlong m_result;
221   public:
result()222     longlong result() const { return m_result; }
223   };
224 
225   class Converter_strntoll: public Converter_string_to_longlong
226   {
227   public:
Converter_strntoll(CHARSET_INFO * cs,const char * str,size_t length)228     Converter_strntoll(CHARSET_INFO *cs, const char *str, size_t length)
229     {
230       m_result= cs->strntoll(str, length, 10, &m_end_of_num, &m_error);
231       /*
232          All non-zero errors means EDOM error.
233          strntoll() does not set an error if the input string was empty.
234          Check it here.
235          Notice the different with the same condition in Converter_strntoll10.
236       */
237       m_edom= m_error != 0 || str == m_end_of_num;
238     }
239   };
240 
241   class Converter_strtoll10: public Converter_string_to_longlong
242   {
243   public:
Converter_strtoll10(CHARSET_INFO * cs,const char * str,size_t length)244     Converter_strtoll10(CHARSET_INFO *cs, const char *str, size_t length)
245     {
246       m_end_of_num= (char *) str + length;
247       m_result= cs->strtoll10(str, &m_end_of_num, &m_error);
248       /*
249         Negative error means "good negative number".
250         Only a positive m_error value means a real error.
251         strtoll10() sets error to MY_ERRNO_EDOM in case of an empty string,
252         so we don't have to additionally catch empty strings here.
253       */
254       m_edom= m_error > 0;
255     }
256   };
257 
258   class Converter_str2my_decimal: public Converter_string_to_number
259   {
260   public:
Converter_str2my_decimal(uint mask,CHARSET_INFO * cs,const char * str,size_t length,my_decimal * buf)261     Converter_str2my_decimal(uint mask,
262                              CHARSET_INFO *cs, const char *str, size_t length,
263                              my_decimal *buf)
264     {
265       DBUG_ASSERT(length < UINT_MAX32);
266       m_error= str2my_decimal(mask, str, length, cs,
267                               buf, (const char **) &m_end_of_num);
268       // E_DEC_TRUNCATED means a very minor truncation: '1e-100' -> 0
269       m_edom= m_error && m_error != E_DEC_TRUNCATED;
270     }
271   };
272 
273 
274   // String-to-number converters with automatic warning generation
275   class Converter_strntod_with_warn: public Converter_strntod
276   {
277   public:
Converter_strntod_with_warn(THD * thd,Warn_filter filter,CHARSET_INFO * cs,const char * str,size_t length)278     Converter_strntod_with_warn(THD *thd, Warn_filter filter,
279                                 CHARSET_INFO *cs,
280                                 const char *str, size_t length)
281       :Converter_strntod(cs, str, length)
282     {
283       check_edom_and_truncation(thd, filter, "DOUBLE", cs, str, length);
284     }
285   };
286 
287   class Converter_strntoll_with_warn: public Converter_strntoll
288   {
289   public:
Converter_strntoll_with_warn(THD * thd,Warn_filter filter,CHARSET_INFO * cs,const char * str,size_t length)290     Converter_strntoll_with_warn(THD *thd, Warn_filter filter,
291                                  CHARSET_INFO *cs,
292                                  const char *str, size_t length)
293       :Converter_strntoll(cs, str, length)
294     {
295       check_edom_and_truncation(thd, filter, "INTEGER", cs, str, length);
296     }
297   };
298 
299   class Converter_strtoll10_with_warn: public Converter_strtoll10
300   {
301   public:
Converter_strtoll10_with_warn(THD * thd,Warn_filter filter,CHARSET_INFO * cs,const char * str,size_t length)302     Converter_strtoll10_with_warn(THD *thd, Warn_filter filter,
303                                  CHARSET_INFO *cs,
304                                  const char *str, size_t length)
305       :Converter_strtoll10(cs, str, length)
306     {
307       check_edom_and_truncation(thd, filter, "INTEGER", cs, str, length);
308     }
309   };
310 
311   class Converter_str2my_decimal_with_warn: public Converter_str2my_decimal
312   {
313   public:
Converter_str2my_decimal_with_warn(THD * thd,Warn_filter filter,uint mask,CHARSET_INFO * cs,const char * str,size_t length,my_decimal * buf)314     Converter_str2my_decimal_with_warn(THD *thd, Warn_filter filter,
315                                        uint mask, CHARSET_INFO *cs,
316                                        const char *str, size_t length,
317                                        my_decimal *buf)
318      :Converter_str2my_decimal(mask, cs, str, length, buf)
319     {
320       check_edom_and_truncation(thd, filter, "DECIMAL", cs, str, length);
321     }
322   };
323 
324 
325   // String-to-number conversion methods for the old code compatibility
longlong_from_string_with_check(CHARSET_INFO * cs,const char * cptr,const char * end)326   longlong longlong_from_string_with_check(CHARSET_INFO *cs, const char *cptr,
327                                            const char *end) const
328   {
329     /*
330       TODO: Give error if we wanted a signed integer and we got an unsigned
331       one
332 
333       Notice, longlong_from_string_with_check() honors thd->no_error, because
334       it's used to handle queries like this:
335         SELECT COUNT(@@basedir);
336       and is called when Item_func_get_system_var::update_null_value()
337       suppresses warnings and then calls val_int().
338       The other methods {double|decimal}_from_string_with_check() ignore
339       thd->no_errors, because they are not used for update_null_value()
340       and they always allow all kind of warnings.
341     */
342     THD *thd= current_thd;
343     return Converter_strtoll10_with_warn(thd, Warn_filter(thd),
344                                          cs, cptr, end - cptr).result();
345   }
346 
double_from_string_with_check(CHARSET_INFO * cs,const char * cptr,const char * end)347   double double_from_string_with_check(CHARSET_INFO *cs, const char *cptr,
348                                        const char *end) const
349   {
350     return Converter_strntod_with_warn(NULL, Warn_filter_all(),
351                                        cs, cptr, end - cptr).result();
352   }
decimal_from_string_with_check(my_decimal * decimal_value,CHARSET_INFO * cs,const char * cptr,const char * end)353   my_decimal *decimal_from_string_with_check(my_decimal *decimal_value,
354                                              CHARSET_INFO *cs,
355                                              const char *cptr,
356                                              const char *end)
357   {
358     Converter_str2my_decimal_with_warn(NULL, Warn_filter_all(),
359                                        E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM,
360                                        cs, cptr, end - cptr, decimal_value);
361     return decimal_value;
362   }
363 
longlong_from_hex_hybrid(const char * str,size_t length)364   longlong longlong_from_hex_hybrid(const char *str, size_t length)
365   {
366     const char *end= str + length;
367     const char *ptr= end - MY_MIN(length, sizeof(longlong));
368     ulonglong value= 0;
369     for ( ; ptr != end ; ptr++)
370       value= (value << 8) + (ulonglong) (uchar) *ptr;
371     return (longlong) value;
372   }
373 
longlong_from_string_with_check(const String * str)374   longlong longlong_from_string_with_check(const String *str) const
375   {
376     return longlong_from_string_with_check(str->charset(),
377                                            str->ptr(), str->end());
378   }
double_from_string_with_check(const String * str)379   double double_from_string_with_check(const String *str) const
380   {
381     return double_from_string_with_check(str->charset(),
382                                          str->ptr(), str->end());
383   }
decimal_from_string_with_check(my_decimal * decimal_value,const String * str)384   my_decimal *decimal_from_string_with_check(my_decimal *decimal_value,
385                                              const String *str)
386   {
387     return decimal_from_string_with_check(decimal_value, str->charset(),
388                                           str->ptr(), str->end());
389   }
390   // End of String-to-number conversion methods
391 
392 public:
393   /*
394     The enumeration Subst_constraint is currently used only in implementations
395     of the virtual function subst_argument_checker.
396   */
397   enum Subst_constraint
398   {
399     ANY_SUBST,           /* Any substitution for a field is allowed  */
400     IDENTITY_SUBST       /* Substitution for a field is allowed if any two
401                             different values of the field type are not equal */
402   };
403   /*
404     Item context attributes.
405     Comparison functions pass their attributes to propagate_equal_fields().
406     For example, for string comparison, the collation of the comparison
407     operation is important inside propagate_equal_fields().
408   */
409   class Context
410   {
411     /*
412       Which type of propagation is allowed:
413       - ANY_SUBST (loose equality, according to the collation), or
414       - IDENTITY_SUBST (strict binary equality).
415     */
416     Subst_constraint m_subst_constraint;
417     /*
418       Comparison type.
419       Important only when ANY_SUBSTS.
420     */
421     const Type_handler *m_compare_handler;
422     /*
423       Collation of the comparison operation.
424       Important only when ANY_SUBST.
425     */
426     CHARSET_INFO *m_compare_collation;
427   public:
Context(Subst_constraint subst,const Type_handler * h,CHARSET_INFO * cs)428     Context(Subst_constraint subst, const Type_handler *h, CHARSET_INFO *cs)
429       :m_subst_constraint(subst),
430        m_compare_handler(h),
431        m_compare_collation(cs)
432     { DBUG_ASSERT(h == h->type_handler_for_comparison()); }
subst_constraint()433     Subst_constraint subst_constraint() const { return m_subst_constraint; }
compare_type_handler()434     const Type_handler *compare_type_handler() const
435     {
436       DBUG_ASSERT(m_subst_constraint == ANY_SUBST);
437       return m_compare_handler;
438     }
compare_collation()439     CHARSET_INFO *compare_collation() const
440     {
441       DBUG_ASSERT(m_subst_constraint == ANY_SUBST);
442       return m_compare_collation;
443     }
444   };
445   class Context_identity: public Context
446   { // Use this to request only exact value, no invariants.
447   public:
Context_identity()448      Context_identity()
449       :Context(IDENTITY_SUBST, &type_handler_long_blob, &my_charset_bin) { }
450   };
451   class Context_boolean: public Context
452   { // Use this when an item is [a part of] a boolean expression
453   public:
Context_boolean()454     Context_boolean()
455       :Context(ANY_SUBST, &type_handler_slonglong, &my_charset_bin) { }
456   };
457 };
458 
459 
460 #define STORAGE_TYPE_MASK 7
461 #define COLUMN_FORMAT_MASK 7
462 #define COLUMN_FORMAT_SHIFT 3
463 
464 /* The length of the header part for each virtual column in the .frm file */
465 #define FRM_VCOL_OLD_HEADER_SIZE(b) (3 + MY_TEST(b))
466 #define FRM_VCOL_NEW_BASE_SIZE 16
467 #define FRM_VCOL_NEW_HEADER_SIZE 6
468 
469 class Count_distinct_field;
470 
471 struct ha_field_option_struct;
472 
473 struct st_cache_field;
474 int field_conv(Field *to,Field *from);
475 int truncate_double(double *nr, uint field_length, uint dec,
476                     bool unsigned_flag, double max_value);
477 
get_enum_pack_length(int elements)478 inline uint get_enum_pack_length(int elements)
479 {
480   return elements < 256 ? 1 : 2;
481 }
482 
get_set_pack_length(int elements)483 inline uint get_set_pack_length(int elements)
484 {
485   uint len= (elements + 7) / 8;
486   return len > 4 ? 8 : len;
487 }
488 
489 
490 /**
491   Tests if field type is temporal and has date part,
492   i.e. represents DATE, DATETIME or TIMESTAMP types in SQL.
493 
494   @param type    Field type, as returned by field->type().
495   @retval true   If field type is temporal type with date part.
496   @retval false  If field type is not temporal type with date part.
497 */
is_temporal_type_with_date(enum_field_types type)498 inline bool is_temporal_type_with_date(enum_field_types type)
499 {
500   switch (type)
501   {
502   case MYSQL_TYPE_DATE:
503   case MYSQL_TYPE_DATETIME:
504   case MYSQL_TYPE_TIMESTAMP:
505     return true;
506   case MYSQL_TYPE_DATETIME2:
507   case MYSQL_TYPE_TIMESTAMP2:
508     DBUG_ASSERT(0); // field->real_type() should not get to here.
509     return false;
510   default:
511     return false;
512   }
513 }
514 
515 
516 enum enum_vcol_info_type
517 {
518   VCOL_GENERATED_VIRTUAL, VCOL_GENERATED_STORED,
519   VCOL_DEFAULT, VCOL_CHECK_FIELD, VCOL_CHECK_TABLE,
520   VCOL_USING_HASH,
521   /* Additional types should be added here */
522   /* Following is the highest value last   */
523   VCOL_TYPE_NONE = 127 // Since the 0 value is already in use
524 };
525 
vcol_type_name(enum_vcol_info_type type)526 static inline const char *vcol_type_name(enum_vcol_info_type type)
527 {
528   switch (type)
529   {
530   case VCOL_GENERATED_VIRTUAL:
531   case VCOL_GENERATED_STORED:
532     return "GENERATED ALWAYS AS";
533   case VCOL_DEFAULT:
534     return "DEFAULT";
535   case VCOL_CHECK_FIELD:
536   case VCOL_CHECK_TABLE:
537     return "CHECK";
538   case VCOL_USING_HASH:
539     return "USING HASH";
540   case VCOL_TYPE_NONE:
541     return "UNTYPED";
542   }
543   return 0;
544 }
545 
546 /*
547   Flags for Virtual_column_info. If none is set, the expression must be
548   a constant with no side-effects, so it's calculated at CREATE TABLE time,
549   stored in table->record[2], and not recalculated for every statement.
550 */
551 #define VCOL_FIELD_REF         1
552 #define VCOL_NON_DETERMINISTIC 2
553 #define VCOL_SESSION_FUNC      4  /* uses session data, e.g. USER or DAYNAME */
554 #define VCOL_TIME_FUNC         8
555 #define VCOL_AUTO_INC         16
556 #define VCOL_IMPOSSIBLE       32
557 #define VCOL_NOT_VIRTUAL      64  /* Function can't be virtual */
558 #define VCOL_CHECK_CONSTRAINT_IF_NOT_EXISTS 128
559 
560 #define VCOL_NOT_STRICTLY_DETERMINISTIC                       \
561   (VCOL_NON_DETERMINISTIC | VCOL_TIME_FUNC | VCOL_SESSION_FUNC)
562 
563 /*
564   Virtual_column_info is the class to contain additional
565   characteristics that is specific for a virtual/computed
566   field such as:
567    - the defining expression that is evaluated to compute the value
568   of the field
569   - whether the field is to be stored in the database
570   - whether the field is used in a partitioning expression
571 */
572 
573 class Virtual_column_info: public Sql_alloc,
574                            private Type_handler_hybrid_field_type
575 {
576 private:
577   enum_vcol_info_type vcol_type; /* Virtual column expression type */
578   /*
579     The following data is only updated by the parser and read
580     when a Create_field object is created/initialized.
581   */
582   /* Flag indicating that the field used in a partitioning expression */
583   bool in_partitioning_expr;
584 
585 public:
586   /* Flag indicating  that the field is physically stored in the database */
587   bool stored_in_db;
588   bool utf8;                                    /* Already in utf8 */
589   bool automatic_name;
590   Item *expr;
591   Lex_ident name;                               /* Name of constraint */
592   /* see VCOL_* (VCOL_FIELD_REF, ...) */
593   uint flags;
594 
Virtual_column_info()595   Virtual_column_info()
596    :Type_handler_hybrid_field_type(&type_handler_null),
597     vcol_type((enum_vcol_info_type)VCOL_TYPE_NONE),
598     in_partitioning_expr(FALSE), stored_in_db(FALSE),
599     utf8(TRUE), automatic_name(FALSE), expr(NULL), flags(0)
600   {
601     name.str= NULL;
602     name.length= 0;
603   };
604   Virtual_column_info* clone(THD *thd);
~Virtual_column_info()605   ~Virtual_column_info() {};
get_vcol_type()606   enum_vcol_info_type get_vcol_type() const
607   {
608     return vcol_type;
609   }
set_vcol_type(enum_vcol_info_type v_type)610   void set_vcol_type(enum_vcol_info_type v_type)
611   {
612     vcol_type= v_type;
613   }
get_vcol_type_name()614   const char *get_vcol_type_name() const
615   {
616     DBUG_ASSERT(vcol_type != VCOL_TYPE_NONE);
617     return vcol_type_name(vcol_type);
618   }
set_handler(const Type_handler * handler)619   void set_handler(const Type_handler *handler)
620   {
621     /* Calling this function can only be done once. */
622     DBUG_ASSERT(type_handler() == &type_handler_null);
623     Type_handler_hybrid_field_type::set_handler(handler);
624   }
is_stored()625   bool is_stored() const
626   {
627     return stored_in_db;
628   }
set_stored_in_db_flag(bool stored)629   void set_stored_in_db_flag(bool stored)
630   {
631     stored_in_db= stored;
632   }
is_in_partitioning_expr()633   bool is_in_partitioning_expr() const
634   {
635     return in_partitioning_expr;
636   }
mark_as_in_partitioning_expr()637   void mark_as_in_partitioning_expr()
638   {
639     in_partitioning_expr= TRUE;
640   }
641   inline bool is_equal(const Virtual_column_info* vcol) const;
642   inline void print(String*);
643 };
644 
645 class Binlog_type_info
646 {
647 public:
648    enum binlog_sign_t
649    {
650      SIGN_SIGNED,
651      SIGN_UNSIGNED,
652      SIGN_NOT_APPLICABLE // for non-numeric types
653    };
654    uchar m_type_code;     // according to Field::binlog_type()
655   /**
656      Retrieve the field metadata for fields.
657   */
658    uint16 m_metadata;
659    uint8 m_metadata_size;
660    binlog_sign_t m_signedness;
661    CHARSET_INFO *m_cs; // NULL if not relevant
662    TYPELIB *m_enum_typelib; // NULL if not relevant
663    TYPELIB *m_set_typelib; // NULL if not relevant
664    uchar m_geom_type; // Non-geometry fields can return 0
Binlog_type_info(uchar type_code,uint16 metadata,uint8 metadata_size)665    Binlog_type_info(uchar type_code,
666                     uint16 metadata,
667                     uint8 metadata_size)
668     :m_type_code(type_code),
669      m_metadata(metadata),
670      m_metadata_size(metadata_size),
671      m_signedness(SIGN_NOT_APPLICABLE),
672      m_cs(NULL),
673      m_enum_typelib(NULL),
674      m_set_typelib(NULL),
675      m_geom_type(0)
676     {};
Binlog_type_info(uchar type_code,uint16 metadata,uint8 metadata_size,binlog_sign_t signedness)677    Binlog_type_info(uchar type_code, uint16 metadata,
678                    uint8 metadata_size,
679                    binlog_sign_t signedness)
680     :m_type_code(type_code),
681      m_metadata(metadata),
682      m_metadata_size(metadata_size),
683      m_signedness(signedness),
684      m_cs(NULL),
685      m_enum_typelib(NULL),
686      m_set_typelib(NULL),
687      m_geom_type(0)
688     {};
Binlog_type_info(uchar type_code,uint16 metadata,uint8 metadata_size,CHARSET_INFO * cs)689    Binlog_type_info(uchar type_code, uint16 metadata,
690                    uint8 metadata_size,
691                    CHARSET_INFO *cs)
692     :m_type_code(type_code),
693      m_metadata(metadata),
694      m_metadata_size(metadata_size),
695      m_signedness(SIGN_NOT_APPLICABLE),
696      m_cs(cs),
697      m_enum_typelib(NULL),
698      m_set_typelib(NULL),
699      m_geom_type(0)
700     {};
Binlog_type_info(uchar type_code,uint16 metadata,uint8 metadata_size,CHARSET_INFO * cs,TYPELIB * t_enum,TYPELIB * t_set)701    Binlog_type_info(uchar type_code, uint16 metadata,
702                    uint8 metadata_size,
703                    CHARSET_INFO *cs,
704                    TYPELIB *t_enum, TYPELIB *t_set)
705     :m_type_code(type_code),
706      m_metadata(metadata),
707      m_metadata_size(metadata_size),
708      m_signedness(SIGN_NOT_APPLICABLE),
709      m_cs(cs),
710      m_enum_typelib(t_enum),
711      m_set_typelib(t_set),
712      m_geom_type(0)
713     {};
Binlog_type_info(uchar type_code,uint16 metadata,uint8 metadata_size,CHARSET_INFO * cs,uchar geom_type)714    Binlog_type_info(uchar type_code, uint16 metadata,
715                    uint8 metadata_size, CHARSET_INFO *cs,
716                    uchar geom_type)
717     :m_type_code(type_code),
718      m_metadata(metadata),
719      m_metadata_size(metadata_size),
720      m_signedness(SIGN_NOT_APPLICABLE),
721      m_cs(cs),
722      m_enum_typelib(NULL),
723      m_set_typelib(NULL),
724      m_geom_type(geom_type)
725     {};
new(size_t size,MEM_ROOT * mem_root)726   static void *operator new(size_t size, MEM_ROOT *mem_root) throw ()
727   { return alloc_root(mem_root, size); }
728 };
729 
730 
731 class Binlog_type_info_fixed_string: public Binlog_type_info
732 {
733 public:
734   Binlog_type_info_fixed_string(uchar type_code,
735                                 uint32 octet_length,
736                                 CHARSET_INFO *cs);
737 };
738 
739 
740 class Field: public Value_source
741 {
742   Field(const Item &);				/* Prevent use of these */
743   void operator=(Field &);
744 protected:
save_in_field_str(Field * to)745   int save_in_field_str(Field *to)
746   {
747     StringBuffer<MAX_FIELD_WIDTH> result(charset());
748     val_str(&result);
749     return to->store(result.ptr(), result.length(), charset());
750   }
751   void error_generated_column_function_is_not_allowed(THD *thd, bool error)
752                                                       const;
753   static void do_field_eq(Copy_field *copy);
754   static void do_field_int(Copy_field *copy);
755   static void do_field_real(Copy_field *copy);
756   static void do_field_string(Copy_field *copy);
757   static void do_field_date(Copy_field *copy);
758   static void do_field_temporal(Copy_field *copy, date_mode_t fuzzydate);
759   static void do_field_datetime(Copy_field *copy);
760   static void do_field_timestamp(Copy_field *copy);
761   static void do_field_decimal(Copy_field *copy);
762 public:
new(size_t size,MEM_ROOT * mem_root)763   static void *operator new(size_t size, MEM_ROOT *mem_root) throw ()
764   { return alloc_root(mem_root, size); }
new(size_t size)765   static void *operator new(size_t size) throw ()
766   {
767     DBUG_ASSERT(size < UINT_MAX32);
768     return thd_alloc(current_thd, (uint) size);
769   }
delete(void * ptr_arg,size_t size)770   static void operator delete(void *ptr_arg, size_t size) { TRASH_FREE(ptr_arg, size); }
delete(void * ptr,MEM_ROOT * mem_root)771   static void operator delete(void *ptr, MEM_ROOT *mem_root)
772   { DBUG_ASSERT(0); }
773 
774   bool marked_for_read() const;
775   bool marked_for_write_or_computed() const;
776 
777   /**
778      Used by System Versioning.
779    */
set_max()780   virtual void set_max()
781   { DBUG_ASSERT(0); }
is_max()782   virtual bool is_max()
783   { DBUG_ASSERT(0); return false; }
784 
785   uchar		*ptr;			// Position to field in record
786 
787   field_visibility_t invisible;
788   /**
789      Byte where the @c NULL bit is stored inside a record. If this Field is a
790      @c NOT @c NULL field, this member is @c NULL.
791   */
792   uchar		*null_ptr;
793   /*
794     Note that you can use table->in_use as replacement for current_thd member
795     only inside of val_*() and store() members (e.g. you can't use it in cons)
796   */
797   TABLE *table;                                 // Pointer for table
798   TABLE *orig_table;                            // Pointer to original table
799   const char * const *table_name;               // Pointer to alias in TABLE
800   LEX_CSTRING field_name;
801   LEX_CSTRING comment;
802   /** reference to the list of options or NULL */
803   engine_option_value *option_list;
804   ha_field_option_struct *option_struct;   /* structure with parsed options */
805   /* Field is part of the following keys */
806   key_map	key_start, part_of_key, part_of_key_not_clustered;
807 
808   /*
809     Bitmap of indexes that have records ordered by col1, ... this_field, ...
810 
811     For example, INDEX (col(prefix_n)) is not present in col.part_of_sortkey.
812   */
813   key_map       part_of_sortkey;
814   /*
815     We use three additional unireg types for TIMESTAMP to overcome limitation
816     of current binary format of .frm file. We'd like to be able to support
817     NOW() as default and on update value for such fields but unable to hold
818     this info anywhere except unireg_check field. This issue will be resolved
819     in more clean way with transition to new text based .frm format.
820     See also comment for Field_timestamp::Field_timestamp().
821   */
822   enum utype  {
823     NONE=0,
824     NEXT_NUMBER=15,             // AUTO_INCREMENT
825     TIMESTAMP_OLD_FIELD=18,     // TIMESTAMP created before 4.1.3
826     TIMESTAMP_DN_FIELD=21,      // TIMESTAMP DEFAULT NOW()
827     TIMESTAMP_UN_FIELD=22,      // TIMESTAMP ON UPDATE NOW()
828     TIMESTAMP_DNUN_FIELD=23,    // TIMESTAMP DEFAULT NOW() ON UPDATE NOW()
829     TMYSQL_COMPRESSED= 24,      // Compatibility with TMySQL
830     };
831   enum imagetype { itRAW, itMBR};
832 
833   utype		unireg_check;
834   uint32	field_length;		// Length of field
835   uint32	flags;
836   uint16        field_index;            // field number in fields array
837   uchar		null_bit;		// Bit used to test null bit
838   /**
839      If true, this field was created in create_tmp_field_from_item from a NULL
840      value. This means that the type of the field is just a guess, and the type
841      may be freely coerced to another type.
842 
843      @see create_tmp_field_from_item
844      @see Item_type_holder::get_real_type
845 
846    */
847   bool is_created_from_null_item;
848 
849   /*
850     Selectivity of the range condition over this field.
851     When calculating this selectivity a range predicate
852     is taken into account only if:
853     - it is extracted from the WHERE clause
854     - it depends only on the table the field belongs to
855   */
856   double cond_selectivity;
857 
858   /*
859     The next field in the class of equal fields at the top AND level
860     of the WHERE clause
861   */
862   Field *next_equal_field;
863 
864   /*
865     This structure is used for statistical data on the column
866     that has been read from the statistical table column_stat
867   */
868   Column_statistics *read_stats;
869   /*
870     This structure is used for statistical data on the column that
871     is collected by the function collect_statistics_for_table
872   */
873   Column_statistics_collected *collected_stats;
874 
875   /*
876     This is additional data provided for any computed(virtual) field,
877     default function or check constraint.
878     In particular it includes a pointer to the item by which this field
879     can be computed from other fields.
880   */
881   Virtual_column_info *vcol_info, *check_constraint, *default_value;
882 
883   Field(uchar *ptr_arg,uint32 length_arg,uchar *null_ptr_arg,
884         uchar null_bit_arg, utype unireg_check_arg,
885         const LEX_CSTRING *field_name_arg);
~Field()886   virtual ~Field() {}
887 
type_numeric_attributes()888   virtual Type_numeric_attributes type_numeric_attributes() const
889   {
890     return Type_numeric_attributes(field_length, decimals(), is_unsigned());
891   }
type_std_attributes()892   Type_std_attributes type_std_attributes() const
893   {
894     return Type_std_attributes(type_numeric_attributes(), dtcollation());
895   }
896 
is_unsigned()897   bool is_unsigned() const { return flags & UNSIGNED_FLAG; }
898 
899   /**
900     Convenience definition of a copy function returned by
901     Field::get_copy_func()
902   */
903   typedef void Copy_func(Copy_field*);
904   virtual Copy_func *get_copy_func(const Field *from) const= 0;
get_copy_func_to(const Field * to)905   virtual Copy_func *get_copy_func_to(const Field *to) const
906   {
907     return to->get_copy_func(this);
908   }
909   /* Store functions returns 1 on overflow and -1 on fatal error */
store_field(Field * from)910   virtual int  store_field(Field *from) { return from->save_in_field(this); }
911   virtual int  save_in_field(Field *to)= 0;
912   /**
913     Check if it is possible just copy the value
914     of the field 'from' to the field 'this', e.g. for
915       INSERT INTO t1 (field1) SELECT field2 FROM t2;
916     @param from   - The field to copy from
917     @retval true  - it is possible to just copy value of 'from' to 'this'
918     @retval false - conversion is needed
919   */
920   virtual bool memcpy_field_possible(const Field *from) const= 0;
921   virtual bool make_empty_rec_store_default_value(THD *thd, Item *item);
make_empty_rec_reset(THD * thd)922   virtual void make_empty_rec_reset(THD *thd)
923   {
924     reset();
925   }
926   virtual int  store(const char *to, size_t length,CHARSET_INFO *cs)=0;
927   /*
928     This is used by engines like CSV and Federated to signal the field
929     that the data is going to be in text (rather than binary) representation,
930     even if cs points to &my_charset_bin.
931 
932     If a Field distinguishes between text and binary formats (e.g. INET6),
933     we cannot call store(str,length,&my_charset_bin),
934     to avoid "field" mis-interpreting the data format as binary.
935   */
store_text(const char * to,size_t length,CHARSET_INFO * cs)936   virtual int  store_text(const char *to, size_t length, CHARSET_INFO *cs)
937   {
938     return store(to, length, cs);
939   }
store_binary(const char * to,size_t length)940   virtual int  store_binary(const char *to, size_t length)
941   {
942     return store(to, length, &my_charset_bin);
943   }
944   virtual int  store_hex_hybrid(const char *str, size_t length);
945   virtual int  store(double nr)=0;
946   virtual int  store(longlong nr, bool unsigned_val)=0;
947   virtual int  store_decimal(const my_decimal *d)=0;
948   virtual int  store_time_dec(const MYSQL_TIME *ltime, uint dec);
949   virtual int  store_timestamp_dec(const timeval &ts, uint dec);
store_timestamp(my_time_t timestamp,ulong sec_part)950   int store_timestamp(my_time_t timestamp, ulong sec_part)
951   {
952     return store_timestamp_dec(Timeval(timestamp, sec_part),
953                                TIME_SECOND_PART_DIGITS);
954   }
955   /**
956     Store a value represented in native format
957   */
store_native(const Native & value)958   virtual int store_native(const Native &value)
959   {
960     DBUG_ASSERT(0);
961     reset();
962     return 0;
963   }
store_time(const MYSQL_TIME * ltime)964   int store_time(const MYSQL_TIME *ltime)
965   { return store_time_dec(ltime, TIME_SECOND_PART_DIGITS); }
966   int store(const char *to, size_t length, CHARSET_INFO *cs,
967             enum_check_fields check_level);
968   int store_text(const char *to, size_t length, CHARSET_INFO *cs,
969                  enum_check_fields check_level);
store(const LEX_STRING * ls,CHARSET_INFO * cs)970   int store(const LEX_STRING *ls, CHARSET_INFO *cs)
971   {
972     DBUG_ASSERT(ls->length < UINT_MAX32);
973     return store(ls->str, (uint) ls->length, cs);
974   }
store(const LEX_CSTRING * ls,CHARSET_INFO * cs)975   int store(const LEX_CSTRING *ls, CHARSET_INFO *cs)
976   {
977     DBUG_ASSERT(ls->length < UINT_MAX32);
978     return store(ls->str, (uint) ls->length, cs);
979   }
store(const LEX_CSTRING & ls,CHARSET_INFO * cs)980   int store(const LEX_CSTRING &ls, CHARSET_INFO *cs)
981   {
982     DBUG_ASSERT(ls.length < UINT_MAX32);
983     return store(ls.str, (uint) ls.length, cs);
984   }
985 
986   /*
987     @brief
988       Store minimum/maximum value of a column in the statistics table.
989     @param
990       field                  statistical table field
991       str                    value buffer
992   */
993   virtual int store_to_statistical_minmax_field(Field *field, String *str);
994 
995   /*
996     @brief
997       Store minimum/maximum value of a column from the statistical table.
998     @param
999       field                  statistical table field
1000       str                    value buffer
1001   */
1002   virtual int store_from_statistical_minmax_field(Field *field, String *str);
1003 
1004 #ifdef HAVE_MEM_CHECK
1005   /**
1006     Mark unused memory in the field as defined. Mainly used to ensure
1007     that if we write full field to disk (for example in
1008     Count_distinct_field::add(), we don't write unitalized data to
1009     disk which would confuse valgrind or MSAN.
1010   */
mark_unused_memory_as_defined()1011   virtual void mark_unused_memory_as_defined() {}
1012 #else
mark_unused_memory_as_defined()1013   void mark_unused_memory_as_defined() {}
1014 #endif
1015 
1016   virtual double val_real()=0;
1017   virtual longlong val_int()=0;
1018   /*
1019     Get ulonglong representation.
1020     Negative values are truncated to 0.
1021   */
val_uint(void)1022   virtual ulonglong val_uint(void)
1023   {
1024     longlong nr= val_int();
1025     return nr < 0 ? 0 : (ulonglong) nr;
1026   }
1027   virtual bool val_bool()= 0;
1028   virtual my_decimal *val_decimal(my_decimal *)=0;
val_str(String * str)1029   inline String *val_str(String *str) { return val_str(str, str); }
1030   /*
1031      val_str(buf1, buf2) gets two buffers and should use them as follows:
1032      if it needs a temp buffer to convert result to string - use buf1
1033        example Field_tiny::val_str()
1034      if the value exists as a string already - use buf2
1035        example Field_string::val_str()
1036      consequently, buf2 may be created as 'String buf;' - no memory
1037      will be allocated for it. buf1 will be allocated to hold a
1038      value if it's too small. Using allocated buffer for buf2 may result in
1039      an unnecessary free (and later, may be an alloc).
1040      This trickery is used to decrease a number of malloc calls.
1041   */
1042   virtual String *val_str(String*,String *)=0;
val_native(Native * to)1043   virtual bool val_native(Native *to)
1044   {
1045     DBUG_ASSERT(!is_null());
1046     return to->copy((const char *) ptr, pack_length());
1047   }
1048   String *val_int_as_str(String *val_buffer, bool unsigned_flag);
1049   /*
1050     Return the field value as a LEX_CSTRING, without padding to full length
1051     (MODE_PAD_CHAR_TO_FULL_LENGTH is temporarily suppressed during the call).
1052 
1053     In case of an empty value, to[0] is assigned to empty_clex_string,
1054     memory is not allocated.
1055     In case of a non-empty value, the memory is allocated on mem_root.
1056     In case of a memory allocation failure, to[0] is assigned to {NULL,0}.
1057 
1058     @param  [IN] mem_root  store non-empty values here
1059     @param  [OUT to        return the string here
1060     @retval                false (success)
1061     @retval                true  (EOM)
1062   */
1063   bool val_str_nopad(MEM_ROOT *mem_root, LEX_CSTRING *to);
1064   fast_field_copier get_fast_field_copier(const Field *from);
1065   /*
1066    str_needs_quotes() returns TRUE if the value returned by val_str() needs
1067    to be quoted when used in constructing an SQL query.
1068   */
str_needs_quotes()1069   virtual bool str_needs_quotes() const { return false; }
type_handler_for_comparison()1070   const Type_handler *type_handler_for_comparison() const
1071   {
1072     return type_handler()->type_handler_for_comparison();
1073   }
result_type()1074   Item_result result_type () const
1075   {
1076     return type_handler()->result_type();
1077   }
cmp_type()1078   Item_result cmp_type () const
1079   {
1080     return type_handler()->cmp_type();
1081   }
eq(Field * field)1082   virtual bool eq(Field *field)
1083   {
1084     return (ptr == field->ptr && null_ptr == field->null_ptr &&
1085             null_bit == field->null_bit && field->type() == type());
1086   }
1087   virtual bool eq_def(const Field *field) const;
1088 
1089   /*
1090     pack_length() returns size (in bytes) used to store field data in memory
1091     (i.e. it returns the maximum size of the field in a row of the table,
1092     which is located in RAM).
1093   */
pack_length()1094   virtual uint32 pack_length() const { return (uint32) field_length; }
1095 
1096   /*
1097     pack_length_in_rec() returns size (in bytes) used to store field data on
1098     storage (i.e. it returns the maximal size of the field in a row of the
1099     table, which is located on disk).
1100   */
pack_length_in_rec()1101   virtual uint32 pack_length_in_rec() const { return pack_length(); }
1102   virtual bool compatible_field_size(uint metadata, const Relay_log_info *rli,
1103                                      uint16 mflags, int *order) const;
pack_length_from_metadata(uint field_metadata)1104   virtual uint pack_length_from_metadata(uint field_metadata) const
1105   {
1106     DBUG_ENTER("Field::pack_length_from_metadata");
1107     DBUG_RETURN(field_metadata);
1108   }
row_pack_length()1109   virtual uint row_pack_length() const { return 0; }
1110 
1111   /*
1112     data_length() return the "real size" of the data in memory.
1113   */
data_length()1114   virtual uint32 data_length() { return pack_length(); }
sort_length()1115   virtual uint32 sort_length() const { return pack_length(); }
1116 
1117   /*
1118     sort_suffix_length() return the length bytes needed to store the length
1119     for binary charset
1120   */
sort_suffix_length()1121   virtual uint32 sort_suffix_length() const { return 0; }
1122 
1123   /*
1124     Get the number bytes occupied by the value in the field.
1125     CHAR values are stripped of trailing spaces.
1126     Flexible values are stripped of their length.
1127   */
value_length()1128   virtual uint32 value_length()
1129   {
1130     uint len;
1131     if (!zero_pack() &&
1132 	(type() == MYSQL_TYPE_STRING &&
1133         (len= pack_length()) >= 4 && len < 256))
1134     {
1135       uchar *str, *end;
1136       for (str= ptr, end= str+len; end > str && end[-1] == ' '; end--) {}
1137       len=(uint) (end-str);
1138       return len;
1139     }
1140     return data_length();
1141   }
1142 
1143   /**
1144      Get the maximum size of the data in packed format.
1145 
1146      @return Maximum data length of the field when packed using the
1147      Field::pack() function.
1148    */
max_data_length()1149   virtual uint32 max_data_length() const {
1150     return pack_length();
1151   };
1152 
reset()1153   virtual int reset() { bzero(ptr,pack_length()); return 0; }
reset_fields()1154   virtual void reset_fields() {}
ptr_in_record(const uchar * record)1155   const uchar *ptr_in_record(const uchar *record) const
1156   {
1157     my_ptrdiff_t l_offset= (my_ptrdiff_t) (ptr -  table->record[0]);
1158     DBUG_ASSERT(l_offset >= 0 && table->s->rec_buff_length - l_offset > 0);
1159     return record + l_offset;
1160   }
1161   virtual int set_default();
1162 
has_update_default_function()1163   bool has_update_default_function() const
1164   {
1165     return flags & ON_UPDATE_NOW_FLAG;
1166   }
has_default_now_unireg_check()1167   bool has_default_now_unireg_check() const
1168   {
1169     return unireg_check == TIMESTAMP_DN_FIELD
1170         || unireg_check == TIMESTAMP_DNUN_FIELD;
1171   }
1172 
1173   /*
1174     Mark the field as having a value supplied by the client, thus it should
1175     not be auto-updated.
1176   */
set_has_explicit_value()1177   void set_has_explicit_value()
1178   {
1179     bitmap_set_bit(&table->has_value_set, field_index);
1180   }
has_explicit_value()1181   bool has_explicit_value()
1182   {
1183     return bitmap_is_set(&table->has_value_set, field_index);
1184   }
clear_has_explicit_value()1185   void clear_has_explicit_value()
1186   {
1187     bitmap_clear_bit(&table->has_value_set, field_index);
1188   }
1189 
get_timestamp(const uchar * pos,ulong * sec_part)1190   virtual my_time_t get_timestamp(const uchar *pos, ulong *sec_part) const
1191   { DBUG_ASSERT(0); return 0; }
get_timestamp(ulong * sec_part)1192   my_time_t get_timestamp(ulong *sec_part) const
1193   {
1194     return get_timestamp(ptr, sec_part);
1195   }
1196 
binary()1197   virtual bool binary() const { return 1; }
zero_pack()1198   virtual bool zero_pack() const { return 1; }
key_type()1199   virtual enum ha_base_keytype key_type() const { return HA_KEYTYPE_BINARY; }
key_part_flag()1200   virtual uint16 key_part_flag() const { return 0; }
key_part_length_bytes()1201   virtual uint16 key_part_length_bytes() const { return 0; }
key_length()1202   virtual uint32 key_length() const { return pack_length(); }
1203   virtual const Type_handler *type_handler() const= 0;
type()1204   virtual enum_field_types type() const
1205   {
1206     return type_handler()->field_type();
1207   }
real_type()1208   virtual enum_field_types real_type() const
1209   {
1210     return type_handler()->real_field_type();
1211   }
binlog_type()1212   virtual enum_field_types binlog_type() const
1213   {
1214     /*
1215       Binlog stores field->type() as type code by default. For example,
1216       it puts MYSQL_TYPE_STRING in case of CHAR, VARCHAR, SET and ENUM,
1217       with extra data type details put into metadata.
1218 
1219       Binlog behaviour slightly differs between various MySQL and MariaDB
1220       versions for the temporal data types TIME, DATETIME and TIMESTAMP.
1221 
1222       MySQL prior to 5.6 uses MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME
1223       and MYSQL_TYPE_TIMESTAMP type codes in binlog and stores no
1224       additional metadata.
1225 
1226       MariaDB-5.3 implements new versions for TIME, DATATIME, TIMESTAMP
1227       with fractional second precision, but uses the old format for the
1228       types TIME(0), DATETIME(0), TIMESTAMP(0), and it still stores
1229       MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME and MYSQL_TYPE_TIMESTAMP in binlog,
1230       with no additional metadata.
1231       So row-based replication between temporal data types of
1232       different precision is not possible in MariaDB.
1233 
1234       MySQL-5.6 also implements a new version of TIME, DATETIME, TIMESTAMP
1235       which support fractional second precision 0..6, and use the new
1236       format even for the types TIME(0), DATETIME(0), TIMESTAMP(0).
1237       For these new data types, MySQL-5.6 stores new type codes
1238       MYSQL_TYPE_TIME2, MYSQL_TYPE_DATETIME2, MYSQL_TYPE_TIMESTAMP2 in binlog,
1239       with fractional precision 0..6 put into metadata.
1240       This makes it in theory possible to do row-based replication between
1241       columns of different fractional precision (e.g. from TIME(1) on master
1242       to TIME(6) on slave). However, it's not currently fully implemented yet.
1243       MySQL-5.6 can only do row-based replication from the old types
1244       TIME, DATETIME, TIMESTAMP (represented by MYSQL_TYPE_TIME,
1245       MYSQL_TYPE_DATETIME and MYSQL_TYPE_TIMESTAMP type codes in binlog)
1246       to the new corresponding types TIME(0), DATETIME(0), TIMESTAMP(0).
1247 
1248       Note: MariaDB starting from the version 10.0 understands the new
1249       MySQL-5.6 type codes MYSQL_TYPE_TIME2, MYSQL_TYPE_DATETIME2,
1250       MYSQL_TYPE_TIMESTAMP2. When started over MySQL-5.6 tables both on
1251       master and on slave, MariaDB-10.0 can also do row-based replication
1252       from the old types TIME, DATETIME, TIMESTAMP to the new MySQL-5.6
1253       types TIME(0), DATETIME(0), TIMESTAMP(0).
1254 
1255       Note: perhaps binlog should eventually be modified to store
1256       real_type() instead of type() for all column types.
1257     */
1258     return type();
1259   }
binlog_type_info()1260   virtual Binlog_type_info binlog_type_info() const
1261   {
1262     DBUG_ASSERT(Field::type() == binlog_type());
1263     return Binlog_type_info(Field::type(), 0, 0);
1264   }
tmp_engine_column_type(bool use_packed_rows)1265   virtual en_fieldtype tmp_engine_column_type(bool use_packed_rows) const
1266   {
1267     return FIELD_NORMAL;
1268   }
1269   /*
1270     Conversion type for from the source to the current field.
1271   */
1272   virtual enum_conv_type rpl_conv_type_from(const Conv_source &source,
1273                                             const Relay_log_info *rli,
1274                                             const Conv_param &param)
1275                                             const= 0;
1276   enum_conv_type rpl_conv_type_from_same_data_type(uint16 metadata,
1277                                                    const Relay_log_info *rli,
1278                                                    const Conv_param &param)
1279                                                    const;
cmp(const uchar * str)1280   inline  int cmp(const uchar *str) const { return cmp(ptr,str); }
1281   /*
1282     The following method is used for comparing prefix keys.
1283     Currently it's only used in partitioning.
1284   */
cmp_prefix(const uchar * a,const uchar * b,size_t prefix_len)1285   virtual int cmp_prefix(const uchar *a, const uchar *b,
1286                          size_t prefix_len) const
1287   { return cmp(a, b); }
1288   virtual int cmp(const uchar *,const uchar *) const=0;
1289   virtual int cmp_binary(const uchar *a,const uchar *b, uint32 max_length=~0U) const
1290   { return memcmp(a,b,pack_length()); }
cmp_offset(my_ptrdiff_t row_offset)1291   virtual int cmp_offset(my_ptrdiff_t row_offset)
1292   { return cmp(ptr,ptr+row_offset); }
cmp_binary_offset(uint row_offset)1293   virtual int cmp_binary_offset(uint row_offset)
1294   { return cmp_binary(ptr, ptr+row_offset); };
key_cmp(const uchar * a,const uchar * b)1295   virtual int key_cmp(const uchar *a,const uchar *b) const
1296   { return cmp(a, b); }
key_cmp(const uchar * str,uint length)1297   virtual int key_cmp(const uchar *str, uint length) const
1298   { return cmp(ptr,str); }
1299   /*
1300     Update the value m of the 'min_val' field with the current value v
1301     of this field if force_update is set to TRUE or if v < m.
1302     Return TRUE if the value has been updated.
1303   */
update_min(Field * min_val,bool force_update)1304   virtual bool update_min(Field *min_val, bool force_update)
1305   {
1306     bool update_fl= force_update || cmp(ptr, min_val->ptr) < 0;
1307     if (update_fl)
1308     {
1309       min_val->set_notnull();
1310       memcpy(min_val->ptr, ptr, pack_length());
1311     }
1312     return update_fl;
1313   }
1314   /*
1315     Update the value m of the 'max_val' field with the current value v
1316     of this field if force_update is set to TRUE or if v > m.
1317     Return TRUE if the value has been updated.
1318   */
update_max(Field * max_val,bool force_update)1319   virtual bool update_max(Field *max_val, bool force_update)
1320   {
1321     bool update_fl= force_update || cmp(ptr, max_val->ptr) > 0;
1322     if (update_fl)
1323     {
1324       max_val->set_notnull();
1325       memcpy(max_val->ptr, ptr, pack_length());
1326     }
1327     return update_fl;
1328   }
store_field_value(uchar * val,uint len)1329   virtual void store_field_value(uchar *val, uint len)
1330   {
1331      memcpy(ptr, val, len);
1332   }
decimals()1333   virtual uint decimals() const { return 0; }
1334   virtual Information_schema_numeric_attributes
information_schema_numeric_attributes()1335             information_schema_numeric_attributes() const
1336   {
1337     return Information_schema_numeric_attributes();
1338   }
1339   virtual Information_schema_character_attributes
information_schema_character_attributes()1340             information_schema_character_attributes() const
1341   {
1342     return Information_schema_character_attributes();
1343   }
update_data_type_statistics(Data_type_statistics * st)1344   virtual void update_data_type_statistics(Data_type_statistics *st) const
1345   { }
1346   /*
1347     Caller beware: sql_type can change str.Ptr, so check
1348     ptr() to see if it changed if you are using your own buffer
1349     in str and restore it with set() if needed
1350   */
1351   virtual void sql_type(String &str) const =0;
sql_rpl_type(String * str)1352   virtual void sql_rpl_type(String *str) const { sql_type(*str); }
1353   virtual uint size_of() const =0;		// For new field
1354   inline bool is_null(my_ptrdiff_t row_offset= 0) const
1355   {
1356     /*
1357       The table may have been marked as containing only NULL values
1358       for all fields if it is a NULL-complemented row of an OUTER JOIN
1359       or if the query is an implicitly grouped query (has aggregate
1360       functions but no GROUP BY clause) with no qualifying rows. If
1361       this is the case (in which TABLE::null_row is true), the field
1362       is considered to be NULL.
1363 
1364       Note that if a table->null_row is set then also all null_bits are
1365       set for the row.
1366 
1367       In the case of the 'result_field' for GROUP BY, table->null_row might
1368       refer to the *next* row in the table (when the algorithm is: read the
1369       next row, see if any of group column values have changed, send the
1370       result - grouped - row to the client if yes). So, table->null_row might
1371       be wrong, but such a result_field is always nullable (that's defined by
1372       original_field->maybe_null()) and we trust its null bit.
1373     */
1374     return null_ptr ? null_ptr[row_offset] & null_bit : table->null_row;
1375   }
1376   inline bool is_real_null(my_ptrdiff_t row_offset= 0) const
1377     { return null_ptr && (null_ptr[row_offset] & null_bit); }
is_null_in_record(const uchar * record)1378   inline bool is_null_in_record(const uchar *record) const
1379   {
1380     if (maybe_null_in_table())
1381       return record[(uint) (null_ptr - table->record[0])] & null_bit;
1382     return 0;
1383   }
1384   inline void set_null(my_ptrdiff_t row_offset= 0)
1385     { if (null_ptr) null_ptr[row_offset]|= null_bit; }
1386   inline void set_notnull(my_ptrdiff_t row_offset= 0)
1387     { if (null_ptr) null_ptr[row_offset]&= (uchar) ~null_bit; }
maybe_null(void)1388   inline bool maybe_null(void) const
1389   { return null_ptr != 0 || table->maybe_null; }
1390   // Set to NULL on LOAD DATA or LOAD XML
1391   virtual bool load_data_set_null(THD *thd);
1392   // Reset when a LOAD DATA file ended unexpectedly
1393   virtual bool load_data_set_no_data(THD *thd, bool fixed_format);
1394   void load_data_set_value(const char *pos, uint length, CHARSET_INFO *cs);
1395 
1396   /* @return true if this field is NULL-able (even if temporarily) */
real_maybe_null()1397   inline bool real_maybe_null() const { return null_ptr != 0; }
null_offset(const uchar * record)1398   uint null_offset(const uchar *record) const
1399   { return (uint) (null_ptr - record); }
1400   /*
1401     For a NULL-able field (that can actually store a NULL value in a table)
1402     null_ptr points to the "null bitmap" in the table->record[0] header. For
1403     NOT NULL fields it is either 0 or points outside table->record[0] into the
1404     table->triggers->extra_null_bitmap (so that the field can store a NULL
1405     value temporarily, only in memory)
1406   */
maybe_null_in_table()1407   bool maybe_null_in_table() const
1408   { return null_ptr >= table->record[0] && null_ptr <= ptr; }
1409 
null_offset()1410   uint null_offset() const
1411   { return null_offset(table->record[0]); }
set_null_ptr(uchar * p_null_ptr,uint p_null_bit)1412   void set_null_ptr(uchar *p_null_ptr, uint p_null_bit)
1413   {
1414     null_ptr= p_null_ptr;
1415     null_bit= static_cast<uchar>(p_null_bit);
1416   }
1417 
stored_in_db()1418   bool stored_in_db() const { return !vcol_info || vcol_info->stored_in_db; }
1419   bool check_vcol_sql_mode_dependency(THD *, vcol_init_mode mode) const;
1420 
value_depends_on_sql_mode()1421   virtual sql_mode_t value_depends_on_sql_mode() const
1422   {
1423     return 0;
1424   }
conversion_depends_on_sql_mode(THD * thd,Item * expr)1425   virtual sql_mode_t conversion_depends_on_sql_mode(THD *thd,
1426                                                     Item *expr) const
1427   {
1428     return (sql_mode_t) 0;
1429   }
can_handle_sql_mode_dependency_on_store()1430   virtual sql_mode_t can_handle_sql_mode_dependency_on_store() const
1431   {
1432     return 0;
1433   }
1434 
get_thd()1435   inline THD *get_thd() const
1436   { return likely(table) ? table->in_use : current_thd; }
1437 
1438   enum {
1439     LAST_NULL_BYTE_UNDEF= 0
1440   };
1441 
1442   /*
1443     Find the position of the last null byte for the field.
1444 
1445     SYNOPSIS
1446       last_null_byte()
1447 
1448     DESCRIPTION
1449       Return a pointer to the last byte of the null bytes where the
1450       field conceptually is placed.
1451 
1452     RETURN VALUE
1453       The position of the last null byte relative to the beginning of
1454       the record. If the field does not use any bits of the null
1455       bytes, the value 0 (LAST_NULL_BYTE_UNDEF) is returned.
1456    */
last_null_byte()1457   size_t last_null_byte() const {
1458     size_t bytes= do_last_null_byte();
1459     DBUG_PRINT("debug", ("last_null_byte() ==> %ld", (long) bytes));
1460     DBUG_ASSERT(bytes <= table->s->null_bytes);
1461     return bytes;
1462   }
1463 
1464   /*
1465     Create mem-comparable sort key part for a sort key
1466   */
1467   void make_sort_key_part(uchar *buff, uint length);
1468 
1469   /*
1470     create a compact sort key which can be compared with a comparison
1471     function. They are called packed sort keys
1472   */
1473   virtual uint make_packed_sort_key_part(uchar *buff,
1474                                          const SORT_FIELD_ATTR *sort_field);
1475 
1476   virtual void make_send_field(Send_field *);
1477 
1478   /*
1479     Some implementations actually may write up to 8 bytes regardless of what
1480     size was requested. This is due to the minimum value of the system variable
1481     max_sort_length.
1482   */
1483 
1484   virtual void sort_string(uchar *buff,uint length)=0;
1485   virtual bool optimize_range(uint idx, uint part) const;
free()1486   virtual void free() {}
1487   virtual Field *make_new_field(MEM_ROOT *root, TABLE *new_table,
1488                                 bool keep_type);
1489   virtual Field *new_key_field(MEM_ROOT *root, TABLE *new_table,
1490                                uchar *new_ptr, uint32 length,
1491                                uchar *new_null_ptr, uint new_null_bit);
1492   Field *create_tmp_field(MEM_ROOT *root, TABLE *new_table,
1493                           bool maybe_null_arg);
create_tmp_field(MEM_ROOT * root,TABLE * new_table)1494   Field *create_tmp_field(MEM_ROOT *root, TABLE *new_table)
1495   {
1496     return create_tmp_field(root, new_table, maybe_null());
1497   }
1498   Field *clone(MEM_ROOT *mem_root, TABLE *new_table);
1499   Field *clone(MEM_ROOT *mem_root, TABLE *new_table, my_ptrdiff_t diff);
move_field(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg)1500   inline void move_field(uchar *ptr_arg,uchar *null_ptr_arg,uchar null_bit_arg)
1501   {
1502     ptr=ptr_arg; null_ptr=null_ptr_arg; null_bit=null_bit_arg;
1503   }
move_field(uchar * ptr_arg)1504   inline void move_field(uchar *ptr_arg) { ptr=ptr_arg; }
record_ptr()1505   inline uchar *record_ptr() // record[0] or wherever the field was moved to
1506   {
1507     my_ptrdiff_t offset= table->s->field[field_index]->ptr - table->s->default_values;
1508     return ptr - offset;
1509   }
move_field_offset(my_ptrdiff_t ptr_diff)1510   virtual void move_field_offset(my_ptrdiff_t ptr_diff)
1511   {
1512     ptr=ADD_TO_PTR(ptr,ptr_diff, uchar*);
1513     if (null_ptr)
1514       null_ptr=ADD_TO_PTR(null_ptr,ptr_diff,uchar*);
1515   }
get_image(uchar * buff,uint length,CHARSET_INFO * cs)1516   void get_image(uchar *buff, uint length, CHARSET_INFO *cs) const
1517   { get_image(buff, length, ptr, cs); }
get_image(uchar * buff,uint length,const uchar * ptr_arg,CHARSET_INFO * cs)1518   virtual void get_image(uchar *buff, uint length,
1519                          const uchar *ptr_arg, CHARSET_INFO *cs) const
1520     { memcpy(buff,ptr_arg,length); }
set_image(const uchar * buff,uint length,CHARSET_INFO * cs)1521   virtual void set_image(const uchar *buff,uint length, CHARSET_INFO *cs)
1522     { memcpy(ptr,buff,length); }
1523 
1524 
1525   /*
1526     Copy a field part into an output buffer.
1527 
1528     SYNOPSIS
1529       Field::get_key_image()
1530       buff   [out] output buffer
1531       length       output buffer size
1532       type         itMBR for geometry blobs, otherwise itRAW
1533 
1534     DESCRIPTION
1535       This function makes a copy of field part of size equal to or
1536       less than "length" parameter value.
1537       For fields of string types (CHAR, VARCHAR, TEXT) the rest of buffer
1538       is padded by zero byte.
1539 
1540     NOTES
1541       For variable length character fields (i.e. UTF-8) the "length"
1542       parameter means a number of output buffer bytes as if all field
1543       characters have maximal possible size (mbmaxlen). In the other words,
1544       "length" parameter is a number of characters multiplied by
1545       field_charset->mbmaxlen.
1546 
1547     RETURN
1548       Number of copied bytes (excluding padded zero bytes -- see above).
1549   */
1550 
get_key_image(uchar * buff,uint length,imagetype type_arg)1551   uint get_key_image(uchar *buff, uint length, imagetype type_arg) const
1552   { return get_key_image(buff, length, ptr, type_arg); }
get_key_image(uchar * buff,uint length,const uchar * ptr_arg,imagetype type_arg)1553   virtual uint get_key_image(uchar *buff, uint length, const uchar *ptr_arg, imagetype type_arg) const
1554   {
1555     get_image(buff, length, ptr_arg, &my_charset_bin);
1556     return length;
1557   }
set_key_image(const uchar * buff,uint length)1558   virtual void set_key_image(const uchar *buff,uint length)
1559     { set_image(buff,length, &my_charset_bin); }
val_int_offset(uint row_offset)1560   inline longlong val_int_offset(uint row_offset)
1561     {
1562       ptr+=row_offset;
1563       longlong tmp=val_int();
1564       ptr-=row_offset;
1565       return tmp;
1566     }
val_int(const uchar * new_ptr)1567   inline longlong val_int(const uchar *new_ptr)
1568   {
1569     uchar *old_ptr= ptr;
1570     longlong return_value;
1571     ptr= (uchar*) new_ptr;
1572     return_value= val_int();
1573     ptr= old_ptr;
1574     return return_value;
1575   }
val_str(String * str,const uchar * new_ptr)1576   inline String *val_str(String *str, const uchar *new_ptr)
1577   {
1578     uchar *old_ptr= ptr;
1579     ptr= (uchar*) new_ptr;
1580     val_str(str);
1581     ptr= old_ptr;
1582     return str;
1583   }
1584   virtual bool send(Protocol *protocol);
1585 
1586   virtual uchar *pack(uchar *to, const uchar *from, uint max_length);
1587   /**
1588      @overload Field::pack(uchar*, const uchar*, uint, bool)
1589   */
pack(uchar * to,const uchar * from)1590   uchar *pack(uchar *to, const uchar *from)
1591   {
1592     DBUG_ENTER("Field::pack");
1593     uchar *result= this->pack(to, from, UINT_MAX);
1594     DBUG_RETURN(result);
1595   }
1596 
1597   virtual const uchar *unpack(uchar* to, const uchar *from,
1598                               const uchar *from_end, uint param_data=0);
1599 
packed_col_length(const uchar * to,uint length)1600   virtual uint packed_col_length(const uchar *to, uint length)
1601   { return length;}
max_packed_col_length(uint max_length)1602   virtual uint max_packed_col_length(uint max_length)
1603   { return max_length;}
is_packable()1604   virtual bool is_packable() const { return false; }
1605 
offset(const uchar * record)1606   uint offset(const uchar *record) const
1607   {
1608     return (uint) (ptr - record);
1609   }
1610   void copy_from_tmp(int offset);
1611   uint fill_cache_field(struct st_cache_field *copy);
1612   virtual bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate);
1613   virtual longlong val_datetime_packed(THD *thd);
1614   virtual longlong val_time_packed(THD *thd);
get_typelib()1615   virtual const TYPELIB *get_typelib() const { return NULL; }
1616   virtual CHARSET_INFO *charset() const= 0;
1617   virtual const DTCollation &dtcollation() const= 0;
charset_for_protocol(void)1618   virtual CHARSET_INFO *charset_for_protocol(void) const
1619   { return binary() ? &my_charset_bin : charset(); }
sort_charset(void)1620   virtual CHARSET_INFO *sort_charset(void) const { return charset(); }
has_charset(void)1621   virtual bool has_charset(void) const { return FALSE; }
set_time()1622   virtual int set_time() { return 1; }
1623   bool set_warning(Sql_condition::enum_warning_level, unsigned int code,
1624                    int cuted_increment, ulong current_row=0) const;
1625   virtual void print_key_value(String *out, uint32 length);
1626   void print_key_part_value(String *out, const uchar *key, uint32 length);
1627   void print_key_value_binary(String *out, const uchar* key, uint32 length);
1628 protected:
set_warning(unsigned int code,int cuted_increment)1629   bool set_warning(unsigned int code, int cuted_increment) const
1630   {
1631     return set_warning(Sql_condition::WARN_LEVEL_WARN, code, cuted_increment);
1632   }
set_note(unsigned int code,int cuted_increment)1633   bool set_note(unsigned int code, int cuted_increment) const
1634   {
1635     return set_warning(Sql_condition::WARN_LEVEL_NOTE, code, cuted_increment);
1636   }
1637   void set_datetime_warning(Sql_condition::enum_warning_level, uint code,
1638                             const ErrConv *str, const char *typestr,
1639                             int cuted_increment) const;
set_datetime_warning(uint code,const ErrConv * str,const char * typestr,int cuted_increment)1640   void set_datetime_warning(uint code,
1641                             const ErrConv *str, const char *typestr,
1642                             int cuted_increment) const
1643   {
1644     set_datetime_warning(Sql_condition::WARN_LEVEL_WARN, code, str, typestr,
1645                          cuted_increment);
1646   }
1647   void set_warning_truncated_wrong_value(const char *type, const char *value);
check_overflow(int op_result)1648   inline bool check_overflow(int op_result)
1649   {
1650     return (op_result == E_DEC_OVERFLOW);
1651   }
1652   int warn_if_overflow(int op_result);
1653   Copy_func *get_identical_copy_func() const;
1654   bool cmp_is_done_using_type_handler_of_this(const Item_bool_func *cond,
1655                                               const Item *item) const;
1656   bool can_optimize_scalar_range(const RANGE_OPT_PARAM *param,
1657                                  const KEY_PART *key_part,
1658                                  const Item_bool_func *cond,
1659                                  scalar_comparison_op op,
1660                                  const Item *value) const;
1661   uchar *make_key_image(MEM_ROOT *mem_root, const KEY_PART *key_part);
1662   SEL_ARG *get_mm_leaf_int(RANGE_OPT_PARAM *param, KEY_PART *key_part,
1663                            const Item_bool_func *cond,
1664                            scalar_comparison_op op, Item *value,
1665                            bool unsigned_field);
1666   /*
1667     Make a leaf tree for the cases when the value was stored
1668     to the field exactly, without any truncation, rounding or adjustments.
1669     For example, if we stored an INT value into an INT column,
1670     and value->save_in_field_no_warnings() returned 0,
1671     we know that the value was stored exactly.
1672   */
1673   SEL_ARG *stored_field_make_mm_leaf_exact(RANGE_OPT_PARAM *param,
1674                                            KEY_PART *key_part,
1675                                            scalar_comparison_op op,
1676                                            Item *value);
1677   /*
1678     Make a leaf tree for the cases when we don't know if
1679     the value was stored to the field without any data loss,
1680     or was modified to a smaller or a greater value.
1681     Used for the data types whose methods Field::store*()
1682     silently adjust the value. This is the most typical case.
1683   */
1684   SEL_ARG *stored_field_make_mm_leaf(RANGE_OPT_PARAM *param,
1685                                      KEY_PART *key_part,
1686                                      scalar_comparison_op op, Item *value);
1687   /*
1688     Make a leaf tree when an INT value was stored into a field of INT type,
1689     and some truncation happened. Tries to adjust the range search condition
1690     when possible, e.g. "tinytint < 300" -> "tinyint <= 127".
1691     Can also return SEL_ARG_IMPOSSIBLE(), and NULL (not sargable).
1692   */
1693   SEL_ARG *stored_field_make_mm_leaf_bounded_int(RANGE_OPT_PARAM *param,
1694                                                  KEY_PART *key_part,
1695                                                  scalar_comparison_op op,
1696                                                  Item *value,
1697                                                  bool unsigned_field);
1698   /*
1699     Make a leaf tree when some truncation happened during
1700     value->save_in_field_no_warning(this), and we cannot yet adjust the range
1701     search condition for the current combination of the field and the value
1702     data types.
1703     Returns SEL_ARG_IMPOSSIBLE() for "=" and "<=>".
1704     Returns NULL (not sargable) for other comparison operations.
1705   */
1706   SEL_ARG *stored_field_make_mm_leaf_truncated(RANGE_OPT_PARAM *prm,
1707                                                scalar_comparison_op,
1708                                                Item *value);
1709 public:
set_table_name(String * alias)1710   void set_table_name(String *alias)
1711   {
1712     table_name= &alias->Ptr;
1713   }
init(TABLE * table_arg)1714   void init(TABLE *table_arg)
1715   {
1716     orig_table= table= table_arg;
1717     set_table_name(&table_arg->alias);
1718   }
init_for_tmp_table(Field * org_field,TABLE * new_table)1719   virtual void init_for_tmp_table(Field *org_field, TABLE *new_table)
1720   {
1721     init(new_table);
1722     orig_table= org_field->orig_table;
1723     vcol_info= 0;
1724     cond_selectivity= 1.0;
1725     next_equal_field= NULL;
1726     option_list= NULL;
1727     option_struct= NULL;
1728     if (org_field->type() == MYSQL_TYPE_VAR_STRING ||
1729         org_field->type() == MYSQL_TYPE_VARCHAR)
1730       new_table->s->db_create_options|= HA_OPTION_PACK_RECORD;
1731   }
init_for_make_new_field(TABLE * new_table_arg,TABLE * orig_table_arg)1732   void init_for_make_new_field(TABLE *new_table_arg, TABLE *orig_table_arg)
1733   {
1734     init(new_table_arg);
1735     /*
1736       Normally orig_table is different from table only if field was
1737       created via ::make_new_field.  Here we alter the type of field,
1738       so ::make_new_field is not applicable. But we still need to
1739       preserve the original field metadata for the client-server
1740       protocol.
1741     */
1742     orig_table= orig_table_arg;
1743   }
1744 
1745   /* maximum possible display length */
1746   virtual uint32 max_display_length() const= 0;
1747   /**
1748     Whether a field being created has the samle type.
1749     Used by the ALTER TABLE
1750   */
1751   virtual bool is_equal(const Column_definition &new_field) const= 0;
1752   // Used as double dispatch pattern: calls virtual method of handler
1753   virtual bool
can_be_converted_by_engine(const Column_definition & new_type)1754   can_be_converted_by_engine(const Column_definition &new_type) const
1755   {
1756     return false;
1757   }
1758   /* convert decimal to longlong with overflow check */
1759   longlong convert_decimal2longlong(const my_decimal *val, bool unsigned_flag,
1760                                     int *err);
1761   /*
1762     Maximum number of bytes in character representation.
1763     - For string types it is equal to the field capacity, in bytes.
1764     - For non-string types it represents the longest possible string length
1765       after conversion to string.
1766   */
character_octet_length()1767   virtual uint32 character_octet_length() const
1768   {
1769     return field_length;
1770   }
1771   /* The max. number of characters */
char_length()1772   virtual uint32 char_length() const
1773   {
1774     return field_length / charset()->mbmaxlen;
1775   }
1776 
field_storage_type()1777   ha_storage_media field_storage_type() const
1778   {
1779     return (ha_storage_media)
1780       ((flags >> FIELD_FLAGS_STORAGE_MEDIA) & 3);
1781   }
1782 
set_storage_type(ha_storage_media storage_type_arg)1783   void set_storage_type(ha_storage_media storage_type_arg)
1784   {
1785     DBUG_ASSERT(field_storage_type() == HA_SM_DEFAULT);
1786     flags |= static_cast<uint32>(storage_type_arg) <<
1787       FIELD_FLAGS_STORAGE_MEDIA;
1788   }
1789 
column_format()1790   column_format_type column_format() const
1791   {
1792     return (column_format_type)
1793       ((flags >> FIELD_FLAGS_COLUMN_FORMAT) & 3);
1794   }
1795 
set_column_format(column_format_type column_format_arg)1796   void set_column_format(column_format_type column_format_arg)
1797   {
1798     DBUG_ASSERT(column_format() == COLUMN_FORMAT_TYPE_DEFAULT);
1799     flags |= static_cast<uint32>(column_format_arg) <<
1800       FIELD_FLAGS_COLUMN_FORMAT;
1801   }
1802 
vers_sys_field()1803   bool vers_sys_field() const
1804   {
1805     return flags & (VERS_ROW_START | VERS_ROW_END);
1806   }
1807 
vers_update_unversioned()1808   bool vers_update_unversioned() const
1809   {
1810     return flags & VERS_UPDATE_UNVERSIONED_FLAG;
1811   }
1812 
1813   /*
1814     Validate a non-null field value stored in the given record
1815     according to the current thread settings, e.g. sql_mode.
1816     @param thd     - the thread
1817     @param record  - the record to check in
1818   */
validate_value_in_record(THD * thd,const uchar * record)1819   virtual bool validate_value_in_record(THD *thd, const uchar *record) const
1820   { return false; }
1821   bool validate_value_in_record_with_warn(THD *thd, const uchar *record);
1822   key_map get_possible_keys();
1823 
1824   /* Hash value */
1825   virtual void hash(ulong *nr, ulong *nr2);
1826 
1827   /**
1828     Get the upper limit of the MySQL integral and floating-point type.
1829 
1830     @return maximum allowed value for the field
1831   */
get_max_int_value()1832   virtual ulonglong get_max_int_value() const
1833   {
1834     DBUG_ASSERT(false);
1835     return 0ULL;
1836   }
1837 
1838 /**
1839   Checks whether a string field is part of write_set.
1840 
1841   @return
1842     FALSE  - If field is not char/varchar/....
1843            - If field is char/varchar/.. and is not part of write set.
1844     TRUE   - If field is char/varchar/.. and is part of write set.
1845 */
is_varchar_and_in_write_set()1846   virtual bool is_varchar_and_in_write_set() const { return FALSE; }
1847 
1848   /* Check whether the field can be used as a join attribute in hash join */
hash_join_is_possible()1849   virtual bool hash_join_is_possible() { return TRUE; }
eq_cmp_as_binary()1850   virtual bool eq_cmp_as_binary() { return TRUE; }
1851 
1852   /* Position of the field value within the interval of [min, max] */
pos_in_interval(Field * min,Field * max)1853   virtual double pos_in_interval(Field *min, Field *max)
1854   {
1855     return (double) 0.5;
1856   }
1857 
1858   /*
1859     Check if comparison between the field and an item unambiguously
1860     identifies a distinct field value.
1861 
1862     Example1: SELECT * FROM t1 WHERE int_column=10;
1863               This example returns distinct integer value of 10.
1864 
1865     Example2: SELECT * FROM t1 WHERE varchar_column=DATE'2001-01-01'
1866               This example returns non-distinct values.
1867               Comparison as DATE will return '2001-01-01' and '2001-01-01x',
1868               but these two values are not equal to each other as VARCHARs.
1869     See also the function with the same name in sql_select.cc.
1870   */
1871   virtual bool test_if_equality_guarantees_uniqueness(const Item *const_item)
1872                                                       const;
1873   virtual bool can_be_substituted_to_equal_item(const Context &ctx,
1874                                         const Item_equal *item);
get_equal_const_item(THD * thd,const Context & ctx,Item * const_item)1875   virtual Item *get_equal_const_item(THD *thd, const Context &ctx,
1876                                      Item *const_item)
1877   {
1878     return const_item;
1879   }
1880   virtual bool can_optimize_keypart_ref(const Item_bool_func *cond,
1881                                         const Item *item) const;
can_optimize_hash_join(const Item_bool_func * cond,const Item * item)1882   virtual bool can_optimize_hash_join(const Item_bool_func *cond,
1883                                       const Item *item) const
1884   {
1885     return can_optimize_keypart_ref(cond, item);
1886   }
1887   virtual bool can_optimize_group_min_max(const Item_bool_func *cond,
1888                                           const Item *const_item) const;
1889   /**
1890     Test if Field can use range optimizer for a standard comparison operation:
1891       <=, <, =, <=>, >, >=
1892     Note, this method does not cover spatial operations.
1893   */
1894   virtual bool can_optimize_range(const Item_bool_func *cond,
1895                                   const Item *item,
1896                                   bool is_eq_func) const;
1897 
1898   virtual SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part,
1899                                const Item_bool_func *cond,
1900                                scalar_comparison_op op, Item *value)= 0;
1901 
can_optimize_outer_join_table_elimination(const Item_bool_func * cond,const Item * item)1902   bool can_optimize_outer_join_table_elimination(const Item_bool_func *cond,
1903                                                  const Item *item) const
1904   {
1905     // Exactly the same rules with REF access
1906     return can_optimize_keypart_ref(cond, item);
1907   }
1908 
1909   bool save_in_field_default_value(bool view_eror_processing);
1910   bool save_in_field_ignore_value(bool view_error_processing);
1911 
1912   /* Mark field in read map. Updates also virtual fields */
1913   void register_field_in_read_map();
1914 
compression_method()1915   virtual Compression_method *compression_method() const { return 0; }
1916 
virtual_tmp_table_addr()1917   virtual Virtual_tmp_table **virtual_tmp_table_addr()
1918   {
1919     return NULL;
1920   }
1921   virtual bool sp_prepare_and_store_item(THD *thd, Item **value);
1922 
1923   friend int cre_myisam(char * name, TABLE *form, uint options,
1924 			ulonglong auto_increment_value);
1925   friend class Copy_field;
1926   friend class Item_avg_field;
1927   friend class Item_std_field;
1928   friend class Item_sum_num;
1929   friend class Item_sum_sum;
1930   friend class Item_sum_count;
1931   friend class Item_sum_avg;
1932   friend class Item_sum_std;
1933   friend class Item_sum_min;
1934   friend class Item_sum_max;
1935   friend class Item_func_group_concat;
1936 
1937 private:
1938   /*
1939     Primitive for implementing last_null_byte().
1940 
1941     SYNOPSIS
1942       do_last_null_byte()
1943 
1944     DESCRIPTION
1945       Primitive for the implementation of the last_null_byte()
1946       function. This represents the inheritance interface and can be
1947       overridden by subclasses.
1948    */
1949   virtual size_t do_last_null_byte() const;
1950 
1951 protected:
pack_int(uchar * to,const uchar * from,size_t size)1952   uchar *pack_int(uchar *to, const uchar *from, size_t size)
1953   {
1954     memcpy(to, from, size);
1955     return to + size;
1956   }
1957 
unpack_int(uchar * to,const uchar * from,const uchar * from_end,size_t size)1958   const uchar *unpack_int(uchar* to, const uchar *from,
1959                           const uchar *from_end, size_t size)
1960   {
1961     if (from + size > from_end)
1962       return 0;
1963     memcpy(to, from, size);
1964     return from + size;
1965   }
1966 
pack_int16(uchar * to,const uchar * from)1967   uchar *pack_int16(uchar *to, const uchar *from)
1968   { return pack_int(to, from, 2); }
unpack_int16(uchar * to,const uchar * from,const uchar * from_end)1969   const uchar *unpack_int16(uchar* to, const uchar *from, const uchar *from_end)
1970   { return unpack_int(to, from, from_end, 2); }
pack_int24(uchar * to,const uchar * from)1971   uchar *pack_int24(uchar *to, const uchar *from)
1972   { return pack_int(to, from, 3); }
unpack_int24(uchar * to,const uchar * from,const uchar * from_end)1973   const uchar *unpack_int24(uchar* to, const uchar *from, const uchar *from_end)
1974   { return unpack_int(to, from, from_end, 3); }
pack_int32(uchar * to,const uchar * from)1975   uchar *pack_int32(uchar *to, const uchar *from)
1976   { return pack_int(to, from, 4); }
unpack_int32(uchar * to,const uchar * from,const uchar * from_end)1977   const uchar *unpack_int32(uchar* to, const uchar *from, const uchar *from_end)
1978   { return unpack_int(to, from, from_end, 4); }
pack_int64(uchar * to,const uchar * from)1979   uchar *pack_int64(uchar* to, const uchar *from)
1980   { return pack_int(to, from, 8); }
unpack_int64(uchar * to,const uchar * from,const uchar * from_end)1981   const uchar *unpack_int64(uchar* to, const uchar *from,  const uchar *from_end)
1982   { return unpack_int(to, from, from_end, 8); }
1983 
1984   double pos_in_interval_val_real(Field *min, Field *max);
1985   double pos_in_interval_val_str(Field *min, Field *max, uint data_offset);
1986 };
1987 
1988 
1989 class Field_num :public Field {
1990 protected:
1991   int check_edom_and_important_data_truncation(const char *type, bool edom,
1992                                                CHARSET_INFO *cs,
1993                                                const char *str, size_t length,
1994                                                const char *end_of_num);
1995   int check_edom_and_truncation(const char *type, bool edom,
1996                                 CHARSET_INFO *cs,
1997                                 const char *str, size_t length,
1998                                 const char *end_of_num);
check_int(CHARSET_INFO * cs,const char * str,size_t length,const char * int_end,int error)1999   int check_int(CHARSET_INFO *cs, const char *str, size_t length,
2000                 const char *int_end, int error)
2001   {
2002     return check_edom_and_truncation("integer",
2003                                      error == MY_ERRNO_EDOM || str == int_end,
2004                                      cs, str, length, int_end);
2005   }
2006   bool get_int(CHARSET_INFO *cs, const char *from, size_t len,
2007                longlong *rnd, ulonglong unsigned_max,
2008                longlong signed_min, longlong signed_max);
2009   void prepend_zeros(String *value) const;
2010   Item *get_equal_zerofill_const_item(THD *thd, const Context &ctx,
2011                                       Item *const_item);
binlog_signedness()2012   Binlog_type_info::binlog_sign_t binlog_signedness() const
2013   {
2014     return (flags & UNSIGNED_FLAG) ? Binlog_type_info::SIGN_UNSIGNED :
2015                                      Binlog_type_info::SIGN_SIGNED;
2016   }
2017   bool send_numeric_zerofill_str(Protocol_text *protocol,
2018                                  protocol_send_type_t send_type);
2019 
2020 public:
2021   const uint8 dec;
2022   bool zerofill,unsigned_flag;	// Purify cannot handle bit fields
2023   Field_num(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
2024 	    uchar null_bit_arg, utype unireg_check_arg,
2025 	    const LEX_CSTRING *field_name_arg,
2026             uint8 dec_arg, bool zero_arg, bool unsigned_arg);
charset()2027   CHARSET_INFO *charset() const override
2028   {
2029     return DTCollation_numeric::singleton().collation;
2030   }
dtcollation()2031   const DTCollation &dtcollation() const override
2032   {
2033     return DTCollation_numeric::singleton();
2034   }
2035   sql_mode_t can_handle_sql_mode_dependency_on_store() const override;
get_equal_const_item(THD * thd,const Context & ctx,Item * const_item)2036   Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item)
2037     override
2038   {
2039     return (flags & ZEROFILL_FLAG) ?
2040            get_equal_zerofill_const_item(thd, ctx, const_item) :
2041            const_item;
2042   }
2043   void add_zerofill_and_unsigned(String &res) const;
2044   friend class Create_field;
2045   void make_send_field(Send_field *) override;
decimals()2046   uint decimals() const override { return (uint) dec; }
size_of()2047   uint size_of() const override { return sizeof(*this); }
2048   bool eq_def(const Field *field) const override;
get_copy_func(const Field * from)2049   Copy_func *get_copy_func(const Field *from) const override
2050   {
2051     if (unsigned_flag && from->cmp_type() == DECIMAL_RESULT)
2052       return do_field_decimal;
2053     return do_field_int;
2054   }
save_in_field(Field * to)2055   int save_in_field(Field *to) override
2056   {
2057     return to->store(val_int(), MY_TEST(flags & UNSIGNED_FLAG));
2058   }
2059   bool is_equal(const Column_definition &new_field) const override;
row_pack_length()2060   uint row_pack_length() const override { return pack_length(); }
pack_length_from_metadata(uint field_metadata)2061   uint32 pack_length_from_metadata(uint field_metadata) const override
2062   {
2063     uint32 length= pack_length();
2064     DBUG_PRINT("result", ("pack_length_from_metadata(%d): %u",
2065                           field_metadata, length));
2066     return length;
2067   }
pos_in_interval(Field * min,Field * max)2068   double pos_in_interval(Field *min, Field *max) override
2069   {
2070     return pos_in_interval_val_real(min, max);
2071   }
2072   SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part,
2073                        const Item_bool_func *cond,
2074                        scalar_comparison_op op, Item *value) override;
binlog_type_info()2075   Binlog_type_info binlog_type_info() const override
2076   {
2077     DBUG_ASSERT(Field_num::type() == binlog_type());
2078     return Binlog_type_info(Field_num::type(), 0, 0, binlog_signedness());
2079   }
2080 };
2081 
2082 
2083 class Field_str :public Field {
2084 protected:
2085   DTCollation m_collation;
2086   // A short alias for m_collation.collation with non-virtual linkage
field_charset()2087   const CHARSET_INFO *field_charset() const { return m_collation.collation; }
mbmaxlen()2088   uint mbmaxlen() const { return m_collation.collation->mbmaxlen; }
2089 public:
2090   bool can_be_substituted_to_equal_item(const Context &ctx,
2091                                         const Item_equal *item_equal) override;
2092   Field_str(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
2093 	    uchar null_bit_arg, utype unireg_check_arg,
2094 	    const LEX_CSTRING *field_name_arg,
2095 	    const DTCollation &collation);
decimals()2096   uint decimals() const override { return is_created_from_null_item ? 0 : NOT_FIXED_DEC; }
save_in_field(Field * to)2097   int  save_in_field(Field *to) override { return save_in_field_str(to); }
memcpy_field_possible(const Field * from)2098   bool memcpy_field_possible(const Field *from) const override
2099   {
2100     return real_type() == from->real_type() &&
2101            pack_length() == from->pack_length() &&
2102            charset() == from->charset();
2103   }
2104   int  store(double nr) override;
2105   int  store(longlong nr, bool unsigned_val) override;
2106   int  store_decimal(const my_decimal *) override;
2107   int  store(const char *to,size_t length,CHARSET_INFO *cs) override=0;
store_hex_hybrid(const char * str,size_t length)2108   int  store_hex_hybrid(const char *str, size_t length) override
2109   {
2110     return store(str, length, &my_charset_bin);
2111   }
charset()2112   CHARSET_INFO *charset() const override { return m_collation.collation; }
dtcollation()2113   const DTCollation &dtcollation() const override
2114   {
2115     return m_collation;
2116   }
binary()2117   bool binary() const override { return field_charset() == &my_charset_bin; }
max_display_length()2118   uint32 max_display_length() const override { return field_length; }
character_octet_length()2119   uint32 character_octet_length() const override { return field_length; }
char_length()2120   uint32 char_length() const override
2121   {
2122     return field_length / mbmaxlen();
2123   }
2124   Information_schema_character_attributes
information_schema_character_attributes()2125     information_schema_character_attributes() const override
2126   {
2127     return Information_schema_character_attributes(max_display_length(),
2128                                                    char_length());
2129   }
2130   friend class Create_field;
2131   my_decimal *val_decimal(my_decimal *) override;
val_bool()2132   bool val_bool() override { return val_real() != 0e0; }
str_needs_quotes()2133   bool str_needs_quotes() const override { return true; }
eq_cmp_as_binary()2134   bool eq_cmp_as_binary() override { return MY_TEST(flags & BINARY_FLAG); }
length_size()2135   virtual uint length_size() const { return 0; }
pos_in_interval(Field * min,Field * max)2136   double pos_in_interval(Field *min, Field *max) override
2137   {
2138     return pos_in_interval_val_str(min, max, length_size());
2139   }
2140   bool test_if_equality_guarantees_uniqueness(const Item *const_item) const
2141     override;
2142   SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part,
2143                        const Item_bool_func *cond,
2144                        scalar_comparison_op op, Item *value) override;
binlog_type_info()2145   Binlog_type_info binlog_type_info() const override
2146   {
2147     DBUG_ASSERT(Field_str::type() == binlog_type());
2148     return Binlog_type_info(Field_str::type(), 0, 0, charset());
2149   }
2150 };
2151 
2152 /* base class for Field_string, Field_varstring and Field_blob */
2153 
2154 class Field_longstr :public Field_str
2155 {
2156 protected:
2157   int report_if_important_data(const char *ptr, const char *end,
2158                                bool count_spaces);
2159   bool check_string_copy_error(const String_copier *copier,
2160                                const char *end, CHARSET_INFO *cs);
check_conversion_status(const String_copier * copier,const char * end,CHARSET_INFO * cs,bool count_spaces)2161   int check_conversion_status(const String_copier *copier,
2162                               const char *end, CHARSET_INFO *cs,
2163                               bool count_spaces)
2164   {
2165     if (check_string_copy_error(copier, end, cs))
2166       return 2;
2167     return report_if_important_data(copier->source_end_pos(),
2168                                     end, count_spaces);
2169   }
well_formed_copy_with_check(char * to,size_t to_length,CHARSET_INFO * from_cs,const char * from,size_t from_length,size_t nchars,bool count_spaces,uint * copy_length)2170   int well_formed_copy_with_check(char *to, size_t to_length,
2171                                   CHARSET_INFO *from_cs,
2172                                   const char *from, size_t from_length,
2173                                   size_t nchars, bool count_spaces,
2174                                   uint *copy_length)
2175   {
2176     String_copier copier;
2177 
2178     *copy_length= copier.well_formed_copy(field_charset(), to, to_length,
2179                                           from_cs, from, from_length,
2180                                           nchars);
2181 
2182     return check_conversion_status(&copier, from + from_length, from_cs, count_spaces);
2183   }
2184   bool cmp_to_string_with_same_collation(const Item_bool_func *cond,
2185                                          const Item *item) const;
2186   bool cmp_to_string_with_stricter_collation(const Item_bool_func *cond,
2187                                              const Item *item) const;
2188   int compress(char *to, uint to_length,
2189                const char *from, uint length,
2190                uint max_length,
2191                uint *out_length,
2192                CHARSET_INFO *cs, size_t nchars);
2193   String *uncompress(String *val_buffer, String *val_ptr,
2194                      const uchar *from, uint from_length) const;
2195 public:
Field_longstr(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,utype unireg_check_arg,const LEX_CSTRING * field_name_arg,const DTCollation & collation)2196   Field_longstr(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
2197                 uchar null_bit_arg, utype unireg_check_arg,
2198                 const LEX_CSTRING *field_name_arg,
2199                 const DTCollation &collation)
2200     :Field_str(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg,
2201                field_name_arg, collation)
2202     {}
2203   enum_conv_type rpl_conv_type_from(const Conv_source &source,
2204                                     const Relay_log_info *rli,
2205                                     const Conv_param &param) const override;
2206   int store_decimal(const my_decimal *d) override;
2207   uint32 max_data_length() const override;
2208   void make_send_field(Send_field *) override;
2209   bool send(Protocol *protocol) override;
2210 
is_varchar_and_in_write_set()2211   bool is_varchar_and_in_write_set() const override
2212   {
2213     DBUG_ASSERT(table && table->write_set);
2214     return bitmap_is_set(table->write_set, field_index);
2215   }
match_collation_to_optimize_range()2216   bool match_collation_to_optimize_range() const { return true; }
2217 
2218   bool can_optimize_keypart_ref(const Item_bool_func *cond,
2219                                 const Item *item) const override;
2220   bool can_optimize_hash_join(const Item_bool_func *cond,
2221                               const Item *item) const override;
2222   bool can_optimize_group_min_max(const Item_bool_func *cond,
2223                                   const Item *const_item) const override;
2224   bool can_optimize_range(const Item_bool_func *cond,
2225                           const Item *item,
2226                           bool is_eq_func) const override;
is_packable()2227   bool is_packable() const override { return true; }
2228   uint make_packed_sort_key_part(uchar *buff,
2229                                  const SORT_FIELD_ATTR *sort_field)override;
2230   uchar* pack_sort_string(uchar *to, const SORT_FIELD_ATTR *sort_field);
2231 };
2232 
2233 /* base class for float and double and decimal (old one) */
2234 class Field_real :public Field_num {
2235 protected:
2236   double get_double(const char *str, size_t length, CHARSET_INFO *cs, int *err);
2237 public:
2238   bool not_fixed;
2239 
Field_real(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,utype unireg_check_arg,const LEX_CSTRING * field_name_arg,uint8 dec_arg,bool zero_arg,bool unsigned_arg)2240   Field_real(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
2241              uchar null_bit_arg, utype unireg_check_arg,
2242              const LEX_CSTRING *field_name_arg,
2243              uint8 dec_arg, bool zero_arg, bool unsigned_arg)
2244     :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg,
2245                field_name_arg, dec_arg, zero_arg, unsigned_arg),
2246     not_fixed(dec_arg >= FLOATING_POINT_DECIMALS)
2247     {}
get_copy_func(const Field * from)2248   Copy_func *get_copy_func(const Field *from) const override
2249   {
2250     return do_field_real;
2251   }
2252   enum_conv_type rpl_conv_type_from(const Conv_source &source,
2253                                     const Relay_log_info *rli,
2254                                     const Conv_param &param) const override;
2255   Information_schema_numeric_attributes
information_schema_numeric_attributes()2256     information_schema_numeric_attributes() const override
2257   {
2258     return dec == NOT_FIXED_DEC ?
2259                   Information_schema_numeric_attributes(field_length) :
2260                   Information_schema_numeric_attributes(field_length, dec);
2261   }
2262   void sql_type(String &str) const override;
save_in_field(Field * to)2263   int save_in_field(Field *to) override { return to->store(val_real()); }
memcpy_field_possible(const Field * from)2264   bool memcpy_field_possible(const Field *from) const override
2265   {
2266     /*
2267       Cannot do memcpy from a longer field to a shorter field,
2268       e.g. a DOUBLE(53,10) into a DOUBLE(10,10).
2269       But it should be OK the other way around.
2270     */
2271     return real_type() == from->real_type() &&
2272            pack_length() == from->pack_length() &&
2273            is_unsigned() <= from->is_unsigned() &&
2274            decimals() == from->decimals() &&
2275            field_length >= from->field_length;
2276   }
store_decimal(const my_decimal * dec)2277   int store_decimal(const my_decimal *dec) override
2278   { return store(dec->to_double()); }
2279   int  store_time_dec(const MYSQL_TIME *ltime, uint dec) override;
2280   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
2281   my_decimal *val_decimal(my_decimal *) override;
val_bool()2282   bool val_bool() override { return val_real() != 0e0; }
max_display_length()2283   uint32 max_display_length() const override { return field_length; }
size_of()2284   uint size_of() const override { return sizeof *this; }
2285   Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item)
2286     override;
2287 };
2288 
2289 
2290 class Field_decimal final  :public Field_real {
2291 public:
Field_decimal(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,uint8 dec_arg,bool zero_arg,bool unsigned_arg)2292   Field_decimal(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
2293 		uchar null_bit_arg,
2294 		enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
2295 		uint8 dec_arg,bool zero_arg,bool unsigned_arg)
2296     :Field_real(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
2297                 unireg_check_arg, field_name_arg,
2298                 dec_arg, zero_arg, unsigned_arg)
2299     {}
2300   Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type)
2301     override;
type_handler()2302   const Type_handler *type_handler() const override
2303   { return &type_handler_olddecimal; }
key_type()2304   enum ha_base_keytype key_type() const override
2305   { return zerofill ? HA_KEYTYPE_BINARY : HA_KEYTYPE_NUM; }
2306   Information_schema_numeric_attributes
information_schema_numeric_attributes()2307     information_schema_numeric_attributes() const override
2308   {
2309     uint tmp= dec ? 2 : 1; // The sign and the decimal point
2310     return Information_schema_numeric_attributes(field_length - tmp, dec);
2311   }
get_copy_func(const Field * from)2312   Copy_func *get_copy_func(const Field *from) const override
2313   {
2314     return eq_def(from) ? get_identical_copy_func() : do_field_string;
2315   }
2316   int reset() override;
2317   int store(const char *to,size_t length,CHARSET_INFO *charset) override;
2318   int store(double nr) override;
2319   int store(longlong nr, bool unsigned_val) override;
2320   double val_real() override;
2321   longlong val_int() override;
2322   String *val_str(String *, String *) override;
2323   int cmp(const uchar *,const uchar *) const override;
2324   void sort_string(uchar *buff,uint length) override;
2325   void overflow(bool negative);
zero_pack()2326   bool zero_pack() const override { return false; }
2327   void sql_type(String &str) const override;
pack(uchar * to,const uchar * from,uint max_length)2328   uchar *pack(uchar* to, const uchar *from, uint max_length) override
2329   {
2330     return Field::pack(to, from, max_length);
2331   }
2332 };
2333 
2334 
2335 /* New decimal/numeric field which use fixed point arithmetic */
2336 class Field_new_decimal final :public Field_num {
2337 public:
2338   /* The maximum number of decimal digits can be stored */
2339   uint precision;
2340   uint bin_size;
2341   /*
2342     Constructors take max_length of the field as a parameter - not the
2343     precision as the number of decimal digits allowed.
2344     So for example we need to count length from precision handling
2345     CREATE TABLE ( DECIMAL(x,y))
2346   */
2347   Field_new_decimal(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
2348                     uchar null_bit_arg,
2349                     enum utype unireg_check_arg,
2350                     const LEX_CSTRING *field_name_arg,
2351                     uint8 dec_arg, bool zero_arg, bool unsigned_arg);
type_handler()2352   const Type_handler *type_handler() const override
2353   { return &type_handler_newdecimal; }
key_type()2354   enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BINARY; }
get_copy_func(const Field * from)2355   Copy_func *get_copy_func(const Field *from) const override
2356   {
2357     //  if (from->real_type() == MYSQL_TYPE_BIT) // QQ: why?
2358     //    return do_field_int;
2359     return do_field_decimal;
2360   }
save_in_field(Field * to)2361   int save_in_field(Field *to) override
2362   {
2363     my_decimal tmp(ptr, precision, dec);
2364     return to->store_decimal(&tmp);
2365   }
memcpy_field_possible(const Field * from)2366   bool memcpy_field_possible(const Field *from) const override
2367   {
2368     return real_type() == from->real_type() &&
2369            pack_length() == from->pack_length() &&
2370            is_unsigned() <= from->is_unsigned() &&
2371            decimals() == from->decimals() &&
2372            field_length == from->field_length;
2373   }
2374   enum_conv_type rpl_conv_type_from(const Conv_source &source,
2375                                     const Relay_log_info *rli,
2376                                     const Conv_param &param) const override;
2377   int  reset() override;
2378   bool store_value(const my_decimal *decimal_value);
2379   bool store_value(const my_decimal *decimal_value, int *native_error);
2380   void set_value_on_overflow(my_decimal *decimal_value, bool sign);
2381   int  store(const char *to, size_t length, CHARSET_INFO *charset) override;
2382   int  store(double nr) override;
2383   int  store(longlong nr, bool unsigned_val) override;
2384   int  store_time_dec(const MYSQL_TIME *ltime, uint dec) override;
2385   int  store_decimal(const my_decimal *) override;
val_real()2386   double val_real() override
2387   {
2388     return my_decimal(ptr, precision, dec).to_double();
2389   }
val_int()2390   longlong val_int() override
2391   {
2392     return my_decimal(ptr, precision, dec).to_longlong(unsigned_flag);
2393   }
val_uint()2394   ulonglong val_uint() override
2395   {
2396     return (ulonglong) my_decimal(ptr, precision, dec).to_longlong(true);
2397   }
2398   my_decimal *val_decimal(my_decimal *) override;
val_str(String * val_buffer,String *)2399   String *val_str(String *val_buffer, String *) override
2400   {
2401     uint fixed_precision= zerofill ? precision : 0;
2402     return my_decimal(ptr, precision, dec).
2403              to_string(val_buffer, fixed_precision, dec, '0');
2404   }
get_date(MYSQL_TIME * ltime,date_mode_t fuzzydate)2405   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override
2406   {
2407     my_decimal nr(ptr, precision, dec);
2408     return decimal_to_datetime_with_warn(get_thd(), &nr, ltime,
2409                                          fuzzydate, table->s, field_name.str);
2410   }
val_bool()2411   bool val_bool() override
2412   {
2413     return my_decimal(ptr, precision, dec).to_bool();
2414   }
2415   int cmp(const uchar *, const uchar *) const override;
2416   void sort_string(uchar *buff, uint length) override;
zero_pack()2417   bool zero_pack() const override { return false; }
2418   void sql_type(String &str) const override;
max_display_length()2419   uint32 max_display_length() const override { return field_length; }
2420   Information_schema_numeric_attributes
information_schema_numeric_attributes()2421     information_schema_numeric_attributes() const override
2422   {
2423     return Information_schema_numeric_attributes(precision, dec);
2424   }
size_of()2425   uint size_of() const override { return sizeof *this; }
pack_length()2426   uint32 pack_length() const override { return (uint32) bin_size; }
2427   uint pack_length_from_metadata(uint field_metadata) const override;
row_pack_length()2428   uint row_pack_length() const override { return pack_length(); }
2429   bool compatible_field_size(uint field_metadata, const Relay_log_info *rli,
2430                              uint16 mflags, int *order_var) const override;
2431   bool is_equal(const Column_definition &new_field) const override;
2432   const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end,
2433                       uint param_data) override;
2434   Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item)
2435     override;
2436   Binlog_type_info binlog_type_info() const override;
2437 };
2438 
2439 
2440 class Field_int :public Field_num
2441 {
2442 protected:
2443   String *val_str_from_long(String *val_buffer, uint max_char_length,
2444                             int radix, long nr);
2445 public:
Field_int(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,bool zero_arg,bool unsigned_arg)2446   Field_int(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
2447             uchar null_bit_arg, enum utype unireg_check_arg,
2448             const LEX_CSTRING *field_name_arg, bool zero_arg, bool unsigned_arg)
2449     :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
2450                unireg_check_arg, field_name_arg, 0, zero_arg, unsigned_arg)
2451     {}
2452   enum_conv_type rpl_conv_type_from(const Conv_source &source,
2453                                     const Relay_log_info *rli,
2454                                     const Conv_param &param) const override;
memcpy_field_possible(const Field * from)2455   bool memcpy_field_possible(const Field *from) const override
2456   {
2457     return real_type() == from->real_type() &&
2458            pack_length() == from->pack_length() &&
2459            is_unsigned() == from->is_unsigned();
2460   }
2461   int store_decimal(const my_decimal *) override;
2462   my_decimal *val_decimal(my_decimal *) override;
val_bool()2463   bool val_bool() override { return val_int() != 0; }
val_uint()2464   ulonglong val_uint() override
2465   {
2466     longlong nr= val_int();
2467     return nr < 0 && !unsigned_flag ? 0 : (ulonglong) nr;
2468   }
2469   int  store_time_dec(const MYSQL_TIME *ltime, uint dec) override;
2470   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
2471   virtual const Type_limits_int *type_limits_int() const= 0;
max_display_length()2472   uint32 max_display_length() const override
2473   {
2474     return type_limits_int()->char_length();
2475   }
type_numeric_attributes()2476   Type_numeric_attributes type_numeric_attributes() const override
2477   {
2478     /*
2479       For integer data types, the user-specified length does not constrain the
2480       supported range, so e.g. a column of the INT(1) data type supports the
2481       full integer range anyway.
2482       Choose the maximum from the user-specified length and the maximum
2483       possible length determined by the data type capacity:
2484         INT(1)  -> 11
2485         INT(10) -> 11
2486         INT(40) -> 40
2487     */
2488     uint32 length1= max_display_length();
2489     uint32 length2= field_length;
2490     return Type_numeric_attributes(MY_MAX(length1, length2),
2491                                    decimals(), is_unsigned());
2492   }
2493   Information_schema_numeric_attributes
information_schema_numeric_attributes()2494     information_schema_numeric_attributes() const override
2495   {
2496     uint32 prec= type_limits_int()->precision();
2497     return Information_schema_numeric_attributes(prec, 0);
2498   }
2499   void sql_type(String &str) const override;
get_mm_leaf(RANGE_OPT_PARAM * param,KEY_PART * key_part,const Item_bool_func * cond,scalar_comparison_op op,Item * value)2500   SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part,
2501                        const Item_bool_func *cond,
2502                        scalar_comparison_op op, Item *value) override
2503   {
2504     return get_mm_leaf_int(param, key_part, cond, op, value, unsigned_flag);
2505   }
2506 };
2507 
2508 
2509 class Field_tiny :public Field_int
2510 {
type_handler_priv()2511   const Type_handler_general_purpose_int *type_handler_priv() const
2512   {
2513     if (is_unsigned())
2514       return &type_handler_utiny;
2515     return &type_handler_stiny;
2516   }
2517 public:
Field_tiny(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,bool zero_arg,bool unsigned_arg)2518   Field_tiny(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
2519 	     uchar null_bit_arg,
2520 	     enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
2521 	     bool zero_arg, bool unsigned_arg)
2522     :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
2523                unireg_check_arg, field_name_arg, zero_arg, unsigned_arg)
2524     {}
type_handler()2525   const Type_handler *type_handler() const override
2526     { return type_handler_priv(); }
key_type()2527   enum ha_base_keytype key_type() const override
2528     { return unsigned_flag ? HA_KEYTYPE_BINARY : HA_KEYTYPE_INT8; }
2529   int store(const char *to,size_t length,CHARSET_INFO *charset) override;
2530   int store(double nr) override;
2531   int store(longlong nr, bool unsigned_val) override;
reset()2532   int reset() override { ptr[0]=0; return 0; }
2533   double val_real() override;
2534   longlong val_int() override;
2535   String *val_str(String *, String *) override;
2536   bool send(Protocol *protocol) override;
2537   int cmp(const uchar *,const uchar *) const override;
2538   void sort_string(uchar *buff,uint length) override;
pack_length()2539   uint32 pack_length() const override { return 1; }
type_limits_int()2540   const Type_limits_int *type_limits_int() const override
2541   {
2542     return type_handler_priv()->type_limits_int();
2543   }
2544 
pack(uchar * to,const uchar * from,uint max_length)2545   uchar *pack(uchar* to, const uchar *from, uint max_length) override
2546   {
2547     *to= *from;
2548     return to + 1;
2549   }
2550 
unpack(uchar * to,const uchar * from,const uchar * from_end,uint param_data)2551   const uchar *unpack(uchar* to, const uchar *from,
2552 		      const uchar *from_end, uint param_data) override
2553   {
2554     if (from == from_end)
2555       return 0;
2556     *to= *from;
2557     return from + 1;
2558   }
get_max_int_value()2559   ulonglong get_max_int_value() const override
2560   {
2561     return unsigned_flag ? 0xFFULL : 0x7FULL;
2562   }
2563 };
2564 
2565 
2566 class Field_short final :public Field_int
2567 {
type_handler_priv()2568   const Type_handler_general_purpose_int *type_handler_priv() const
2569   {
2570     if (is_unsigned())
2571       return &type_handler_ushort;
2572     return &type_handler_sshort;
2573   }
2574 public:
Field_short(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,bool zero_arg,bool unsigned_arg)2575   Field_short(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
2576 	      uchar null_bit_arg,
2577 	      enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
2578 	      bool zero_arg, bool unsigned_arg)
2579     :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
2580                unireg_check_arg, field_name_arg, zero_arg, unsigned_arg)
2581     {}
Field_short(uint32 len_arg,bool maybe_null_arg,const LEX_CSTRING * field_name_arg,bool unsigned_arg)2582   Field_short(uint32 len_arg,bool maybe_null_arg,
2583               const LEX_CSTRING *field_name_arg,
2584 	      bool unsigned_arg)
2585     :Field_int((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0,0,
2586                NONE, field_name_arg, 0, unsigned_arg)
2587     {}
type_handler()2588   const Type_handler *type_handler() const override
2589   { return type_handler_priv(); }
key_type()2590   enum ha_base_keytype key_type() const override
2591     { return unsigned_flag ? HA_KEYTYPE_USHORT_INT : HA_KEYTYPE_SHORT_INT;}
2592   int store(const char *to,size_t length,CHARSET_INFO *charset) override;
2593   int store(double nr) override;
2594   int store(longlong nr, bool unsigned_val) override;
reset()2595   int reset() override { ptr[0]=ptr[1]=0; return 0; }
2596   double val_real() override;
2597   longlong val_int() override;
2598   String *val_str(String *, String *) override;
2599   bool send(Protocol *protocol) override;
2600   int cmp(const uchar *,const uchar *) const override;
2601   void sort_string(uchar *buff,uint length) override;
pack_length()2602   uint32 pack_length() const override { return 2; }
type_limits_int()2603   const Type_limits_int *type_limits_int() const override
2604   {
2605     return type_handler_priv()->type_limits_int();
2606   }
pack(uchar * to,const uchar * from,uint)2607   uchar *pack(uchar* to, const uchar *from, uint) override
2608   { return pack_int16(to, from); }
2609 
unpack(uchar * to,const uchar * from,const uchar * from_end,uint)2610   const uchar *unpack(uchar* to, const uchar *from,
2611                       const uchar *from_end, uint) override
2612   { return unpack_int16(to, from, from_end); }
get_max_int_value()2613   ulonglong get_max_int_value() const override
2614   {
2615     return unsigned_flag ? 0xFFFFULL : 0x7FFFULL;
2616   }
2617 };
2618 
2619 class Field_medium final :public Field_int
2620 {
type_handler_priv()2621   const Type_handler_general_purpose_int *type_handler_priv() const
2622   {
2623     if (is_unsigned())
2624       return &type_handler_uint24;
2625     return &type_handler_sint24;
2626   }
2627 public:
Field_medium(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,bool zero_arg,bool unsigned_arg)2628   Field_medium(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
2629 	      uchar null_bit_arg,
2630 	      enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
2631 	      bool zero_arg, bool unsigned_arg)
2632     :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
2633                unireg_check_arg, field_name_arg, zero_arg, unsigned_arg)
2634     {}
type_handler()2635   const Type_handler *type_handler() const override
2636   { return type_handler_priv(); }
key_type()2637   enum ha_base_keytype key_type() const override
2638     { return unsigned_flag ? HA_KEYTYPE_UINT24 : HA_KEYTYPE_INT24; }
2639   int store(const char *to,size_t length,CHARSET_INFO *charset) override;
2640   int store(double nr) override;
2641   int store(longlong nr, bool unsigned_val) override;
reset()2642   int reset() override { ptr[0]=ptr[1]=ptr[2]=0; return 0; }
2643   double val_real() override;
2644   longlong val_int() override;
2645   String *val_str(String *, String *) override;
2646   bool send(Protocol *protocol) override;
2647   int cmp(const uchar *,const uchar *) const override;
2648   void sort_string(uchar *buff,uint length) override;
pack_length()2649   uint32 pack_length() const override { return 3; }
type_limits_int()2650   const Type_limits_int *type_limits_int() const override
2651   {
2652     return type_handler_priv()->type_limits_int();
2653   }
pack(uchar * to,const uchar * from,uint max_length)2654   uchar *pack(uchar* to, const uchar *from, uint max_length) override
2655   {
2656     return Field::pack(to, from, max_length);
2657   }
get_max_int_value()2658   ulonglong get_max_int_value() const override
2659   {
2660     return unsigned_flag ? 0xFFFFFFULL : 0x7FFFFFULL;
2661   }
2662 };
2663 
2664 
2665 class Field_long final :public Field_int
2666 {
type_handler_priv()2667   const Type_handler_general_purpose_int *type_handler_priv() const
2668   {
2669     if (is_unsigned())
2670       return &type_handler_ulong;
2671     return &type_handler_slong;
2672   }
2673 public:
Field_long(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,bool zero_arg,bool unsigned_arg)2674   Field_long(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
2675 	     uchar null_bit_arg,
2676 	     enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
2677 	     bool zero_arg, bool unsigned_arg)
2678     :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
2679                unireg_check_arg, field_name_arg, zero_arg, unsigned_arg)
2680     {}
Field_long(uint32 len_arg,bool maybe_null_arg,const LEX_CSTRING * field_name_arg,bool unsigned_arg)2681   Field_long(uint32 len_arg,bool maybe_null_arg,
2682              const LEX_CSTRING *field_name_arg,
2683 	     bool unsigned_arg)
2684     :Field_int((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0,0,
2685                NONE, field_name_arg, 0, unsigned_arg)
2686     {}
type_handler()2687   const Type_handler *type_handler() const override
2688   { return type_handler_priv(); }
key_type()2689   enum ha_base_keytype key_type() const override
2690     { return unsigned_flag ? HA_KEYTYPE_ULONG_INT : HA_KEYTYPE_LONG_INT; }
2691   int store(const char *to,size_t length,CHARSET_INFO *charset) override;
2692   int store(double nr) override;
2693   int store(longlong nr, bool unsigned_val) override;
reset()2694   int reset() override { ptr[0]=ptr[1]=ptr[2]=ptr[3]=0; return 0; }
2695   double val_real() override;
2696   longlong val_int() override;
2697   bool send(Protocol *protocol) override;
2698   String *val_str(String *, String *) override;
2699   int cmp(const uchar *,const uchar *) const override;
2700   void sort_string(uchar *buff,uint length) override;
pack_length()2701   uint32 pack_length() const override { return 4; }
type_limits_int()2702   const Type_limits_int *type_limits_int() const override
2703   {
2704     return type_handler_priv()->type_limits_int();
2705   }
pack(uchar * to,const uchar * from,uint)2706   uchar *pack(uchar* to, const uchar *from, uint) override
2707   {
2708     return pack_int32(to, from);
2709   }
unpack(uchar * to,const uchar * from,const uchar * from_end,uint)2710   const uchar *unpack(uchar* to, const uchar *from,
2711                       const uchar *from_end, uint) override
2712   {
2713     return unpack_int32(to, from, from_end);
2714   }
get_max_int_value()2715   ulonglong get_max_int_value() const override
2716   {
2717     return unsigned_flag ? 0xFFFFFFFFULL : 0x7FFFFFFFULL;
2718   }
2719 };
2720 
2721 
2722 class Field_longlong :public Field_int
2723 {
type_handler_priv()2724   const Type_handler_general_purpose_int *type_handler_priv() const
2725   {
2726     if (is_unsigned())
2727       return &type_handler_ulonglong;
2728     return &type_handler_slonglong;
2729   }
2730 public:
Field_longlong(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,bool zero_arg,bool unsigned_arg)2731   Field_longlong(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
2732 	      uchar null_bit_arg,
2733 	      enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
2734 	      bool zero_arg, bool unsigned_arg)
2735     :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
2736                unireg_check_arg, field_name_arg, zero_arg, unsigned_arg)
2737     {}
Field_longlong(uint32 len_arg,bool maybe_null_arg,const LEX_CSTRING * field_name_arg,bool unsigned_arg)2738   Field_longlong(uint32 len_arg,bool maybe_null_arg,
2739 		 const LEX_CSTRING *field_name_arg,
2740                  bool unsigned_arg)
2741     :Field_int((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0,0,
2742                 NONE, field_name_arg, 0, unsigned_arg)
2743     {}
type_handler()2744   const Type_handler *type_handler() const override
2745   { return type_handler_priv(); }
key_type()2746   enum ha_base_keytype key_type() const override
2747   { return unsigned_flag ? HA_KEYTYPE_ULONGLONG : HA_KEYTYPE_LONGLONG; }
2748   int store(const char *to,size_t length,CHARSET_INFO *charset) override;
2749   int store(double nr) override;
2750   int store(longlong nr, bool unsigned_val) override;
reset()2751   int reset() override
2752   {
2753     ptr[0]=ptr[1]=ptr[2]=ptr[3]=ptr[4]=ptr[5]=ptr[6]=ptr[7]=0;
2754     return 0;
2755   }
2756   double val_real() override;
2757   longlong val_int() override;
2758   String *val_str(String *, String *) override;
2759   bool send(Protocol *protocol) override;
2760   int cmp(const uchar *,const uchar *) const override;
2761   void sort_string(uchar *buff,uint length) override;
pack_length()2762   uint32 pack_length() const override { return 8; }
type_limits_int()2763   const Type_limits_int *type_limits_int() const override
2764   {
2765     return type_handler_priv()->type_limits_int();
2766   }
pack(uchar * to,const uchar * from,uint)2767   uchar *pack(uchar* to, const uchar *from, uint) override
2768   {
2769     return pack_int64(to, from);
2770   }
unpack(uchar * to,const uchar * from,const uchar * from_end,uint)2771   const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end,
2772 		      uint) override
2773   {
2774     return unpack_int64(to, from, from_end);
2775   }
2776   void set_max() override;
2777   bool is_max() override;
get_max_int_value()2778   ulonglong get_max_int_value() const override
2779   {
2780     return unsigned_flag ? 0xFFFFFFFFFFFFFFFFULL : 0x7FFFFFFFFFFFFFFFULL;
2781   }
2782 };
2783 
2784 
2785 class Field_vers_trx_id :public Field_longlong {
2786   MYSQL_TIME cache;
2787   ulonglong cached;
2788 public:
Field_vers_trx_id(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,bool zero_arg,bool unsigned_arg)2789   Field_vers_trx_id(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
2790                     uchar null_bit_arg, enum utype unireg_check_arg,
2791                     const LEX_CSTRING *field_name_arg, bool zero_arg,
2792                     bool unsigned_arg)
2793       : Field_longlong(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
2794                        unireg_check_arg, field_name_arg, zero_arg,
2795                        unsigned_arg),
2796         cached(0)
2797   {}
type_handler()2798   const Type_handler *type_handler() const override
2799   { return &type_handler_vers_trx_id; }
size_of()2800   uint size_of() const override { return sizeof *this; }
2801   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate, ulonglong trx_id);
get_date(MYSQL_TIME * ltime,date_mode_t fuzzydate)2802   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override
2803   {
2804     return get_date(ltime, fuzzydate, (ulonglong) val_int());
2805   }
2806   bool test_if_equality_guarantees_uniqueness(const Item *item) const override;
can_optimize_keypart_ref(const Item_bool_func *,const Item *)2807   bool can_optimize_keypart_ref(const Item_bool_func *, const Item *)
2808     const override
2809   {
2810     return true;
2811   }
2812 
can_optimize_group_min_max(const Item_bool_func *,const Item *)2813   bool can_optimize_group_min_max(const Item_bool_func *, const Item *)
2814     const override
2815   {
2816     return true;
2817   }
can_optimize_range(const Item_bool_func *,const Item *,bool)2818   bool can_optimize_range(const Item_bool_func *, const Item *, bool)
2819     const override
2820   {
2821     return true;
2822   }
2823   /* cmp_type() cannot be TIME_RESULT, because we want to compare this field against
2824      integers. But in all other cases we treat it as TIME_RESULT! */
2825 };
2826 
2827 
2828 class Field_float final :public Field_real {
2829 public:
Field_float(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,uint8 dec_arg,bool zero_arg,bool unsigned_arg)2830   Field_float(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
2831 	      uchar null_bit_arg,
2832 	      enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
2833               uint8 dec_arg,bool zero_arg,bool unsigned_arg)
2834     :Field_real(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
2835                 unireg_check_arg, field_name_arg,
2836                 dec_arg, zero_arg, unsigned_arg)
2837     {
2838       if (dec_arg >= FLOATING_POINT_DECIMALS)
2839         dec_arg= NOT_FIXED_DEC;
2840     }
Field_float(uint32 len_arg,bool maybe_null_arg,const LEX_CSTRING * field_name_arg,uint8 dec_arg)2841   Field_float(uint32 len_arg, bool maybe_null_arg,
2842               const LEX_CSTRING *field_name_arg, uint8 dec_arg)
2843     :Field_real((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0, (uint) 0,
2844                 NONE, field_name_arg, dec_arg, 0, 0)
2845     {
2846       if (dec_arg >= FLOATING_POINT_DECIMALS)
2847         dec_arg= NOT_FIXED_DEC;
2848     }
type_handler()2849   const Type_handler *type_handler() const override
2850   { return &type_handler_float; }
key_type()2851   enum ha_base_keytype key_type() const override { return HA_KEYTYPE_FLOAT; }
2852   int store(const char *to,size_t length,CHARSET_INFO *charset) override;
2853   int store(double nr) override;
2854   int store(longlong nr, bool unsigned_val) override;
reset()2855   int reset() override { bzero(ptr,sizeof(float)); return 0; }
2856   double val_real() override;
2857   longlong val_int() override;
2858   String *val_str(String *, String *) override;
2859   bool send(Protocol *protocol) override;
2860   int cmp(const uchar *,const uchar *) const override;
2861   void sort_string(uchar *buff, uint length) override;
pack_length()2862   uint32 pack_length() const override { return sizeof(float); }
row_pack_length()2863   uint row_pack_length() const override { return pack_length(); }
get_max_int_value()2864   ulonglong get_max_int_value() const override
2865   {
2866     /*
2867       We use the maximum as per IEEE754-2008 standard, 2^24
2868     */
2869     return 0x1000000ULL;
2870   }
2871   Binlog_type_info binlog_type_info() const override;
2872 };
2873 
2874 
2875 class Field_double :public Field_real {
2876   longlong val_int_from_real(bool want_unsigned_result);
2877 public:
Field_double(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,uint8 dec_arg,bool zero_arg,bool unsigned_arg)2878   Field_double(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
2879 	       uchar null_bit_arg,
2880 	       enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
2881 	       uint8 dec_arg,bool zero_arg,bool unsigned_arg)
2882     :Field_real(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
2883                 unireg_check_arg, field_name_arg,
2884                 dec_arg, zero_arg, unsigned_arg)
2885     {
2886       if (dec_arg >= FLOATING_POINT_DECIMALS)
2887         dec_arg= NOT_FIXED_DEC;
2888     }
Field_double(uint32 len_arg,bool maybe_null_arg,const LEX_CSTRING * field_name_arg,uint8 dec_arg)2889   Field_double(uint32 len_arg, bool maybe_null_arg,
2890                const LEX_CSTRING *field_name_arg, uint8 dec_arg)
2891     :Field_real((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "" : 0, (uint) 0,
2892                 NONE, field_name_arg, dec_arg, 0, 0)
2893     {
2894       if (dec_arg >= FLOATING_POINT_DECIMALS)
2895         dec_arg= NOT_FIXED_DEC;
2896     }
Field_double(uint32 len_arg,bool maybe_null_arg,const LEX_CSTRING * field_name_arg,uint8 dec_arg,bool not_fixed_arg)2897   Field_double(uint32 len_arg, bool maybe_null_arg,
2898                const LEX_CSTRING *field_name_arg,
2899 	       uint8 dec_arg, bool not_fixed_arg)
2900     :Field_real((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "" : 0, (uint) 0,
2901                 NONE, field_name_arg, dec_arg, 0, 0)
2902     {
2903       not_fixed= not_fixed_arg;
2904       if (dec_arg >= FLOATING_POINT_DECIMALS)
2905         dec_arg= NOT_FIXED_DEC;
2906     }
init_for_tmp_table(Field * org_field,TABLE * new_table)2907   void init_for_tmp_table(Field *org_field, TABLE *new_table) override
2908   {
2909     Field::init_for_tmp_table(org_field, new_table);
2910     not_fixed= true;
2911   }
type_handler()2912   const Type_handler *type_handler() const override
2913   { return &type_handler_double; }
key_type()2914   enum ha_base_keytype key_type() const override final { return HA_KEYTYPE_DOUBLE; }
2915   int  store(const char *to,size_t length,CHARSET_INFO *charset) override final;
2916   int  store(double nr) override final;
2917   int  store(longlong nr, bool unsigned_val) override final;
reset()2918   int reset() override final { bzero(ptr,sizeof(double)); return 0; }
2919   double val_real() override final;
val_int()2920   longlong val_int() override final { return val_int_from_real(false); }
val_uint()2921   ulonglong val_uint() override final { return (ulonglong) val_int_from_real(true); }
2922   String *val_str(String *, String *) override final;
2923   bool send(Protocol *protocol) override;
2924   int cmp(const uchar *,const uchar *) const override final;
2925   void sort_string(uchar *buff, uint length) override final;
pack_length()2926   uint32 pack_length() const override final { return sizeof(double); }
row_pack_length()2927   uint row_pack_length() const override final { return pack_length(); }
get_max_int_value()2928   ulonglong get_max_int_value() const override final
2929   {
2930     /*
2931       We use the maximum as per IEEE754-2008 standard, 2^53
2932     */
2933     return 0x20000000000000ULL;
2934   }
2935   Binlog_type_info binlog_type_info() const override final;
2936 };
2937 
2938 
2939 /* Everything saved in this will disappear. It will always return NULL */
2940 
2941 class Field_null :public Field_str {
2942   static uchar null[1];
2943 public:
Field_null(uchar * ptr_arg,uint32 len_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,const DTCollation & collation)2944   Field_null(uchar *ptr_arg, uint32 len_arg,
2945 	     enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
2946 	     const DTCollation &collation)
2947     :Field_str(ptr_arg, len_arg, null, 1,
2948 	       unireg_check_arg, field_name_arg, collation)
2949     {}
type_handler()2950   const Type_handler *type_handler() const override
2951   { return &type_handler_null; }
2952   enum_conv_type rpl_conv_type_from(const Conv_source &source,
2953                                     const Relay_log_info *rli,
2954                                     const Conv_param &param) const override;
2955   Information_schema_character_attributes
information_schema_character_attributes()2956     information_schema_character_attributes() const override
2957   {
2958     return Information_schema_character_attributes();
2959   }
get_copy_func(const Field * from)2960   Copy_func *get_copy_func(const Field *from) const override
2961   {
2962     return do_field_string;
2963   }
store(const char * to,size_t length,CHARSET_INFO * cs)2964   int  store(const char *to, size_t length, CHARSET_INFO *cs) override final
2965   { null[0]=1; return 0; }
store(double nr)2966   int store(double nr) override final { null[0]=1; return 0; }
store(longlong nr,bool unsigned_val)2967   int store(longlong nr, bool unsigned_val) override final { null[0]=1; return 0; }
store_decimal(const my_decimal * d)2968   int store_decimal(const my_decimal *d) override final { null[0]=1; return 0; }
reset()2969   int reset() override final { return 0; }
val_real()2970   double val_real() override final { return 0.0;}
val_int()2971   longlong val_int() override final { return 0;}
val_bool()2972   bool val_bool() override final { return false; }
val_decimal(my_decimal *)2973   my_decimal *val_decimal(my_decimal *) override final { return 0; }
val_str(String * value,String * value2)2974   String *val_str(String *value,String *value2) override final
2975   { value2->length(0); return value2;}
2976   bool is_equal(const Column_definition &new_field) const override final;
cmp(const uchar * a,const uchar * b)2977   int cmp(const uchar *a, const uchar *b) const override final { return 0;}
sort_string(uchar * buff,uint length)2978   void sort_string(uchar *buff, uint length) override final {}
pack_length()2979   uint32 pack_length() const override final { return 0; }
2980   void sql_type(String &str) const override final;
size_of()2981   uint size_of() const override final { return sizeof *this; }
max_display_length()2982   uint32 max_display_length() const override final { return 4; }
move_field_offset(my_ptrdiff_t ptr_diff)2983   void move_field_offset(my_ptrdiff_t ptr_diff) override final {}
can_optimize_keypart_ref(const Item_bool_func * cond,const Item * item)2984   bool can_optimize_keypart_ref(const Item_bool_func *cond,
2985                                 const Item *item) const override final
2986   {
2987     return false;
2988   }
can_optimize_group_min_max(const Item_bool_func * cond,const Item * const_item)2989   bool can_optimize_group_min_max(const Item_bool_func *cond,
2990                                   const Item *const_item) const override final
2991   {
2992     return false;
2993   }
2994 };
2995 
2996 
2997 class Field_temporal :public Field {
2998 protected:
2999   Item *get_equal_const_item_datetime(THD *thd, const Context &ctx,
3000                                       Item *const_item);
3001   void set_warnings(Sql_condition::enum_warning_level trunc_level,
3002                     const ErrConv *str, int was_cut, const char *typestr);
store_TIME_return_code_with_warnings(int warn,const ErrConv * str,const char * typestr)3003   int store_TIME_return_code_with_warnings(int warn, const ErrConv *str,
3004                                            const char *typestr)
3005   {
3006     if (!MYSQL_TIME_WARN_HAVE_WARNINGS(warn) &&
3007         MYSQL_TIME_WARN_HAVE_NOTES(warn))
3008     {
3009       set_warnings(Sql_condition::WARN_LEVEL_NOTE, str,
3010                    warn | MYSQL_TIME_WARN_TRUNCATED, typestr);
3011       return 3;
3012     }
3013     set_warnings(Sql_condition::WARN_LEVEL_WARN, str, warn, typestr);
3014     return warn ? 2 : 0;
3015   }
store_invalid_with_warning(const ErrConv * str,int was_cut,const char * typestr)3016   int store_invalid_with_warning(const ErrConv *str, int was_cut,
3017                                  const char *typestr)
3018   {
3019     DBUG_ASSERT(was_cut);
3020     reset();
3021     Sql_condition::enum_warning_level level= Sql_condition::WARN_LEVEL_WARN;
3022     if (was_cut & MYSQL_TIME_WARN_ZERO_DATE)
3023     {
3024       set_warnings(level, str, MYSQL_TIME_WARN_OUT_OF_RANGE, typestr);
3025       return 2;
3026     }
3027     set_warnings(level, str, MYSQL_TIME_WARN_TRUNCATED, typestr);
3028     return 1;
3029   }
3030   void sql_type_comment(String &str,
3031                         const Name &name,
3032                         const Name &comment) const;
3033   void sql_type_dec_comment(String &str,
3034                             const Name &name, uint dec,
3035                             const Name &comment) const;
sql_type_opt_dec_comment(String & str,const Name & name,uint dec,const Name & comment)3036   void sql_type_opt_dec_comment(String &str,
3037                                 const Name &name, uint dec,
3038                                 const Name &comment) const
3039   {
3040     if (dec)
3041       sql_type_dec_comment(str, name, dec, comment);
3042     else
3043       sql_type_comment(str, name, comment);
3044   }
3045   static const Name &type_version_mysql56();
3046 public:
Field_temporal(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,utype unireg_check_arg,const LEX_CSTRING * field_name_arg)3047   Field_temporal(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
3048                  uchar null_bit_arg, utype unireg_check_arg,
3049                  const LEX_CSTRING *field_name_arg)
3050     :Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg,
3051                field_name_arg)
3052     { flags|= BINARY_FLAG; }
store_hex_hybrid(const char * str,size_t length)3053   int  store_hex_hybrid(const char *str, size_t length) override
3054   {
3055     return store(str, length, &my_charset_bin);
3056   }
3057   sql_mode_t can_handle_sql_mode_dependency_on_store() const override;
3058   Copy_func *get_copy_func(const Field *from) const override;
save_in_field(Field * to)3059   int save_in_field(Field *to) override
3060   {
3061     MYSQL_TIME ltime;
3062     // For temporal types no truncation needed. Rounding mode is not important.
3063     if (get_date(&ltime, TIME_CONV_NONE | TIME_FRAC_NONE))
3064       return to->reset();
3065     return to->store_time_dec(&ltime, decimals());
3066   }
3067   bool memcpy_field_possible(const Field *from) const override;
max_display_length()3068   uint32 max_display_length() const override { return field_length; }
str_needs_quotes()3069   bool str_needs_quotes() const override { return true; }
charset()3070   CHARSET_INFO *charset() const override
3071   {
3072     return DTCollation_numeric::singleton().collation;
3073   }
dtcollation()3074   const DTCollation &dtcollation() const override
3075   {
3076     return DTCollation_numeric::singleton();
3077   }
sort_charset()3078   CHARSET_INFO *sort_charset() const override { return &my_charset_bin; }
binary()3079   bool binary() const override { return true; }
val_bool()3080   bool val_bool() override { return val_real() != 0e0; }
3081   bool is_equal(const Column_definition &new_field) const override;
eq_def(const Field * field)3082   bool eq_def(const Field *field) const override
3083   {
3084     return (Field::eq_def(field) && decimals() == field->decimals());
3085   }
3086   my_decimal *val_decimal(my_decimal*) override;
pos_in_interval(Field * min,Field * max)3087   double pos_in_interval(Field *min, Field *max) override
3088   {
3089     return pos_in_interval_val_real(min, max);
3090   }
3091   bool can_optimize_keypart_ref(const Item_bool_func *cond,
3092                                 const Item *item) const override;
3093   bool can_optimize_group_min_max(const Item_bool_func *cond,
3094                                   const Item *const_item) const override;
can_optimize_range(const Item_bool_func * cond,const Item * item,bool is_eq_func)3095   bool can_optimize_range(const Item_bool_func *cond,
3096                                   const Item *item,
3097                                   bool is_eq_func) const override
3098   {
3099     return true;
3100   }
3101   SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part,
3102                        const Item_bool_func *cond,
3103                        scalar_comparison_op op, Item *value) override;
3104 };
3105 
3106 
3107 /**
3108   Abstract class for:
3109   - DATE
3110   - DATETIME
3111   - DATETIME(1..6)
3112   - DATETIME(0..6) - MySQL56 version
3113 */
3114 class Field_temporal_with_date :public Field_temporal {
3115 protected:
3116   virtual void store_TIME(const MYSQL_TIME *ltime) = 0;
store_datetime(const Datetime & dt)3117   void store_datetime(const Datetime &dt)
3118   {
3119     return store_TIME(dt.get_mysql_time());
3120   }
3121   virtual bool get_TIME(MYSQL_TIME *ltime, const uchar *pos,
3122                         date_mode_t fuzzydate) const = 0;
validate_MMDD(bool not_zero_date,uint month,uint day,date_mode_t fuzzydate)3123   bool validate_MMDD(bool not_zero_date, uint month, uint day,
3124                      date_mode_t fuzzydate) const
3125   {
3126     if (!not_zero_date)
3127       return bool(fuzzydate & TIME_NO_ZERO_DATE);
3128     if (!month || !day)
3129       return bool(fuzzydate & TIME_NO_ZERO_IN_DATE);
3130     return false;
3131   }
3132 public:
Field_temporal_with_date(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,utype unireg_check_arg,const LEX_CSTRING * field_name_arg)3133   Field_temporal_with_date(uchar *ptr_arg, uint32 len_arg,
3134                            uchar *null_ptr_arg, uchar null_bit_arg,
3135                            utype unireg_check_arg,
3136                            const LEX_CSTRING *field_name_arg)
3137     :Field_temporal(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
3138                     unireg_check_arg, field_name_arg)
3139     {}
3140   bool validate_value_in_record(THD *thd, const uchar *record) const;
3141 };
3142 
3143 
3144 class Field_timestamp :public Field_temporal {
3145 protected:
3146   int store_TIME_with_warning(THD *, const Datetime *,
3147                               const ErrConv *, int warn);
3148   virtual void store_TIMEVAL(const timeval &tv)= 0;
store_TIMESTAMP(const Timestamp & ts)3149   void store_TIMESTAMP(const Timestamp &ts)
3150   {
3151     store_TIMEVAL(ts.tv());
3152   }
3153   int zero_time_stored_return_code_with_warning();
3154 public:
3155   Field_timestamp(uchar *ptr_arg, uint32 len_arg,
3156                   uchar *null_ptr_arg, uchar null_bit_arg,
3157 		  enum utype unireg_check_arg,
3158                   const LEX_CSTRING *field_name_arg,
3159 		  TABLE_SHARE *share);
type_handler()3160   const Type_handler *type_handler() const override
3161   { return &type_handler_timestamp; }
3162   enum_conv_type rpl_conv_type_from(const Conv_source &source,
3163                                     const Relay_log_info *rli,
3164                                     const Conv_param &param) const override;
3165   Copy_func *get_copy_func(const Field *from) const override;
3166   sql_mode_t conversion_depends_on_sql_mode(THD *, Item *) const override;
3167   int  store(const char *to,size_t length,CHARSET_INFO *charset) override;
3168   int  store(double nr) override;
3169   int  store(longlong nr, bool unsigned_val) override;
3170   int  store_time_dec(const MYSQL_TIME *ltime, uint dec) override;
3171   int  store_decimal(const my_decimal *) override;
3172   int  store_timestamp_dec(const timeval &ts, uint dec) override;
3173   int  save_in_field(Field *to) override;
3174   longlong val_int() override;
3175   String *val_str(String *, String *) override;
zero_pack()3176   bool zero_pack() const override { return false; }
3177   /*
3178     This method is used by storage/perfschema and
3179     Item_func_now_local::save_in_field().
3180   */
store_TIME(my_time_t ts,ulong sec_part)3181   void store_TIME(my_time_t ts, ulong sec_part)
3182   {
3183     int warn;
3184     time_round_mode_t mode= Datetime::default_round_mode(get_thd());
3185     store_TIMESTAMP(Timestamp(ts, sec_part).round(decimals(), mode, &warn));
3186   }
3187   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
3188   int store_native(const Native &value) override;
3189   bool validate_value_in_record(THD *thd, const uchar *record) const override;
get_equal_const_item(THD * thd,const Context & ctx,Item * const_item)3190   Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item)
3191     override
3192   {
3193     return get_equal_const_item_datetime(thd, ctx, const_item);
3194   }
3195   bool load_data_set_null(THD *thd) override;
3196   bool load_data_set_no_data(THD *thd, bool fixed_format) override;
3197 };
3198 
3199 
3200 class Field_timestamp0 :public Field_timestamp
3201 {
store_TIMEVAL(const timeval & tv)3202   void store_TIMEVAL(const timeval &tv) override
3203   {
3204     int4store(ptr, tv.tv_sec);
3205   }
3206 public:
Field_timestamp0(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,TABLE_SHARE * share)3207   Field_timestamp0(uchar *ptr_arg, uint32 len_arg,
3208                    uchar *null_ptr_arg, uchar null_bit_arg,
3209 		   enum utype unireg_check_arg,
3210                    const LEX_CSTRING *field_name_arg,
3211 		   TABLE_SHARE *share)
3212    :Field_timestamp(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
3213                     unireg_check_arg, field_name_arg, share)
3214   { }
key_type()3215   enum ha_base_keytype key_type() const override
3216   { return HA_KEYTYPE_ULONG_INT; }
sql_type(String & str)3217   void sql_type(String &str) const override
3218   {
3219     sql_type_comment(str, Field_timestamp0::type_handler()->name(),
3220                      Type_handler::version_mariadb53());
3221   }
val_real()3222   double val_real() override
3223   {
3224     return (double) Field_timestamp0::val_int();
3225   }
3226   bool send(Protocol *protocol) override;
3227   int cmp(const uchar *,const uchar *) const override;
3228   void sort_string(uchar *buff,uint length) override;
pack_length()3229   uint32 pack_length() const override { return 4; }
3230   int set_time() override;
3231   /* Get TIMESTAMP field value as seconds since begging of Unix Epoch */
3232   my_time_t get_timestamp(const uchar *pos, ulong *sec_part) const override;
3233   bool val_native(Native *to) override;
pack(uchar * to,const uchar * from,uint)3234   uchar *pack(uchar *to, const uchar *from, uint) override
3235   {
3236     return pack_int32(to, from);
3237   }
unpack(uchar * to,const uchar * from,const uchar * from_end,uint)3238   const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end,
3239                       uint) override
3240   {
3241     return unpack_int32(to, from, from_end);
3242   }
size_of()3243   uint size_of() const override { return sizeof *this; }
3244 };
3245 
3246 
3247 /**
3248   Abstract class for:
3249   - TIMESTAMP(1..6)
3250   - TIMESTAMP(0..6) - MySQL56 version
3251 */
3252 class Field_timestamp_with_dec :public Field_timestamp {
3253 protected:
3254   uint dec;
3255 public:
Field_timestamp_with_dec(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,TABLE_SHARE * share,uint dec_arg)3256   Field_timestamp_with_dec(uchar *ptr_arg,
3257                            uchar *null_ptr_arg, uchar null_bit_arg,
3258                            enum utype unireg_check_arg,
3259                            const LEX_CSTRING *field_name_arg,
3260                            TABLE_SHARE *share, uint dec_arg) :
3261   Field_timestamp(ptr_arg,
3262                   MAX_DATETIME_WIDTH + dec_arg + MY_TEST(dec_arg), null_ptr_arg,
3263                   null_bit_arg, unireg_check_arg, field_name_arg, share),
3264   dec(dec_arg)
3265   {
3266     DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS);
3267   }
decimals()3268   uint decimals() const override { return dec; }
key_type()3269   enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BINARY; }
pack(uchar * to,const uchar * from,uint max_length)3270   uchar *pack(uchar *to, const uchar *from, uint max_length) override
3271   { return Field::pack(to, from, max_length); }
unpack(uchar * to,const uchar * from,const uchar * from_end,uint param_data)3272   const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end,
3273                       uint param_data) override
3274   { return Field::unpack(to, from, from_end, param_data); }
3275   void make_send_field(Send_field *field) override;
sort_string(uchar * to,uint length)3276   void sort_string(uchar *to, uint length) override
3277   {
3278     DBUG_ASSERT(length == pack_length());
3279     memcpy(to, ptr, length);
3280   }
3281   bool send(Protocol *protocol) override;
3282   double val_real() override;
3283   my_decimal* val_decimal(my_decimal*) override;
3284   int set_time() override;
3285 };
3286 
3287 
3288 class Field_timestamp_hires :public Field_timestamp_with_dec {
sec_part_bytes(uint dec)3289   uint sec_part_bytes(uint dec) const
3290   {
3291     return Type_handler_timestamp::sec_part_bytes(dec);
3292   }
3293   void store_TIMEVAL(const timeval &tv) override;
3294 public:
Field_timestamp_hires(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,TABLE_SHARE * share,uint dec_arg)3295   Field_timestamp_hires(uchar *ptr_arg,
3296                         uchar *null_ptr_arg, uchar null_bit_arg,
3297                         enum utype unireg_check_arg,
3298                         const LEX_CSTRING *field_name_arg,
3299                         TABLE_SHARE *share, uint dec_arg) :
3300   Field_timestamp_with_dec(ptr_arg, null_ptr_arg, null_bit_arg,
3301                            unireg_check_arg, field_name_arg, share, dec_arg)
3302   {
3303     DBUG_ASSERT(dec);
3304   }
sql_type(String & str)3305   void sql_type(String &str) const override
3306   {
3307     sql_type_dec_comment(str, Field_timestamp_hires::type_handler()->name(),
3308                          dec, Type_handler::version_mariadb53());
3309   }
3310   bool val_native(Native *to) override;
3311   my_time_t get_timestamp(const uchar *pos, ulong *sec_part) const override;
3312   int cmp(const uchar *,const uchar *) const override;
pack_length()3313   uint32 pack_length() const override { return 4 + sec_part_bytes(dec); }
size_of()3314   uint size_of() const override { return sizeof *this; }
3315 };
3316 
3317 
3318 /**
3319   TIMESTAMP(0..6) - MySQL56 version
3320 */
3321 class Field_timestampf final :public Field_timestamp_with_dec {
3322   void store_TIMEVAL(const timeval &tv) override;
3323 public:
Field_timestampf(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,TABLE_SHARE * share,uint dec_arg)3324   Field_timestampf(uchar *ptr_arg,
3325                    uchar *null_ptr_arg, uchar null_bit_arg,
3326                    enum utype unireg_check_arg,
3327                    const LEX_CSTRING *field_name_arg,
3328                    TABLE_SHARE *share, uint dec_arg) :
3329     Field_timestamp_with_dec(ptr_arg, null_ptr_arg, null_bit_arg,
3330                              unireg_check_arg, field_name_arg, share, dec_arg)
3331     {}
type_handler()3332   const Type_handler *type_handler() const override
3333   { return &type_handler_timestamp2; }
binlog_type()3334   enum_field_types binlog_type() const override
3335   { return MYSQL_TYPE_TIMESTAMP2; }
sql_type(String & str)3336   void sql_type(String &str) const override
3337   {
3338     sql_type_opt_dec_comment(str, Field_timestampf::type_handler()->name(),
3339                              dec, type_version_mysql56());
3340 
3341   }
3342   enum_conv_type rpl_conv_type_from(const Conv_source &source,
3343                                     const Relay_log_info *rli,
3344                                     const Conv_param &param) const override;
pack_length()3345   uint32 pack_length() const override
3346   {
3347     return my_timestamp_binary_length(dec);
3348   }
row_pack_length()3349   uint row_pack_length() const override { return pack_length(); }
pack_length_from_metadata(uint field_metadata)3350   uint pack_length_from_metadata(uint field_metadata) const override
3351   {
3352     DBUG_ENTER("Field_timestampf::pack_length_from_metadata");
3353     uint tmp= my_timestamp_binary_length(field_metadata);
3354     DBUG_RETURN(tmp);
3355   }
cmp(const uchar * a_ptr,const uchar * b_ptr)3356   int cmp(const uchar *a_ptr,const uchar *b_ptr) const override
3357   {
3358     return memcmp(a_ptr, b_ptr, pack_length());
3359   }
3360   void set_max() override;
3361   bool is_max() override;
3362   my_time_t get_timestamp(const uchar *pos, ulong *sec_part) const override;
3363   bool val_native(Native *to) override;
size_of()3364   uint size_of() const override { return sizeof *this; }
3365   Binlog_type_info binlog_type_info() const override;
3366 };
3367 
3368 
3369 class Field_year final :public Field_tiny {
3370 public:
Field_year(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg)3371   Field_year(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
3372 	     uchar null_bit_arg,
3373 	     enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg)
3374     :Field_tiny(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
3375 		unireg_check_arg, field_name_arg, 1, 1)
3376     {}
type_handler()3377   const Type_handler *type_handler() const override
3378   {
3379     return field_length == 2 ? &type_handler_year2 : &type_handler_year;
3380   }
3381   enum_conv_type rpl_conv_type_from(const Conv_source &source,
3382                                     const Relay_log_info *rli,
3383                                     const Conv_param &param) const override;
get_copy_func(const Field * from)3384   Copy_func *get_copy_func(const Field *from) const override
3385   {
3386     if (eq_def(from))
3387       return get_identical_copy_func();
3388     switch (from->cmp_type()) {
3389     case STRING_RESULT:
3390     {
3391       const Type_handler *handler= from->type_handler();
3392       if (handler == &type_handler_enum || handler == &type_handler_set)
3393         return do_field_int;
3394       return do_field_string;
3395     }
3396     case TIME_RESULT:
3397       return do_field_date;
3398     case DECIMAL_RESULT:
3399       return do_field_decimal;
3400     case REAL_RESULT:
3401       return do_field_real;
3402     case INT_RESULT:
3403       break;
3404     case ROW_RESULT:
3405     default:
3406       DBUG_ASSERT(0);
3407       break;
3408     }
3409     return do_field_int;
3410   }
3411   int  store(const char *to,size_t length,CHARSET_INFO *charset) override;
3412   int  store(double nr) override;
3413   int  store(longlong nr, bool unsigned_val) override;
3414   int  store_time_dec(const MYSQL_TIME *ltime, uint dec) override;
3415   double val_real() override;
3416   longlong val_int() override;
3417   String *val_str(String *, String *) override;
3418   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
3419   bool send(Protocol *protocol) override;
3420   Information_schema_numeric_attributes
information_schema_numeric_attributes()3421     information_schema_numeric_attributes() const override
3422   {
3423     return Information_schema_numeric_attributes();
3424   }
max_display_length()3425   uint32 max_display_length() const override { return field_length; }
3426   void sql_type(String &str) const override;
3427 };
3428 
3429 
3430 class Field_date_common :public Field_temporal_with_date
3431 {
3432 protected:
3433   int store_TIME_with_warning(const Datetime *ltime, const ErrConv *str,
3434                               int was_cut);
3435 public:
Field_date_common(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg)3436   Field_date_common(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
3437                     enum utype unireg_check_arg,
3438                     const LEX_CSTRING *field_name_arg)
3439     :Field_temporal_with_date(ptr_arg, MAX_DATE_WIDTH,
3440                               null_ptr_arg, null_bit_arg,
3441                               unireg_check_arg, field_name_arg)
3442   {}
3443   Copy_func *get_copy_func(const Field *from) const override;
3444   SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part,
3445                        const Item_bool_func *cond,
3446                        scalar_comparison_op op, Item *value) override;
3447   int  store(const char *to, size_t length, CHARSET_INFO *charset) override;
3448   int  store(double nr) override;
3449   int  store(longlong nr, bool unsigned_val) override;
3450   int  store_time_dec(const MYSQL_TIME *ltime, uint dec) override;
3451   int  store_decimal(const my_decimal *) override;
3452 };
3453 
3454 
3455 class Field_date final :public Field_date_common
3456 {
3457   void store_TIME(const MYSQL_TIME *ltime) override;
3458   bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate)
3459     const override;
3460 public:
Field_date(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg)3461   Field_date(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
3462 	     enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg)
3463     :Field_date_common(ptr_arg, null_ptr_arg, null_bit_arg,
3464                        unireg_check_arg, field_name_arg) {}
type_handler()3465   const Type_handler *type_handler() const override
3466   { return &type_handler_date; }
key_type()3467   enum ha_base_keytype key_type() const override
3468   { return HA_KEYTYPE_ULONG_INT; }
3469   enum_conv_type rpl_conv_type_from(const Conv_source &source,
3470                                     const Relay_log_info *rli,
3471                                     const Conv_param &param) const override;
reset()3472   int reset() override { ptr[0]=ptr[1]=ptr[2]=ptr[3]=0; return 0; }
get_date(MYSQL_TIME * ltime,date_mode_t fuzzydate)3473   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override
3474   { return Field_date::get_TIME(ltime, ptr, fuzzydate); }
3475   double val_real() override;
3476   longlong val_int() override;
3477   String *val_str(String *, String *) override;
3478   bool send(Protocol *protocol) override;
3479   int cmp(const uchar *,const uchar *) const override;
3480   void sort_string(uchar *buff,uint length) override;
pack_length()3481   uint32 pack_length() const override { return 4; }
3482   void sql_type(String &str) const override;
pack(uchar * to,const uchar * from,uint)3483   uchar *pack(uchar* to, const uchar *from, uint) override
3484   {
3485     return pack_int32(to, from);
3486   }
unpack(uchar * to,const uchar * from,const uchar * from_end,uint)3487   const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end,
3488                       uint) override
3489   {
3490     return unpack_int32(to, from, from_end);
3491   }
size_of()3492   uint size_of() const override { return sizeof *this; }
3493 };
3494 
3495 
3496 class Field_newdate final :public Field_date_common
3497 {
3498   void store_TIME(const MYSQL_TIME *ltime) override;
3499   bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate)
3500     const override;
3501 public:
Field_newdate(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg)3502   Field_newdate(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
3503 		enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg)
3504     :Field_date_common(ptr_arg, null_ptr_arg, null_bit_arg,
3505                        unireg_check_arg, field_name_arg)
3506     {}
type_handler()3507   const Type_handler *type_handler() const override
3508   { return &type_handler_newdate; }
key_type()3509   enum ha_base_keytype key_type() const override { return HA_KEYTYPE_UINT24; }
3510   enum_conv_type rpl_conv_type_from(const Conv_source &source,
3511                                     const Relay_log_info *rli,
3512                                     const Conv_param &param) const override;
reset()3513   int reset() override { ptr[0]=ptr[1]=ptr[2]=0; return 0; }
3514   double val_real() override;
3515   longlong val_int() override;
3516   String *val_str(String *, String *) override;
3517   bool send(Protocol *protocol) override;
3518   int cmp(const uchar *,const uchar *) const override;
3519   void sort_string(uchar *buff,uint length) override;
pack_length()3520   uint32 pack_length() const override { return 3; }
3521   void sql_type(String &str) const override;
get_date(MYSQL_TIME * ltime,date_mode_t fuzzydate)3522   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override
3523   { return Field_newdate::get_TIME(ltime, ptr, fuzzydate); }
3524   longlong val_datetime_packed(THD *thd) override;
size_of()3525   uint size_of() const override { return sizeof *this; }
3526   Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item)
3527     override;
3528 };
3529 
3530 
3531 class Field_time :public Field_temporal {
3532   /*
3533     when this Field_time instance is used for storing values for index lookups
3534     (see class store_key, Field::new_key_field(), etc), the following
3535     might be set to TO_DAYS(CURDATE()). See also Field_time::store_time_dec()
3536   */
3537   long curdays;
3538 protected:
3539   virtual void store_TIME(const MYSQL_TIME *ltime)= 0;
store_TIME(const Time & t)3540   void store_TIME(const Time &t) { return store_TIME(t.get_mysql_time()); }
3541   int store_TIME_with_warning(const Time *ltime, const ErrConv *str, int warn);
3542   bool check_zero_in_date_with_warn(date_mode_t fuzzydate);
3543   static void do_field_time(Copy_field *copy);
3544 public:
Field_time(uchar * ptr_arg,uint length_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg)3545   Field_time(uchar *ptr_arg, uint length_arg, uchar *null_ptr_arg,
3546              uchar null_bit_arg, enum utype unireg_check_arg,
3547              const LEX_CSTRING *field_name_arg)
3548     :Field_temporal(ptr_arg, length_arg, null_ptr_arg, null_bit_arg,
3549                     unireg_check_arg, field_name_arg), curdays(0)
3550     {}
3551   bool can_be_substituted_to_equal_item(const Context &ctx,
3552                                         const Item_equal *item_equal) override;
type_handler()3553   const Type_handler *type_handler() const override
3554   { return &type_handler_time; }
3555   enum_conv_type rpl_conv_type_from(const Conv_source &source,
3556                                     const Relay_log_info *rli,
3557                                     const Conv_param &param) const override;
get_copy_func(const Field * from)3558   Copy_func *get_copy_func(const Field *from) const override
3559   {
3560     return from->cmp_type() == REAL_RESULT ? do_field_string : // MDEV-9344
3561            from->type() == MYSQL_TYPE_YEAR ? do_field_int :
3562            from->type() == MYSQL_TYPE_BIT  ? do_field_int :
3563            eq_def(from)                    ? get_identical_copy_func() :
3564                                              do_field_time;
3565   }
memcpy_field_possible(const Field * from)3566   bool memcpy_field_possible(const Field *from) const override
3567   {
3568     return real_type() == from->real_type() &&
3569            decimals() == from->decimals();
3570   }
3571   sql_mode_t conversion_depends_on_sql_mode(THD *, Item *) const override;
3572   int store_native(const Native &value) override;
3573   bool val_native(Native *to) override;
3574   int store_time_dec(const MYSQL_TIME *ltime, uint dec) override;
3575   int store(const char *to,size_t length,CHARSET_INFO *charset) override;
3576   int store(double nr) override;
3577   int store(longlong nr, bool unsigned_val) override;
3578   int  store_decimal(const my_decimal *) override;
3579   String *val_str(String *, String *) override;
3580   bool send(Protocol *protocol) override;
3581   void set_curdays(THD *thd);
3582   Field *new_key_field(MEM_ROOT *root, TABLE *new_table,
3583                        uchar *new_ptr, uint32 length,
3584                        uchar *new_null_ptr, uint new_null_bit) override;
3585   Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item)
3586     override;
3587 };
3588 
3589 
3590 class Field_time0 final :public Field_time
3591 {
3592 protected:
3593   void store_TIME(const MYSQL_TIME *ltime) override;
3594 public:
Field_time0(uchar * ptr_arg,uint length_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg)3595   Field_time0(uchar *ptr_arg, uint length_arg, uchar *null_ptr_arg,
3596              uchar null_bit_arg, enum utype unireg_check_arg,
3597              const LEX_CSTRING *field_name_arg)
3598     :Field_time(ptr_arg, length_arg, null_ptr_arg, null_bit_arg,
3599                 unireg_check_arg, field_name_arg)
3600   { }
key_type()3601   enum ha_base_keytype key_type() const override { return HA_KEYTYPE_INT24; }
sql_type(String & str)3602   void sql_type(String &str) const override
3603   {
3604     sql_type_comment(str, Field_time0::type_handler()->name(),
3605                      Type_handler::version_mariadb53());
3606   }
3607   double val_real() override;
3608   longlong val_int() override;
3609   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
3610   int cmp(const uchar *,const uchar *) const override;
3611   void sort_string(uchar *buff,uint length) override;
pack_length()3612   uint32 pack_length() const override { return 3; }
size_of()3613   uint size_of() const override { return sizeof *this; }
3614 };
3615 
3616 
3617 /**
3618   Abstract class for:
3619   - TIME(1..6)
3620   - TIME(0..6) - MySQL56 version
3621 */
3622 class Field_time_with_dec :public Field_time {
3623 protected:
3624   uint dec;
3625 public:
Field_time_with_dec(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,uint dec_arg)3626   Field_time_with_dec(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
3627                       enum utype unireg_check_arg,
3628                       const LEX_CSTRING *field_name_arg,
3629                       uint dec_arg)
3630     :Field_time(ptr_arg, MIN_TIME_WIDTH + dec_arg + MY_TEST(dec_arg),
3631                 null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg),
3632      dec(dec_arg)
3633   {
3634     DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS);
3635   }
decimals()3636   uint decimals() const override { return dec; }
key_type()3637   enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BINARY; }
3638   longlong val_int() override;
3639   double val_real() override;
3640   void make_send_field(Send_field *) override;
3641 };
3642 
3643 
3644 /**
3645   TIME(1..6)
3646 */
3647 class Field_time_hires final :public Field_time_with_dec {
3648   longlong zero_point;
3649   void store_TIME(const MYSQL_TIME *) override;
3650 public:
Field_time_hires(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,uint dec_arg)3651   Field_time_hires(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
3652              enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
3653              uint dec_arg)
3654     :Field_time_with_dec(ptr_arg, null_ptr_arg,
3655                          null_bit_arg, unireg_check_arg, field_name_arg,
3656                          dec_arg)
3657   {
3658     DBUG_ASSERT(dec);
3659     zero_point= sec_part_shift(
3660                    ((TIME_MAX_VALUE_SECONDS+1LL)*TIME_SECOND_PART_FACTOR), dec);
3661   }
sql_type(String & str)3662   void sql_type(String &str) const override
3663   {
3664     sql_type_dec_comment(str, Field_time_hires::type_handler()->name(),
3665                          dec, Type_handler::version_mariadb53());
3666   }
3667   int reset() override;
3668   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
3669   int cmp(const uchar *,const uchar *) const override;
3670   void sort_string(uchar *buff,uint length) override;
pack_length()3671   uint32 pack_length() const override
3672   { return Type_handler_time::hires_bytes(dec); }
size_of()3673   uint size_of() const override { return sizeof *this; }
3674 };
3675 
3676 
3677 /**
3678   TIME(0..6) - MySQL56 version
3679 */
3680 class Field_timef final :public Field_time_with_dec {
3681   void store_TIME(const MYSQL_TIME *ltime) override;
3682 public:
Field_timef(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,uint dec_arg)3683   Field_timef(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
3684              enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
3685              uint dec_arg)
3686     :Field_time_with_dec(ptr_arg, null_ptr_arg,
3687                          null_bit_arg, unireg_check_arg, field_name_arg,
3688                          dec_arg)
3689   {
3690     DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS);
3691   }
type_handler()3692   const Type_handler *type_handler() const override
3693   { return &type_handler_time2; }
binlog_type()3694   enum_field_types binlog_type() const override { return MYSQL_TYPE_TIME2; }
sql_type(String & str)3695   void sql_type(String &str) const override
3696   {
3697     sql_type_opt_dec_comment(str, Field_timef::type_handler()->name(),
3698                              dec, type_version_mysql56());
3699   }
3700   enum_conv_type rpl_conv_type_from(const Conv_source &source,
3701                                     const Relay_log_info *rli,
3702                                     const Conv_param &param) const override;
pack_length()3703   uint32 pack_length() const override
3704   {
3705     return my_time_binary_length(dec);
3706   }
row_pack_length()3707   uint row_pack_length() const override { return pack_length(); }
pack_length_from_metadata(uint field_metadata)3708   uint pack_length_from_metadata(uint field_metadata) const override
3709   {
3710     DBUG_ENTER("Field_timef::pack_length_from_metadata");
3711     uint tmp= my_time_binary_length(field_metadata);
3712     DBUG_RETURN(tmp);
3713   }
sort_string(uchar * to,uint length)3714   void sort_string(uchar *to, uint length) override
3715   {
3716     DBUG_ASSERT(length == Field_timef::pack_length());
3717     memcpy(to, ptr, length);
3718   }
cmp(const uchar * a_ptr,const uchar * b_ptr)3719   int cmp(const uchar *a_ptr, const uchar *b_ptr) const override
3720   {
3721     return memcmp(a_ptr, b_ptr, pack_length());
3722   }
3723   int reset() override;
3724   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override;
3725   longlong val_time_packed(THD *thd) override;
3726   int store_native(const Native &value) override;
3727   bool val_native(Native *to) override;
size_of()3728   uint size_of() const override { return sizeof *this; }
3729   Binlog_type_info binlog_type_info() const override;
3730 };
3731 
3732 
3733 class Field_datetime :public Field_temporal_with_date {
3734 protected:
3735   int store_TIME_with_warning(const Datetime *ltime, const ErrConv *str,
3736                               int was_cut);
3737 public:
Field_datetime(uchar * ptr_arg,uint length_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg)3738   Field_datetime(uchar *ptr_arg, uint length_arg, uchar *null_ptr_arg,
3739                  uchar null_bit_arg, enum utype unireg_check_arg,
3740                  const LEX_CSTRING *field_name_arg)
3741     :Field_temporal_with_date(ptr_arg, length_arg, null_ptr_arg, null_bit_arg,
3742                               unireg_check_arg, field_name_arg)
3743     {
3744       if (unireg_check == TIMESTAMP_UN_FIELD ||
3745           unireg_check == TIMESTAMP_DNUN_FIELD)
3746         flags|= ON_UPDATE_NOW_FLAG;
3747     }
type_handler()3748   const Type_handler *type_handler() const override
3749   { return &type_handler_datetime; }
3750   sql_mode_t conversion_depends_on_sql_mode(THD *, Item *) const override;
3751   enum_conv_type rpl_conv_type_from(const Conv_source &source,
3752                                     const Relay_log_info *rli,
3753                                     const Conv_param &param) const override;
3754   int  store(const char *to, size_t length, CHARSET_INFO *charset) override;
3755   int  store(double nr) override;
3756   int  store(longlong nr, bool unsigned_val) override;
3757   int  store_time_dec(const MYSQL_TIME *ltime, uint dec) override;
3758   int  store_decimal(const my_decimal *) override;
3759   int set_time() override;
get_equal_const_item(THD * thd,const Context & ctx,Item * const_item)3760   Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item)
3761     override
3762   {
3763     return get_equal_const_item_datetime(thd, ctx, const_item);
3764   }
3765 };
3766 
3767 
3768 /*
3769   Stored as a 8 byte unsigned int. Should sometimes be change to a 6 byte
3770 */
3771 
3772 class Field_datetime0 final :public Field_datetime
3773 {
3774   void store_TIME(const MYSQL_TIME *ltime) override;
3775   bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate)
3776     const override;
3777 public:
Field_datetime0(uchar * ptr_arg,uint length_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg)3778   Field_datetime0(uchar *ptr_arg, uint length_arg, uchar *null_ptr_arg,
3779                  uchar null_bit_arg, enum utype unireg_check_arg,
3780                  const LEX_CSTRING *field_name_arg)
3781     :Field_datetime(ptr_arg, length_arg, null_ptr_arg, null_bit_arg,
3782                     unireg_check_arg, field_name_arg)
3783   {}
key_type()3784   enum ha_base_keytype key_type() const override
3785   { return HA_KEYTYPE_ULONGLONG; }
sql_type(String & str)3786   void sql_type(String &str) const override
3787   {
3788     sql_type_comment(str, Field_datetime0::type_handler()->name(),
3789                      Type_handler::version_mariadb53());
3790   }
val_real()3791   double val_real() override
3792   {
3793     return (double) Field_datetime0::val_int();
3794   }
3795   longlong val_int() override;
3796   String *val_str(String *, String *) override;
3797   bool send(Protocol *protocol) override;
3798   int cmp(const uchar *,const uchar *) const override;
3799   void sort_string(uchar *buff,uint length) override;
pack_length()3800   uint32 pack_length() const override { return 8; }
get_date(MYSQL_TIME * ltime,date_mode_t fuzzydate)3801   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override
3802   { return Field_datetime0::get_TIME(ltime, ptr, fuzzydate); }
pack(uchar * to,const uchar * from,uint)3803   uchar *pack(uchar* to, const uchar *from, uint) override
3804   {
3805     return pack_int64(to, from);
3806   }
unpack(uchar * to,const uchar * from,const uchar * from_end,uint)3807   const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end,
3808 		      uint) override
3809   {
3810     return unpack_int64(to, from, from_end);
3811   }
size_of()3812   uint size_of() const override { return sizeof *this; }
3813 };
3814 
3815 
3816 /**
3817   Abstract class for:
3818   - DATETIME(1..6)
3819   - DATETIME(0..6) - MySQL56 version
3820 */
3821 class Field_datetime_with_dec :public Field_datetime {
3822 protected:
3823   uint dec;
3824 public:
Field_datetime_with_dec(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,uint dec_arg)3825   Field_datetime_with_dec(uchar *ptr_arg, uchar *null_ptr_arg,
3826                           uchar null_bit_arg, enum utype unireg_check_arg,
3827                           const LEX_CSTRING *field_name_arg, uint dec_arg)
3828     :Field_datetime(ptr_arg, MAX_DATETIME_WIDTH + dec_arg + MY_TEST(dec_arg),
3829                     null_ptr_arg, null_bit_arg, unireg_check_arg,
3830                     field_name_arg), dec(dec_arg)
3831   {
3832     DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS);
3833   }
decimals()3834   uint decimals() const override final { return dec; }
key_type()3835   enum ha_base_keytype key_type() const override final { return HA_KEYTYPE_BINARY; }
3836   void make_send_field(Send_field *field) override final;
3837   bool send(Protocol *protocol) override final;
pack(uchar * to,const uchar * from,uint max_length)3838   uchar *pack(uchar *to, const uchar *from, uint max_length) override final
3839   { return Field::pack(to, from, max_length); }
unpack(uchar * to,const uchar * from,const uchar * from_end,uint param_data)3840   const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end,
3841                       uint param_data) override final
3842   { return Field::unpack(to, from, from_end, param_data); }
sort_string(uchar * to,uint length)3843   void sort_string(uchar *to, uint length) override final
3844   {
3845     DBUG_ASSERT(length == pack_length());
3846     memcpy(to, ptr, length);
3847   }
3848   double val_real() override final;
3849   longlong val_int() override final;
3850   String *val_str(String *, String *) override final;
3851 };
3852 
3853 
3854 /**
3855   DATETIME(1..6)
3856 */
3857 class Field_datetime_hires final :public Field_datetime_with_dec {
3858   void store_TIME(const MYSQL_TIME *ltime) override;
3859   bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate)
3860     const override;
3861 public:
Field_datetime_hires(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,uint dec_arg)3862   Field_datetime_hires(uchar *ptr_arg, uchar *null_ptr_arg,
3863                        uchar null_bit_arg, enum utype unireg_check_arg,
3864                        const LEX_CSTRING *field_name_arg, uint dec_arg)
3865     :Field_datetime_with_dec(ptr_arg, null_ptr_arg, null_bit_arg,
3866                              unireg_check_arg, field_name_arg, dec_arg)
3867   {
3868     DBUG_ASSERT(dec);
3869   }
sql_type(String & str)3870   void sql_type(String &str) const override
3871   {
3872     sql_type_dec_comment(str, Field_datetime_hires::type_handler()->name(),
3873                          dec, Type_handler::version_mariadb53());
3874   }
3875   int cmp(const uchar *,const uchar *) const override;
pack_length()3876   uint32 pack_length() const override
3877   { return Type_handler_datetime::hires_bytes(dec); }
get_date(MYSQL_TIME * ltime,date_mode_t fuzzydate)3878   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override
3879   { return Field_datetime_hires::get_TIME(ltime, ptr, fuzzydate); }
size_of()3880   uint size_of() const override { return sizeof *this; }
3881 };
3882 
3883 
3884 /**
3885   DATETIME(0..6) - MySQL56 version
3886 */
3887 
3888 class Field_datetimef final :public Field_datetime_with_dec {
3889   void store_TIME(const MYSQL_TIME *ltime) override;
3890   bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate)
3891     const override;
3892 public:
Field_datetimef(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,uint dec_arg)3893   Field_datetimef(uchar *ptr_arg, uchar *null_ptr_arg,
3894                   uchar null_bit_arg, enum utype unireg_check_arg,
3895                   const LEX_CSTRING *field_name_arg, uint dec_arg)
3896     :Field_datetime_with_dec(ptr_arg, null_ptr_arg, null_bit_arg,
3897                              unireg_check_arg, field_name_arg, dec_arg)
3898   {}
type_handler()3899   const Type_handler *type_handler() const override
3900   { return &type_handler_datetime2; }
binlog_type()3901   enum_field_types binlog_type() const override
3902   { return MYSQL_TYPE_DATETIME2; }
sql_type(String & str)3903   void sql_type(String &str) const override
3904   {
3905     sql_type_opt_dec_comment(str, Field_datetimef::type_handler()->name(),
3906                              dec, type_version_mysql56());
3907   }
3908   enum_conv_type rpl_conv_type_from(const Conv_source &source,
3909                                     const Relay_log_info *rli,
3910                                     const Conv_param &param) const override;
pack_length()3911   uint32 pack_length() const override
3912   {
3913     return my_datetime_binary_length(dec);
3914   }
row_pack_length()3915   uint row_pack_length() const override { return pack_length(); }
pack_length_from_metadata(uint field_metadata)3916   uint pack_length_from_metadata(uint field_metadata) const override
3917   {
3918     DBUG_ENTER("Field_datetimef::pack_length_from_metadata");
3919     uint tmp= my_datetime_binary_length(field_metadata);
3920     DBUG_RETURN(tmp);
3921   }
cmp(const uchar * a_ptr,const uchar * b_ptr)3922   int cmp(const uchar *a_ptr, const uchar *b_ptr) const override
3923   {
3924     return memcmp(a_ptr, b_ptr, pack_length());
3925   }
3926   int reset() override;
get_date(MYSQL_TIME * ltime,date_mode_t fuzzydate)3927   bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override
3928   { return Field_datetimef::get_TIME(ltime, ptr, fuzzydate); }
3929   longlong val_datetime_packed(THD *thd) override;
size_of()3930   uint size_of() const override { return sizeof *this; }
3931   Binlog_type_info binlog_type_info() const override;
3932 };
3933 
3934 
3935 static inline Field_timestamp *
new_Field_timestamp(MEM_ROOT * root,uchar * ptr,uchar * null_ptr,uchar null_bit,enum Field::utype unireg_check,const LEX_CSTRING * field_name,TABLE_SHARE * share,uint dec)3936 new_Field_timestamp(MEM_ROOT *root,uchar *ptr, uchar *null_ptr, uchar null_bit,
3937                     enum Field::utype unireg_check,
3938                     const LEX_CSTRING *field_name,
3939                     TABLE_SHARE *share, uint dec)
3940 {
3941   if (dec==0)
3942     return new (root)
3943       Field_timestamp0(ptr, MAX_DATETIME_WIDTH, null_ptr,
3944                        null_bit, unireg_check, field_name, share);
3945   if (dec >= FLOATING_POINT_DECIMALS)
3946     dec= MAX_DATETIME_PRECISION;
3947   return new (root)
3948     Field_timestamp_hires(ptr, null_ptr, null_bit, unireg_check,
3949                           field_name, share, dec);
3950 }
3951 
3952 static inline Field_time *
new_Field_time(MEM_ROOT * root,uchar * ptr,uchar * null_ptr,uchar null_bit,enum Field::utype unireg_check,const LEX_CSTRING * field_name,uint dec)3953 new_Field_time(MEM_ROOT *root, uchar *ptr, uchar *null_ptr, uchar null_bit,
3954                enum Field::utype unireg_check, const LEX_CSTRING *field_name,
3955                uint dec)
3956 {
3957   if (dec == 0)
3958     return new (root)
3959       Field_time0(ptr, MIN_TIME_WIDTH, null_ptr, null_bit, unireg_check,
3960                   field_name);
3961   if (dec >= FLOATING_POINT_DECIMALS)
3962     dec= MAX_DATETIME_PRECISION;
3963   return new (root)
3964     Field_time_hires(ptr, null_ptr, null_bit, unireg_check, field_name, dec);
3965 }
3966 
3967 static inline Field_datetime *
new_Field_datetime(MEM_ROOT * root,uchar * ptr,uchar * null_ptr,uchar null_bit,enum Field::utype unireg_check,const LEX_CSTRING * field_name,uint dec)3968 new_Field_datetime(MEM_ROOT *root, uchar *ptr, uchar *null_ptr, uchar null_bit,
3969                    enum Field::utype unireg_check,
3970                    const LEX_CSTRING *field_name, uint dec)
3971 {
3972   if (dec == 0)
3973     return new (root)
3974       Field_datetime0(ptr, MAX_DATETIME_WIDTH, null_ptr, null_bit,
3975                       unireg_check, field_name);
3976   if (dec >= FLOATING_POINT_DECIMALS)
3977     dec= MAX_DATETIME_PRECISION;
3978   return new (root)
3979     Field_datetime_hires(ptr, null_ptr, null_bit,
3980                          unireg_check, field_name, dec);
3981 }
3982 
3983 class Field_string final :public Field_longstr {
3984   class Warn_filter_string: public Warn_filter
3985   {
3986   public:
3987     Warn_filter_string(const THD *thd, const Field_string *field);
3988   };
is_var_string()3989   bool is_var_string() const
3990   {
3991     return can_alter_field_type &&
3992            orig_table &&
3993            (orig_table->s->db_create_options & HA_OPTION_PACK_RECORD) &&
3994            field_length >= 4 &&
3995            orig_table->s->frm_version < FRM_VER_TRUE_VARCHAR;
3996   }
3997 public:
3998   bool can_alter_field_type;
Field_string(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,const DTCollation & collation)3999   Field_string(uchar *ptr_arg, uint32 len_arg,uchar *null_ptr_arg,
4000 	       uchar null_bit_arg,
4001 	       enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
4002 	       const DTCollation &collation)
4003     :Field_longstr(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
4004                    unireg_check_arg, field_name_arg, collation),
4005      can_alter_field_type(1) {};
Field_string(uint32 len_arg,bool maybe_null_arg,const LEX_CSTRING * field_name_arg,const DTCollation & collation)4006   Field_string(uint32 len_arg,bool maybe_null_arg,
4007                const LEX_CSTRING *field_name_arg,
4008                const DTCollation &collation)
4009     :Field_longstr((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0, 0,
4010                    NONE, field_name_arg, collation),
4011      can_alter_field_type(1) {};
4012 
4013   const Type_handler *type_handler() const override;
key_type()4014   enum ha_base_keytype key_type() const override
4015     { return binary() ? HA_KEYTYPE_BINARY : HA_KEYTYPE_TEXT; }
4016   en_fieldtype tmp_engine_column_type(bool use_packed_rows) const override;
zero_pack()4017   bool zero_pack() const override { return false; }
4018   Copy_func *get_copy_func(const Field *from) const override;
reset()4019   int reset() override
4020   {
4021     charset()->fill((char*) ptr, field_length, (has_charset() ? ' ' : 0));
4022     return 0;
4023   }
4024   int store(const char *to,size_t length,CHARSET_INFO *charset) override;
4025   using Field_str::store;
4026   double val_real() override;
4027   longlong val_int() override;
4028   String *val_str(String *, String *) override;
4029   my_decimal *val_decimal(my_decimal *) override;
4030   int cmp(const uchar *,const uchar *) const override;
4031   void sort_string(uchar *buff,uint length) override;
update_data_type_statistics(Data_type_statistics * st)4032   void update_data_type_statistics(Data_type_statistics *st) const override
4033   {
4034     st->m_fixed_string_count++;
4035     st->m_fixed_string_total_length+= pack_length();
4036   }
4037   void sql_type(String &str) const override;
4038   void sql_rpl_type(String*) const override;
4039   bool is_equal(const Column_definition &new_field) const override;
can_be_converted_by_engine(const Column_definition & new_type)4040   bool can_be_converted_by_engine(const Column_definition &new_type) const
4041     override
4042   {
4043     return table->file->can_convert_string(this, new_type);
4044   }
4045   uchar *pack(uchar *to, const uchar *from, uint max_length) override;
4046   const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end,
4047                       uint param_data) override;
pack_length_from_metadata(uint field_metadata)4048   uint pack_length_from_metadata(uint field_metadata) const override
4049   {
4050     DBUG_PRINT("debug", ("field_metadata: 0x%04x", field_metadata));
4051     if (field_metadata == 0)
4052       return row_pack_length();
4053     return (((field_metadata >> 4) & 0x300) ^ 0x300) + (field_metadata & 0x00ff);
4054   }
4055   bool compatible_field_size(uint field_metadata, const Relay_log_info *rli,
4056                              uint16 mflags, int *order_var) const override;
row_pack_length()4057   uint row_pack_length() const override { return field_length; }
4058   int pack_cmp(const uchar *a,const uchar *b,uint key_length,
4059                bool insert_or_update);
4060   int pack_cmp(const uchar *b,uint key_length,bool insert_or_update);
4061   uint packed_col_length(const uchar *to, uint length) override;
4062   uint max_packed_col_length(uint max_length) override;
size_of()4063   uint size_of() const override { return sizeof *this; }
has_charset()4064   bool has_charset() const override { return charset() != &my_charset_bin; }
4065   Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type)
4066     override;
4067   uint get_key_image(uchar *buff, uint length,
4068                      const uchar *ptr_arg, imagetype type) const override;
4069   sql_mode_t value_depends_on_sql_mode() const override;
4070   sql_mode_t can_handle_sql_mode_dependency_on_store() const override;
4071   void print_key_value(String *out, uint32 length) override;
4072   Binlog_type_info binlog_type_info() const override;
4073 };
4074 
4075 
4076 class Field_varstring :public Field_longstr {
4077 public:
get_data()4078   const uchar *get_data() const
4079   {
4080     return get_data(ptr);
4081   }
get_data(const uchar * ptr_arg)4082   const uchar *get_data(const uchar *ptr_arg) const
4083   {
4084     return ptr_arg + length_bytes;
4085   }
get_length()4086   uint get_length() const
4087   {
4088     return get_length(ptr);
4089   }
get_length(const uchar * ptr_arg)4090   uint get_length(const uchar *ptr_arg) const
4091   {
4092     return length_bytes == 1 ? (uint) *ptr_arg : uint2korr(ptr_arg);
4093   }
4094 protected:
store_length(uint32 number)4095   void store_length(uint32 number)
4096   {
4097     if (length_bytes == 1)
4098       *ptr= (uchar) number;
4099     else
4100       int2store(ptr, number);
4101   }
4102   virtual void val_str_from_ptr(String *val, const uchar *ptr) const;
4103 public:
4104   /*
4105     The maximum space available in a Field_varstring, in bytes. See
4106     length_bytes.
4107   */
4108   static const uint MAX_SIZE;
4109   /* Store number of bytes used to store length (1 or 2) */
4110   uint32 length_bytes;
Field_varstring(uchar * ptr_arg,uint32 len_arg,uint length_bytes_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,TABLE_SHARE * share,const DTCollation & collation)4111   Field_varstring(uchar *ptr_arg,
4112                   uint32 len_arg, uint length_bytes_arg,
4113                   uchar *null_ptr_arg, uchar null_bit_arg,
4114 		  enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
4115 		  TABLE_SHARE *share, const DTCollation &collation)
4116     :Field_longstr(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
4117                    unireg_check_arg, field_name_arg, collation),
4118      length_bytes(length_bytes_arg)
4119   {
4120     share->varchar_fields++;
4121   }
Field_varstring(uint32 len_arg,bool maybe_null_arg,const LEX_CSTRING * field_name_arg,TABLE_SHARE * share,const DTCollation & collation)4122   Field_varstring(uint32 len_arg,bool maybe_null_arg,
4123                   const LEX_CSTRING *field_name_arg,
4124                   TABLE_SHARE *share, const DTCollation &collation)
4125     :Field_longstr((uchar*) 0,len_arg, maybe_null_arg ? (uchar*) "": 0, 0,
4126                    NONE, field_name_arg, collation),
4127      length_bytes(len_arg < 256 ? 1 :2)
4128   {
4129     share->varchar_fields++;
4130   }
4131 
4132   const Type_handler *type_handler() const override;
tmp_engine_column_type(bool use_packed_rows)4133   en_fieldtype tmp_engine_column_type(bool use_packed_rows) const override
4134   {
4135     return FIELD_VARCHAR;
4136   }
4137   enum ha_base_keytype key_type() const override;
key_part_flag()4138   uint16 key_part_flag() const override { return HA_VAR_LENGTH_PART; }
key_part_length_bytes()4139   uint16 key_part_length_bytes() const override { return HA_KEY_BLOB_LENGTH; }
row_pack_length()4140   uint row_pack_length() const override { return field_length; }
zero_pack()4141   bool zero_pack() const override { return false; }
reset()4142   int  reset() override { bzero(ptr,field_length+length_bytes); return 0; }
pack_length()4143   uint32 pack_length() const override
4144   { return (uint32) field_length+length_bytes; }
key_length()4145   uint32 key_length() const override { return (uint32) field_length; }
sort_length()4146   uint32 sort_length() const override
4147   {
4148     return (uint32) field_length + sort_suffix_length();
4149   }
sort_suffix_length()4150   virtual uint32 sort_suffix_length() const override
4151   {
4152     return (field_charset() == &my_charset_bin ? length_bytes : 0);
4153   }
4154   Copy_func *get_copy_func(const Field *from) const override;
4155   bool memcpy_field_possible(const Field *from) const override;
update_data_type_statistics(Data_type_statistics * st)4156   void update_data_type_statistics(Data_type_statistics *st) const override
4157   {
4158     st->m_variable_string_count++;
4159     st->m_variable_string_total_length+= pack_length();
4160   }
4161   int  store(const char *to,size_t length,CHARSET_INFO *charset) override;
4162   using Field_str::store;
4163 #ifdef HAVE_MEM_CHECK
4164   void mark_unused_memory_as_defined() override;
4165 #endif
4166   double val_real() override;
4167   longlong val_int() override;
4168   String *val_str(String *, String *) override;
4169   my_decimal *val_decimal(my_decimal *) override;
4170   bool send(Protocol *protocol) override;
4171   int cmp(const uchar *a,const uchar *b) const override;
4172   int cmp_prefix(const uchar *a, const uchar *b, size_t prefix_len) const
4173     override;
4174   void sort_string(uchar *buff,uint length) override;
4175   uint get_key_image(uchar *buff, uint length,
4176                      const uchar *ptr_arg, imagetype type) const override;
4177   void set_key_image(const uchar *buff,uint length) override;
4178   void sql_type(String &str) const override;
4179   void sql_rpl_type(String*) const override;
4180   uchar *pack(uchar *to, const uchar *from, uint max_length) override;
4181   const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end,
4182                       uint param_data) override;
4183   int cmp_binary(const uchar *a,const uchar *b, uint32 max_length=~0U) const
4184     override;
4185   int key_cmp(const uchar *,const uchar*) const override;
4186   int key_cmp(const uchar *str, uint length) const override;
4187   uint packed_col_length(const uchar *to, uint length) override;
4188   uint max_packed_col_length(uint max_length) override;
4189   uint32 data_length() override;
size_of()4190   uint size_of() const override { return sizeof *this; }
has_charset()4191   bool has_charset() const override
4192   { return charset() == &my_charset_bin ? FALSE : TRUE; }
4193   Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type)
4194     override;
4195   Field *new_key_field(MEM_ROOT *root, TABLE *new_table,
4196                        uchar *new_ptr, uint32 length,
4197                        uchar *new_null_ptr, uint new_null_bit) override;
4198   bool is_equal(const Column_definition &new_field) const override;
can_be_converted_by_engine(const Column_definition & new_type)4199   bool can_be_converted_by_engine(const Column_definition &new_type) const
4200     override
4201   {
4202     return table->file->can_convert_varstring(this, new_type);
4203   }
4204   void hash(ulong *nr, ulong *nr2) override;
length_size()4205   uint length_size() const override { return length_bytes; }
4206   void print_key_value(String *out, uint32 length) override;
4207   Binlog_type_info binlog_type_info() const override;
4208 };
4209 
4210 
4211 class Field_varstring_compressed final :public Field_varstring {
4212 public:
Field_varstring_compressed(uchar * ptr_arg,uint32 len_arg,uint length_bytes_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,TABLE_SHARE * share,const DTCollation & collation,Compression_method * compression_method_arg)4213   Field_varstring_compressed(uchar *ptr_arg,
4214                              uint32 len_arg, uint length_bytes_arg,
4215                              uchar *null_ptr_arg, uchar null_bit_arg,
4216                              enum utype unireg_check_arg,
4217                              const LEX_CSTRING *field_name_arg,
4218                              TABLE_SHARE *share, const DTCollation &collation,
4219                              Compression_method *compression_method_arg):
4220     Field_varstring(ptr_arg, len_arg, length_bytes_arg, null_ptr_arg,
4221                     null_bit_arg, unireg_check_arg, field_name_arg,
4222                     share, collation),
4223     compression_method_ptr(compression_method_arg) { DBUG_ASSERT(len_arg > 0); }
compression_method()4224   Compression_method *compression_method() const override
4225   { return compression_method_ptr; }
4226 private:
4227   Compression_method *compression_method_ptr;
4228   void val_str_from_ptr(String *val, const uchar *ptr) const override;
4229   int store(const char *to, size_t length, CHARSET_INFO *charset) override;
4230   using Field_str::store;
4231   String *val_str(String *, String *) override;
4232   double val_real() override;
4233   longlong val_int() override;
size_of()4234   uint size_of() const override { return sizeof *this; }
4235   /*
4236     We use the default Field::send() implementation,
4237     because the derived optimized version (from Field_longstr)
4238     is not suitable for compressed fields.
4239   */
send(Protocol * protocol)4240   bool send(Protocol *protocol) override
4241   {
4242     return Field::send(protocol);
4243   }
binlog_type()4244   enum_field_types binlog_type() const override
4245   { return MYSQL_TYPE_VARCHAR_COMPRESSED; }
sql_type(String & str)4246   void sql_type(String &str) const override
4247   {
4248     Field_varstring::sql_type(str);
4249     str.append(STRING_WITH_LEN(" /*!100301 COMPRESSED*/"));
4250   }
max_display_length()4251   uint32 max_display_length() const override { return field_length - 1; }
character_octet_length()4252   uint32 character_octet_length() const override { return field_length - 1; }
char_length()4253   uint32 char_length() const override
4254   {
4255     return (field_length - 1) / mbmaxlen();
4256   }
4257   int cmp(const uchar *a_ptr, const uchar *b_ptr) const override;
4258 
4259   /*
4260     Compressed fields can't have keys as two rows may have different
4261     compression methods or compression levels.
4262   */
4263 
key_cmp(const uchar * str,uint length)4264   int key_cmp(const uchar *str, uint length) const override
4265   { DBUG_ASSERT(0); return 0; }
4266   using Field_varstring::key_cmp;
4267   Binlog_type_info binlog_type_info() const override;
4268 };
4269 
4270 
number_storage_requirement(uint32 n)4271 static inline uint8 number_storage_requirement(uint32 n)
4272 {
4273   return n < 256 ? 1 : n < 65536 ? 2 : n < 16777216 ? 3 : 4;
4274 }
4275 
4276 
store_bigendian(ulonglong num,uchar * to,uint bytes)4277 static inline void store_bigendian(ulonglong num, uchar *to, uint bytes)
4278 {
4279   switch(bytes) {
4280   case 1: mi_int1store(to, num); break;
4281   case 2: mi_int2store(to, num); break;
4282   case 3: mi_int3store(to, num); break;
4283   case 4: mi_int4store(to, num); break;
4284   case 5: mi_int5store(to, num); break;
4285   case 6: mi_int6store(to, num); break;
4286   case 7: mi_int7store(to, num); break;
4287   case 8: mi_int8store(to, num); break;
4288   default: DBUG_ASSERT(0);
4289   }
4290 }
4291 
4292 
read_bigendian(const uchar * from,uint bytes)4293 static inline longlong read_bigendian(const uchar *from, uint bytes)
4294 {
4295   switch(bytes) {
4296   case 1: return mi_uint1korr(from);
4297   case 2: return mi_uint2korr(from);
4298   case 3: return mi_uint3korr(from);
4299   case 4: return mi_uint4korr(from);
4300   case 5: return mi_uint5korr(from);
4301   case 6: return mi_uint6korr(from);
4302   case 7: return mi_uint7korr(from);
4303   case 8: return mi_sint8korr(from);
4304   default: DBUG_ASSERT(0); return 0;
4305   }
4306 }
4307 
store_lowendian(ulonglong num,uchar * to,uint bytes)4308 static inline void store_lowendian(ulonglong num, uchar *to, uint bytes)
4309 {
4310   switch(bytes) {
4311   case 1: *to= (uchar)num;    break;
4312   case 2: int2store(to, num); break;
4313   case 3: int3store(to, num); break;
4314   case 4: int4store(to, num); break;
4315   case 8: int8store(to, num); break;
4316   default: DBUG_ASSERT(0);
4317   }
4318 }
4319 
read_lowendian(const uchar * from,uint bytes)4320 static inline longlong read_lowendian(const uchar *from, uint bytes)
4321 {
4322   switch(bytes) {
4323   case 1: return from[0];
4324   case 2: return uint2korr(from);
4325   case 3: return uint3korr(from);
4326   case 4: return uint4korr(from);
4327   case 8: return sint8korr(from);
4328   default: DBUG_ASSERT(0); return 0;
4329   }
4330 }
4331 
4332 
4333 extern LEX_CSTRING temp_lex_str;
4334 
4335 class Field_blob :public Field_longstr {
4336 protected:
4337   /**
4338     The number of bytes used to represent the length of the blob.
4339   */
4340   uint packlength;
4341 
4342   /**
4343     The 'value'-object is a cache fronting the storage engine.
4344   */
4345   String value;
4346   /**
4347      Cache for blob values when reading a row with a virtual blob
4348      field. This is needed to not destroy the old cached value when
4349      updating the blob with a new value when creating the new row.
4350   */
4351   String read_value;
4352 
4353   static void do_copy_blob(Copy_field *copy);
4354   static void do_conv_blob(Copy_field *copy);
4355   uint get_key_image_itRAW(const uchar *ptr_arg, uchar *buff, uint length) const;
4356 public:
4357   Field_blob(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
4358 	     enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
4359 	     TABLE_SHARE *share, uint blob_pack_length,
4360 	     const DTCollation &collation);
Field_blob(uint32 len_arg,bool maybe_null_arg,const LEX_CSTRING * field_name_arg,const DTCollation & collation)4361   Field_blob(uint32 len_arg,bool maybe_null_arg, const LEX_CSTRING *field_name_arg,
4362              const DTCollation &collation)
4363     :Field_longstr((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0, 0,
4364                    NONE, field_name_arg, collation),
4365     packlength(4)
4366   {
4367     flags|= BLOB_FLAG;
4368   }
Field_blob(uint32 len_arg,bool maybe_null_arg,const LEX_CSTRING * field_name_arg,const DTCollation & collation,bool set_packlength)4369   Field_blob(uint32 len_arg,bool maybe_null_arg,
4370              const LEX_CSTRING *field_name_arg,
4371              const DTCollation &collation, bool set_packlength)
4372     :Field_longstr((uchar*) 0,len_arg, maybe_null_arg ? (uchar*) "": 0, 0,
4373                    NONE, field_name_arg, collation)
4374   {
4375     flags|= BLOB_FLAG;
4376     packlength= set_packlength ? number_storage_requirement(len_arg) : 4;
4377   }
Field_blob(uint32 packlength_arg)4378   Field_blob(uint32 packlength_arg)
4379     :Field_longstr((uchar*) 0, 0, (uchar*) "", 0, NONE, &temp_lex_str,
4380                    system_charset_info),
4381     packlength(packlength_arg) {}
4382   const Type_handler *type_handler() const override;
4383   /* Note that the default copy constructor is used, in clone() */
type()4384   enum_field_types type() const override
4385   {
4386     /*
4387       We cannot return type_handler()->field_type() here.
4388       Some pieces of the code (e.g. in engines) rely on the fact
4389       that Field::type(), Field::real_type() and Item_field::field_type()
4390       return MYSQL_TYPE_BLOB for all blob variants.
4391       We should eventually fix all such code pieces to expect
4392       all BLOB type codes.
4393     */
4394     return MYSQL_TYPE_BLOB;
4395   }
real_type()4396   enum_field_types real_type() const override
4397   {
4398     return MYSQL_TYPE_BLOB;
4399   }
key_type()4400   enum ha_base_keytype key_type() const override
4401     { return binary() ? HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2; }
key_part_flag()4402   uint16 key_part_flag() const override { return HA_BLOB_PART; }
key_part_length_bytes()4403   uint16 key_part_length_bytes() const override { return HA_KEY_BLOB_LENGTH; }
tmp_engine_column_type(bool use_packed_rows)4404   en_fieldtype tmp_engine_column_type(bool use_packed_rows) const override
4405   {
4406     return FIELD_BLOB;
4407   }
type_numeric_attributes()4408   Type_numeric_attributes type_numeric_attributes() const override
4409   {
4410     return Type_numeric_attributes(Field_blob::max_display_length(),
4411                                    decimals(), is_unsigned());
4412   }
4413   Information_schema_character_attributes
information_schema_character_attributes()4414     information_schema_character_attributes() const override
4415   {
4416     uint32 octets= Field_blob::character_octet_length();
4417     uint32 chars= octets / field_charset()->mbminlen;
4418     return Information_schema_character_attributes(octets, chars);
4419   }
update_data_type_statistics(Data_type_statistics * st)4420   void update_data_type_statistics(Data_type_statistics *st) const override
4421   {
4422     st->m_blob_count++;
4423   }
4424   void make_send_field(Send_field *) override;
get_copy_func(const Field * from)4425   Copy_func *get_copy_func(const Field *from) const override
4426   {
4427     /*
4428     TODO: MDEV-9331
4429     if (from->type() == MYSQL_TYPE_BIT)
4430       return do_field_int;
4431     */
4432     if (!(from->flags & BLOB_FLAG) || from->charset() != charset() ||
4433         !from->compression_method() != !compression_method())
4434       return do_conv_blob;
4435     if (from->pack_length() != Field_blob::pack_length())
4436       return do_copy_blob;
4437     return get_identical_copy_func();
4438   }
store_field(Field * from)4439   int  store_field(Field *from) override
4440   {                                             // Be sure the value is stored
4441     if (field_charset() == &my_charset_bin &&
4442         from->type_handler()->convert_to_binary_using_val_native())
4443     {
4444       NativeBuffer<64> tmp;
4445       from->val_native(&tmp);
4446       value.copy(tmp.ptr(), tmp.length(), &my_charset_bin);
4447       return store(value.ptr(), value.length(), &my_charset_bin);
4448     }
4449     from->val_str(&value);
4450     if (table->copy_blobs ||
4451         (!value.is_alloced() && from->is_varchar_and_in_write_set()))
4452       value.copy();
4453     return store(value.ptr(), value.length(), from->charset());
4454   }
memcpy_field_possible(const Field * from)4455   bool memcpy_field_possible(const Field *from) const override
4456   {
4457     return Field_str::memcpy_field_possible(from) &&
4458            !compression_method() == !from->compression_method() &&
4459            !table->copy_blobs;
4460   }
4461   bool make_empty_rec_store_default_value(THD *thd, Item *item) override;
4462   int store(const char *to, size_t length, CHARSET_INFO *charset) override;
4463   using Field_str::store;
4464   double val_real() override;
4465   longlong val_int() override;
4466   String *val_str(String *, String *) override;
4467   my_decimal *val_decimal(my_decimal *) override;
4468   int cmp(const uchar *a, const uchar *b) const override;
4469   int cmp_prefix(const uchar *a, const uchar *b, size_t prefix_len) const
4470     override;
4471   int cmp(const uchar *a, uint32 a_length, const uchar *b, uint32 b_length)
4472     const;
4473   int cmp_binary(const uchar *a,const uchar *b, uint32 max_length=~0U) const
4474      override;
4475   int key_cmp(const uchar *,const uchar*) const override;
4476   int key_cmp(const uchar *str, uint length) const override;
4477   /* Never update the value of min_val for a blob field */
update_min(Field * min_val,bool force_update)4478   bool update_min(Field *min_val, bool force_update) override { return false; }
4479   /* Never update the value of max_val for a blob field */
update_max(Field * max_val,bool force_update)4480   bool update_max(Field *max_val, bool force_update) override { return false; }
key_length()4481   uint32 key_length() const override { return 0; }
4482   void sort_string(uchar *buff,uint length) override;
pack_length()4483   uint32 pack_length() const override
4484   { return (uint32) (packlength + portable_sizeof_char_ptr); }
4485 
4486   /**
4487      Return the packed length without the pointer size added.
4488 
4489      This is used to determine the size of the actual data in the row
4490      buffer.
4491 
4492      @returns The length of the raw data itself without the pointer.
4493   */
pack_length_no_ptr()4494   uint32 pack_length_no_ptr() const
4495   { return (uint32) (packlength); }
row_pack_length()4496   uint row_pack_length() const override { return pack_length_no_ptr(); }
4497   uint32 sort_length() const override;
4498   uint32 sort_suffix_length() const override;
value_length()4499   uint32 value_length() override { return get_length(); }
max_data_length()4500   virtual uint32 max_data_length() const override
4501   {
4502     return (uint32) (((ulonglong) 1 << (packlength*8)) -1);
4503   }
reset()4504   int reset() override { bzero(ptr, packlength+sizeof(uchar*)); return 0; }
reset_fields()4505   void reset_fields() override
4506   {
4507     bzero((uchar*) &value, sizeof value);
4508     bzero((uchar*) &read_value, sizeof read_value);
4509   }
get_field_buffer_size()4510   uint32 get_field_buffer_size() { return value.alloced_length(); }
4511   void store_length(uchar *i_ptr, uint i_packlength, uint32 i_number);
store_length(size_t number)4512   void store_length(size_t number)
4513   {
4514     DBUG_ASSERT(number < UINT_MAX32);
4515     store_length(ptr, packlength, (uint32)number);
4516   }
4517   inline uint32 get_length(my_ptrdiff_t row_offset= 0) const
4518   { return get_length(ptr+row_offset, this->packlength); }
4519   uint32 get_length(const uchar *ptr, uint packlength) const;
get_length(const uchar * ptr_arg)4520   uint32 get_length(const uchar *ptr_arg) const
4521   { return get_length(ptr_arg, this->packlength); }
get_ptr()4522   inline uchar *get_ptr() const { return get_ptr(ptr); }
get_ptr(const uchar * ptr_arg)4523   inline uchar *get_ptr(const uchar *ptr_arg) const
4524   {
4525     uchar *s;
4526     memcpy(&s, ptr_arg + packlength, sizeof(uchar*));
4527     return s;
4528   }
set_ptr(uchar * length,uchar * data)4529   inline void set_ptr(uchar *length, uchar *data)
4530   {
4531     memcpy(ptr,length,packlength);
4532     memcpy(ptr+packlength, &data,sizeof(char*));
4533   }
set_ptr_offset(my_ptrdiff_t ptr_diff,uint32 length,const uchar * data)4534   void set_ptr_offset(my_ptrdiff_t ptr_diff, uint32 length, const uchar *data)
4535   {
4536     uchar *ptr_ofs= ADD_TO_PTR(ptr,ptr_diff,uchar*);
4537     store_length(ptr_ofs, packlength, length);
4538     memcpy(ptr_ofs+packlength, &data, sizeof(char*));
4539   }
set_ptr(uint32 length,uchar * data)4540   inline void set_ptr(uint32 length, uchar *data)
4541   {
4542     set_ptr_offset(0, length, data);
4543   }
4544   int copy_value(Field_blob *from);
get_key_image(uchar * buff,uint length,const uchar * ptr_arg,imagetype type)4545   uint get_key_image(uchar *buff, uint length,
4546                      const uchar *ptr_arg, imagetype type) const override
4547   {
4548     DBUG_ASSERT(type == itRAW);
4549     return get_key_image_itRAW(ptr_arg, buff, length);
4550   }
4551   void set_key_image(const uchar *buff,uint length) override;
4552   Field *new_key_field(MEM_ROOT *root, TABLE *new_table,
4553                        uchar *new_ptr, uint32 length,
4554                        uchar *new_null_ptr, uint new_null_bit) override;
4555   void sql_type(String &str) const override;
4556   /**
4557      Copy blob buffer into internal storage "value" and update record pointer.
4558 
4559      @retval true     Memory allocation error
4560      @retval false    Success
4561   */
copy()4562   bool copy()
4563   {
4564     uchar *tmp= get_ptr();
4565     if (value.copy((char*) tmp, get_length(), charset()))
4566     {
4567       Field_blob::reset();
4568       return 1;
4569     }
4570     tmp=(uchar*) value.ptr();
4571     memcpy(ptr+packlength, &tmp, sizeof(char*));
4572     return 0;
4573   }
swap(String & inout,bool set_read_value)4574   void swap(String &inout, bool set_read_value)
4575   {
4576     if (set_read_value)
4577       read_value.swap(inout);
4578     else
4579       value.swap(inout);
4580   }
4581   /**
4582      Return pointer to blob cache or NULL if not cached.
4583   */
cached(bool * set_read_value)4584   String * cached(bool *set_read_value)
4585   {
4586     char *tmp= (char *) get_ptr();
4587     if (!value.is_empty() && tmp == value.ptr())
4588     {
4589       *set_read_value= false;
4590       return &value;
4591     }
4592 
4593     if (!read_value.is_empty() && tmp == read_value.ptr())
4594     {
4595       *set_read_value= true;
4596       return &read_value;
4597     }
4598 
4599     return NULL;
4600   }
4601   /* store value for the duration of the current read record */
swap_value_and_read_value()4602   inline void swap_value_and_read_value()
4603   {
4604     read_value.swap(value);
4605   }
set_value(uchar * data)4606   inline void set_value(uchar *data)
4607   {
4608     /* Set value pointer. Lengths are not important */
4609     value.reset((char*) data, 1, 1, &my_charset_bin);
4610   }
4611   uchar *pack(uchar *to, const uchar *from, uint max_length) override;
4612   const uchar *unpack(uchar *to, const uchar *from, const uchar *from_end,
4613                       uint param_data) override;
4614   uint packed_col_length(const uchar *col_ptr, uint length) override;
4615   uint max_packed_col_length(uint max_length) override;
free()4616   void free() override
4617   {
4618     value.free();
4619     read_value.free();
4620   }
clear_temporary()4621   inline void clear_temporary()
4622   {
4623     uchar *tmp= get_ptr();
4624     if (likely(value.ptr() == (char*) tmp))
4625       bzero((uchar*) &value, sizeof(value));
4626     else
4627     {
4628       /*
4629         Currently read_value should never point to tmp, the following code
4630         is mainly here to make things future proof.
4631       */
4632       if (unlikely(read_value.ptr() == (char*) tmp))
4633         bzero((uchar*) &read_value, sizeof(read_value));
4634     }
4635   }
size_of()4636   uint size_of() const override { return sizeof *this; }
has_charset()4637   bool has_charset() const override { return charset() != &my_charset_bin; }
4638   uint32 max_display_length() const override;
4639   uint32 char_length() const override;
4640   uint32 character_octet_length() const override;
4641   bool is_equal(const Column_definition &new_field) const override;
can_be_converted_by_engine(const Column_definition & new_type)4642   bool can_be_converted_by_engine(const Column_definition &new_type) const
4643     override
4644   {
4645     return table->file->can_convert_blob(this, new_type);
4646   }
4647   void print_key_value(String *out, uint32 length) override;
4648   Binlog_type_info binlog_type_info() const override;
4649 
4650   friend void TABLE::remember_blob_values(String *blob_storage);
4651   friend void TABLE::restore_blob_values(String *blob_storage);
4652 };
4653 
4654 
4655 class Field_blob_compressed final :public Field_blob {
4656 public:
Field_blob_compressed(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,TABLE_SHARE * share,uint blob_pack_length,const DTCollation & collation,Compression_method * compression_method_arg)4657   Field_blob_compressed(uchar *ptr_arg, uchar *null_ptr_arg,
4658                         uchar null_bit_arg, enum utype unireg_check_arg,
4659                         const LEX_CSTRING *field_name_arg, TABLE_SHARE *share,
4660                         uint blob_pack_length, const DTCollation &collation,
4661                         Compression_method *compression_method_arg):
4662     Field_blob(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg,
4663                field_name_arg, share, blob_pack_length, collation),
4664     compression_method_ptr(compression_method_arg) {}
compression_method()4665   Compression_method *compression_method() const override
4666   { return compression_method_ptr; }
4667 private:
4668   Compression_method *compression_method_ptr;
4669   int store(const char *to, size_t length, CHARSET_INFO *charset) override;
4670   using Field_str::store;
4671   String *val_str(String *, String *) override;
4672   double val_real() override;
4673   longlong val_int() override;
4674   /*
4675     We use the default Field::send() implementation,
4676     because the derived optimized version (from Field_longstr)
4677     is not suitable for compressed fields.
4678   */
send(Protocol * protocol)4679   bool send(Protocol *protocol) override
4680   {
4681     return Field::send(protocol);
4682   }
size_of()4683   uint size_of() const override { return sizeof *this; }
binlog_type()4684   enum_field_types binlog_type() const override
4685   { return MYSQL_TYPE_BLOB_COMPRESSED; }
sql_type(String & str)4686   void sql_type(String &str) const override
4687   {
4688     Field_blob::sql_type(str);
4689     str.append(STRING_WITH_LEN(" /*!100301 COMPRESSED*/"));
4690   }
4691 
4692   /*
4693     Compressed fields can't have keys as two rows may have different
4694     compression methods or compression levels.
4695   */
4696 
get_key_image(uchar * buff,uint length,const uchar * ptr_arg,imagetype type_arg)4697   uint get_key_image(uchar *buff, uint length,
4698                      const uchar *ptr_arg, imagetype type_arg) const override
4699   { DBUG_ASSERT(0); return 0; }
set_key_image(const uchar *,uint)4700   void set_key_image(const uchar *, uint) override
4701   { DBUG_ASSERT(0); }
key_cmp(const uchar *,const uchar *)4702   int key_cmp(const uchar *, const uchar *) const override
4703   { DBUG_ASSERT(0); return 0; }
key_cmp(const uchar *,uint)4704   int key_cmp(const uchar *, uint) const override
4705   { DBUG_ASSERT(0); return 0; }
new_key_field(MEM_ROOT *,TABLE *,uchar *,uint32,uchar *,uint)4706   Field *new_key_field(MEM_ROOT *, TABLE *, uchar *, uint32, uchar *, uint)
4707     override
4708   { DBUG_ASSERT(0); return 0; }
4709   Binlog_type_info binlog_type_info() const override;
4710 };
4711 
4712 
4713 class Field_enum :public Field_str {
4714   static void do_field_enum(Copy_field *copy_field);
4715   longlong val_int(const uchar *) const;
4716   bool can_optimize_range_or_keypart_ref(const Item_bool_func *cond,
4717                                          const Item *item) const;
4718 protected:
4719   uint packlength;
4720 public:
4721   const TYPELIB *typelib;
Field_enum(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,uint packlength_arg,const TYPELIB * typelib_arg,const DTCollation & collation)4722   Field_enum(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
4723              uchar null_bit_arg,
4724              enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
4725              uint packlength_arg,
4726              const TYPELIB *typelib_arg,
4727              const DTCollation &collation)
4728     :Field_str(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
4729 	       unireg_check_arg, field_name_arg, collation),
4730     packlength(packlength_arg),typelib(typelib_arg)
4731   {
4732       flags|=ENUM_FLAG;
4733   }
4734   Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type)
4735     override;
type_handler()4736   const Type_handler *type_handler() const override
4737   { return &type_handler_enum; }
4738   enum ha_base_keytype key_type() const override;
4739   sql_mode_t can_handle_sql_mode_dependency_on_store() const override;
4740   enum_conv_type rpl_conv_type_from(const Conv_source &source,
4741                                     const Relay_log_info *rli,
4742                                     const Conv_param &param) const override;
get_copy_func(const Field * from)4743   Copy_func *get_copy_func(const Field *from) const override
4744   {
4745     if (eq_def(from))
4746       return get_identical_copy_func();
4747     if (real_type() == MYSQL_TYPE_ENUM &&
4748         from->real_type() == MYSQL_TYPE_ENUM)
4749       return do_field_enum;
4750     if (from->result_type() == STRING_RESULT)
4751       return do_field_string;
4752     return do_field_int;
4753   }
store_field(Field * from)4754   int store_field(Field *from) override
4755   {
4756     if (from->real_type() == MYSQL_TYPE_ENUM && from->val_int() == 0)
4757     {
4758       store_type(0);
4759       return 0;
4760     }
4761     return from->save_in_field(this);
4762   }
save_in_field(Field * to)4763   int save_in_field(Field *to) override
4764   {
4765     if (to->result_type() != STRING_RESULT)
4766       return to->store(val_int(), 0);
4767     return save_in_field_str(to);
4768   }
memcpy_field_possible(const Field * from)4769   bool memcpy_field_possible(const Field *from) const override
4770   { return false; }
make_empty_rec_reset(THD *)4771   void make_empty_rec_reset(THD *) override
4772   {
4773     if (flags & NOT_NULL_FLAG)
4774     {
4775       set_notnull();
4776       store((longlong) 1, true);
4777     }
4778     else
4779       reset();
4780   }
4781   int  store(const char *to,size_t length,CHARSET_INFO *charset) override;
4782   int  store(double nr) override;
4783   int  store(longlong nr, bool unsigned_val) override;
4784   double val_real() override;
4785   longlong val_int() override;
4786   String *val_str(String *, String *) override;
4787   int cmp(const uchar *,const uchar *) const override;
4788   void sort_string(uchar *buff,uint length) override;
pack_length()4789   uint32 pack_length() const override { return (uint32) packlength; }
4790   void store_type(ulonglong value);
4791   void sql_type(String &str) const override;
size_of()4792   uint size_of() const override { return sizeof *this; }
pack_length_from_metadata(uint field_metadata)4793   uint pack_length_from_metadata(uint field_metadata) const override
4794   { return (field_metadata & 0x00ff); }
row_pack_length()4795   uint row_pack_length() const override { return pack_length(); }
zero_pack()4796   bool zero_pack() const override { return false; }
optimize_range(uint,uint)4797   bool optimize_range(uint, uint) const override { return false; }
4798   bool eq_def(const Field *field) const override;
has_charset()4799   bool has_charset() const override { return true; }
4800   /* enum and set are sorted as integers */
sort_charset()4801   CHARSET_INFO *sort_charset() const override { return &my_charset_bin; }
decimals()4802   uint decimals() const override { return 0; }
get_typelib()4803   const TYPELIB *get_typelib() const override { return typelib; }
4804 
4805   uchar *pack(uchar *to, const uchar *from, uint max_length) override;
4806   const uchar *unpack(uchar *to, const uchar *from, const uchar *from_end,
4807                       uint param_data) override;
4808 
can_optimize_keypart_ref(const Item_bool_func * cond,const Item * item)4809   bool can_optimize_keypart_ref(const Item_bool_func *cond,
4810                                 const Item *item) const override
4811   {
4812     return can_optimize_range_or_keypart_ref(cond, item);
4813   }
can_optimize_group_min_max(const Item_bool_func * cond,const Item * const_item)4814   bool can_optimize_group_min_max(const Item_bool_func *cond,
4815                                   const Item *const_item) const override
4816   {
4817     /*
4818       Can't use GROUP_MIN_MAX optimization for ENUM and SET,
4819       because the values are stored as numbers in index,
4820       while MIN() and MAX() work as strings.
4821       It would return the records with min and max enum numeric indexes.
4822      "Bug#45300 MAX() and ENUM type" should be fixed first.
4823     */
4824     return false;
4825   }
can_optimize_range(const Item_bool_func * cond,const Item * item,bool is_eq_func)4826   bool can_optimize_range(const Item_bool_func *cond,
4827                           const Item *item,
4828                           bool is_eq_func) const override
4829   {
4830     return can_optimize_range_or_keypart_ref(cond, item);
4831   }
4832   Binlog_type_info binlog_type_info() const override;
4833 private:
4834   bool is_equal(const Column_definition &new_field) const override;
4835 };
4836 
4837 
4838 class Field_set final :public Field_enum {
4839 public:
Field_set(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const LEX_CSTRING * field_name_arg,uint32 packlength_arg,const TYPELIB * typelib_arg,const DTCollation & collation)4840   Field_set(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
4841 	    uchar null_bit_arg,
4842 	    enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg,
4843 	    uint32 packlength_arg,
4844 	    const TYPELIB *typelib_arg, const DTCollation &collation)
4845     :Field_enum(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
4846 		    unireg_check_arg, field_name_arg,
4847                 packlength_arg,
4848                 typelib_arg, collation),
4849       empty_set_string("", 0, collation.collation)
4850     {
4851       flags=(flags & ~ENUM_FLAG) | SET_FLAG;
4852     }
make_empty_rec_reset(THD * thd)4853   void make_empty_rec_reset(THD *thd) override
4854   {
4855     Field::make_empty_rec_reset(thd);
4856   }
4857 
store_field(Field * from)4858   int  store_field(Field *from) override { return from->save_in_field(this); }
4859   int  store(const char *to,size_t length,CHARSET_INFO *charset) override;
store(double nr)4860   int  store(double nr) override
4861   { return Field_set::store((longlong) nr, FALSE); }
4862   int  store(longlong nr, bool unsigned_val) override;
4863 
zero_pack()4864   bool zero_pack() const override { return true; }
4865   String *val_str(String *, String *) override;
4866   void sql_type(String &str) const override;
size_of()4867   uint size_of() const override { return sizeof *this; }
type_handler()4868   const Type_handler *type_handler() const override
4869   { return &type_handler_set; }
has_charset()4870   bool has_charset() const override { return true; }
4871   Binlog_type_info binlog_type_info() const override;
4872 private:
4873   const String empty_set_string;
4874 };
4875 
4876 
4877 /*
4878   Note:
4879     To use Field_bit::cmp_binary() you need to copy the bits stored in
4880     the beginning of the record (the NULL bytes) to each memory you
4881     want to compare (where the arguments point).
4882 
4883     This is the reason:
4884     - Field_bit::cmp_binary() is only implemented in the base class
4885       (Field::cmp_binary()).
4886     - Field::cmp_binary() currently uses pack_length() to calculate how
4887       long the data is.
4888     - pack_length() includes size of the bits stored in the NULL bytes
4889       of the record.
4890 */
4891 class Field_bit :public Field {
4892 public:
4893   uchar *bit_ptr;     // position in record where 'uneven' bits store
4894   uchar bit_ofs;      // offset to 'uneven' high bits
4895   uint bit_len;       // number of 'uneven' high bits
4896   uint bytes_in_rec;
4897   Field_bit(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
4898             uchar null_bit_arg, uchar *bit_ptr_arg, uchar bit_ofs_arg,
4899             enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg);
type_handler()4900   const Type_handler *type_handler() const override
4901   { return &type_handler_bit; }
key_type()4902   enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BIT; }
key_part_flag()4903   uint16 key_part_flag() const override { return HA_BIT_PART; }
key_length()4904   uint32 key_length() const override
4905   { return (uint32) (field_length + 7) / 8; }
max_data_length()4906   uint32 max_data_length() const override { return key_length(); }
max_display_length()4907   uint32 max_display_length() const override { return field_length; }
4908   enum_conv_type rpl_conv_type_from(const Conv_source &source,
4909                                     const Relay_log_info *rli,
4910                                     const Conv_param &param) const override;
charset()4911   CHARSET_INFO *charset() const override { return &my_charset_bin; }
4912   const DTCollation & dtcollation() const override;
4913   Information_schema_numeric_attributes
information_schema_numeric_attributes()4914     information_schema_numeric_attributes() const override
4915   {
4916     return Information_schema_numeric_attributes(field_length);
4917   }
update_data_type_statistics(Data_type_statistics * st)4918   void update_data_type_statistics(Data_type_statistics *st) const override
4919   {
4920     st->m_uneven_bit_length+= field_length & 7;
4921   }
size_of()4922   uint size_of() const override { return sizeof *this; }
reset()4923   int reset() override
4924   {
4925     bzero(ptr, bytes_in_rec);
4926     if (bit_ptr && (bit_len > 0))  // reset odd bits among null bits
4927       clr_rec_bits(bit_ptr, bit_ofs, bit_len);
4928     return 0;
4929   }
get_copy_func(const Field * from)4930   Copy_func *get_copy_func(const Field *from) const override
4931   {
4932     if (from->cmp_type() == DECIMAL_RESULT)
4933       return do_field_decimal;
4934     return do_field_int;
4935   }
save_in_field(Field * to)4936   int save_in_field(Field *to) override { return to->store(val_int(), true); }
memcpy_field_possible(const Field * from)4937   bool memcpy_field_possible(const Field *from) const override{ return false; }
4938   int store(const char *to, size_t length, CHARSET_INFO *charset) override;
4939   int store(double nr) override;
4940   int store(longlong nr, bool unsigned_val) override;
4941   int store_decimal(const my_decimal *) override;
4942   double val_real() override;
4943   longlong val_int() override;
4944   String *val_str(String*, String *) override;
str_needs_quotes()4945   bool str_needs_quotes() const override { return true; }
4946   my_decimal *val_decimal(my_decimal *) override;
val_bool()4947   bool val_bool() override { return val_int() != 0; }
cmp(const uchar * a,const uchar * b)4948   int cmp(const uchar *a, const uchar *b) const override
4949   {
4950     DBUG_ASSERT(ptr == a || ptr == b);
4951     if (ptr == a)
4952       return Field_bit::key_cmp(b, bytes_in_rec + MY_TEST(bit_len));
4953     else
4954       return Field_bit::key_cmp(a, bytes_in_rec + MY_TEST(bit_len)) * -1;
4955   }
cmp_binary_offset(uint row_offset)4956   int cmp_binary_offset(uint row_offset) override
4957   { return cmp_offset(row_offset); }
4958   int cmp_prefix(const uchar *a, const uchar *b,
4959                  size_t  max_length) const override;
key_cmp(const uchar * a,const uchar * b)4960   int key_cmp(const uchar *a, const uchar *b) const override
4961   { return cmp_binary((uchar *) a, (uchar *) b); }
4962   int key_cmp(const uchar *str, uint length) const override;
4963   int cmp_offset(my_ptrdiff_t row_offset) override;
update_min(Field * min_val,bool force_update)4964   bool update_min(Field *min_val, bool force_update) override
4965   {
4966     longlong val= val_int();
4967     bool update_fl= force_update || val < min_val->val_int();
4968     if (update_fl)
4969     {
4970       min_val->set_notnull();
4971       min_val->store(val, FALSE);
4972     }
4973     return update_fl;
4974   }
update_max(Field * max_val,bool force_update)4975   bool update_max(Field *max_val, bool force_update) override
4976   {
4977     longlong val= val_int();
4978     bool update_fl= force_update || val > max_val->val_int();
4979     if (update_fl)
4980     {
4981       max_val->set_notnull();
4982       max_val->store(val, FALSE);
4983     }
4984     return update_fl;
4985   }
store_field_value(uchar * val,uint)4986   void store_field_value(uchar *val, uint) override
4987   {
4988     store(*((longlong *)val), TRUE);
4989   }
pos_in_interval(Field * min,Field * max)4990   double pos_in_interval(Field *min, Field *max) override
4991   {
4992     return pos_in_interval_val_real(min, max);
4993   }
get_image(uchar * buff,uint length,const uchar * ptr_arg,CHARSET_INFO * cs)4994   void get_image(uchar *buff, uint length,
4995                  const uchar *ptr_arg, CHARSET_INFO *cs) const override
4996   { get_key_image(buff, length, ptr_arg, itRAW); }
set_image(const uchar * buff,uint length,CHARSET_INFO * cs)4997   void set_image(const uchar *buff,uint length, CHARSET_INFO *cs) override
4998   { Field_bit::store((char *) buff, length, cs); }
4999   uint get_key_image(uchar *buff, uint length,
5000                      const uchar *ptr_arg, imagetype type) const override;
set_key_image(const uchar * buff,uint length)5001   void set_key_image(const uchar *buff, uint length) override
5002   { Field_bit::store((char*) buff, length, &my_charset_bin); }
sort_string(uchar * buff,uint length)5003   void sort_string(uchar *buff, uint length) override
5004   { get_key_image(buff, length, ptr, itRAW); }
pack_length()5005   uint32 pack_length() const override
5006   { return (uint32) (field_length + 7) / 8; }
pack_length_in_rec()5007   uint32 pack_length_in_rec() const override { return bytes_in_rec; }
5008   uint pack_length_from_metadata(uint field_metadata) const override;
row_pack_length()5009   uint row_pack_length() const override
5010   { return (bytes_in_rec + ((bit_len > 0) ? 1 : 0)); }
5011   bool compatible_field_size(uint metadata, const Relay_log_info *rli,
5012                              uint16 mflags, int *order_var) const override;
5013   void sql_type(String &str) const override;
5014   uchar *pack(uchar *to, const uchar *from, uint max_length) override;
5015   const uchar *unpack(uchar *to, const uchar *from,
5016                       const uchar *from_end, uint param_data) override;
5017   int set_default() override;
5018 
5019   Field *new_key_field(MEM_ROOT *root, TABLE *new_table,
5020                        uchar *new_ptr, uint32 length,
5021                        uchar *new_null_ptr, uint new_null_bit) override;
set_bit_ptr(uchar * bit_ptr_arg,uchar bit_ofs_arg)5022   void set_bit_ptr(uchar *bit_ptr_arg, uchar bit_ofs_arg)
5023   {
5024     bit_ptr= bit_ptr_arg;
5025     bit_ofs= bit_ofs_arg;
5026   }
eq(Field * field)5027   bool eq(Field *field) override
5028   {
5029     return (Field::eq(field) &&
5030             bit_ptr == ((Field_bit *)field)->bit_ptr &&
5031             bit_ofs == ((Field_bit *)field)->bit_ofs);
5032   }
5033   bool is_equal(const Column_definition &new_field) const override;
move_field_offset(my_ptrdiff_t ptr_diff)5034   void move_field_offset(my_ptrdiff_t ptr_diff) override
5035   {
5036     Field::move_field_offset(ptr_diff);
5037 
5038     /*
5039       clang does not like when things are added to a null pointer, even if
5040       it is never referenced.
5041     */
5042     if (bit_ptr)
5043       bit_ptr= ADD_TO_PTR(bit_ptr, ptr_diff, uchar*);
5044   }
5045   void hash(ulong *nr, ulong *nr2) override;
5046 
get_mm_leaf(RANGE_OPT_PARAM * param,KEY_PART * key_part,const Item_bool_func * cond,scalar_comparison_op op,Item * value)5047   SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part,
5048                        const Item_bool_func *cond,
5049                        scalar_comparison_op op, Item *value) override
5050   {
5051     return get_mm_leaf_int(param, key_part, cond, op, value, true);
5052   }
print_key_value(String * out,uint32 length)5053   void print_key_value(String *out, uint32 length) override
5054   {
5055     val_int_as_str(out, 1);
5056   }
5057   /**
5058      Save the field metadata for bit fields.
5059      Saves the bit length in the first byte and bytes in record in the
5060      second byte of the field metadata array at index of *metadata_ptr and
5061      *(metadata_ptr + 1).
5062 
5063      @param   metadata_ptr   First byte of field metadata
5064 
5065      @returns number of bytes written to metadata_ptr
5066   */
binlog_type_info()5067   Binlog_type_info binlog_type_info() const override
5068   {
5069     DBUG_PRINT("debug", ("bit_len: %d, bytes_in_rec: %d",
5070                        bit_len, bytes_in_rec));
5071     /*
5072       Since this class and Field_bit_as_char have different ideas of
5073       what should be stored here, we compute the values of the metadata
5074       explicitly using the field_length.
5075     */
5076     return Binlog_type_info(type(),
5077                             static_cast<uint16>((field_length & 7) |
5078                                                 ((field_length / 8) << 8)), 2);
5079   }
5080 
5081 private:
5082   size_t do_last_null_byte() const override;
5083 };
5084 
5085 
5086 /**
5087   BIT field represented as chars for non-MyISAM tables.
5088 
5089   @todo The inheritance relationship is backwards since Field_bit is
5090   an extended version of Field_bit_as_char and not the other way
5091   around. Hence, we should refactor it to fix the hierarchy order.
5092  */
5093 class Field_bit_as_char final :public Field_bit {
5094 public:
5095   Field_bit_as_char(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
5096                     uchar null_bit_arg,
5097                     enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg);
key_type()5098   enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BINARY; }
size_of()5099   uint size_of() const override { return sizeof *this; }
5100   int store(const char *to, size_t length, CHARSET_INFO *charset) override;
store(double nr)5101   int store(double nr) override { return Field_bit::store(nr); }
store(longlong nr,bool unsigned_val)5102   int store(longlong nr, bool unsigned_val) override
5103   { return Field_bit::store(nr, unsigned_val); }
5104   void sql_type(String &str) const override;
5105 };
5106 
5107 
5108 class Field_row final :public Field_null
5109 {
5110   class Virtual_tmp_table *m_table;
5111 public:
Field_row(uchar * ptr_arg,const LEX_CSTRING * field_name_arg)5112   Field_row(uchar *ptr_arg, const LEX_CSTRING *field_name_arg)
5113     :Field_null(ptr_arg, 0, Field::NONE, field_name_arg, &my_charset_bin),
5114      m_table(NULL)
5115     {}
5116   ~Field_row();
tmp_engine_column_type(bool use_packed_rows)5117   en_fieldtype tmp_engine_column_type(bool use_packed_rows) const
5118   {
5119     DBUG_ASSERT(0);
5120     return Field::tmp_engine_column_type(use_packed_rows);
5121   }
rpl_conv_type_from(const Conv_source & source,const Relay_log_info * rli,const Conv_param & param)5122   enum_conv_type rpl_conv_type_from(const Conv_source &source,
5123                                     const Relay_log_info *rli,
5124                                     const Conv_param &param) const
5125   {
5126     DBUG_ASSERT(0);
5127     return CONV_TYPE_IMPOSSIBLE;
5128   }
virtual_tmp_table_addr()5129   Virtual_tmp_table **virtual_tmp_table_addr() { return &m_table; }
5130   bool sp_prepare_and_store_item(THD *thd, Item **value);
5131 };
5132 
5133 
5134 extern const LEX_CSTRING null_clex_str;
5135 
5136 class Column_definition_attributes
5137 {
5138 public:
5139   /*
5140     At various stages in execution this can be length of field in bytes or
5141     max number of characters.
5142   */
5143   ulonglong length;
5144   uint decimals;
5145   Field::utype unireg_check;
5146   const TYPELIB *interval;            // Which interval to use
5147   CHARSET_INFO *charset;
5148   uint32 srid;
5149   uint pack_flag;
Column_definition_attributes()5150   Column_definition_attributes()
5151    :length(0),
5152     decimals(0),
5153     unireg_check(Field::NONE),
5154     interval(NULL),
5155     charset(&my_charset_bin),
5156     srid(0),
5157     pack_flag(0)
5158   { }
5159   Column_definition_attributes(const Field *field);
5160   Column_definition_attributes(const Type_all_attributes &attr);
5161   Field *make_field(TABLE_SHARE *share, MEM_ROOT *mem_root,
5162                     const Record_addr *rec,
5163                     const Type_handler *handler,
5164                     const LEX_CSTRING *field_name,
5165                     uint32 flags) const;
temporal_dec(uint intlen)5166   uint temporal_dec(uint intlen) const
5167   {
5168     return (uint) (length > intlen ? length - intlen - 1 : 0);
5169   }
5170   uint pack_flag_to_pack_length() const;
5171   void frm_pack_basic(uchar *buff) const;
5172   void frm_pack_charset(uchar *buff) const;
5173   void frm_pack_numeric_with_dec(uchar *buff) const;
5174   void frm_unpack_basic(const uchar *buff);
5175   bool frm_unpack_charset(TABLE_SHARE *share, const uchar *buff);
5176   bool frm_unpack_numeric_with_dec(TABLE_SHARE *share, const uchar *buff);
5177   bool frm_unpack_temporal_with_dec(TABLE_SHARE *share, uint intlen,
5178                                     const uchar *buff);
5179   void set_length_and_dec(const Lex_length_and_dec_st &attr);
explicit_or_derived_charset(const Column_derived_attributes * derived_attr)5180   CHARSET_INFO *explicit_or_derived_charset(const Column_derived_attributes
5181                                                   *derived_attr) const
5182   {
5183     return charset ? charset : derived_attr->charset();
5184   }
5185 };
5186 
5187 
5188 /*
5189   Create field class for CREATE TABLE
5190 */
5191 class Column_definition: public Sql_alloc,
5192                          public Type_handler_hybrid_field_type,
5193                          public Column_definition_attributes
5194 {
5195   /**
5196     Create "interval" from "interval_list".
5197     @param mem_root                   - memory root to create the TYPELIB
5198                                         instance and its values on
5199     @param reuse_interval_list_values - determines if TYPELIB can reuse strings
5200                                         from interval_list, or should always
5201                                         allocate a copy on mem_root, even if
5202                                         character set conversion is not needed
5203     @retval false on success
5204     @retval true  on error (bad values, or EOM)
5205   */
5206   bool create_interval_from_interval_list(MEM_ROOT *mem_root,
5207                                           bool reuse_interval_list_values);
5208 
5209   /*
5210     Calculate TYPELIB (set or enum) max and total lengths
5211 
5212     @param  cs            charset+collation pair of the interval
5213     @param  max_length    length of the longest item
5214     @param  tot_length    sum of the item lengths
5215 
5216     After this method call:
5217     - ENUM uses max_length
5218     - SET uses tot_length.
5219   */
calculate_interval_lengths(uint32 * max_length,uint32 * tot_length)5220   void calculate_interval_lengths(uint32 *max_length, uint32 *tot_length)
5221   {
5222     const char **pos;
5223     uint *len;
5224     *max_length= *tot_length= 0;
5225     for (pos= interval->type_names, len= interval->type_lengths;
5226          *pos ; pos++, len++)
5227     {
5228       size_t length= charset->numchars(*pos, *pos + *len);
5229       DBUG_ASSERT(length < UINT_MAX32);
5230       *tot_length+= (uint) length;
5231       set_if_bigger(*max_length, (uint32)length);
5232     }
5233   }
5234   bool prepare_stage1_check_typelib_default();
5235   bool prepare_stage1_convert_default(THD *, MEM_ROOT *, CHARSET_INFO *to);
5236   const Type_handler *field_type() const; // Prevent using this
5237   Compression_method *compression_method_ptr;
5238 public:
5239   LEX_CSTRING field_name;
5240   LEX_CSTRING comment;			// Comment for field
5241   enum enum_column_versioning
5242   {
5243     VERSIONING_NOT_SET,
5244     WITH_VERSIONING,
5245     WITHOUT_VERSIONING
5246   };
5247   Item *on_update;		        // ON UPDATE NOW()
5248   field_visibility_t invisible;
5249   /*
5250     The value of `length' as set by parser: is the number of characters
5251     for most of the types, or of bytes for BLOBs or numeric types.
5252   */
5253   uint32 char_length;
5254   uint  flags, pack_length;
5255   List<String> interval_list;
5256   engine_option_value *option_list;
5257 
5258 
5259   /*
5260     This is additinal data provided for any computed(virtual) field.
5261     In particular it includes a pointer to the item by  which this field
5262     can be computed from other fields.
5263   */
5264   Virtual_column_info
5265     *vcol_info,                      // Virtual field
5266     *default_value,                  // Default value
5267     *check_constraint;               // Check constraint
5268 
5269   enum_column_versioning versioning;
5270 
5271   Table_period_info *period;
5272 
Column_definition()5273   Column_definition()
5274    :Type_handler_hybrid_field_type(&type_handler_null),
5275     compression_method_ptr(0),
5276     comment(null_clex_str),
5277     on_update(NULL), invisible(VISIBLE), char_length(0),
5278     flags(0), pack_length(0),
5279     option_list(NULL),
5280     vcol_info(0), default_value(0), check_constraint(0),
5281     versioning(VERSIONING_NOT_SET), period(NULL)
5282   {
5283     interval_list.empty();
5284   }
5285 
5286   Column_definition(THD *thd, Field *field, Field *orig_field);
5287   bool set_attributes(THD *thd,
5288                       const Lex_field_type_st &attr,
5289                       CHARSET_INFO *cs,
5290                       column_definition_type_t type);
create_length_to_internal_length_null()5291   void create_length_to_internal_length_null()
5292   {
5293     DBUG_ASSERT(length == 0);
5294     pack_length= 0;
5295   }
create_length_to_internal_length_simple()5296   void create_length_to_internal_length_simple()
5297   {
5298     pack_length= type_handler()->calc_pack_length((uint32) length);
5299   }
create_length_to_internal_length_string()5300   void create_length_to_internal_length_string()
5301   {
5302     length*= charset->mbmaxlen;
5303     if (real_field_type() == MYSQL_TYPE_VARCHAR && compression_method())
5304       length++;
5305     set_if_smaller(length, UINT_MAX32);
5306     pack_length= type_handler()->calc_pack_length((uint32) length);
5307   }
create_length_to_internal_length_typelib()5308   void create_length_to_internal_length_typelib()
5309   {
5310     /* Pack_length already calculated in sql_parse.cc */
5311     length*= charset->mbmaxlen;
5312   }
vers_sys_field()5313   bool vers_sys_field() const
5314   {
5315     return flags & (VERS_ROW_START | VERS_ROW_END);
5316   }
5317   void create_length_to_internal_length_bit();
5318   void create_length_to_internal_length_newdecimal();
5319 
5320   /*
5321     Prepare the "charset" member for string data types,
5322     such as CHAR, VARCHAR, TEXT, ENUM, SET:
5323     - derive the charset if not specified explicitly
5324     - find a _bin collation if the BINARY comparison style was specified, e.g.:
5325        CREATE TABLE t1 (a VARCHAR(10) BINARY) CHARSET utf8;
5326   */
5327   bool prepare_charset_for_string(const Column_derived_attributes *dattr);
5328 
5329   /**
5330     Prepare a SET/ENUM field.
5331     Create "interval" from "interval_list" if needed, and adjust "length".
5332     @param mem_root                   - Memory root to allocate TYPELIB and
5333                                         its values on
5334     @param reuse_interval_list_values - determines if TYPELIB can reuse value
5335                                         buffers from interval_list, or should
5336                                         always allocate a copy on mem_root,
5337                                         even if character set conversion
5338                                         is not needed
5339   */
5340   bool prepare_interval_field(MEM_ROOT *mem_root,
5341                               bool reuse_interval_list_values);
5342 
prepare_interval_field_calc_length()5343   void prepare_interval_field_calc_length()
5344   {
5345     uint32 field_length, dummy;
5346     if (real_field_type() == MYSQL_TYPE_SET)
5347     {
5348       calculate_interval_lengths(&dummy, &field_length);
5349       length= field_length + (interval->count - 1);
5350     }
5351     else /* MYSQL_TYPE_ENUM */
5352     {
5353       calculate_interval_lengths(&field_length, &dummy);
5354       length= field_length;
5355     }
5356     set_if_smaller(length, MAX_FIELD_WIDTH - 1);
5357   }
5358 
5359   bool prepare_blob_field(THD *thd);
5360 
5361   bool sp_prepare_create_field(THD *thd, MEM_ROOT *mem_root);
5362 
5363   bool prepare_stage1(THD *thd, MEM_ROOT *mem_root,
5364                       handler *file, ulonglong table_flags,
5365                       const Column_derived_attributes *derived_attr);
prepare_stage1_simple(CHARSET_INFO * cs)5366   void prepare_stage1_simple(CHARSET_INFO *cs)
5367   {
5368     charset= cs;
5369     create_length_to_internal_length_simple();
5370   }
5371   bool prepare_stage1_typelib(THD *thd, MEM_ROOT *mem_root,
5372                               handler *file, ulonglong table_flags);
5373   bool prepare_stage1_string(THD *thd, MEM_ROOT *mem_root,
5374                              handler *file, ulonglong table_flags);
5375   bool prepare_stage1_bit(THD *thd, MEM_ROOT *mem_root,
5376                           handler *file, ulonglong table_flags);
5377 
bulk_alter(const Column_derived_attributes * derived_attr,const Column_bulk_alter_attributes * bulk_attr)5378   bool bulk_alter(const Column_derived_attributes *derived_attr,
5379                   const Column_bulk_alter_attributes *bulk_attr)
5380   {
5381     return type_handler()->Column_definition_bulk_alter(this,
5382                                                         derived_attr,
5383                                                         bulk_attr);
5384   }
5385   void redefine_stage1_common(const Column_definition *dup_field,
5386                               const handler *file);
redefine_stage1(const Column_definition * dup_field,const handler * file)5387   bool redefine_stage1(const Column_definition *dup_field, const handler *file)
5388   {
5389     const Type_handler *handler= dup_field->type_handler();
5390     return handler->Column_definition_redefine_stage1(this, dup_field, file);
5391   }
5392   bool prepare_stage2(handler *handler, ulonglong table_flags);
5393   bool prepare_stage2_blob(handler *handler,
5394                            ulonglong table_flags, uint field_flags);
5395   bool prepare_stage2_varchar(ulonglong table_flags);
5396   bool prepare_stage2_typelib(const char *type_name, uint field_flags,
5397                               uint *dup_val_count);
5398   uint pack_flag_numeric() const;
sign_length()5399   uint sign_length() const { return flags & UNSIGNED_FLAG ? 0 : 1; }
5400   bool check_length(uint mysql_errno, uint max_allowed_length) const;
5401   bool fix_attributes_real(uint default_length);
5402   bool fix_attributes_int(uint default_length);
5403   bool fix_attributes_decimal();
5404   bool fix_attributes_temporal_with_time(uint int_part_length);
5405   bool fix_attributes_bit();
5406 
5407   bool check(THD *thd);
5408   bool validate_check_constraint(THD *thd);
5409 
stored_in_db()5410   bool stored_in_db() const { return !vcol_info || vcol_info->stored_in_db; }
5411 
field_storage_type()5412   ha_storage_media field_storage_type() const
5413   {
5414     return (ha_storage_media)
5415       ((flags >> FIELD_FLAGS_STORAGE_MEDIA) & 3);
5416   }
5417 
column_format()5418   column_format_type column_format() const
5419   {
5420     return (column_format_type)
5421       ((flags >> FIELD_FLAGS_COLUMN_FORMAT) & 3);
5422   }
5423 
has_default_function()5424   bool has_default_function() const
5425   {
5426     return unireg_check != Field::NONE;
5427   }
5428 
make_field(TABLE_SHARE * share,MEM_ROOT * mem_root,const Record_addr * addr,const LEX_CSTRING * field_name_arg)5429   Field *make_field(TABLE_SHARE *share, MEM_ROOT *mem_root,
5430                     const Record_addr *addr,
5431                     const LEX_CSTRING *field_name_arg) const
5432   {
5433     return Column_definition_attributes::make_field(share, mem_root, addr,
5434                                                     type_handler(),
5435                                                     field_name_arg, flags);
5436   }
make_field(TABLE_SHARE * share,MEM_ROOT * mem_root,const LEX_CSTRING * field_name_arg)5437   Field *make_field(TABLE_SHARE *share, MEM_ROOT *mem_root,
5438                     const LEX_CSTRING *field_name_arg) const
5439   {
5440     Record_addr addr(true);
5441     return make_field(share, mem_root, &addr, field_name_arg);
5442   }
5443   /* Return true if default is an expression that must be saved explicitely */
5444   bool has_default_expression();
5445 
has_default_now_unireg_check()5446   bool has_default_now_unireg_check() const
5447   {
5448     return unireg_check == Field::TIMESTAMP_DN_FIELD
5449         || unireg_check == Field::TIMESTAMP_DNUN_FIELD;
5450   }
5451 
set_type(const Column_definition & other)5452   void set_type(const Column_definition &other)
5453   {
5454     set_handler(other.type_handler());
5455     length= other.length;
5456     char_length= other.char_length;
5457     decimals= other.decimals;
5458     flags= other.flags;
5459     pack_length= other.pack_length;
5460     unireg_check= other.unireg_check;
5461     interval= other.interval;
5462     charset= other.charset;
5463     srid= other.srid;
5464     pack_flag= other.pack_flag;
5465   }
5466 
5467   // Replace the entire value by another definition
set_column_definition(const Column_definition * def)5468   void set_column_definition(const Column_definition *def)
5469   {
5470     *this= *def;
5471   }
5472   bool set_compressed(const char *method);
5473   bool set_compressed_deprecated(THD *thd, const char *method);
5474   bool set_compressed_deprecated_column_attribute(THD *thd,
5475                                                   const char *pos,
5476                                                   const char *method);
set_compression_method(Compression_method * compression_method_arg)5477   void set_compression_method(Compression_method *compression_method_arg)
5478   { compression_method_ptr= compression_method_arg; }
compression_method()5479   Compression_method *compression_method() const
5480   { return compression_method_ptr; }
5481 
5482   bool check_vcol_for_key(THD *thd) const;
5483 };
5484 
5485 
5486 /**
5487   List of ROW element definitions, e.g.:
5488     DECLARE a ROW(a INT,b VARCHAR(10))
5489 */
5490 class Row_definition_list: public List<class Spvar_definition>
5491 {
5492 public:
5493   inline bool eq_name(const Spvar_definition *def, const LEX_CSTRING *name) const;
5494   /**
5495     Find a ROW field by name.
5496     @param [IN]  name   - the name
5497     @param [OUT] offset - if the ROW field found, its offset it returned here
5498     @retval NULL        - the ROW field was not found
5499     @retval !NULL       - the pointer to the found ROW field
5500   */
find_row_field_by_name(const LEX_CSTRING * name,uint * offset)5501   Spvar_definition *find_row_field_by_name(const LEX_CSTRING *name, uint *offset) const
5502   {
5503     // Cast-off the "const" qualifier
5504     List_iterator<Spvar_definition> it(*((List<Spvar_definition>*)this));
5505     Spvar_definition *def;
5506     for (*offset= 0; (def= it++); (*offset)++)
5507     {
5508       if (eq_name(def, name))
5509         return def;
5510     }
5511     return 0;
5512   }
make(MEM_ROOT * mem_root,Spvar_definition * var)5513   static Row_definition_list *make(MEM_ROOT *mem_root, Spvar_definition *var)
5514   {
5515     Row_definition_list *list;
5516     if (!(list= new (mem_root) Row_definition_list()))
5517       return NULL;
5518     return list->push_back(var, mem_root) ? NULL : list;
5519   }
5520   bool append_uniq(MEM_ROOT *thd, Spvar_definition *var);
5521   bool adjust_formal_params_to_actual_params(THD *thd, List<Item> *args);
5522   bool adjust_formal_params_to_actual_params(THD *thd,
5523                                              Item **args, uint arg_count);
5524   bool resolve_type_refs(THD *);
5525 };
5526 
5527 /**
5528   This class is used during a stored routine or a trigger execution,
5529   at sp_rcontext::create() time.
5530   Currently it can represent:
5531   - variables with explicit data types:   DECLARE a INT;
5532   - variables with data type references:  DECLARE a t1.a%TYPE;
5533   - ROW type variables
5534 
5535   Notes:
5536   - Scalar variables have m_field_definitions==NULL.
5537   - ROW variables are defined as having MYSQL_TYPE_NULL,
5538     with a non-empty m_field_definitions.
5539 
5540   Data type references to other object types will be added soon, e.g.:
5541   - DECLARE a table_name%ROWTYPE;
5542   - DECLARE a cursor_name%ROWTYPE;
5543   - DECLARE a record_name%TYPE;
5544   - DECLARE a variable_name%TYPE;
5545 */
5546 class Spvar_definition: public Column_definition
5547 {
5548   Qualified_column_ident *m_column_type_ref; // for %TYPE
5549   Table_ident *m_table_rowtype_ref;          // for table%ROWTYPE
5550   bool m_cursor_rowtype_ref;                       // for cursor%ROWTYPE
5551   uint m_cursor_rowtype_offset;                    // for cursor%ROWTYPE
5552   Row_definition_list *m_row_field_definitions;    // for ROW
5553 public:
Spvar_definition()5554   Spvar_definition()
5555    :m_column_type_ref(NULL),
5556     m_table_rowtype_ref(NULL),
5557     m_cursor_rowtype_ref(false),
5558     m_cursor_rowtype_offset(0),
5559     m_row_field_definitions(NULL)
5560   { }
Spvar_definition(THD * thd,Field * field)5561   Spvar_definition(THD *thd, Field *field)
5562    :Column_definition(thd, field, NULL),
5563     m_column_type_ref(NULL),
5564     m_table_rowtype_ref(NULL),
5565     m_cursor_rowtype_ref(false),
5566     m_cursor_rowtype_offset(0),
5567     m_row_field_definitions(NULL)
5568   { }
type_handler()5569   const Type_handler *type_handler() const
5570   {
5571     return Type_handler_hybrid_field_type::type_handler();
5572   }
is_column_type_ref()5573   bool is_column_type_ref() const { return m_column_type_ref != 0; }
is_table_rowtype_ref()5574   bool is_table_rowtype_ref() const { return m_table_rowtype_ref != 0; }
is_cursor_rowtype_ref()5575   bool is_cursor_rowtype_ref() const { return m_cursor_rowtype_ref; }
is_explicit_data_type()5576   bool is_explicit_data_type() const
5577   {
5578     return !is_column_type_ref() &&
5579            !is_table_rowtype_ref() &&
5580            !is_cursor_rowtype_ref();
5581   }
column_type_ref()5582   Qualified_column_ident *column_type_ref() const
5583   {
5584     return m_column_type_ref;
5585   }
set_column_type_ref(Qualified_column_ident * ref)5586   void set_column_type_ref(Qualified_column_ident *ref)
5587   {
5588     m_column_type_ref= ref;
5589   }
5590 
table_rowtype_ref()5591   Table_ident *table_rowtype_ref() const
5592   {
5593     return m_table_rowtype_ref;
5594   }
set_table_rowtype_ref(Table_ident * ref)5595   void set_table_rowtype_ref(Table_ident *ref)
5596   {
5597     DBUG_ASSERT(ref);
5598     set_handler(&type_handler_row);
5599     m_table_rowtype_ref= ref;
5600   }
5601 
cursor_rowtype_offset()5602   uint cursor_rowtype_offset() const
5603   {
5604     return m_cursor_rowtype_offset;
5605   }
set_cursor_rowtype_ref(uint offset)5606   void set_cursor_rowtype_ref(uint offset)
5607   {
5608     set_handler(&type_handler_row);
5609     m_cursor_rowtype_ref= true;
5610     m_cursor_rowtype_offset= offset;
5611   }
5612 
5613   /*
5614     Find a ROW field by name.
5615     See Row_field_list::find_row_field_by_name() for details.
5616   */
find_row_field_by_name(const LEX_CSTRING * name,uint * offset)5617   Spvar_definition *find_row_field_by_name(const LEX_CSTRING *name, uint *offset) const
5618   {
5619     DBUG_ASSERT(m_row_field_definitions);
5620     return m_row_field_definitions->find_row_field_by_name(name, offset);
5621   }
is_row()5622   uint is_row() const
5623   {
5624     return m_row_field_definitions != NULL;
5625   }
5626   // Check if "this" defines a ROW variable with n elements
is_row(uint n)5627   uint is_row(uint n) const
5628   {
5629     return m_row_field_definitions != NULL &&
5630            m_row_field_definitions->elements == n;
5631   }
row_field_definitions()5632   Row_definition_list *row_field_definitions() const
5633   {
5634     return m_row_field_definitions;
5635   }
set_row_field_definitions(Row_definition_list * list)5636   void set_row_field_definitions(Row_definition_list *list)
5637   {
5638     DBUG_ASSERT(list);
5639     set_handler(&type_handler_row);
5640     m_row_field_definitions= list;
5641   }
5642 
5643 };
5644 
5645 
eq_name(const Spvar_definition * def,const LEX_CSTRING * name)5646 inline bool Row_definition_list::eq_name(const Spvar_definition *def,
5647                                          const LEX_CSTRING *name) const
5648 {
5649   return def->field_name.length == name->length && my_strcasecmp(system_charset_info, def->field_name.str, name->str) == 0;
5650 }
5651 
5652 
5653 class Create_field :public Column_definition
5654 {
5655 public:
5656   LEX_CSTRING change;			// If done with alter table
5657   LEX_CSTRING after;			// Put column after this one
5658   Field *field;				// For alter table
5659   const TYPELIB *save_interval;         // Temporary copy for the above
5660                                         // Used only for UCS2 intervals
5661 
5662   /** structure with parsed options (for comparing fields in ALTER TABLE) */
5663   ha_field_option_struct *option_struct;
5664   uint	offset;
5665   uint8 interval_id;
5666   bool create_if_not_exists;            // Used in ALTER TABLE IF NOT EXISTS
5667 
Create_field()5668   Create_field():
5669     Column_definition(),
5670     field(0), option_struct(NULL),
5671     create_if_not_exists(false)
5672   {
5673     change= after= null_clex_str;
5674   }
Create_field(THD * thd,Field * old_field,Field * orig_field)5675   Create_field(THD *thd, Field *old_field, Field *orig_field):
5676     Column_definition(thd, old_field, orig_field),
5677     change(old_field->field_name),
5678     field(old_field), option_struct(old_field->option_struct),
5679     create_if_not_exists(false)
5680   {
5681     after= null_clex_str;
5682   }
5683   /* Used to make a clone of this object for ALTER/CREATE TABLE */
5684   Create_field *clone(MEM_ROOT *mem_root) const;
5685 };
5686 
5687 
5688 /*
5689   A class for sending info to the client
5690 */
5691 
5692 class Send_field :public Sql_alloc,
5693                   public Type_handler_hybrid_field_type,
5694                   public Send_field_extended_metadata
5695 {
5696 public:
5697   LEX_CSTRING db_name;
5698   LEX_CSTRING table_name, org_table_name;
5699   LEX_CSTRING col_name, org_col_name;
5700   ulong length;
5701   uint flags, decimals;
Send_field(Field * field)5702   Send_field(Field *field)
5703   {
5704     field->make_send_field(this);
5705     DBUG_ASSERT(table_name.str != 0);
5706     normalize();
5707   }
5708   Send_field(THD *thd, Item *item);
Send_field(Field * field,const LEX_CSTRING & db_name_arg,const LEX_CSTRING & table_name_arg)5709   Send_field(Field *field,
5710              const LEX_CSTRING &db_name_arg,
5711              const LEX_CSTRING &table_name_arg)
5712    :Type_handler_hybrid_field_type(field->type_handler()),
5713     db_name(db_name_arg),
5714     table_name(table_name_arg),
5715     org_table_name(table_name_arg),
5716     col_name(field->field_name),
5717     org_col_name(field->field_name),
5718     length(field->field_length),
5719     flags(field->table->maybe_null ?
5720           (field->flags & ~NOT_NULL_FLAG) : field->flags),
5721     decimals(field->decimals())
5722   {
5723     normalize();
5724   }
5725 
5726 private:
normalize()5727   void normalize()
5728   {
5729     /* limit number of decimals for float and double */
5730     if (type_handler()->field_type() == MYSQL_TYPE_FLOAT ||
5731         type_handler()->field_type() == MYSQL_TYPE_DOUBLE)
5732       set_if_smaller(decimals, FLOATING_POINT_DECIMALS);
5733   }
5734 public:
5735   // This should move to Type_handler eventually
max_char_length(CHARSET_INFO * cs)5736   uint32 max_char_length(CHARSET_INFO *cs) const
5737   {
5738     return type_handler()->field_type() >= MYSQL_TYPE_TINY_BLOB &&
5739            type_handler()->field_type() <= MYSQL_TYPE_BLOB
5740       ? static_cast<uint32>(length / cs->mbminlen)
5741       : static_cast<uint32>(length / cs->mbmaxlen);
5742   }
max_octet_length(CHARSET_INFO * from,CHARSET_INFO * to)5743   uint32 max_octet_length(CHARSET_INFO *from, CHARSET_INFO *to) const
5744   {
5745     /*
5746       For TEXT/BLOB columns, field_length describes the maximum data
5747       length in bytes. There is no limit to the number of characters
5748       that a TEXT column can store, as long as the data fits into
5749       the designated space.
5750       For the rest of textual columns, field_length is evaluated as
5751       char_count * mbmaxlen, where character count is taken from the
5752       definition of the column. In other words, the maximum number
5753       of characters here is limited by the column definition.
5754 
5755       When one has a LONG TEXT column with a single-byte
5756       character set, and the connection character set is multi-byte, the
5757       client may get fields longer than UINT_MAX32, due to
5758       <character set column> -> <character set connection> conversion.
5759       In that case column max length would not fit into the 4 bytes
5760       reserved for it in the protocol. So we cut it here to UINT_MAX32.
5761     */
5762     return char_to_byte_length_safe(max_char_length(from), to->mbmaxlen);
5763   }
5764 
5765   // This should move to Type_handler eventually
is_sane_float()5766   bool is_sane_float() const
5767   {
5768     return (decimals <= FLOATING_POINT_DECIMALS ||
5769             (type_handler()->field_type() != MYSQL_TYPE_FLOAT &&
5770              type_handler()->field_type() != MYSQL_TYPE_DOUBLE));
5771   }
is_sane_signess()5772   bool is_sane_signess() const
5773   {
5774     if (type_handler() == type_handler()->type_handler_signed() &&
5775         type_handler() == type_handler()->type_handler_unsigned())
5776       return true; // Any signess is allowed, e.g. DOUBLE, DECIMAL
5777     /*
5778       We are here e.g. in case of INT data type.
5779       The UNSIGNED_FLAG bit must match in flags and in the type handler.
5780     */
5781     return ((bool) (flags & UNSIGNED_FLAG)) == type_handler()->is_unsigned();
5782   }
is_sane()5783   bool is_sane() const
5784   {
5785     return is_sane_float() && is_sane_signess();
5786   }
5787 };
5788 
5789 
5790 /*
5791   A class for quick copying data to fields
5792 */
5793 
5794 class Copy_field :public Sql_alloc {
5795 public:
5796   uchar *from_ptr,*to_ptr;
5797   uchar *from_null_ptr,*to_null_ptr;
5798   bool *null_row;
5799   uint	from_bit,to_bit;
5800   /**
5801     Number of bytes in the fields pointed to by 'from_ptr' and
5802     'to_ptr'. Usually this is the number of bytes that are copied from
5803     'from_ptr' to 'to_ptr'.
5804 
5805     For variable-length fields (VARCHAR), the first byte(s) describe
5806     the actual length of the text. For VARCHARs with length
5807        < 256 there is 1 length byte
5808        >= 256 there is 2 length bytes
5809     Thus, if from_field is VARCHAR(10), from_length (and in most cases
5810     to_length) is 11. For VARCHAR(1024), the length is 1026. @see
5811     Field_varstring::length_bytes
5812 
5813     Note that for VARCHARs, do_copy() will be do_varstring*() which
5814     only copies the length-bytes (1 or 2) + the actual length of the
5815     text instead of from/to_length bytes.
5816   */
5817   uint from_length,to_length;
5818   Field *from_field,*to_field;
5819   String tmp;					// For items
5820 
Copy_field()5821   Copy_field() {}
~Copy_field()5822   ~Copy_field() {}
5823   void set(Field *to,Field *from,bool save);	// Field to field
5824   void set(uchar *to,Field *from);		// Field to string
5825   void (*do_copy)(Copy_field *);
5826   void (*do_copy2)(Copy_field *);		// Used to handle null values
5827 };
5828 
5829 
5830 uint pack_length_to_packflag(uint type);
5831 enum_field_types get_blob_type_from_length(ulong length);
5832 int set_field_to_null(Field *field);
5833 int set_field_to_null_with_conversions(Field *field, bool no_conversions);
5834 int convert_null_to_field_value_or_error(Field *field);
5835 bool check_expression(Virtual_column_info *vcol, const LEX_CSTRING *name,
5836                       enum_vcol_info_type type, Alter_info *alter_info= NULL);
5837 
5838 /*
5839   The following are for the interface with the .frm file
5840 */
5841 
5842 #define FIELDFLAG_DECIMAL		1U
5843 #define FIELDFLAG_BINARY		1U	// Shares same flag
5844 #define FIELDFLAG_NUMBER		2U
5845 #define FIELDFLAG_ZEROFILL		4U
5846 #define FIELDFLAG_PACK			120U	// Bits used for packing
5847 #define FIELDFLAG_INTERVAL		256U    // mangled with decimals!
5848 #define FIELDFLAG_BITFIELD		512U	// mangled with decimals!
5849 #define FIELDFLAG_BLOB			1024U	// mangled with decimals!
5850 #define FIELDFLAG_GEOM			2048U   // mangled with decimals!
5851 
5852 #define FIELDFLAG_TREAT_BIT_AS_CHAR     4096U   /* use Field_bit_as_char */
5853 #define FIELDFLAG_LONG_DECIMAL          8192U
5854 #define FIELDFLAG_NO_DEFAULT		16384U  /* sql */
5855 #define FIELDFLAG_MAYBE_NULL		32768U	// sql
5856 #define FIELDFLAG_HEX_ESCAPE		0x10000U
5857 #define FIELDFLAG_PACK_SHIFT		3
5858 #define FIELDFLAG_DEC_SHIFT		8
5859 #define FIELDFLAG_MAX_DEC               63U
5860 
5861 #define FIELDFLAG_DEC_MASK              0x3F00U
5862 
5863 #define MTYP_TYPENR(type) ((type) & 127U) // Remove bits from type
5864 
5865 #define f_is_dec(x)		((x) & FIELDFLAG_DECIMAL)
5866 #define f_is_num(x)		((x) & FIELDFLAG_NUMBER)
5867 #define f_is_zerofill(x)	((x) & FIELDFLAG_ZEROFILL)
5868 #define f_is_packed(x)		((x) & FIELDFLAG_PACK)
5869 #define f_packtype(x)		(((x) >> FIELDFLAG_PACK_SHIFT) & 15)
5870 #define f_decimals(x)		((uint8) (((x) >> FIELDFLAG_DEC_SHIFT) & FIELDFLAG_MAX_DEC))
5871 #define f_is_alpha(x)		(!f_is_num(x))
5872 #define f_is_binary(x)          ((x) & FIELDFLAG_BINARY) // 4.0- compatibility
5873 #define f_is_enum(x)            (((x) & (FIELDFLAG_INTERVAL | FIELDFLAG_NUMBER)) == FIELDFLAG_INTERVAL)
5874 #define f_is_bitfield(x)        (((x) & (FIELDFLAG_BITFIELD | FIELDFLAG_NUMBER)) == FIELDFLAG_BITFIELD)
5875 #define f_is_blob(x)		(((x) & (FIELDFLAG_BLOB | FIELDFLAG_NUMBER)) == FIELDFLAG_BLOB)
5876 #define f_is_geom(x)		(((x) & (FIELDFLAG_GEOM | FIELDFLAG_NUMBER)) == FIELDFLAG_GEOM)
5877 #define f_settype(x)		(((uint) (x)) << FIELDFLAG_PACK_SHIFT)
5878 #define f_maybe_null(x)		((x) & FIELDFLAG_MAYBE_NULL)
5879 #define f_no_default(x)		((x) & FIELDFLAG_NO_DEFAULT)
5880 #define f_bit_as_char(x)        ((x) & FIELDFLAG_TREAT_BIT_AS_CHAR)
5881 #define f_is_hex_escape(x)      ((x) & FIELDFLAG_HEX_ESCAPE)
5882 #define f_visibility(x)         (static_cast<field_visibility_t> ((x) & INVISIBLE_MAX_BITS))
5883 
5884 inline
vers_end_id()5885 ulonglong TABLE::vers_end_id() const
5886 {
5887   DBUG_ASSERT(versioned(VERS_TRX_ID));
5888   return static_cast<ulonglong>(vers_end_field()->val_int());
5889 }
5890 
5891 inline
vers_start_id()5892 ulonglong TABLE::vers_start_id() const
5893 {
5894   DBUG_ASSERT(versioned(VERS_TRX_ID));
5895   return static_cast<ulonglong>(vers_start_field()->val_int());
5896 }
5897 
5898 
5899 #endif /* FIELD_INCLUDED */
5900