1 /*
2    Copyright (c) 2000, 2020, Oracle and/or its affiliates.
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License, version 2.0,
6    as published by the Free Software Foundation.
7 
8    This program is also distributed with certain software (including
9    but not limited to OpenSSL) that is licensed under separate terms,
10    as designated in a particular file or component or in included license
11    documentation.  The authors of MySQL hereby grant you an additional
12    permission to link the program and your derivative works with the
13    separately licensed software that they have included with MySQL.
14 
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License, version 2.0, for more details.
19 
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
23 */
24 
25 
26 /**
27   @file
28 
29   @brief
30   This file implements classes defined in field.h
31 */
32 
33 #include "field.h"
34 
35 #include "filesort.h"                    // change_double_for_sort
36 #include "item_timefunc.h"               // Item_func_now_local
37 #include "json_binary.h"                 // json_binary::serialize
38 #include "json_dom.h"                    // Json_dom, Json_wrapper
39 #include "item_json_func.h"              // ensure_utf8mb4
40 #include "log_event.h"                   // class Table_map_log_event
41 #include "rpl_rli.h"                     // Relay_log_info
42 #include "rpl_slave.h"                   // rpl_master_has_bug
43 #include "sql_class.h"                   // THD
44 #include "sql_join_buffer.h"             // CACHE_FIELD
45 #include "sql_time.h"                    // str_to_datetime_with_warn
46 #include "strfunc.h"                     // find_type2
47 #include "template_utils.h"              // pointer_cast
48 #include "tztime.h"                      // Time_zone
49 #include "spatial.h"                     // Geometry
50 #include "sql_base.h"                    // is_equal
51 
52 #include <algorithm>
53 #include <memory>                        // auto_ptr
54 
55 using std::max;
56 using std::min;
57 
58 #define FLAGSTR(V,F) ((V)&(F)?#F" ":"")
59 
60 // Maximum allowed exponent value for converting string to decimal
61 #define MAX_EXPONENT 1024
62 
63 /**
64   Static variables
65 */
66 uchar Field_null::null[1]={1};
67 const char field_separator=',';
68 
69 #define DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE FLOATING_POINT_BUFFER
70 #define LONGLONG_TO_STRING_CONVERSION_BUFFER_SIZE 128
71 #define DECIMAL_TO_STRING_CONVERSION_BUFFER_SIZE 128
72 #define BLOB_PACK_LENGTH_TO_MAX_LENGH(arg) \
73 ((ulong) ((1LL << MY_MIN(arg, 4) * 8) - 1LL))
74 
75 /*
76   Rules for merging different types of fields in UNION
77 
78   NOTE: to avoid 256*256 table, gap in table types numeration is skiped
79   following #defines describe that gap and how to canculate number of fields
80   and index of field in thia array.
81 */
82 #define FIELDTYPE_TEAR_FROM (MYSQL_TYPE_BIT + 1)
83 #define FIELDTYPE_TEAR_TO   (MYSQL_TYPE_JSON - 1)
84 #define FIELDTYPE_NUM (FIELDTYPE_TEAR_FROM + (255 - FIELDTYPE_TEAR_TO))
85 
86 
field_type2index(enum_field_types field_type)87 inline int field_type2index (enum_field_types field_type)
88 {
89   field_type= real_type_to_type(field_type);
90   DBUG_ASSERT(field_type < FIELDTYPE_TEAR_FROM ||
91               field_type > FIELDTYPE_TEAR_TO);
92   return (field_type < FIELDTYPE_TEAR_FROM ?
93           field_type :
94           ((int)FIELDTYPE_TEAR_FROM) + (field_type - FIELDTYPE_TEAR_TO) - 1);
95 }
96 
97 
98 static enum_field_types field_types_merge_rules [FIELDTYPE_NUM][FIELDTYPE_NUM]=
99 {
100   /* MYSQL_TYPE_DECIMAL -> */
101   {
102   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
103     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
104   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
105     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
106   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
107     MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
108   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
109     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
110   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
111     MYSQL_TYPE_DECIMAL,     MYSQL_TYPE_DECIMAL,
112   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
113     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
114   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
115     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
116   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
117     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
118   //MYSQL_TYPE_BIT          <16>-<244>
119     MYSQL_TYPE_VARCHAR,
120   //MYSQL_TYPE_JSON
121     MYSQL_TYPE_VARCHAR,
122   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
123     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
124   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
125     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
126   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
127     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
128   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
129     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
130   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
131     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
132   },
133   /* MYSQL_TYPE_TINY -> */
134   {
135   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
136     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_TINY,
137   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
138     MYSQL_TYPE_SHORT,       MYSQL_TYPE_LONG,
139   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
140     MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
141   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
142     MYSQL_TYPE_TINY,        MYSQL_TYPE_VARCHAR,
143   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
144     MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_INT24,
145   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
146     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
147   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
148     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY,
149   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
150     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
151   //MYSQL_TYPE_BIT          <16>-<244>
152     MYSQL_TYPE_VARCHAR,
153   //MYSQL_TYPE_JSON
154     MYSQL_TYPE_VARCHAR,
155   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
156     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
157   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
158     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
159   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
160     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
161   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
162     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
163   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
164     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
165   },
166   /* MYSQL_TYPE_SHORT -> */
167   {
168   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
169     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_SHORT,
170   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
171     MYSQL_TYPE_SHORT,       MYSQL_TYPE_LONG,
172   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
173     MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
174   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
175     MYSQL_TYPE_SHORT,       MYSQL_TYPE_VARCHAR,
176   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
177     MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_INT24,
178   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
179     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
180   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
181     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_SHORT,
182   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
183     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
184   //MYSQL_TYPE_BIT          <16>-<244>
185     MYSQL_TYPE_VARCHAR,
186   //MYSQL_TYPE_JSON
187     MYSQL_TYPE_VARCHAR,
188   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
189     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
190   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
191     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
192   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
193     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
194   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
195     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
196   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
197     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
198   },
199   /* MYSQL_TYPE_LONG -> */
200   {
201   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
202     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_LONG,
203   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
204     MYSQL_TYPE_LONG,        MYSQL_TYPE_LONG,
205   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
206     MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
207   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
208     MYSQL_TYPE_LONG,         MYSQL_TYPE_VARCHAR,
209   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
210     MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONG,
211   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
212     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
213   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
214     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_LONG,
215   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
216     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
217   //MYSQL_TYPE_BIT          <16>-<244>
218     MYSQL_TYPE_VARCHAR,
219   //MYSQL_TYPE_JSON
220     MYSQL_TYPE_VARCHAR,
221   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
222     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
223   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
224     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
225   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
226     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
227   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
228     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
229   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
230     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
231   },
232   /* MYSQL_TYPE_FLOAT -> */
233   {
234   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
235     MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_FLOAT,
236   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
237     MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
238   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
239     MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
240   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
241     MYSQL_TYPE_FLOAT,       MYSQL_TYPE_VARCHAR,
242   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
243     MYSQL_TYPE_FLOAT,       MYSQL_TYPE_FLOAT,
244   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
245     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
246   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
247     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_FLOAT,
248   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
249     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
250   //MYSQL_TYPE_BIT          <16>-<244>
251     MYSQL_TYPE_VARCHAR,
252   //MYSQL_TYPE_JSON
253     MYSQL_TYPE_VARCHAR,
254   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
255     MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_VARCHAR,
256   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
257     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
258   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
259     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
260   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
261     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
262   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
263     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
264   },
265   /* MYSQL_TYPE_DOUBLE -> */
266   {
267   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
268     MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
269   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
270     MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
271   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
272     MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
273   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
274     MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_VARCHAR,
275   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
276     MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
277   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
278     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
279   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
280     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_DOUBLE,
281   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
282     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
283   //MYSQL_TYPE_BIT          <16>-<244>
284     MYSQL_TYPE_VARCHAR,
285   //MYSQL_TYPE_JSON
286     MYSQL_TYPE_VARCHAR,
287   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
288     MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_VARCHAR,
289   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
290     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
291   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
292     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
293   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
294     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
295   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
296     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
297   },
298   /* MYSQL_TYPE_NULL -> */
299   {
300   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
301     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_TINY,
302   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
303     MYSQL_TYPE_SHORT,       MYSQL_TYPE_LONG,
304   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
305     MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
306   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
307     MYSQL_TYPE_NULL,        MYSQL_TYPE_TIMESTAMP,
308   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
309     MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONGLONG,
310   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
311     MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_TIME,
312   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
313     MYSQL_TYPE_DATETIME,    MYSQL_TYPE_YEAR,
314   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
315     MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
316   //MYSQL_TYPE_BIT          <16>-<244>
317     MYSQL_TYPE_BIT,
318   //MYSQL_TYPE_JSON
319     MYSQL_TYPE_JSON,
320   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
321     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_ENUM,
322   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
323     MYSQL_TYPE_SET,         MYSQL_TYPE_TINY_BLOB,
324   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
325     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
326   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
327     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
328   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
329     MYSQL_TYPE_STRING,      MYSQL_TYPE_GEOMETRY
330   },
331   /* MYSQL_TYPE_TIMESTAMP -> */
332   {
333   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
334     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
335   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
336     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
337   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
338     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
339   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
340     MYSQL_TYPE_TIMESTAMP,   MYSQL_TYPE_TIMESTAMP,
341   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
342     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
343   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
344     MYSQL_TYPE_DATETIME,    MYSQL_TYPE_DATETIME,
345   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
346     MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
347   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
348     MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
349   //MYSQL_TYPE_BIT          <16>-<244>
350     MYSQL_TYPE_VARCHAR,
351   //MYSQL_TYPE_JSON
352     MYSQL_TYPE_VARCHAR,
353   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
354     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
355   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
356     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
357   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
358     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
359   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
360     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
361   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
362     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
363   },
364   /* MYSQL_TYPE_LONGLONG -> */
365   {
366   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
367     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_LONGLONG,
368   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
369     MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONGLONG,
370   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
371     MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
372   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
373     MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_VARCHAR,
374   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
375     MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONG,
376   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
377     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
378   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
379     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_LONGLONG,
380   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
381     MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
382   //MYSQL_TYPE_BIT          <16>-<244>
383     MYSQL_TYPE_VARCHAR,
384   //MYSQL_TYPE_JSON
385     MYSQL_TYPE_VARCHAR,
386   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
387     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
388   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
389     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
390   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
391     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
392   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
393     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
394   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
395     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
396   },
397   /* MYSQL_TYPE_INT24 -> */
398   {
399   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
400     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_INT24,
401   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
402     MYSQL_TYPE_INT24,       MYSQL_TYPE_LONG,
403   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
404     MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
405   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
406     MYSQL_TYPE_INT24,       MYSQL_TYPE_VARCHAR,
407   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
408     MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_INT24,
409   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
410     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
411   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
412     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_INT24,
413   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
414     MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
415   //MYSQL_TYPE_BIT          <16>-<244>
416     MYSQL_TYPE_VARCHAR,
417   //MYSQL_TYPE_JSON
418     MYSQL_TYPE_VARCHAR,
419   //MYSQL_TYPE_NEWDECIMAL    MYSQL_TYPE_ENUM
420     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
421   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
422     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
423   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
424     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
425   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
426     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
427   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
428     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
429   },
430   /* MYSQL_TYPE_DATE -> */
431   {
432   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
433     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
434   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
435     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
436   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
437     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
438   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
439     MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_DATETIME,
440   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
441     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
442   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
443     MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_DATETIME,
444   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
445     MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
446   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
447     MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
448   //MYSQL_TYPE_BIT          <16>-<244>
449     MYSQL_TYPE_VARCHAR,
450   //MYSQL_TYPE_JSON
451     MYSQL_TYPE_VARCHAR,
452   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
453     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
454   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
455     MYSQL_TYPE_VARCHAR,  MYSQL_TYPE_TINY_BLOB,
456   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
457     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
458   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
459     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
460   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
461     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
462   },
463   /* MYSQL_TYPE_TIME -> */
464   {
465   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
466     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
467   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
468     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
469   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
470     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
471   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
472     MYSQL_TYPE_TIME,        MYSQL_TYPE_DATETIME,
473   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
474     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
475   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
476     MYSQL_TYPE_DATETIME,    MYSQL_TYPE_TIME,
477   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
478     MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
479   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
480     MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
481   //MYSQL_TYPE_BIT          <16>-<244>
482     MYSQL_TYPE_VARCHAR,
483   //MYSQL_TYPE_JSON
484     MYSQL_TYPE_VARCHAR,
485   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
486     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
487   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
488     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
489   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
490     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
491   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
492     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
493   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
494     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
495   },
496   /* MYSQL_TYPE_DATETIME -> */
497   {
498   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
499     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
500   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
501     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
502   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
503     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
504   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
505     MYSQL_TYPE_DATETIME,    MYSQL_TYPE_DATETIME,
506   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
507     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
508   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
509     MYSQL_TYPE_DATETIME,    MYSQL_TYPE_DATETIME,
510   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
511     MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
512   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
513     MYSQL_TYPE_DATETIME,     MYSQL_TYPE_VARCHAR,
514   //MYSQL_TYPE_BIT          <16>-<244>
515     MYSQL_TYPE_VARCHAR,
516   //MYSQL_TYPE_JSON
517     MYSQL_TYPE_VARCHAR,
518   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
519     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
520   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
521     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
522   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
523     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
524   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
525     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
526   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
527     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
528   },
529   /* MYSQL_TYPE_YEAR -> */
530   {
531   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
532     MYSQL_TYPE_DECIMAL,     MYSQL_TYPE_TINY,
533   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
534     MYSQL_TYPE_SHORT,       MYSQL_TYPE_LONG,
535   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
536     MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
537   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
538     MYSQL_TYPE_YEAR,        MYSQL_TYPE_VARCHAR,
539   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
540     MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_INT24,
541   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
542     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
543   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
544     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_YEAR,
545   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
546     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
547   //MYSQL_TYPE_BIT          <16>-<244>
548     MYSQL_TYPE_VARCHAR,
549   //MYSQL_TYPE_JSON
550     MYSQL_TYPE_VARCHAR,
551   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
552     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
553   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
554     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
555   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
556     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
557   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
558     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
559   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
560     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
561   },
562   /* MYSQL_TYPE_NEWDATE -> */
563   {
564   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
565     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
566   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
567     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
568   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
569     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
570   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
571     MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_DATETIME,
572   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
573     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
574   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
575     MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_DATETIME,
576   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
577     MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
578   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
579     MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
580   //MYSQL_TYPE_BIT          <16>-<244>
581     MYSQL_TYPE_VARCHAR,
582   //MYSQL_TYPE_JSON
583     MYSQL_TYPE_VARCHAR,
584   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
585     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
586   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
587     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
588   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
589     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
590   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
591     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
592   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
593     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
594   },
595   /* MYSQL_TYPE_VARCHAR -> */
596   {
597   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
598     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
599   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
600     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
601   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
602     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
603   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
604     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
605   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
606     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
607   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
608     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
609   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
610     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
611   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
612     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
613   //MYSQL_TYPE_BIT          <16>-<244>
614     MYSQL_TYPE_VARCHAR,
615   //MYSQL_TYPE_JSON
616     MYSQL_TYPE_VARCHAR,
617   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
618     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
619   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
620     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
621   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
622     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
623   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
624     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
625   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
626     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR
627   },
628   /* MYSQL_TYPE_BIT -> */
629   {
630   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
631     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
632   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
633     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
634   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
635     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
636   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
637     MYSQL_TYPE_BIT,         MYSQL_TYPE_VARCHAR,
638   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
639     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
640   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
641     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
642   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
643     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
644   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
645     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
646   //MYSQL_TYPE_BIT          <16>-<244>
647     MYSQL_TYPE_BIT,
648   //MYSQL_TYPE_JSON
649     MYSQL_TYPE_VARCHAR,
650   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
651     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
652   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
653     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
654   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
655     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
656   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
657     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
658   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
659     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
660   },
661   /* MYSQL_TYPE_JSON -> */
662   {
663   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
664     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
665   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
666     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
667   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
668     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
669   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
670     MYSQL_TYPE_JSON,        MYSQL_TYPE_VARCHAR,
671   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
672     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
673   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
674     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
675   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
676     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
677   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
678     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
679   //MYSQL_TYPE_BIT          <16>-<244>
680     MYSQL_TYPE_VARCHAR,
681   //MYSQL_TYPE_JSON
682     MYSQL_TYPE_JSON,
683   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
684     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
685   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
686     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_LONG_BLOB,
687   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
688     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
689   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
690     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_VARCHAR,
691   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
692     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
693   },
694   /* MYSQL_TYPE_NEWDECIMAL -> */
695   {
696   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
697     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
698   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
699     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
700   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
701     MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
702   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
703     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
704   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
705     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
706   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
707     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
708   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
709     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_NEWDECIMAL,
710   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
711     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
712   //MYSQL_TYPE_BIT          <16>-<244>
713     MYSQL_TYPE_VARCHAR,
714   //MYSQL_TYPE_JSON
715     MYSQL_TYPE_VARCHAR,
716   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
717     MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
718   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
719     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
720   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
721     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
722   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
723     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
724   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
725     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
726   },
727   /* MYSQL_TYPE_ENUM -> */
728   {
729   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
730     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
731   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
732     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
733   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
734     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
735   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
736     MYSQL_TYPE_ENUM,        MYSQL_TYPE_VARCHAR,
737   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
738     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
739   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
740     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
741   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
742     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
743   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
744     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
745   //MYSQL_TYPE_BIT          <16>-<244>
746     MYSQL_TYPE_VARCHAR,
747   //MYSQL_TYPE_JSON
748     MYSQL_TYPE_VARCHAR,
749   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
750     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
751   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
752     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
753   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
754     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
755   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
756     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
757   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
758     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
759   },
760   /* MYSQL_TYPE_SET -> */
761   {
762   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
763     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
764   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
765     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
766   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
767     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
768   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
769     MYSQL_TYPE_SET,         MYSQL_TYPE_VARCHAR,
770   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
771     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
772   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
773     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
774   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
775     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
776   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
777     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
778   //MYSQL_TYPE_BIT          <16>-<244>
779     MYSQL_TYPE_VARCHAR,
780   //MYSQL_TYPE_JSON
781     MYSQL_TYPE_VARCHAR,
782   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
783     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
784   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
785     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
786   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
787     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
788   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
789     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
790   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
791     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
792   },
793   /* MYSQL_TYPE_TINY_BLOB -> */
794   {
795   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
796     MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
797   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
798     MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
799   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
800     MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
801   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
802     MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
803   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
804     MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
805   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
806     MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
807   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
808     MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
809   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
810     MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
811   //MYSQL_TYPE_BIT          <16>-<244>
812     MYSQL_TYPE_TINY_BLOB,
813   //MYSQL_TYPE_JSON
814     MYSQL_TYPE_LONG_BLOB,
815   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
816     MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
817   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
818     MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
819   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
820     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
821   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
822     MYSQL_TYPE_BLOB,        MYSQL_TYPE_TINY_BLOB,
823   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
824     MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB
825   },
826   /* MYSQL_TYPE_MEDIUM_BLOB -> */
827   {
828   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
829     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
830   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
831     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
832   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
833     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
834   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
835     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
836   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
837     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
838   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
839     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
840   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
841     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
842   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
843     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
844   //MYSQL_TYPE_BIT          <16>-<244>
845     MYSQL_TYPE_MEDIUM_BLOB,
846   //MYSQL_TYPE_JSON
847     MYSQL_TYPE_LONG_BLOB,
848   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
849     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
850   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
851     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
852   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
853     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
854   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
855     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
856   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
857     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB
858   },
859   /* MYSQL_TYPE_LONG_BLOB -> */
860   {
861   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
862     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
863   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
864     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
865   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
866     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
867   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
868     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
869   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
870     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
871   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
872     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
873   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
874     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
875   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
876     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
877   //MYSQL_TYPE_BIT          <16>-<244>
878     MYSQL_TYPE_LONG_BLOB,
879   //MYSQL_TYPE_JSON
880     MYSQL_TYPE_LONG_BLOB,
881   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
882     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
883   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
884     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
885   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
886     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
887   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
888     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
889   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
890     MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB
891   },
892   /* MYSQL_TYPE_BLOB -> */
893   {
894   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
895     MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
896   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
897     MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
898   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
899     MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
900   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
901     MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
902   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
903     MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
904   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
905     MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
906   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
907     MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
908   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
909     MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
910   //MYSQL_TYPE_BIT          <16>-<244>
911     MYSQL_TYPE_BLOB,
912   //MYSQL_TYPE_JSON
913     MYSQL_TYPE_LONG_BLOB,
914   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
915     MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
916   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
917     MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
918   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
919     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
920   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
921     MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
922   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
923     MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB
924   },
925   /* MYSQL_TYPE_VAR_STRING -> */
926   {
927   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
928     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
929   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
930     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
931   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
932     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
933   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
934     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
935   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
936     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
937   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
938     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
939   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
940     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
941   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
942     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
943   //MYSQL_TYPE_BIT          <16>-<244>
944     MYSQL_TYPE_VARCHAR,
945   //MYSQL_TYPE_JSON
946     MYSQL_TYPE_VARCHAR,
947   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
948     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
949   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
950     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
951   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
952     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
953   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
954     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
955   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
956     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR
957   },
958   /* MYSQL_TYPE_STRING -> */
959   {
960   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
961     MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
962   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
963     MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
964   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
965     MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
966   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
967     MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
968   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
969     MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
970   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
971     MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
972   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
973     MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
974   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
975     MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR,
976   //MYSQL_TYPE_BIT          <16>-<244>
977     MYSQL_TYPE_STRING,
978   //MYSQL_TYPE_JSON
979     MYSQL_TYPE_STRING,
980   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
981     MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
982   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
983     MYSQL_TYPE_STRING,      MYSQL_TYPE_TINY_BLOB,
984   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
985     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
986   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
987     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
988   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
989     MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING
990   },
991   /* MYSQL_TYPE_GEOMETRY -> */
992   {
993   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
994     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
995   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
996     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
997   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
998     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
999   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
1000     MYSQL_TYPE_GEOMETRY,    MYSQL_TYPE_VARCHAR,
1001   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
1002     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
1003   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
1004     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
1005   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
1006     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
1007   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
1008     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
1009   //MYSQL_TYPE_BIT          <16>-<244>
1010     MYSQL_TYPE_VARCHAR,
1011   //MYSQL_TYPE_JSON
1012     MYSQL_TYPE_VARCHAR,
1013   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
1014     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
1015   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
1016     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
1017   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
1018     MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
1019   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
1020     MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
1021   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
1022     MYSQL_TYPE_STRING,      MYSQL_TYPE_GEOMETRY
1023   }
1024 };
1025 
1026 
1027 /**
1028   Set field to temporary value NULL.
1029 */
set_tmp_null()1030 void Field::set_tmp_null()
1031 {
1032   m_is_tmp_null= true;
1033 
1034   m_count_cuted_fields_saved= table ? table->in_use->count_cuted_fields :
1035                                       current_thd->count_cuted_fields;
1036 }
1037 
1038 
1039 /**
1040   Return type of which can carry value of both given types in UNION result.
1041 
1042   @param a  type for merging
1043   @param b  type for merging
1044 
1045   @return
1046     type of field
1047 */
1048 
field_type_merge(enum_field_types a,enum_field_types b)1049 enum_field_types Field::field_type_merge(enum_field_types a,
1050                                          enum_field_types b)
1051 {
1052   return field_types_merge_rules[field_type2index(a)]
1053                                 [field_type2index(b)];
1054 }
1055 
1056 
1057 static Item_result field_types_result_type [FIELDTYPE_NUM]=
1058 {
1059   //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
1060   DECIMAL_RESULT,           INT_RESULT,
1061   //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
1062   INT_RESULT,               INT_RESULT,
1063   //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
1064   REAL_RESULT,              REAL_RESULT,
1065   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
1066   STRING_RESULT,            STRING_RESULT,
1067   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
1068   INT_RESULT,               INT_RESULT,
1069   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
1070   STRING_RESULT,            STRING_RESULT,
1071   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
1072   STRING_RESULT,            INT_RESULT,
1073   //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
1074   STRING_RESULT,            STRING_RESULT,
1075   //MYSQL_TYPE_BIT          <16>-<244>
1076   STRING_RESULT,
1077   //MYSQL_TYPE_JSON
1078   STRING_RESULT,
1079   //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
1080   DECIMAL_RESULT,           STRING_RESULT,
1081   //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
1082   STRING_RESULT,            STRING_RESULT,
1083   //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
1084   STRING_RESULT,            STRING_RESULT,
1085   //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
1086   STRING_RESULT,            STRING_RESULT,
1087   //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
1088   STRING_RESULT,            STRING_RESULT
1089 };
1090 
1091 
1092 /**
1093   Convert Field::geometry_type to the corresponding Geometry::wkbType.
1094 
1095   @param t The geometry_type to convert
1096 
1097   @return The corresponding Geometry::wkbType, or
1098           Geometry::wkb_invalid_type if there's not suitable type.
1099 */
geometry_type_to_wkb_type(Field::geometry_type t)1100 static Geometry::wkbType geometry_type_to_wkb_type(Field::geometry_type t)
1101 {
1102   switch(t)
1103   {
1104   case Field::GEOM_GEOMETRY:
1105     return Geometry::wkb_invalid_type;
1106   case Field::GEOM_POINT:
1107     return Geometry::wkb_point;
1108   case Field::GEOM_LINESTRING:
1109     return Geometry::wkb_linestring;
1110   case Field::GEOM_POLYGON:
1111     return Geometry::wkb_polygon;
1112   case Field::GEOM_MULTIPOINT:
1113     return Geometry::wkb_multipoint;
1114   case Field::GEOM_MULTILINESTRING:
1115     return Geometry::wkb_multilinestring;
1116   case Field::GEOM_MULTIPOLYGON:
1117     return Geometry::wkb_multipolygon;
1118   case Field::GEOM_GEOMETRYCOLLECTION:
1119     return Geometry::wkb_geometrycollection;
1120   default:
1121     DBUG_ASSERT(0);
1122     return Geometry::wkb_invalid_type;
1123   }
1124 }
1125 
1126 
1127 /*
1128   Test if the given string contains important data:
1129   not spaces for character string,
1130   or any data for binary string.
1131 
1132   SYNOPSIS
1133     test_if_important_data()
1134     cs          Character set
1135     str         String to test
1136     strend      String end
1137 
1138   RETURN
1139     FALSE - If string does not have important data
1140     TRUE  - If string has some important data
1141 */
1142 
1143 static bool
test_if_important_data(const CHARSET_INFO * cs,const char * str,const char * strend)1144 test_if_important_data(const CHARSET_INFO *cs, const char *str,
1145                        const char *strend)
1146 {
1147   if (cs != &my_charset_bin)
1148     str+= cs->cset->scan(cs, str, strend, MY_SEQ_SPACES);
1149   return (str < strend);
1150 }
1151 
1152 
1153 /**
1154    Function to compare two unsigned integers for their relative order.
1155    Used below. In an anonymous namespace to not clash with definitions
1156    in other files.
1157  */
1158 
1159 namespace {
1160 
compare(unsigned int a,unsigned int b)1161 int compare(unsigned int a, unsigned int b)
1162 {
1163   if (a < b)
1164     return -1;
1165   if (b < a)
1166     return 1;
1167   return 0;
1168 }
1169 
1170 } // namespace
1171 
1172 /**
1173   Detect Item_result by given field type of UNION merge result.
1174 
1175   @param field_type  given field type
1176 
1177   @return
1178     Item_result (type of internal MySQL expression result)
1179 */
1180 
result_merge_type(enum_field_types field_type)1181 Item_result Field::result_merge_type(enum_field_types field_type)
1182 {
1183   return field_types_result_type[field_type2index(field_type)];
1184 }
1185 
1186 /*****************************************************************************
1187   Static help functions
1188 *****************************************************************************/
1189 
1190 /**
1191   Output a warning for erroneous conversion of strings to numerical
1192   values. For use with ER_TRUNCATED_WRONG_VALUE[_FOR_FIELD]
1193 
1194   @param thd         THD object
1195   @param str         pointer to string that failed to be converted
1196   @param length      length of string
1197   @param cs          charset for string
1198   @param typestr     string describing type converted to
1199   @param error       error value to output
1200   @param field_name  (for *_FOR_FIELD) name of field
1201   @param row_num     (for *_FOR_FIELD) row number
1202  */
push_numerical_conversion_warning(THD * thd,const char * str,uint length,const CHARSET_INFO * cs,const char * typestr,int error,const char * field_name="UNKNOWN",ulong row_num=0)1203 static void push_numerical_conversion_warning(THD* thd, const char* str,
1204                                               uint length,
1205                                               const CHARSET_INFO* cs,
1206                                               const char* typestr, int error,
1207                                               const char* field_name="UNKNOWN",
1208                                               ulong row_num=0)
1209 {
1210     char buf[MY_MAX(MY_MAX(DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE,
1211       LONGLONG_TO_STRING_CONVERSION_BUFFER_SIZE),
1212       DECIMAL_TO_STRING_CONVERSION_BUFFER_SIZE)];
1213 
1214     String tmp(buf, sizeof(buf), cs);
1215     tmp.copy(str, length, cs);
1216     push_warning_printf(thd, Sql_condition::SL_WARNING,
1217                         error, ER(error), typestr, tmp.c_ptr(),
1218                         field_name, row_num);
1219 }
1220 
1221 
1222 /**
1223   Emits a warning for the decimal conversion error. May modify
1224   dec_value if there was conversion overflow or bad number.
1225 
1226 
1227   @param dec_error         decimal library return code
1228                            (E_DEC_* see include/decimal.h)
1229   @param dec_value[in,out] Decimal value returned by convertion function.
1230   @param from              Value converted from
1231   @param length            Length of 'from'
1232   @param charset_arg       Charset of 'from'
1233 */
set_decimal_warning(Field_new_decimal * field,int dec_error,my_decimal * dec_value,const char * from,size_t length,const CHARSET_INFO * charset_arg)1234 static void set_decimal_warning(Field_new_decimal *field,
1235                                 int dec_error,
1236                                 my_decimal *dec_value,
1237                                 const char *from,
1238                                 size_t length,
1239                                 const CHARSET_INFO *charset_arg)
1240 {
1241   switch (dec_error) {
1242   case E_DEC_TRUNCATED:
1243     field->set_warning(Sql_condition::SL_NOTE, WARN_DATA_TRUNCATED, 1);
1244     break;
1245   case E_DEC_OVERFLOW:
1246     field->set_warning(Sql_condition::SL_WARNING,
1247                        ER_WARN_DATA_OUT_OF_RANGE, 1);
1248     field->set_value_on_overflow(dec_value, dec_value->sign());
1249     break;
1250   case E_DEC_BAD_NUM:
1251     ErrConvString errmsg(from, length, charset_arg);
1252     const Diagnostics_area *da= field->table->in_use->get_stmt_da();
1253     push_warning_printf(field->table->in_use, Sql_condition::SL_WARNING,
1254                         ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
1255                         ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
1256                         "decimal", errmsg.ptr(), field->field_name,
1257                         da->current_row_for_condition());
1258     my_decimal_set_zero(dec_value);
1259   }
1260 }
1261 
1262 
1263 /**
1264   Copy string with optional character set conversion.
1265 
1266   This calls helper function well_formed_copy_nchars to copy string
1267   with optional character set convertion. Specially, it checks if
1268   the ASCII code point exceeds code range. If YES, it allows the
1269   input but raises a warning.
1270 
1271   @param to_cs                    Character set of "to" string
1272   @param to                       Store result here
1273   @param to_length                Maxinum length of "to" string
1274   @param from_cs                  From character set
1275   @param from                     Copy from here
1276   @param from_length              Length of from string
1277   @param nchars                   Copy not more that nchars characters
1278   @param well_formed_error_pos    Return position when "from" is not well
1279                                   formed or NULL otherwise.
1280   @param cannot_convert_error_pos Return position where a not convertable
1281                                   character met, or NULL otherwise.
1282   @param from_end_pos             Return position where scanning of "from"
1283                                   string stopped.
1284 
1285   @retval length of bytes copied to 'to'
1286 */
1287 
field_well_formed_copy_nchars(const CHARSET_INFO * to_cs,char * to,size_t to_length,const CHARSET_INFO * from_cs,const char * from,size_t from_length,size_t nchars,const char ** well_formed_error_pos,const char ** cannot_convert_error_pos,const char ** from_end_pos)1288 size_t field_well_formed_copy_nchars(const CHARSET_INFO *to_cs,
1289                                      char *to, size_t to_length,
1290                                      const CHARSET_INFO *from_cs,
1291                                      const char *from, size_t from_length,
1292                                      size_t nchars,
1293                                      const char **well_formed_error_pos,
1294                                      const char **cannot_convert_error_pos,
1295                                      const char **from_end_pos)
1296 {
1297   size_t res = well_formed_copy_nchars(to_cs, to, to_length, from_cs,
1298                                        from, from_length, nchars,
1299                                        well_formed_error_pos,
1300                                        cannot_convert_error_pos,
1301                                        from_end_pos);
1302   /*
1303    If the code point is out of ascii range, we only give user a warning
1304    in 5.7. Need to change to give a ERROR in future version.
1305   */
1306   if ((to_cs->state & MY_CS_PUREASCII) && *well_formed_error_pos != NULL)
1307   {
1308     char tmp[32];
1309     *well_formed_error_pos = NULL;
1310     convert_to_printable(tmp, sizeof(tmp), from, from_length, from_cs, 6);
1311     push_warning_printf(current_thd, Sql_condition::SL_WARNING,
1312                         ER_INVALID_CHARACTER_STRING,
1313                         ER_THD(current_thd, ER_INVALID_CHARACTER_STRING),
1314                         "ascii", tmp);
1315   }
1316   return res;
1317 
1318 }
1319 
1320 
1321 /**
1322   Check whether a field type can be partially indexed by a key.
1323 
1324   This is a static method, rather than a virtual function, because we need
1325   to check the type of a non-Field in mysql_alter_table().
1326 
1327   @param type  field type
1328 
1329   @retval
1330     TRUE  Type can have a prefixed key
1331   @retval
1332     FALSE Type can not have a prefixed key
1333 */
1334 
type_can_have_key_part(enum enum_field_types type)1335 bool Field::type_can_have_key_part(enum enum_field_types type)
1336 {
1337   switch (type) {
1338   case MYSQL_TYPE_VARCHAR:
1339   case MYSQL_TYPE_TINY_BLOB:
1340   case MYSQL_TYPE_MEDIUM_BLOB:
1341   case MYSQL_TYPE_LONG_BLOB:
1342   case MYSQL_TYPE_BLOB:
1343   case MYSQL_TYPE_VAR_STRING:
1344   case MYSQL_TYPE_STRING:
1345   case MYSQL_TYPE_GEOMETRY:
1346     return TRUE;
1347   default:
1348     return FALSE;
1349   }
1350 }
1351 
1352 
1353 /**
1354   Numeric fields base class constructor.
1355 */
Field_num(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,utype unireg_check_arg,const char * field_name_arg,uint8 dec_arg,bool zero_arg,bool unsigned_arg)1356 Field_num::Field_num(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
1357                      uchar null_bit_arg, utype unireg_check_arg,
1358                      const char *field_name_arg,
1359                      uint8 dec_arg, bool zero_arg, bool unsigned_arg)
1360   :Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
1361          unireg_check_arg, field_name_arg),
1362   dec(dec_arg),zerofill(zero_arg),unsigned_flag(unsigned_arg)
1363 {
1364   if (zerofill)
1365     flags|=ZEROFILL_FLAG;
1366   if (unsigned_flag)
1367     flags|=UNSIGNED_FLAG;
1368 }
1369 
1370 
prepend_zeros(String * value)1371 void Field_num::prepend_zeros(String *value)
1372 {
1373   int diff;
1374   if ((diff= (int) (field_length - value->length())) > 0)
1375   {
1376     const bool error= value->mem_realloc(field_length);
1377     if (!error)
1378     {
1379       memmove(const_cast<char*>(value->ptr()) + field_length - value->length(),
1380             value->ptr(), value->length());
1381       memset(const_cast<char*>(value->ptr()), '0', diff);
1382       value->length(field_length);
1383     }
1384   }
1385 }
1386 
1387 /**
1388   Test if given number is a int.
1389 
1390   @todo
1391     Make this multi-byte-character safe
1392 
1393   @param str		String to test
1394   @param length        Length of 'str'
1395   @param int_end	Pointer to char after last used digit
1396   @param cs		Character set
1397 
1398   @note
1399     This is called after one has called strntoull10rnd() function.
1400 
1401   @return TYPE_OK, TYPE_ERR_BAD_VALUE or TYPE_WARN_TRUNCATED
1402 */
1403 
1404 type_conversion_status
check_int(const CHARSET_INFO * cs,const char * str,size_t length,const char * int_end,int error)1405 Field_num::check_int(const CHARSET_INFO *cs, const char *str, size_t length,
1406                      const char *int_end, int error)
1407 {
1408   /* Test if we get an empty string or wrong integer */
1409   if (str == int_end || error == MY_ERRNO_EDOM)
1410   {
1411     ErrConvString err(str, length, cs);
1412     push_warning_printf(table->in_use, Sql_condition::SL_WARNING,
1413                         ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
1414                         ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
1415                         "integer", err.ptr(), field_name,
1416                         table->in_use->get_stmt_da()->
1417                         current_row_for_condition());
1418     return TYPE_ERR_BAD_VALUE;
1419   }
1420   /* Test if we have garbage at the end of the given string. */
1421   if (test_if_important_data(cs, int_end, str + length))
1422   {
1423     set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
1424     return TYPE_WARN_TRUNCATED;
1425   }
1426   return TYPE_OK;
1427 }
1428 
1429 
1430 /*
1431   Conver a string to an integer then check bounds.
1432 
1433   SYNOPSIS
1434     Field_num::get_int
1435     cs            Character set
1436     from          String to convert
1437     len           Length of the string
1438     rnd           OUT longlong value
1439     unsigned_max  max unsigned value
1440     signed_min    min signed value
1441     signed_max    max signed value
1442 
1443   DESCRIPTION
1444     The function calls strntoull10rnd() to get an integer value then
1445     check bounds and errors returned. In case of any error a warning
1446     is raised.
1447 
1448   @return TYPE_OK, TYPE_WARN_OUT_OF_RANGE, TYPE_ERR_BAD_VALUE or
1449           TYPE_WARN_TRUNCATED
1450 */
1451 
1452 type_conversion_status
get_int(const CHARSET_INFO * cs,const char * from,size_t len,longlong * rnd,ulonglong unsigned_max,longlong signed_min,longlong signed_max)1453 Field_num::get_int(const CHARSET_INFO *cs, const char *from, size_t len,
1454                    longlong *rnd, ulonglong unsigned_max,
1455                    longlong signed_min, longlong signed_max)
1456 {
1457   char *end;
1458   int error;
1459 
1460   *rnd= (longlong) cs->cset->strntoull10rnd(cs, from, len,
1461                                             unsigned_flag, &end,
1462                                             &error);
1463   if (unsigned_flag)
1464   {
1465     if ((((ulonglong) *rnd > unsigned_max) &&
1466          (*rnd= (longlong) unsigned_max)) ||
1467         error == MY_ERRNO_ERANGE)
1468       goto out_of_range;
1469   }
1470   else
1471   {
1472     if (*rnd < signed_min)
1473     {
1474       *rnd= signed_min;
1475       goto out_of_range;
1476     }
1477     else if (*rnd > signed_max)
1478     {
1479       *rnd= signed_max;
1480       goto out_of_range;
1481     }
1482   }
1483   if (table->in_use->count_cuted_fields != 0)
1484     return check_int(cs, from, len, end, error);
1485 
1486   return TYPE_OK;
1487 
1488 out_of_range:
1489   set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
1490   return TYPE_WARN_OUT_OF_RANGE;
1491 }
1492 
1493 
1494 /*
1495   This is a generic method which is executed only for
1496   Field_short, Field_medium, Field_long, Field_longlong and Field_tiny.
1497 
1498   The other field types that come from Field_num override this method:
1499   Field_real (common parent for Field_decimal, Field_float, Field_double),
1500   Field_new_decimal, Field_year.
1501 */
1502 type_conversion_status
store_time(MYSQL_TIME * ltime,uint8 dec_arg MY_ATTRIBUTE ((unused)))1503 Field_num::store_time(MYSQL_TIME *ltime,
1504                       uint8 dec_arg MY_ATTRIBUTE((unused)))
1505 {
1506   longlong nr= TIME_to_ulonglong_round(ltime);
1507   return store(ltime->neg ? -nr : nr, 0);
1508 }
1509 
1510 
1511 /**
1512   Process decimal library return codes and issue warnings for overflow and
1513   truncation.
1514 
1515   @param op_result  decimal library return code (E_DEC_* see include/decimal.h)
1516 
1517   @retval 0 No error or some other errors except overflow
1518   @retval 1 There was overflow
1519 */
1520 
warn_if_overflow(int op_result)1521 bool Field::warn_if_overflow(int op_result)
1522 {
1523   if (op_result == E_DEC_OVERFLOW)
1524   {
1525     set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
1526     return true;
1527   }
1528   if (op_result == E_DEC_TRUNCATED)
1529   {
1530     set_warning(Sql_condition::SL_NOTE, WARN_DATA_TRUNCATED, 1);
1531     /* We return 0 here as this is not a critical issue */
1532   }
1533   return false;
1534 }
1535 
1536 
1537 /**
1538   Interpret field value as an integer but return the result as a string.
1539 
1540   This is used for printing bit_fields as numbers while debugging.
1541 */
1542 
val_int_as_str(String * val_buffer,my_bool unsigned_val)1543 String *Field::val_int_as_str(String *val_buffer, my_bool unsigned_val)
1544 {
1545   ASSERT_COLUMN_MARKED_FOR_READ;
1546   const CHARSET_INFO *cs= &my_charset_bin;
1547   uint length;
1548   longlong value= val_int();
1549 
1550   if (val_buffer->alloc(MY_INT64_NUM_DECIMAL_DIGITS))
1551     return 0;
1552   length= (uint) (*cs->cset->longlong10_to_str)(cs, (char*) val_buffer->ptr(),
1553                                                 MY_INT64_NUM_DECIMAL_DIGITS,
1554                                                 unsigned_val ? 10 : -10,
1555                                                 value);
1556   val_buffer->length(length);
1557   return val_buffer;
1558 }
1559 
1560 
1561 /// This is used as a table name when the table structure is not set up
Field(uchar * ptr_arg,uint32 length_arg,uchar * null_ptr_arg,uchar null_bit_arg,utype unireg_check_arg,const char * field_name_arg)1562 Field::Field(uchar *ptr_arg,uint32 length_arg,uchar *null_ptr_arg,
1563 	     uchar null_bit_arg,
1564 	     utype unireg_check_arg, const char *field_name_arg)
1565   :ptr(ptr_arg),
1566    m_null_ptr(null_ptr_arg),
1567    m_is_tmp_nullable(false),
1568    m_is_tmp_null(false),
1569    table(0), orig_table(0), table_name(0),
1570    field_name(field_name_arg),
1571    unireg_check(unireg_check_arg),
1572    field_length(length_arg), null_bit(null_bit_arg),
1573    is_created_from_null_item(FALSE), m_indexed(false),
1574    m_warnings_pushed(0),
1575    gcol_info(0), stored_in_db(TRUE)
1576 
1577 {
1578   flags=real_maybe_null() ? 0: NOT_NULL_FLAG;
1579   comment.str= (char*) "";
1580   comment.length=0;
1581   field_index= 0;
1582 }
1583 
1584 
1585 /**
1586   Check NOT NULL constraint on the field after temporary nullability is
1587   disabled.
1588 
1589   @param warning_no Warning to report.
1590 
1591   @return TYPE_OK if the value is Ok, or corresponding error code from
1592   the type_conversion_status enum.
1593 */
check_constraints(int mysql_errno)1594 type_conversion_status Field::check_constraints(int mysql_errno)
1595 {
1596   /*
1597     Ensure that Field::check_constraints() is called only when temporary
1598     nullability is disabled.
1599   */
1600 
1601   DBUG_ASSERT(!is_tmp_nullable());
1602 
1603   if (real_maybe_null())
1604     return TYPE_OK; // If the field is nullable, we're Ok.
1605 
1606   if (!m_is_tmp_null)
1607     return TYPE_OK; // If the field was not NULL, we're Ok.
1608 
1609   // The field has been set to NULL.
1610 
1611   /*
1612     If the field is of AUTO_INCREMENT, and the next number
1613     has been assigned to it, we're Ok.
1614   */
1615 
1616   if (this == table->next_number_field)
1617     return TYPE_OK;
1618 
1619   /*
1620     If the field is of TIMESTAMP its default value is CURRENT_TIMESTAMP
1621     and was set before calling this method. Therefore m_is_tmp_null == false
1622     for such field and we leave check_constraints() before this
1623     DBUG_ASSERT is fired.
1624   */
1625   DBUG_ASSERT (type() != MYSQL_TYPE_TIMESTAMP);
1626 
1627   switch (m_count_cuted_fields_saved) {
1628   case CHECK_FIELD_WARN:
1629     set_warning(Sql_condition::SL_WARNING, mysql_errno, 1);
1630     /* fall through */
1631   case CHECK_FIELD_IGNORE:
1632     return TYPE_OK;
1633   case CHECK_FIELD_ERROR_FOR_NULL:
1634     if (!table->in_use->no_errors)
1635       my_error(ER_BAD_NULL_ERROR, MYF(0), field_name);
1636     return TYPE_ERR_NULL_CONSTRAINT_VIOLATION;
1637   }
1638 
1639   DBUG_ASSERT(0); // impossible
1640   return TYPE_ERR_NULL_CONSTRAINT_VIOLATION;
1641 }
1642 
1643 
1644 /**
1645   Set field to value NULL.
1646 
1647   @param row_offset    This is the offset between the row being updated
1648                        and table->record[0]
1649 */
set_null(my_ptrdiff_t row_offset)1650 void Field::set_null(my_ptrdiff_t row_offset)
1651 {
1652   if (real_maybe_null())
1653   {
1654     m_null_ptr[row_offset]|= null_bit;
1655   }
1656   else if (is_tmp_nullable())
1657   {
1658     set_tmp_null();
1659   }
1660 }
1661 
1662 
1663 /**
1664   Set field to value NOT NULL.
1665 
1666   @param row_offset    This is the offset between the row being updated
1667                        and table->record[0]
1668 */
set_notnull(my_ptrdiff_t row_offset)1669 void Field::set_notnull(my_ptrdiff_t row_offset)
1670 {
1671   if (real_maybe_null())
1672   {
1673     m_null_ptr[row_offset]&= (uchar) ~null_bit;
1674   }
1675   else if (is_tmp_nullable())
1676   {
1677     reset_tmp_null();
1678   }
1679 }
1680 
1681 
hash(ulong * nr,ulong * nr2)1682 void Field::hash(ulong *nr, ulong *nr2)
1683 {
1684   if (is_null())
1685   {
1686     *nr^= (*nr << 1) | 1;
1687   }
1688   else
1689   {
1690     uint len= pack_length();
1691     const CHARSET_INFO *cs= sort_charset();
1692     cs->coll->hash_sort(cs, ptr, len, nr, nr2);
1693   }
1694 }
1695 
do_last_null_byte() const1696 size_t Field::do_last_null_byte() const
1697 {
1698   DBUG_ASSERT(!real_maybe_null() || m_null_ptr >= table->record[0]);
1699   return real_maybe_null() ? null_offset() + 1 : (size_t) LAST_NULL_BYTE_UNDEF;
1700 }
1701 
1702 
copy_data(my_ptrdiff_t src_record_offset)1703 void Field::copy_data(my_ptrdiff_t src_record_offset)
1704 {
1705   memcpy(ptr, ptr + src_record_offset, pack_length());
1706 
1707   if (real_maybe_null())
1708   {
1709     // Set to NULL if the source record is NULL, otherwise set to NOT-NULL.
1710     m_null_ptr[0]= (m_null_ptr[0]                 & ~null_bit) |
1711                    (m_null_ptr[src_record_offset] &  null_bit);
1712   } else if (is_tmp_nullable())
1713     m_is_tmp_null= false;
1714 }
1715 
1716 
send_text(Protocol * protocol)1717 bool Field::send_text(Protocol *protocol)
1718 {
1719   if (is_null())
1720     return protocol->store_null();
1721   char buff[MAX_FIELD_WIDTH];
1722   String str(buff, sizeof(buff), &my_charset_bin);
1723 #ifndef DBUG_OFF
1724   my_bitmap_map *old_map= 0;
1725   if (table->file)
1726     old_map= dbug_tmp_use_all_columns(table, table->read_set);
1727 #endif
1728 
1729   String *res= val_str(&str);
1730 #ifndef DBUG_OFF
1731   if (old_map)
1732     dbug_tmp_restore_column_map(table->read_set, old_map);
1733 #endif
1734 
1735   return res ? protocol->store(res) : protocol->store_null();
1736 }
1737 
1738 
send_binary(Protocol * protocol)1739 bool Field::send_binary(Protocol *protocol)
1740 {
1741   char buff[MAX_FIELD_WIDTH];
1742   String tmp(buff,sizeof(buff),charset());
1743   if (is_null())
1744     return protocol->store_null();
1745   String *res= val_str(&tmp);
1746   return res ? protocol->store(res) : protocol->store_null();
1747 }
1748 
1749 
1750 /**
1751    Check to see if field size is compatible with destination.
1752 
1753    This method is used in row-based replication to verify that the
1754    slave's field size is less than or equal to the master's field
1755    size. The encoded field metadata (from the master or source) is
1756    decoded and compared to the size of this field (the slave or
1757    destination).
1758 
1759    @note
1760 
1761    The comparison is made so that if the source data (from the master)
1762    is less than the target data (on the slave), -1 is returned in @c
1763    <code>*order_var</code>. This implies that a conversion is
1764    necessary, but that it is lossy and can result in truncation of the
1765    value.
1766 
1767    If the source data is strictly greater than the target data, 1 is
1768    returned in <code>*order_var</code>. This implies that the source
1769    type can is contained in the target type and that a conversion is
1770    necessary but is non-lossy.
1771 
1772    If no conversion is required to fit the source type in the target
1773    type, 0 is returned in <code>*order_var</code>.
1774 
1775    @param   field_metadata   Encoded size in field metadata
1776    @param   mflags           Flags from the table map event for the table.
1777    @param   order_var        Pointer to variable where the order
1778                              between the source field and this field
1779                              will be returned.
1780 
1781    @return @c true if this field's size is compatible with the
1782    master's field size, @c false otherwise.
1783 */
compatible_field_size(uint field_metadata,Relay_log_info * rli_arg MY_ATTRIBUTE ((unused)),uint16 mflags MY_ATTRIBUTE ((unused)),int * order_var)1784 bool Field::compatible_field_size(uint field_metadata,
1785                                   Relay_log_info *rli_arg MY_ATTRIBUTE((unused)),
1786                                   uint16 mflags MY_ATTRIBUTE((unused)),
1787                                   int *order_var)
1788 {
1789   uint const source_size= pack_length_from_metadata(field_metadata);
1790   uint const destination_size= row_pack_length();
1791   DBUG_PRINT("debug", ("real_type: %d, source_size: %u, destination_size: %u",
1792                        real_type(), source_size, destination_size));
1793   *order_var = compare(source_size, destination_size);
1794   return true;
1795 }
1796 
1797 
1798 type_conversion_status
store(const char * to,size_t length,const CHARSET_INFO * cs,enum_check_fields check_level)1799 Field::store(const char *to, size_t length, const CHARSET_INFO *cs,
1800              enum_check_fields check_level)
1801 {
1802   enum_check_fields old_check_level= table->in_use->count_cuted_fields;
1803   table->in_use->count_cuted_fields= check_level;
1804   const type_conversion_status res= store(to, length, cs);
1805   table->in_use->count_cuted_fields= old_check_level;
1806   return res;
1807 }
1808 
1809 
1810 /**
1811    Pack the field into a format suitable for storage and transfer.
1812 
1813    To implement packing functionality, only the virtual function
1814    should be overridden. The other functions are just convenience
1815    functions and hence should not be overridden.
1816 
1817    The value of <code>low_byte_first</code> is dependent on how the
1818    packed data is going to be used: for local use, e.g., temporary
1819    store on disk or in memory, use the native format since that is
1820    faster. For data that is going to be transfered to other machines
1821    (e.g., when writing data to the binary log), data should always be
1822    stored in little-endian format.
1823 
1824    @note The default method for packing fields just copy the raw bytes
1825    of the record into the destination, but never more than
1826    <code>max_length</code> characters.
1827 
1828    @param to
1829    Pointer to memory area where representation of field should be put.
1830 
1831    @param from
1832    Pointer to memory area where record representation of field is
1833    stored.
1834 
1835    @param max_length
1836    Maximum length of the field, as given in the column definition. For
1837    example, for <code>CHAR(1000)</code>, the <code>max_length</code>
1838    is 1000. This information is sometimes needed to decide how to pack
1839    the data.
1840 
1841    @param low_byte_first
1842    @c TRUE if integers should be stored little-endian, @c FALSE if
1843    native format should be used. Note that for little-endian machines,
1844    the value of this flag is a moot point since the native format is
1845    little-endian.
1846 */
1847 uchar *
pack(uchar * to,const uchar * from,uint max_length,bool low_byte_first MY_ATTRIBUTE ((unused)))1848 Field::pack(uchar *to, const uchar *from, uint max_length,
1849             bool low_byte_first MY_ATTRIBUTE((unused)))
1850 {
1851   uint32 length= pack_length();
1852   set_if_smaller(length, max_length);
1853   memcpy(to, from, length);
1854   return to+length;
1855 }
1856 
1857 /**
1858    Unpack a field from row data.
1859 
1860    This method is used to unpack a field from a master whose size of
1861    the field is less than that of the slave.
1862 
1863    The <code>param_data</code> parameter is a two-byte integer (stored
1864    in the least significant 16 bits of the unsigned integer) usually
1865    consisting of two parts: the real type in the most significant byte
1866    and a original pack length in the least significant byte.
1867 
1868    The exact layout of the <code>param_data</code> field is given by
1869    the <code>Table_map_log_event::save_field_metadata()</code>.
1870 
1871    This is the default method for unpacking a field. It just copies
1872    the memory block in byte order (of original pack length bytes or
1873    length of field, whichever is smaller).
1874 
1875    @param   to         Destination of the data
1876    @param   from       Source of the data
1877    @param   param_data Real type and original pack length of the field
1878                        data
1879 
1880    @param low_byte_first
1881    If this flag is @c true, all composite entities (e.g., lengths)
1882    should be unpacked in little-endian format; otherwise, the entities
1883    are unpacked in native order.
1884 
1885    @return  New pointer into memory based on from + length of the data
1886 */
1887 const uchar *
unpack(uchar * to,const uchar * from,uint param_data,bool low_byte_first MY_ATTRIBUTE ((unused)))1888 Field::unpack(uchar* to, const uchar *from, uint param_data,
1889               bool low_byte_first MY_ATTRIBUTE((unused)))
1890 {
1891   uint length=pack_length();
1892   int from_type= 0;
1893   /*
1894     If from length is > 255, it has encoded data in the upper bits. Need
1895     to mask it out.
1896   */
1897   if (param_data > 255)
1898   {
1899     from_type= (param_data & 0xff00) >> 8U;  // real_type.
1900     param_data= param_data & 0x00ff;        // length.
1901   }
1902 
1903   if ((param_data == 0) ||
1904       (length == param_data) ||
1905       (from_type != real_type()))
1906   {
1907     memcpy(to, from, length);
1908     return from+length;
1909   }
1910 
1911   uint len= (param_data && (param_data < length)) ?
1912             param_data : length;
1913 
1914   memcpy(to, from, param_data > length ? length : len);
1915   return from+len;
1916 }
1917 
1918 
add_zerofill_and_unsigned(String & res) const1919 void Field_num::add_zerofill_and_unsigned(String &res) const
1920 {
1921   if (unsigned_flag)
1922     res.append(STRING_WITH_LEN(" unsigned"));
1923   if (zerofill)
1924     res.append(STRING_WITH_LEN(" zerofill"));
1925 }
1926 
1927 
make_field(Send_field * field)1928 void Field::make_field(Send_field *field)
1929 {
1930   if (orig_table && orig_table->s->db.str && *orig_table->s->db.str)
1931   {
1932     field->db_name= orig_table->s->db.str;
1933     if (orig_table->pos_in_table_list &&
1934         orig_table->pos_in_table_list->schema_table)
1935       field->org_table_name= (orig_table->pos_in_table_list->
1936                               schema_table->table_name);
1937     else
1938       field->org_table_name= orig_table->s->table_name.str;
1939   }
1940   else
1941     field->org_table_name= field->db_name= "";
1942   if (orig_table && orig_table->alias)
1943   {
1944     field->table_name= orig_table->alias;
1945     field->org_col_name= field_name;
1946   }
1947   else
1948   {
1949     field->table_name= "";
1950     field->org_col_name= "";
1951   }
1952   field->col_name= field_name;
1953   field->charsetnr= charset()->number;
1954   field->length=field_length;
1955   field->type=type();
1956   field->flags=table->is_nullable() ? (flags & ~NOT_NULL_FLAG) : flags;
1957   field->decimals= decimals();
1958   field->field= false;
1959 }
1960 
1961 
1962 /**
1963   Conversion from decimal to longlong. Checks overflow and returns
1964   correct value (min/max) in case of overflow.
1965 
1966   @param val             value to be converted
1967   @param unsigned_flag   type of integer to which we convert val
1968   @param has_overflow    true if there is overflow
1969 
1970   @return
1971     value converted from val
1972 */
convert_decimal2longlong(const my_decimal * val,bool unsigned_flag,bool * has_overflow)1973 longlong Field::convert_decimal2longlong(const my_decimal *val,
1974                                          bool unsigned_flag,
1975                                          bool *has_overflow)
1976 {
1977   if (unsigned_flag && val->sign())
1978   {
1979     // Converting a signed decimal to unsigned int
1980     set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
1981     *has_overflow= true;
1982     return 0;
1983   }
1984 
1985   longlong val_ll;
1986   int conversion_error= my_decimal2int(E_DEC_ERROR & ~E_DEC_OVERFLOW
1987                                                    & ~E_DEC_TRUNCATED,
1988                                        val, unsigned_flag, &val_ll);
1989 
1990   if (warn_if_overflow(conversion_error))
1991   {
1992     *has_overflow= true;
1993     if (unsigned_flag)
1994       return ULLONG_MAX;
1995 
1996     return (val->sign() ? LLONG_MIN : LLONG_MAX);
1997   }
1998 
1999   return val_ll;
2000 }
2001 
2002 
2003 /**
2004   Storing decimal in integer fields.
2005 
2006   @param val       value for storing
2007 
2008   @note
2009     This method is used by all integer fields, real/decimal redefine it
2010 
2011   @retval TYPE_OK   Storage of value went fine without warnings or errors
2012   @retval !TYPE_OK  Warning/error as indicated by type_conversion_status enum
2013                     value
2014 */
store_decimal(const my_decimal * val)2015 type_conversion_status Field_num::store_decimal(const my_decimal *val)
2016 {
2017   ASSERT_COLUMN_MARKED_FOR_WRITE;
2018   bool has_overflow= false;
2019   longlong i= convert_decimal2longlong(val, unsigned_flag, &has_overflow);
2020   const type_conversion_status res= store(i, unsigned_flag);
2021   return has_overflow ? TYPE_WARN_OUT_OF_RANGE : res;
2022 }
2023 
2024 
2025 /**
2026   Return decimal value of integer field.
2027 
2028   @param decimal_value     buffer for storing decimal value
2029 
2030   @note
2031     This method is used by all integer fields, real/decimal redefine it.
2032     All longlong values fit in our decimal buffer which cal store 8*9=72
2033     digits of integer number
2034 
2035   @return
2036     pointer to decimal buffer with value of field
2037 */
2038 
val_decimal(my_decimal * decimal_value)2039 my_decimal* Field_num::val_decimal(my_decimal *decimal_value)
2040 {
2041   ASSERT_COLUMN_MARKED_FOR_READ;
2042   DBUG_ASSERT(result_type() == INT_RESULT);
2043   longlong nr= val_int();
2044   int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
2045   return decimal_value;
2046 }
2047 
2048 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)2049 bool Field_num::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
2050 {
2051   DBUG_ASSERT(result_type() == INT_RESULT);
2052   return my_longlong_to_datetime_with_warn(val_int(), ltime, fuzzydate);
2053 }
2054 
2055 
get_time(MYSQL_TIME * ltime)2056 bool Field_num::get_time(MYSQL_TIME *ltime)
2057 {
2058   DBUG_ASSERT(result_type() == INT_RESULT);
2059   return my_longlong_to_time_with_warn(val_int(), ltime);
2060 }
2061 
2062 
Field_str(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,utype unireg_check_arg,const char * field_name_arg,const CHARSET_INFO * charset_arg)2063 Field_str::Field_str(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
2064                      uchar null_bit_arg, utype unireg_check_arg,
2065                      const char *field_name_arg,
2066                      const CHARSET_INFO *charset_arg)
2067   :Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
2068          unireg_check_arg, field_name_arg)
2069 {
2070   field_charset= charset_arg;
2071   if (charset_arg->state & MY_CS_BINSORT)
2072     flags|=BINARY_FLAG;
2073   field_derivation= DERIVATION_IMPLICIT;
2074 }
2075 
2076 
make_field(Send_field * field)2077 void Field_str::make_field(Send_field *field)
2078 {
2079   Field::make_field(field);
2080   field->decimals= 0;
2081 }
2082 
2083 /**
2084   Decimal representation of Field_str.
2085 
2086   @param d         value for storing
2087 
2088   @note
2089     Field_str is the base class for fields implemeting
2090     [VAR]CHAR, VAR[BINARY], BLOB/TEXT, GEOMETRY, JSON.
2091     String value should be converted to floating point value according
2092     our rules, so we use double to store value of decimal in string.
2093 
2094   @todo
2095     use decimal2string?
2096 
2097   @retval
2098     0     OK
2099   @retval
2100     !=0  error
2101 */
2102 
store_decimal(const my_decimal * d)2103 type_conversion_status Field_str::store_decimal(const my_decimal *d)
2104 {
2105   ASSERT_COLUMN_MARKED_FOR_WRITE;
2106   double val;
2107   /* TODO: use decimal2string? */
2108   int err= my_decimal2double(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW, d, &val);
2109   warn_if_overflow(err);
2110   const type_conversion_status res= store(val);
2111 
2112   return (err != E_DEC_OK) ? decimal_err_to_type_conv_status(err) : res;
2113 }
2114 
2115 
fill_cache_field(CACHE_FIELD * copy)2116 uint Field::fill_cache_field(CACHE_FIELD *copy)
2117 {
2118   uint store_length;
2119   copy->str= ptr;
2120   copy->length= pack_length();
2121   copy->field= this;
2122   if (flags & BLOB_FLAG)
2123   {
2124     copy->type= CACHE_BLOB;
2125     copy->length-= portable_sizeof_char_ptr;
2126     return copy->length;
2127   }
2128   else if (!zero_pack() &&
2129            (type() == MYSQL_TYPE_STRING && copy->length >= 4 &&
2130             copy->length < 256))
2131   {
2132     copy->type= CACHE_STRIPPED;			    /* Remove end space */
2133     store_length= 2;
2134   }
2135   else if (type() ==  MYSQL_TYPE_VARCHAR)
2136   {
2137     copy->type= pack_length()-row_pack_length() == 1 ? CACHE_VARSTR1:
2138                                                       CACHE_VARSTR2;
2139     store_length= 0;
2140   }
2141   else
2142   {
2143     copy->type= 0;
2144     store_length= 0;
2145   }
2146   return copy->length + store_length;
2147 }
2148 
2149 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)2150 bool Field::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
2151 {
2152   char buff[MAX_DATE_STRING_REP_LENGTH];
2153   String tmp(buff,sizeof(buff),&my_charset_bin),*res;
2154   return !(res= val_str(&tmp)) ||
2155            str_to_datetime_with_warn(res, ltime, fuzzydate);
2156 }
2157 
2158 
get_time(MYSQL_TIME * ltime)2159 bool Field::get_time(MYSQL_TIME *ltime)
2160 {
2161   char buff[MAX_DATE_STRING_REP_LENGTH];
2162   String tmp(buff,sizeof(buff),&my_charset_bin),*res;
2163   return !(res= val_str(&tmp)) || str_to_time_with_warn(res, ltime);
2164 }
2165 
2166 
get_timestamp(struct timeval * tm,int * warnings)2167 bool Field::get_timestamp(struct timeval *tm, int *warnings)
2168 {
2169   MYSQL_TIME ltime;
2170   DBUG_ASSERT(!is_null());
2171   return get_date(&ltime, TIME_FUZZY_DATE) ||
2172          datetime_to_timeval(current_thd, &ltime, tm, warnings);
2173 }
2174 
2175 
2176 /**
2177   This is called when storing a date in a string.
2178 
2179   @note
2180     Needs to be changed if/when we want to support different time formats.
2181 */
2182 
store_time(MYSQL_TIME * ltime,uint8 dec_arg)2183 type_conversion_status Field::store_time(MYSQL_TIME *ltime, uint8 dec_arg)
2184 {
2185   ASSERT_COLUMN_MARKED_FOR_WRITE;
2186   char buff[MAX_DATE_STRING_REP_LENGTH];
2187   uint length= (uint) my_TIME_to_str(ltime, buff,
2188                                      MY_MIN(dec_arg, DATETIME_MAX_DECIMALS));
2189   /* Avoid conversion when field character set is ASCII compatible */
2190   return store(buff, length, (charset()->state & MY_CS_NONASCII) ?
2191                               &my_charset_latin1 : charset());
2192 }
2193 
2194 
optimize_range(uint idx,uint part)2195 bool Field::optimize_range(uint idx, uint part)
2196 {
2197   return MY_TEST(table->file->index_flags(idx, part, 1) & HA_READ_RANGE);
2198 }
2199 
2200 
new_field(MEM_ROOT * root,TABLE * new_table,bool keep_type MY_ATTRIBUTE ((unused)))2201 Field *Field::new_field(MEM_ROOT *root, TABLE *new_table,
2202                         bool keep_type MY_ATTRIBUTE((unused)))
2203 {
2204   Field *tmp= clone(root);
2205   if (tmp == NULL)
2206     return 0;
2207 
2208   if (tmp->table->is_nullable())
2209     tmp->flags&= ~NOT_NULL_FLAG;
2210   tmp->table= new_table;
2211   tmp->key_start.init(0);
2212   tmp->part_of_key.init(0);
2213   tmp->part_of_sortkey.init(0);
2214   tmp->m_indexed= false;
2215   /*
2216     todo: We should never alter unireg_check after an object is constructed,
2217     and the member should be made const. But a lot of code depends upon this
2218     hack, and the different utype values are completely unrelated so we can
2219     never be quite sure which parts of the server will break.
2220   */
2221   tmp->unireg_check= Field::NONE;
2222   tmp->flags&= (NOT_NULL_FLAG | BLOB_FLAG | UNSIGNED_FLAG |
2223                 ZEROFILL_FLAG | BINARY_FLAG | ENUM_FLAG | SET_FLAG);
2224   tmp->reset_fields();
2225   return tmp;
2226 }
2227 
2228 
new_key_field(MEM_ROOT * root,TABLE * new_table,uchar * new_ptr,uchar * new_null_ptr,uint new_null_bit)2229 Field *Field::new_key_field(MEM_ROOT *root, TABLE *new_table,
2230                             uchar *new_ptr, uchar *new_null_ptr,
2231                             uint new_null_bit)
2232 {
2233   Field *tmp;
2234   if ((tmp= new_field(root, new_table, table == new_table)))
2235   {
2236     tmp->ptr=      new_ptr;
2237     tmp->m_null_ptr= new_null_ptr;
2238     tmp->null_bit= new_null_bit;
2239   }
2240   return tmp;
2241 }
2242 
evaluate_insert_default_function()2243 void Field::evaluate_insert_default_function()
2244 {
2245   if (has_insert_default_function())
2246     Item_func_now_local::store_in(this);
2247 }
2248 
evaluate_update_default_function()2249 void Field::evaluate_update_default_function()
2250 {
2251   if (has_update_default_function())
2252     Item_func_now_local::store_in(this);
2253 }
2254 
2255 /****************************************************************************
2256   Field_null, a field that always return NULL
2257 ****************************************************************************/
2258 
sql_type(String & res) const2259 void Field_null::sql_type(String &res) const
2260 {
2261   res.set_ascii(STRING_WITH_LEN("null"));
2262 }
2263 
2264 
2265 /****************************************************************************
2266   Functions for the Field_decimal class
2267   This is an number stored as a pre-space (or pre-zero) string
2268 ****************************************************************************/
2269 
reset(void)2270 type_conversion_status Field_decimal::reset(void)
2271 {
2272   Field_decimal::store(STRING_WITH_LEN("0"),&my_charset_bin);
2273   return TYPE_OK;
2274 }
2275 
overflow(bool negative)2276 void Field_decimal::overflow(bool negative)
2277 {
2278   uint len=field_length;
2279   uchar *to=ptr, filler= '9';
2280 
2281   set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
2282   if (negative)
2283   {
2284     if (!unsigned_flag)
2285     {
2286       /* Put - sign as a first digit so we'll have -999..999 or 999..999 */
2287       *to++ = '-';
2288       len--;
2289     }
2290     else
2291     {
2292       filler= '0';				// Fill up with 0
2293       if (!zerofill)
2294       {
2295 	/*
2296 	  Handle unsigned integer without zerofill, in which case
2297 	  the number should be of format '   0' or '   0.000'
2298 	*/
2299 	uint whole_part=field_length- (dec ? dec+2 : 1);
2300 	// Fill with spaces up to the first digit
2301 	memset(to, ' ', whole_part);
2302 	to+=  whole_part;
2303 	len-= whole_part;
2304 	// The main code will also handle the 0 before the decimal point
2305       }
2306     }
2307   }
2308   memset(to, filler, len);
2309   if (dec)
2310     ptr[field_length-dec-1]='.';
2311   return;
2312 }
2313 
2314 
store(const char * from_arg,size_t len,const CHARSET_INFO * cs)2315 type_conversion_status Field_decimal::store(const char *from_arg, size_t len,
2316                                             const CHARSET_INFO *cs)
2317 {
2318   ASSERT_COLUMN_MARKED_FOR_WRITE;
2319   char buff[STRING_BUFFER_USUAL_SIZE];
2320   String tmp(buff,sizeof(buff), &my_charset_bin);
2321   const uchar *from= (uchar*) from_arg;
2322 
2323   /* Convert character set if the old one is multi uchar */
2324   if (cs->mbmaxlen > 1)
2325   {
2326     uint dummy_errors;
2327     tmp.copy((char*) from, len, cs, &my_charset_bin, &dummy_errors);
2328     from= (uchar*) tmp.ptr();
2329     len=  tmp.length();
2330   }
2331 
2332   const uchar *end= from+len;
2333   /* The pointer where the field value starts (i.e., "where to write") */
2334   uchar *to= ptr;
2335   uint tmp_dec, tmp_uint;
2336   /*
2337     The sign of the number : will be 0 (means positive but sign not
2338     specified), '+' or '-'
2339   */
2340   uchar sign_char=0;
2341   /* The pointers where prezeros start and stop */
2342   const uchar *pre_zeros_from, *pre_zeros_end;
2343   /* The pointers where digits at the left of '.' start and stop */
2344   const uchar *int_digits_from, *int_digits_end;
2345   /* The pointers where digits at the right of '.' start and stop */
2346   const uchar *frac_digits_from, *frac_digits_end;
2347   /* The sign of the exponent : will be 0 (means no exponent), '+' or '-' */
2348   char expo_sign_char=0;
2349   uint exponent=0;                                // value of the exponent
2350   /*
2351     Pointers used when digits move from the left of the '.' to the
2352     right of the '.' (explained below)
2353   */
2354   const uchar *int_digits_tail_from= NULL;
2355   /* Number of 0 that need to be added at the left of the '.' (1E3: 3 zeros) */
2356   uint int_digits_added_zeros= 0;
2357   /*
2358     Pointer used when digits move from the right of the '.' to the left
2359     of the '.'
2360   */
2361   const uchar *frac_digits_head_end= NULL;
2362   /* Number of 0 that need to be added at the right of the '.' (for 1E-3) */
2363   uint frac_digits_added_zeros= 0;
2364   uchar *pos,*tmp_left_pos,*tmp_right_pos;
2365   /* Pointers that are used as limits (begin and end of the field buffer) */
2366   uchar *left_wall,*right_wall;
2367   uchar tmp_char;
2368   /*
2369     To remember if table->in_use->cuted_fields has already been incremented,
2370     to do that only once
2371   */
2372   bool is_cuted_fields_incr=0;
2373 
2374   /*
2375     There are three steps in this function :
2376     - parse the input string
2377     - modify the position of digits around the decimal dot '.'
2378       according to the exponent value (if specified)
2379     - write the formatted number
2380   */
2381 
2382   if ((tmp_dec=dec))
2383     tmp_dec++;
2384 
2385   /* skip pre-space */
2386   while (from != end && my_isspace(&my_charset_bin,*from))
2387     from++;
2388   if (from == end)
2389   {
2390     set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
2391     is_cuted_fields_incr=1;
2392   }
2393   else if (*from == '+' || *from == '-')	// Found some sign ?
2394   {
2395     sign_char= *from++;
2396     /*
2397       We allow "+" for unsigned decimal unless defined different
2398       Both options allowed as one may wish not to have "+" for unsigned numbers
2399       because of data processing issues
2400     */
2401     if (unsigned_flag)
2402     {
2403       if (sign_char=='-')
2404       {
2405         Field_decimal::overflow(1);
2406         return TYPE_WARN_OUT_OF_RANGE;
2407       }
2408     }
2409   }
2410 
2411   pre_zeros_from= from;
2412   for (; from!=end && *from == '0'; from++) ;	// Read prezeros
2413   pre_zeros_end=int_digits_from=from;
2414   /* Read non zero digits at the left of '.'*/
2415   for (; from != end && my_isdigit(&my_charset_bin, *from) ; from++) ;
2416   int_digits_end=from;
2417   if (from!=end && *from == '.')		// Some '.' ?
2418     from++;
2419   frac_digits_from= from;
2420   /* Read digits at the right of '.' */
2421   for (;from!=end && my_isdigit(&my_charset_bin, *from); from++) ;
2422   frac_digits_end=from;
2423   // Some exponentiation symbol ?
2424   if (from != end && (*from == 'e' || *from == 'E'))
2425   {
2426     from++;
2427     if (from != end && (*from == '+' || *from == '-'))  // Some exponent sign ?
2428       expo_sign_char= *from++;
2429     else
2430       expo_sign_char= '+';
2431     /*
2432       Read digits of the exponent and compute its value.  We must care about
2433       'exponent' overflow, because as unsigned arithmetic is "modulo", big
2434       exponents will become small (e.g. 1e4294967296 will become 1e0, and the
2435       field will finally contain 1 instead of its max possible value).
2436     */
2437     for (;from!=end && my_isdigit(&my_charset_bin, *from); from++)
2438     {
2439       exponent=10*exponent+(*from-'0');
2440       if (exponent>MAX_EXPONENT)
2441         break;
2442     }
2443   }
2444 
2445   /*
2446     We only have to generate warnings if count_cuted_fields is set.
2447     This is to avoid extra checks of the number when they are not needed.
2448     Even if this flag is not set, it's OK to increment warnings, if
2449     it makes the code easer to read.
2450   */
2451 
2452   if (table->in_use->count_cuted_fields)
2453   {
2454     // Skip end spaces
2455     for (;from != end && my_isspace(&my_charset_bin, *from); from++) ;
2456     if (from != end)                     // If still something left, warn
2457     {
2458       set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
2459       is_cuted_fields_incr=1;
2460     }
2461   }
2462 
2463   /*
2464     Now "move" digits around the decimal dot according to the exponent value,
2465     and add necessary zeros.
2466     Examples :
2467     - 1E+3 : needs 3 more zeros at the left of '.' (int_digits_added_zeros=3)
2468     - 1E-3 : '1' moves at the right of '.', and 2 more zeros are needed
2469     between '.' and '1'
2470     - 1234.5E-3 : '234' moves at the right of '.'
2471     These moves are implemented with pointers which point at the begin
2472     and end of each moved segment. Examples :
2473     - 1234.5E-3 : before the code below is executed, the int_digits part is
2474     from '1' to '4' and the frac_digits part from '5' to '5'. After the code
2475     below, the int_digits part is from '1' to '1', the frac_digits_head
2476     part is from '2' to '4', and the frac_digits part from '5' to '5'.
2477     - 1234.5E3 : before the code below is executed, the int_digits part is
2478     from '1' to '4' and the frac_digits part from '5' to '5'. After the code
2479     below, the int_digits part is from '1' to '4', the int_digits_tail
2480     part is from '5' to '5', the frac_digits part is empty, and
2481     int_digits_added_zeros=2 (to make 1234500).
2482   */
2483 
2484   /*
2485      Below tmp_uint cannot overflow with small enough MAX_EXPONENT setting,
2486      as int_digits_added_zeros<=exponent<4G and
2487      (int_digits_end-int_digits_from)<=max_allowed_packet<=2G and
2488      (frac_digits_from-int_digits_tail_from)<=max_allowed_packet<=2G
2489   */
2490 
2491   if (!expo_sign_char)
2492     tmp_uint=tmp_dec+(uint)(int_digits_end-int_digits_from);
2493   else if (expo_sign_char == '-')
2494   {
2495     tmp_uint=min(exponent,(uint)(int_digits_end-int_digits_from));
2496     frac_digits_added_zeros=exponent-tmp_uint;
2497     int_digits_end -= tmp_uint;
2498     frac_digits_head_end=int_digits_end+tmp_uint;
2499     tmp_uint=tmp_dec+(uint)(int_digits_end-int_digits_from);
2500   }
2501   else // (expo_sign_char=='+')
2502   {
2503     tmp_uint=min(exponent,(uint)(frac_digits_end-frac_digits_from));
2504     int_digits_added_zeros=exponent-tmp_uint;
2505     int_digits_tail_from=frac_digits_from;
2506     frac_digits_from=frac_digits_from+tmp_uint;
2507     /*
2508       We "eat" the heading zeros of the
2509       int_digits.int_digits_tail.int_digits_added_zeros concatenation
2510       (for example 0.003e3 must become 3 and not 0003)
2511     */
2512     if (int_digits_from == int_digits_end)
2513     {
2514       /*
2515 	There was nothing in the int_digits part, so continue
2516 	eating int_digits_tail zeros
2517       */
2518       for (; int_digits_tail_from != frac_digits_from &&
2519 	     *int_digits_tail_from == '0'; int_digits_tail_from++) ;
2520       if (int_digits_tail_from == frac_digits_from)
2521       {
2522 	// there were only zeros in int_digits_tail too
2523 	int_digits_added_zeros=0;
2524       }
2525     }
2526     tmp_uint= (uint) (tmp_dec+(int_digits_end-int_digits_from)+
2527                (uint)(frac_digits_from-int_digits_tail_from)+
2528                int_digits_added_zeros);
2529   }
2530 
2531   /*
2532     Now write the formated number
2533 
2534     First the digits of the int_% parts.
2535     Do we have enough room to write these digits ?
2536     If the sign is defined and '-', we need one position for it
2537   */
2538 
2539   if (field_length < tmp_uint + (int) (sign_char == '-'))
2540   {
2541     // too big number, change to max or min number
2542     Field_decimal::overflow(sign_char == '-');
2543     return TYPE_WARN_OUT_OF_RANGE;
2544   }
2545 
2546   /*
2547     Tmp_left_pos is the position where the leftmost digit of
2548     the int_% parts will be written
2549   */
2550   tmp_left_pos=pos=to+(uint)(field_length-tmp_uint);
2551 
2552   // Write all digits of the int_% parts
2553   while (int_digits_from != int_digits_end)
2554     *pos++ = *int_digits_from++ ;
2555 
2556   if (expo_sign_char == '+')
2557   {
2558     while (int_digits_tail_from != frac_digits_from)
2559       *pos++= *int_digits_tail_from++;
2560     while (int_digits_added_zeros-- >0)
2561       *pos++= '0';
2562   }
2563   /*
2564     Note the position where the rightmost digit of the int_% parts has been
2565     written (this is to later check if the int_% parts contained nothing,
2566     meaning an extra 0 is needed).
2567   */
2568   tmp_right_pos=pos;
2569 
2570   /*
2571     Step back to the position of the leftmost digit of the int_% parts,
2572     to write sign and fill with zeros or blanks or prezeros.
2573   */
2574   pos=tmp_left_pos-1;
2575   if (zerofill)
2576   {
2577     left_wall=to-1;
2578     while (pos > left_wall)			// Fill with zeros
2579       *pos--='0';
2580   }
2581   else
2582   {
2583     left_wall=to+(sign_char != 0)-1;
2584     if (!expo_sign_char)	// If exponent was specified, ignore prezeros
2585     {
2586       for (;pos > left_wall && pre_zeros_from !=pre_zeros_end;
2587 	   pre_zeros_from++)
2588 	*pos--= '0';
2589     }
2590     if (pos == tmp_right_pos-1)
2591       *pos--= '0';		// no 0 has ever been written, so write one
2592     left_wall= to-1;
2593     if (sign_char && pos != left_wall)
2594     {
2595       /* Write sign if possible (it is if sign is '-') */
2596       *pos--= sign_char;
2597     }
2598     while (pos != left_wall)
2599       *pos--=' ';  //fill with blanks
2600   }
2601 
2602   /*
2603     Write digits of the frac_% parts ;
2604     Depending on table->in_use->count_cutted_fields, we may also want
2605     to know if some non-zero tail of these parts will
2606     be truncated (for example, 0.002->0.00 will generate a warning,
2607     while 0.000->0.00 will not)
2608     (and 0E1000000000 will not, while 1E-1000000000 will)
2609   */
2610 
2611   pos=to+(uint)(field_length-tmp_dec);	// Calculate post to '.'
2612   right_wall=to+field_length;
2613   if (pos != right_wall)
2614     *pos++='.';
2615 
2616   if (expo_sign_char == '-')
2617   {
2618     while (frac_digits_added_zeros-- > 0)
2619     {
2620       if (pos == right_wall)
2621       {
2622         if (table->in_use->count_cuted_fields && !is_cuted_fields_incr)
2623           break; // Go on below to see if we lose non zero digits
2624         return TYPE_OK;
2625       }
2626       *pos++='0';
2627     }
2628     while (int_digits_end != frac_digits_head_end)
2629     {
2630       tmp_char= *int_digits_end++;
2631       if (pos == right_wall)
2632       {
2633         if (tmp_char != '0')			// Losing a non zero digit ?
2634         {
2635           if (!is_cuted_fields_incr)
2636             set_warning(Sql_condition::SL_WARNING,
2637                         WARN_DATA_TRUNCATED, 1);
2638           return TYPE_OK;
2639         }
2640         continue;
2641       }
2642       *pos++= tmp_char;
2643     }
2644   }
2645 
2646   for (;frac_digits_from!=frac_digits_end;)
2647   {
2648     tmp_char= *frac_digits_from++;
2649     if (pos == right_wall)
2650     {
2651       if (tmp_char != '0')			// Losing a non zero digit ?
2652       {
2653         if (!is_cuted_fields_incr)
2654         {
2655           /*
2656             This is a note, not a warning, as we don't want to abort
2657             when we cut decimals in strict mode
2658           */
2659 	  set_warning(Sql_condition::SL_NOTE, WARN_DATA_TRUNCATED, 1);
2660         }
2661         return TYPE_OK;
2662       }
2663       continue;
2664     }
2665     *pos++= tmp_char;
2666   }
2667 
2668   while (pos != right_wall)
2669    *pos++='0';			// Fill with zeros at right of '.'
2670   return TYPE_OK;
2671 }
2672 
2673 
store(double nr)2674 type_conversion_status Field_decimal::store(double nr)
2675 {
2676   ASSERT_COLUMN_MARKED_FOR_WRITE;
2677   if (unsigned_flag && nr < 0)
2678   {
2679     overflow(1);
2680     return TYPE_WARN_OUT_OF_RANGE;
2681   }
2682 
2683   if (!my_isfinite(nr)) // Handle infinity as special case
2684   {
2685     overflow(nr < 0.0);
2686     return TYPE_WARN_OUT_OF_RANGE;
2687   }
2688 
2689   size_t i;
2690   size_t length;
2691   uchar fyllchar,*to;
2692   char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
2693 
2694   fyllchar = zerofill ? '0' : ' ';
2695   length= my_fcvt(nr, dec, buff, NULL);
2696 
2697   if (length > field_length)
2698   {
2699     overflow(nr < 0.0);
2700     return TYPE_WARN_OUT_OF_RANGE;
2701   }
2702   else
2703   {
2704     to=ptr;
2705     for (i=field_length-length ; i-- > 0 ;)
2706       *to++ = fyllchar;
2707     memcpy(to,buff,length);
2708     return TYPE_OK;
2709   }
2710 }
2711 
2712 
store(longlong nr,bool unsigned_val)2713 type_conversion_status Field_decimal::store(longlong nr, bool unsigned_val)
2714 {
2715   ASSERT_COLUMN_MARKED_FOR_WRITE;
2716   char buff[22];
2717   uint length, int_part;
2718   char fyllchar;
2719   uchar *to;
2720 
2721   if (nr < 0 && unsigned_flag && !unsigned_val)
2722   {
2723     overflow(1);
2724     return TYPE_WARN_OUT_OF_RANGE;
2725   }
2726   length= (uint) (longlong10_to_str(nr,buff,unsigned_val ? 10 : -10) - buff);
2727   int_part= field_length- (dec  ? dec+1 : 0);
2728 
2729   if (length > int_part)
2730   {
2731     overflow(!unsigned_val && nr < 0L);		/* purecov: inspected */
2732     return TYPE_WARN_OUT_OF_RANGE;
2733   }
2734 
2735   fyllchar = zerofill ? '0' : ' ';
2736   to= ptr;
2737   for (uint i=int_part-length ; i-- > 0 ;)
2738     *to++ = fyllchar;
2739   memcpy(to,buff,length);
2740   if (dec)
2741   {
2742     to[length]='.';
2743     memset(to + length + 1, '0', dec);
2744   }
2745   return TYPE_OK;
2746 }
2747 
2748 
val_real(void)2749 double Field_decimal::val_real(void)
2750 {
2751   ASSERT_COLUMN_MARKED_FOR_READ;
2752   int not_used;
2753   char *end_not_used;
2754   return my_strntod(&my_charset_bin, (char*) ptr, field_length, &end_not_used,
2755                     &not_used);
2756 }
2757 
val_int(void)2758 longlong Field_decimal::val_int(void)
2759 {
2760   ASSERT_COLUMN_MARKED_FOR_READ;
2761   int not_used;
2762   if (unsigned_flag)
2763     return my_strntoull(&my_charset_bin, (char*) ptr, field_length, 10, NULL,
2764 			&not_used);
2765   return my_strntoll(&my_charset_bin, (char*) ptr, field_length, 10, NULL,
2766                      &not_used);
2767 }
2768 
2769 
val_str(String * val_buffer MY_ATTRIBUTE ((unused)),String * val_ptr)2770 String *Field_decimal::val_str(String *val_buffer MY_ATTRIBUTE((unused)),
2771 			       String *val_ptr)
2772 {
2773   ASSERT_COLUMN_MARKED_FOR_READ;
2774   uchar *str;
2775   size_t tmp_length;
2776 
2777   for (str=ptr ; *str == ' ' ; str++) ;
2778   val_ptr->set_charset(&my_charset_numeric);
2779   tmp_length= (size_t) (str-ptr);
2780   if (field_length < tmp_length)		// Error in data
2781     val_ptr->length(0);
2782   else
2783     val_ptr->set_ascii((const char*) str, field_length-tmp_length);
2784   return val_ptr;
2785 }
2786 
2787 /**
2788   Should be able to handle at least the following fixed decimal formats:
2789   5.00 , -1.0,  05,  -05, +5 with optional pre/end space
2790 */
2791 
cmp(const uchar * a_ptr,const uchar * b_ptr)2792 int Field_decimal::cmp(const uchar *a_ptr,const uchar *b_ptr)
2793 {
2794   const uchar *end;
2795   int swap=0;
2796   /* First remove prefixes '0', ' ', and '-' */
2797   for (end=a_ptr+field_length;
2798        a_ptr != end &&
2799 	 (*a_ptr == *b_ptr ||
2800 	  ((my_isspace(&my_charset_bin,*a_ptr)  || *a_ptr == '+' ||
2801             *a_ptr == '0') &&
2802 	   (my_isspace(&my_charset_bin,*b_ptr) || *b_ptr == '+' ||
2803             *b_ptr == '0')));
2804        a_ptr++,b_ptr++)
2805   {
2806     if (*a_ptr == '-')				// If both numbers are negative
2807       swap= -1 ^ 1;				// Swap result
2808   }
2809   if (a_ptr == end)
2810     return 0;
2811   if (*a_ptr == '-')
2812     return -1;
2813   if (*b_ptr == '-')
2814     return 1;
2815 
2816   while (a_ptr != end)
2817   {
2818     if (*a_ptr++ != *b_ptr++)
2819       return swap ^ (a_ptr[-1] < b_ptr[-1] ? -1 : 1); // compare digits
2820   }
2821   return 0;
2822 }
2823 
2824 
make_sort_key(uchar * to,size_t length)2825 void Field_decimal::make_sort_key(uchar *to, size_t length)
2826 {
2827   uchar *str,*end;
2828   for (str=ptr,end=ptr+length;
2829        str != end &&
2830 	 ((my_isspace(&my_charset_bin,*str) || *str == '+' ||
2831 	   *str == '0')) ;
2832        str++)
2833     *to++=' ';
2834   if (str == end)
2835     return;					/* purecov: inspected */
2836 
2837   if (*str == '-')
2838   {
2839     *to++=1;					// Smaller than any number
2840     str++;
2841     while (str != end)
2842       if (my_isdigit(&my_charset_bin,*str))
2843 	*to++= (char) ('9' - *str++);
2844       else
2845 	*to++= *str++;
2846   }
2847   else memcpy(to,str,(uint) (end-str));
2848 }
2849 
2850 
sql_type(String & res) const2851 void Field_decimal::sql_type(String &res) const
2852 {
2853   const CHARSET_INFO *cs=res.charset();
2854   uint tmp=field_length;
2855   if (!unsigned_flag)
2856     tmp--;
2857   if (dec)
2858     tmp--;
2859   res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
2860 			  "decimal(%d,%d)",tmp,dec));
2861   add_zerofill_and_unsigned(res);
2862 }
2863 
2864 
2865 /****************************************************************************
2866 ** Field_new_decimal
2867 ****************************************************************************/
2868 
Field_new_decimal(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const char * field_name_arg,uint8 dec_arg,bool zero_arg,bool unsigned_arg)2869 Field_new_decimal::Field_new_decimal(uchar *ptr_arg,
2870                                      uint32 len_arg, uchar *null_ptr_arg,
2871                                      uchar null_bit_arg,
2872                                      enum utype unireg_check_arg,
2873                                      const char *field_name_arg,
2874                                      uint8 dec_arg,bool zero_arg,
2875                                      bool unsigned_arg)
2876   :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
2877              unireg_check_arg, field_name_arg, dec_arg, zero_arg, unsigned_arg)
2878 {
2879   precision= my_decimal_length_to_precision(len_arg, dec_arg, unsigned_arg);
2880   set_if_smaller(precision, DECIMAL_MAX_PRECISION);
2881   DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION) &&
2882               (dec <= DECIMAL_MAX_SCALE));
2883   bin_size= my_decimal_get_binary_size(precision, dec);
2884 }
2885 
2886 
Field_new_decimal(uint32 len_arg,bool maybe_null_arg,const char * name,uint8 dec_arg,bool unsigned_arg)2887 Field_new_decimal::Field_new_decimal(uint32 len_arg,
2888                                      bool maybe_null_arg,
2889                                      const char *name,
2890                                      uint8 dec_arg,
2891                                      bool unsigned_arg)
2892   :Field_num((uchar*) 0, len_arg,
2893              maybe_null_arg ? (uchar*) "": 0, 0,
2894              NONE, name, dec_arg, 0, unsigned_arg)
2895 {
2896   precision= my_decimal_length_to_precision(len_arg, dec_arg, unsigned_arg);
2897   set_if_smaller(precision, DECIMAL_MAX_PRECISION);
2898   DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION) &&
2899               (dec <= DECIMAL_MAX_SCALE));
2900   bin_size= my_decimal_get_binary_size(precision, dec);
2901 }
2902 
2903 
create_from_item(Item * item)2904 Field *Field_new_decimal::create_from_item (Item *item)
2905 {
2906   uint8 dec= item->decimals;
2907   uint8 intg= item->decimal_precision() - dec;
2908   uint32 len= item->max_char_length();
2909 
2910   DBUG_ASSERT (item->result_type() == DECIMAL_RESULT);
2911 
2912   /*
2913     Trying to put too many digits overall in a DECIMAL(prec,dec)
2914     will always throw a warning. We must limit dec to
2915     DECIMAL_MAX_SCALE however to prevent an assert() later.
2916   */
2917 
2918   if (dec > 0)
2919   {
2920     signed int overflow;
2921 
2922     dec= min<int>(dec, DECIMAL_MAX_SCALE);
2923 
2924     /*
2925       If the value still overflows the field with the corrected dec,
2926       we'll throw out decimals rather than integers. This is still
2927       bad and of course throws a truncation warning.
2928       +1: for decimal point
2929       */
2930 
2931     const int required_length=
2932       my_decimal_precision_to_length(intg + dec, dec,
2933                                      item->unsigned_flag);
2934 
2935     overflow= required_length - len;
2936 
2937     if (overflow > 0)
2938       dec= max(0, dec - overflow);            // too long, discard fract
2939     else
2940       /* Corrected value fits. */
2941       len= required_length;
2942   }
2943   return new Field_new_decimal(len, item->maybe_null, item->item_name.ptr(),
2944                                dec, item->unsigned_flag);
2945 }
2946 
2947 
reset(void)2948 type_conversion_status Field_new_decimal::reset(void)
2949 {
2950   store_value(&decimal_zero);
2951   return TYPE_OK;
2952 }
2953 
2954 
2955 /**
2956   Generate max/min decimal value in case of overflow.
2957 
2958   @param decimal_value     buffer for value
2959   @param sign              sign of value which caused overflow
2960 */
2961 
set_value_on_overflow(my_decimal * decimal_value,bool sign)2962 void Field_new_decimal::set_value_on_overflow(my_decimal *decimal_value,
2963                                               bool sign)
2964 {
2965   DBUG_ENTER("Field_new_decimal::set_value_on_overflow");
2966   max_my_decimal(decimal_value, precision, decimals());
2967   if (sign)
2968   {
2969     if (unsigned_flag)
2970       my_decimal_set_zero(decimal_value);
2971     else
2972       decimal_value->sign(TRUE);
2973   }
2974   DBUG_VOID_RETURN;
2975 }
2976 
2977 
2978 /**
2979   Store decimal value in the binary buffer.
2980 
2981   Checks if decimal_value fits into field size.
2982   If it does, stores the decimal in the buffer using binary format.
2983   Otherwise sets maximal number that can be stored in the field.
2984 
2985   @param decimal_value   my_decimal
2986 
2987   @retval
2988     0 ok
2989   @retval
2990     1 error
2991 */
2992 type_conversion_status
store_value(const my_decimal * decimal_value)2993 Field_new_decimal::store_value(const my_decimal *decimal_value)
2994 {
2995   ASSERT_COLUMN_MARKED_FOR_WRITE;
2996   type_conversion_status error= TYPE_OK;
2997   DBUG_ENTER("Field_new_decimal::store_value");
2998 #ifndef DBUG_OFF
2999   {
3000     char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
3001     DBUG_PRINT("enter", ("value: %s", dbug_decimal_as_string(dbug_buff, decimal_value)));
3002   }
3003 #endif
3004 
3005   /* check that we do not try to write negative value in unsigned field */
3006   if (unsigned_flag && decimal_value->sign())
3007   {
3008     DBUG_PRINT("info", ("unsigned overflow"));
3009     set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3010     error= TYPE_WARN_OUT_OF_RANGE;
3011     decimal_value= &decimal_zero;
3012   }
3013 #ifndef DBUG_OFF
3014   {
3015     char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
3016     DBUG_PRINT("info", ("saving with precision %d  scale: %d  value %s",
3017                         (int)precision, (int)dec,
3018                         dbug_decimal_as_string(dbug_buff, decimal_value)));
3019   }
3020 #endif
3021 
3022   int err= my_decimal2binary(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW,
3023                              decimal_value, ptr, precision, dec);
3024   if (warn_if_overflow(err))
3025   {
3026     my_decimal buff;
3027     DBUG_PRINT("info", ("overflow"));
3028     set_value_on_overflow(&buff, decimal_value->sign());
3029     my_decimal2binary(E_DEC_FATAL_ERROR, &buff, ptr, precision, dec);
3030   }
3031   DBUG_EXECUTE("info", print_decimal_buff(decimal_value, ptr,
3032                                           bin_size););
3033   DBUG_RETURN((err != E_DEC_OK) ? decimal_err_to_type_conv_status(err)
3034                                 : error);
3035 }
3036 
3037 
3038 type_conversion_status
store(const char * from,size_t length,const CHARSET_INFO * charset_arg)3039 Field_new_decimal::store(const char *from, size_t length,
3040                          const CHARSET_INFO *charset_arg)
3041 {
3042   ASSERT_COLUMN_MARKED_FOR_WRITE;
3043   my_decimal decimal_value;
3044   DBUG_ENTER("Field_new_decimal::store(char*)");
3045 
3046   int err= str2my_decimal(E_DEC_FATAL_ERROR &
3047                           ~(E_DEC_OVERFLOW | E_DEC_BAD_NUM),
3048                           from, length, charset_arg,
3049                           &decimal_value);
3050 
3051   if (err != 0 && !table->in_use->lex->is_ignore()
3052                && table->in_use->is_strict_mode())
3053   {
3054     ErrConvString errmsg(from, length, charset_arg);
3055     const Diagnostics_area *da= table->in_use->get_stmt_da();
3056     push_warning_printf(table->in_use, Sql_condition::SL_WARNING,
3057                         ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
3058                         ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
3059                         "decimal", errmsg.ptr(), field_name,
3060                         da->current_row_for_condition());
3061     DBUG_RETURN(decimal_err_to_type_conv_status(err));
3062   }
3063 
3064   if (err != 0)
3065     set_decimal_warning(this, err, &decimal_value, from, length, charset_arg);
3066 
3067 #ifndef DBUG_OFF
3068   char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
3069   DBUG_PRINT("enter", ("value: %s",
3070                        dbug_decimal_as_string(dbug_buff, &decimal_value)));
3071 #endif
3072 
3073   type_conversion_status store_stat= store_value(&decimal_value);
3074   DBUG_RETURN(err != 0 ? decimal_err_to_type_conv_status(err) : store_stat);
3075 }
3076 
3077 
3078 type_conversion_status
store_internal_with_error_check(Field_new_decimal * field,int err,my_decimal * value)3079 store_internal_with_error_check(Field_new_decimal *field,
3080                                 int err, my_decimal *value)
3081 {
3082   type_conversion_status stat= TYPE_OK;
3083   if (err != 0)
3084   {
3085     if (field->check_overflow(err))
3086     {
3087       field->set_value_on_overflow(value, value->sign());
3088       stat= TYPE_WARN_OUT_OF_RANGE;
3089     }
3090     else if (field->check_truncated(err))
3091       stat= TYPE_NOTE_TRUNCATED;
3092     /* Only issue a warning if store_value doesn't issue an warning */
3093     field->table->in_use->got_warning= 0;
3094   }
3095   type_conversion_status store_stat= field->store_value(value);
3096   if (store_stat != TYPE_OK)
3097     return store_stat;
3098   else if (err != 0 && !field->table->in_use->got_warning)
3099     field->warn_if_overflow(err);
3100   return stat;
3101 }
3102 
3103 /**
3104   @todo
3105   Fix following when double2my_decimal when double2decimal
3106   will return E_DEC_TRUNCATED always correctly
3107 */
3108 
store(double nr)3109 type_conversion_status Field_new_decimal::store(double nr)
3110 {
3111   ASSERT_COLUMN_MARKED_FOR_WRITE;
3112   DBUG_ENTER("Field_new_decimal::store(double)");
3113   my_decimal decimal_value;
3114 
3115   int conv_err= double2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW, nr,
3116                                   &decimal_value);
3117   DBUG_RETURN(store_internal_with_error_check(this, conv_err, &decimal_value));
3118 }
3119 
3120 type_conversion_status
store(longlong nr,bool unsigned_val)3121 Field_new_decimal::store(longlong nr, bool unsigned_val)
3122 {
3123   ASSERT_COLUMN_MARKED_FOR_WRITE;
3124   DBUG_ENTER("Field_new_decimal::store(double, unsigned_val)");
3125   my_decimal decimal_value;
3126   int conv_err= int2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW,
3127                                nr, unsigned_val, &decimal_value);
3128   DBUG_RETURN(store_internal_with_error_check(this, conv_err, &decimal_value));
3129 }
3130 
3131 
3132 type_conversion_status
store_decimal(const my_decimal * decimal_value)3133 Field_new_decimal::store_decimal(const my_decimal *decimal_value)
3134 {
3135   ASSERT_COLUMN_MARKED_FOR_WRITE;
3136   return store_value(decimal_value);
3137 }
3138 
3139 
3140 type_conversion_status
store_time(MYSQL_TIME * ltime,uint8 dec_arg MY_ATTRIBUTE ((unused)))3141 Field_new_decimal::store_time(MYSQL_TIME *ltime,
3142                                   uint8 dec_arg MY_ATTRIBUTE((unused)))
3143 {
3144   my_decimal decimal_value;
3145   return store_value(date2my_decimal(ltime, &decimal_value));
3146 }
3147 
3148 
val_real(void)3149 double Field_new_decimal::val_real(void)
3150 {
3151   ASSERT_COLUMN_MARKED_FOR_READ;
3152   double dbl;
3153   my_decimal decimal_value;
3154   my_decimal2double(E_DEC_FATAL_ERROR, val_decimal(&decimal_value), &dbl);
3155   return dbl;
3156 }
3157 
3158 
val_int(void)3159 longlong Field_new_decimal::val_int(void)
3160 {
3161   ASSERT_COLUMN_MARKED_FOR_READ;
3162   longlong i;
3163   my_decimal decimal_value;
3164   my_decimal2int(E_DEC_FATAL_ERROR, val_decimal(&decimal_value),
3165                  unsigned_flag, &i);
3166   return i;
3167 }
3168 
3169 
val_decimal(my_decimal * decimal_value)3170 my_decimal* Field_new_decimal::val_decimal(my_decimal *decimal_value)
3171 {
3172   ASSERT_COLUMN_MARKED_FOR_READ;
3173   DBUG_ENTER("Field_new_decimal::val_decimal");
3174   binary2my_decimal(E_DEC_FATAL_ERROR, ptr, decimal_value,
3175                     precision, dec);
3176   DBUG_EXECUTE("info", print_decimal_buff(decimal_value, ptr,
3177                                           bin_size););
3178   DBUG_RETURN(decimal_value);
3179 }
3180 
3181 
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))3182 String *Field_new_decimal::val_str(String *val_buffer,
3183                                    String *val_ptr MY_ATTRIBUTE((unused)))
3184 {
3185   ASSERT_COLUMN_MARKED_FOR_READ;
3186   my_decimal decimal_value;
3187   uint fixed_precision= zerofill ? precision : 0;
3188   my_decimal2string(E_DEC_FATAL_ERROR, val_decimal(&decimal_value),
3189                     fixed_precision, dec, '0', val_buffer);
3190   val_buffer->set_charset(&my_charset_numeric);
3191   return val_buffer;
3192 }
3193 
3194 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)3195 bool Field_new_decimal::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
3196 {
3197   my_decimal buf, *decimal_value= val_decimal(&buf);
3198   if (!decimal_value)
3199   {
3200     set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME);
3201     return true;
3202   }
3203   return my_decimal_to_datetime_with_warn(decimal_value, ltime, fuzzydate);
3204 }
3205 
3206 
get_time(MYSQL_TIME * ltime)3207 bool Field_new_decimal::get_time(MYSQL_TIME *ltime)
3208 {
3209   my_decimal buf, *decimal_value= val_decimal(&buf);
3210   if (!decimal_value)
3211   {
3212     set_zero_time(ltime, MYSQL_TIMESTAMP_TIME);
3213     return true;
3214   }
3215   return my_decimal_to_time_with_warn(decimal_value, ltime);
3216 }
3217 
3218 
cmp(const uchar * a,const uchar * b)3219 int Field_new_decimal::cmp(const uchar *a,const uchar*b)
3220 {
3221   return memcmp(a, b, bin_size);
3222 }
3223 
3224 
make_sort_key(uchar * buff,size_t length)3225 void Field_new_decimal::make_sort_key(uchar *buff, size_t length)
3226 {
3227   memcpy(buff, ptr, min(length, static_cast<size_t>(bin_size)));
3228 }
3229 
3230 
sql_type(String & str) const3231 void Field_new_decimal::sql_type(String &str) const
3232 {
3233   const CHARSET_INFO *cs= str.charset();
3234   str.length(cs->cset->snprintf(cs, (char*) str.ptr(), str.alloced_length(),
3235                                 "decimal(%d,%d)", precision, (int)dec));
3236   add_zerofill_and_unsigned(str);
3237 }
3238 
3239 
3240 /**
3241    Save the field metadata for new decimal fields.
3242 
3243    Saves the precision in the first byte and decimals() in the second
3244    byte of the field metadata array at index of *metadata_ptr and
3245    *(metadata_ptr + 1).
3246 
3247    @param   metadata_ptr   First byte of field metadata
3248 
3249    @returns number of bytes written to metadata_ptr
3250 */
do_save_field_metadata(uchar * metadata_ptr)3251 int Field_new_decimal::do_save_field_metadata(uchar *metadata_ptr)
3252 {
3253   *metadata_ptr= precision;
3254   *(metadata_ptr + 1)= decimals();
3255   return 2;
3256 }
3257 
3258 
3259 /**
3260    Returns the number of bytes field uses in row-based replication
3261    row packed size.
3262 
3263    This method is used in row-based replication to determine the number
3264    of bytes that the field consumes in the row record format. This is
3265    used to skip fields in the master that do not exist on the slave.
3266 
3267    @param   field_metadata   Encoded size in field metadata
3268 
3269    @returns The size of the field based on the field metadata.
3270 */
pack_length_from_metadata(uint field_metadata)3271 uint Field_new_decimal::pack_length_from_metadata(uint field_metadata)
3272 {
3273   uint const source_precision= (field_metadata >> 8U) & 0x00ff;
3274   uint const source_decimal= field_metadata & 0x00ff;
3275   uint const source_size= my_decimal_get_binary_size(source_precision,
3276                                                      source_decimal);
3277   return (source_size);
3278 }
3279 
3280 /**
3281    Check to see if field size is compatible with destination.
3282 
3283    This method is used in row-based replication to verify that the slave's
3284    field size is less than or equal to the master's field size. The
3285    encoded field metadata (from the master or source) is decoded and compared
3286    to the size of this field (the slave or destination).
3287 
3288    @param   field_metadata   Encoded size in field metadata
3289    @param   order_var        Pointer to variable where the order
3290                              between the source field and this field
3291                              will be returned.
3292 
3293    @return @c true
3294 */
compatible_field_size(uint field_metadata,Relay_log_info * MY_ATTRIBUTE ((unused)),uint16 mflags MY_ATTRIBUTE ((unused)),int * order_var)3295 bool Field_new_decimal::compatible_field_size(uint field_metadata,
3296                                               Relay_log_info * MY_ATTRIBUTE((unused)),
3297                                               uint16 mflags MY_ATTRIBUTE((unused)),
3298                                               int *order_var)
3299 {
3300   uint const source_precision= (field_metadata >> 8U) & 0x00ff;
3301   uint const source_decimal= field_metadata & 0x00ff;
3302   int order= compare(source_precision, precision);
3303   *order_var= order != 0 ? order : compare(source_decimal, dec);
3304   return true;
3305 }
3306 
3307 
is_equal(Create_field * new_field)3308 uint Field_new_decimal::is_equal(Create_field *new_field)
3309 {
3310   return ((new_field->sql_type == real_type()) &&
3311           ((new_field->flags & UNSIGNED_FLAG) ==
3312            (uint) (flags & UNSIGNED_FLAG)) &&
3313           ((new_field->flags & AUTO_INCREMENT_FLAG) ==
3314            (uint) (flags & AUTO_INCREMENT_FLAG)) &&
3315           (new_field->length == max_display_length()) &&
3316           (new_field->decimals == dec));
3317 }
3318 
3319 
3320 /**
3321    Unpack a decimal field from row data.
3322 
3323    This method is used to unpack a decimal or numeric field from a master
3324    whose size of the field is less than that of the slave.
3325 
3326    @param   to         Destination of the data
3327    @param   from       Source of the data
3328    @param   param_data Precision (upper) and decimal (lower) values
3329 
3330    @return  New pointer into memory based on from + length of the data
3331 */
3332 const uchar *
unpack(uchar * to,const uchar * from,uint param_data,bool low_byte_first)3333 Field_new_decimal::unpack(uchar* to,
3334                           const uchar *from,
3335                           uint param_data,
3336                           bool low_byte_first)
3337 {
3338   if (param_data == 0)
3339     return Field::unpack(to, from, param_data, low_byte_first);
3340 
3341   uint from_precision= (param_data & 0xff00) >> 8U;
3342   uint from_decimal= param_data & 0x00ff;
3343   uint length=pack_length();
3344   uint from_pack_len= my_decimal_get_binary_size(from_precision, from_decimal);
3345   uint len= (param_data && (from_pack_len < length)) ?
3346             from_pack_len : length;
3347   if ((from_pack_len && (from_pack_len < length)) ||
3348       (from_precision < precision) ||
3349       (from_decimal < decimals()))
3350   {
3351     /*
3352       If the master's data is smaller than the slave, we need to convert
3353       the binary to decimal then resize the decimal converting it back to
3354       a decimal and write that to the raw data buffer.
3355     */
3356     decimal_digit_t dec_buf[DECIMAL_MAX_PRECISION];
3357     decimal_t dec_val;
3358     dec_val.len= from_precision;
3359     dec_val.buf= dec_buf;
3360     /*
3361       Note: bin2decimal does not change the length of the field. So it is
3362       just the first step the resizing operation. The second step does the
3363       resizing using the precision and decimals from the slave.
3364     */
3365     bin2decimal((uchar *)from, &dec_val, from_precision, from_decimal);
3366     decimal2bin(&dec_val, to, precision, decimals());
3367   }
3368   else
3369     memcpy(to, from, len); // Sizes are the same, just copy the data.
3370   return from+len;
3371 }
3372 
send_binary(Protocol * protocol)3373 bool Field_new_decimal::send_binary(Protocol *protocol)
3374 {
3375   my_decimal dec_value;
3376   if (is_null())
3377     return protocol->store_null();
3378   return protocol->store_decimal(val_decimal(&dec_value),
3379                                  zerofill ? precision : 0, dec);
3380 }
3381 
3382 
3383 /****************************************************************************
3384 ** tiny int
3385 ****************************************************************************/
3386 
3387 type_conversion_status
store(const char * from,size_t len,const CHARSET_INFO * cs)3388 Field_tiny::store(const char *from, size_t len, const CHARSET_INFO *cs)
3389 {
3390   ASSERT_COLUMN_MARKED_FOR_WRITE;
3391   longlong rnd;
3392 
3393   const type_conversion_status error= get_int(cs, from, len, &rnd,
3394                                            255, -128, 127);
3395   ptr[0]= unsigned_flag ? (char) (ulonglong) rnd : (char) rnd;
3396   return error;
3397 }
3398 
3399 
store(double nr)3400 type_conversion_status Field_tiny::store(double nr)
3401 {
3402   ASSERT_COLUMN_MARKED_FOR_WRITE;
3403   type_conversion_status error= TYPE_OK;
3404   nr=rint(nr);
3405   if (unsigned_flag)
3406   {
3407     if (nr < 0.0)
3408     {
3409       *ptr=0;
3410       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3411       error= TYPE_WARN_OUT_OF_RANGE;
3412     }
3413     else if (nr > 255.0)
3414     {
3415       *ptr=(char) 255;
3416       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3417       error= TYPE_WARN_OUT_OF_RANGE;
3418     }
3419     else
3420       *ptr=(char) nr;
3421   }
3422   else
3423   {
3424     if (nr < -128.0)
3425     {
3426       *ptr= (char) -128;
3427       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3428       error= TYPE_WARN_OUT_OF_RANGE;
3429     }
3430     else if (nr > 127.0)
3431     {
3432       *ptr=127;
3433       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3434       error= TYPE_WARN_OUT_OF_RANGE;
3435     }
3436     else
3437       *ptr=(char) (int) nr;
3438   }
3439   return error;
3440 }
3441 
3442 
store(longlong nr,bool unsigned_val)3443 type_conversion_status Field_tiny::store(longlong nr, bool unsigned_val)
3444 {
3445   ASSERT_COLUMN_MARKED_FOR_WRITE;
3446   type_conversion_status error= TYPE_OK;
3447 
3448   if (unsigned_flag)
3449   {
3450     if (nr < 0 && !unsigned_val)
3451     {
3452       *ptr= 0;
3453       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3454       error= TYPE_WARN_OUT_OF_RANGE;
3455     }
3456     else if ((ulonglong) nr > (ulonglong) 255)
3457     {
3458       *ptr= (char) 255;
3459       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3460       error= TYPE_WARN_OUT_OF_RANGE;
3461     }
3462     else
3463       *ptr=(char) nr;
3464   }
3465   else
3466   {
3467     if (nr < 0 && unsigned_val)
3468       nr= 256;                                    // Generate overflow
3469     if (nr < -128)
3470     {
3471       *ptr= (char) -128;
3472       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3473       error= TYPE_WARN_OUT_OF_RANGE;
3474     }
3475     else if (nr > 127)
3476     {
3477       *ptr=127;
3478       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3479       error= TYPE_WARN_OUT_OF_RANGE;
3480     }
3481     else
3482       *ptr=(char) nr;
3483   }
3484   return error;
3485 }
3486 
3487 
val_real(void)3488 double Field_tiny::val_real(void)
3489 {
3490   ASSERT_COLUMN_MARKED_FOR_READ;
3491   int tmp= unsigned_flag ? (int) ptr[0] :
3492     (int) ((signed char*) ptr)[0];
3493   return (double) tmp;
3494 }
3495 
3496 
val_int(void)3497 longlong Field_tiny::val_int(void)
3498 {
3499   ASSERT_COLUMN_MARKED_FOR_READ;
3500   int tmp= unsigned_flag ? (int) ptr[0] :
3501     (int) ((signed char*) ptr)[0];
3502   return (longlong) tmp;
3503 }
3504 
3505 
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))3506 String *Field_tiny::val_str(String *val_buffer,
3507 			    String *val_ptr MY_ATTRIBUTE((unused)))
3508 {
3509   ASSERT_COLUMN_MARKED_FOR_READ;
3510   const CHARSET_INFO *cs= &my_charset_numeric;
3511   uint length;
3512   uint mlength=max(field_length+1,5*cs->mbmaxlen);
3513   val_buffer->alloc(mlength);
3514   char *to=(char*) val_buffer->ptr();
3515 
3516   if (unsigned_flag)
3517     length= (uint) cs->cset->long10_to_str(cs,to,mlength, 10,
3518 					   (long) *ptr);
3519   else
3520     length= (uint) cs->cset->long10_to_str(cs,to,mlength,-10,
3521 					   (long) *((signed char*) ptr));
3522 
3523   val_buffer->length(length);
3524   if (zerofill)
3525     prepend_zeros(val_buffer);
3526   val_buffer->set_charset(cs);
3527   return val_buffer;
3528 }
3529 
send_binary(Protocol * protocol)3530 bool Field_tiny::send_binary(Protocol *protocol)
3531 {
3532   if (is_null())
3533     return protocol->store_null();
3534   return protocol->store_tiny((longlong) unsigned_flag? (uint8) ptr[0]:
3535                                                          (int8) ptr[0]);
3536 }
3537 
cmp(const uchar * a_ptr,const uchar * b_ptr)3538 int Field_tiny::cmp(const uchar *a_ptr, const uchar *b_ptr)
3539 {
3540   signed char a,b;
3541   a=(signed char) a_ptr[0]; b= (signed char) b_ptr[0];
3542   if (unsigned_flag)
3543     return ((uchar) a < (uchar) b) ? -1 : ((uchar) a > (uchar) b) ? 1 : 0;
3544   return (a < b) ? -1 : (a > b) ? 1 : 0;
3545 }
3546 
make_sort_key(uchar * to,size_t length)3547 void Field_tiny::make_sort_key(uchar *to, size_t length)
3548 {
3549   DBUG_ASSERT(length >= 1);
3550   if (unsigned_flag)
3551     *to= *ptr;
3552   else
3553     to[0] = (char) (ptr[0] ^ (uchar) 128);	/* Revers signbit */
3554 }
3555 
sql_type(String & res) const3556 void Field_tiny::sql_type(String &res) const
3557 {
3558   const CHARSET_INFO *cs=res.charset();
3559   res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
3560 			  "tinyint(%d)",(int) field_length));
3561   add_zerofill_and_unsigned(res);
3562 }
3563 
3564 /****************************************************************************
3565  Field type short int (2 byte)
3566 ****************************************************************************/
3567 
3568 type_conversion_status
store(const char * from,size_t len,const CHARSET_INFO * cs)3569 Field_short::store(const char *from, size_t len, const CHARSET_INFO *cs)
3570 {
3571   ASSERT_COLUMN_MARKED_FOR_WRITE;
3572   int store_tmp;
3573   longlong rnd;
3574 
3575   const type_conversion_status error=
3576     get_int(cs, from, len, &rnd, UINT_MAX16, INT_MIN16, INT_MAX16);
3577   store_tmp= unsigned_flag ? (int) (ulonglong) rnd : (int) rnd;
3578 #ifdef WORDS_BIGENDIAN
3579   if (table->s->db_low_byte_first)
3580   {
3581     int2store(ptr, store_tmp);
3582   }
3583   else
3584 #endif
3585     shortstore(ptr, (short) store_tmp);
3586   return error;
3587 }
3588 
3589 
store(double nr)3590 type_conversion_status Field_short::store(double nr)
3591 {
3592   ASSERT_COLUMN_MARKED_FOR_WRITE;
3593   type_conversion_status error= TYPE_OK;
3594   int16 res;
3595   nr=rint(nr);
3596   if (unsigned_flag)
3597   {
3598     if (nr < 0)
3599     {
3600       res=0;
3601       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3602       error= TYPE_WARN_OUT_OF_RANGE;
3603     }
3604     else if (nr > (double) UINT_MAX16)
3605     {
3606       res=(int16) UINT_MAX16;
3607       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3608       error= TYPE_WARN_OUT_OF_RANGE;
3609     }
3610     else
3611       res=(int16) (uint16) nr;
3612   }
3613   else
3614   {
3615     if (nr < (double) INT_MIN16)
3616     {
3617       res=INT_MIN16;
3618       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3619       error= TYPE_WARN_OUT_OF_RANGE;
3620     }
3621     else if (nr > (double) INT_MAX16)
3622     {
3623       res=INT_MAX16;
3624       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3625       error= TYPE_WARN_OUT_OF_RANGE;
3626     }
3627     else
3628       res=(int16) (int) nr;
3629   }
3630 #ifdef WORDS_BIGENDIAN
3631   if (table->s->db_low_byte_first)
3632   {
3633     int2store(ptr,res);
3634   }
3635   else
3636 #endif
3637     shortstore(ptr,res);
3638   return error;
3639 }
3640 
3641 
store(longlong nr,bool unsigned_val)3642 type_conversion_status Field_short::store(longlong nr, bool unsigned_val)
3643 {
3644   ASSERT_COLUMN_MARKED_FOR_WRITE;
3645   type_conversion_status error= TYPE_OK;
3646   int16 res;
3647 
3648   if (unsigned_flag)
3649   {
3650     if (nr < 0L && !unsigned_val)
3651     {
3652       res=0;
3653       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3654       error= TYPE_WARN_OUT_OF_RANGE;
3655     }
3656     else if ((ulonglong) nr > (ulonglong) UINT_MAX16)
3657     {
3658       res=(int16) UINT_MAX16;
3659       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3660       error= TYPE_WARN_OUT_OF_RANGE;
3661     }
3662     else
3663       res=(int16) (uint16) nr;
3664   }
3665   else
3666   {
3667     if (nr < 0 && unsigned_val)
3668       nr= UINT_MAX16+1;                         // Generate overflow
3669 
3670     if (nr < INT_MIN16)
3671     {
3672       res=INT_MIN16;
3673       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3674       error= TYPE_WARN_OUT_OF_RANGE;
3675     }
3676     else if (nr > (longlong) INT_MAX16)
3677     {
3678       res=INT_MAX16;
3679       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3680       error= TYPE_WARN_OUT_OF_RANGE;
3681     }
3682     else
3683       res=(int16) nr;
3684   }
3685 #ifdef WORDS_BIGENDIAN
3686   if (table->s->db_low_byte_first)
3687   {
3688     int2store(ptr,res);
3689   }
3690   else
3691 #endif
3692     shortstore(ptr,res);
3693   return error;
3694 }
3695 
3696 
val_real(void)3697 double Field_short::val_real(void)
3698 {
3699   ASSERT_COLUMN_MARKED_FOR_READ;
3700   short j;
3701 #ifdef WORDS_BIGENDIAN
3702   if (table->s->db_low_byte_first)
3703     j=sint2korr(ptr);
3704   else
3705 #endif
3706     shortget(&j, ptr);
3707   return unsigned_flag ? (double) (unsigned short) j : (double) j;
3708 }
3709 
val_int(void)3710 longlong Field_short::val_int(void)
3711 {
3712   ASSERT_COLUMN_MARKED_FOR_READ;
3713   short j;
3714 #ifdef WORDS_BIGENDIAN
3715   if (table->s->db_low_byte_first)
3716     j=sint2korr(ptr);
3717   else
3718 #endif
3719     shortget(&j, ptr);
3720   return unsigned_flag ? (longlong) (unsigned short) j : (longlong) j;
3721 }
3722 
3723 
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))3724 String *Field_short::val_str(String *val_buffer,
3725 			     String *val_ptr MY_ATTRIBUTE((unused)))
3726 {
3727   ASSERT_COLUMN_MARKED_FOR_READ;
3728   const CHARSET_INFO *cs= &my_charset_numeric;
3729   uint length;
3730   uint mlength=max(field_length+1,7*cs->mbmaxlen);
3731   val_buffer->alloc(mlength);
3732   char *to=(char*) val_buffer->ptr();
3733   short j;
3734 #ifdef WORDS_BIGENDIAN
3735   if (table->s->db_low_byte_first)
3736     j=sint2korr(ptr);
3737   else
3738 #endif
3739     shortget(&j, ptr);
3740 
3741   if (unsigned_flag)
3742     length=(uint) cs->cset->long10_to_str(cs, to, mlength, 10,
3743 					  (long) (uint16) j);
3744   else
3745     length=(uint) cs->cset->long10_to_str(cs, to, mlength,-10, (long) j);
3746   val_buffer->length(length);
3747   if (zerofill)
3748     prepend_zeros(val_buffer);
3749   val_buffer->set_charset(cs);
3750   return val_buffer;
3751 }
3752 
3753 
send_binary(Protocol * protocol)3754 bool Field_short::send_binary(Protocol *protocol)
3755 {
3756   if (is_null())
3757     return protocol->store_null();
3758   return protocol->store_short(Field_short::val_int());
3759 }
3760 
3761 
cmp(const uchar * a_ptr,const uchar * b_ptr)3762 int Field_short::cmp(const uchar *a_ptr, const uchar *b_ptr)
3763 {
3764   short a,b;
3765 #ifdef WORDS_BIGENDIAN
3766   if (table->s->db_low_byte_first)
3767   {
3768     a=sint2korr(a_ptr);
3769     b=sint2korr(b_ptr);
3770   }
3771   else
3772 #endif
3773   {
3774     shortget(&a, a_ptr);
3775     shortget(&b, b_ptr);
3776   }
3777 
3778   if (unsigned_flag)
3779     return ((unsigned short) a < (unsigned short) b) ? -1 :
3780     ((unsigned short) a > (unsigned short) b) ? 1 : 0;
3781   return (a < b) ? -1 : (a > b) ? 1 : 0;
3782 }
3783 
make_sort_key(uchar * to,size_t length)3784 void Field_short::make_sort_key(uchar *to, size_t length)
3785 {
3786   DBUG_ASSERT(length >= 2);
3787 #ifdef WORDS_BIGENDIAN
3788   if (!table->s->db_low_byte_first)
3789   {
3790     if (unsigned_flag)
3791       to[0] = ptr[0];
3792     else
3793       to[0] = (char) (ptr[0] ^ 128);		/* Revers signbit */
3794     to[1]   = ptr[1];
3795   }
3796   else
3797 #endif
3798   {
3799     if (unsigned_flag)
3800       to[0] = ptr[1];
3801     else
3802       to[0] = (char) (ptr[1] ^ 128);		/* Revers signbit */
3803     to[1]   = ptr[0];
3804   }
3805 }
3806 
sql_type(String & res) const3807 void Field_short::sql_type(String &res) const
3808 {
3809   const CHARSET_INFO *cs=res.charset();
3810   res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
3811 			  "smallint(%d)",(int) field_length));
3812   add_zerofill_and_unsigned(res);
3813 }
3814 
3815 
3816 /****************************************************************************
3817   Field type medium int (3 byte)
3818 ****************************************************************************/
3819 
store(const char * from,size_t len,const CHARSET_INFO * cs)3820 type_conversion_status Field_medium::store(const char *from, size_t len,
3821                                            const CHARSET_INFO *cs)
3822 {
3823   ASSERT_COLUMN_MARKED_FOR_WRITE;
3824   int store_tmp;
3825   longlong rnd;
3826 
3827   const type_conversion_status error=
3828     get_int(cs, from, len, &rnd, UINT_MAX24, INT_MIN24, INT_MAX24);
3829   store_tmp= unsigned_flag ? (int) (ulonglong) rnd : (int) rnd;
3830   int3store(ptr, store_tmp);
3831   return error;
3832 }
3833 
3834 
store(double nr)3835 type_conversion_status Field_medium::store(double nr)
3836 {
3837   ASSERT_COLUMN_MARKED_FOR_WRITE;
3838   type_conversion_status error= TYPE_OK;
3839   nr=rint(nr);
3840   if (unsigned_flag)
3841   {
3842     if (nr < 0)
3843     {
3844       int3store(ptr,0);
3845       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3846       error= TYPE_WARN_OUT_OF_RANGE;
3847     }
3848     else if (nr >= (double) (long) (1L << 24))
3849     {
3850       uint32 tmp=(uint32) (1L << 24)-1L;
3851       int3store(ptr,tmp);
3852       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3853       error= TYPE_WARN_OUT_OF_RANGE;
3854     }
3855     else
3856       int3store(ptr,(uint32) nr);
3857   }
3858   else
3859   {
3860     if (nr < (double) INT_MIN24)
3861     {
3862       long tmp=(long) INT_MIN24;
3863       int3store(ptr,tmp);
3864       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3865       error= TYPE_WARN_OUT_OF_RANGE;
3866     }
3867     else if (nr > (double) INT_MAX24)
3868     {
3869       long tmp=(long) INT_MAX24;
3870       int3store(ptr,tmp);
3871       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3872       error= TYPE_WARN_OUT_OF_RANGE;
3873     }
3874     else
3875       int3store(ptr,(long) nr);
3876   }
3877   return error;
3878 }
3879 
3880 
store(longlong nr,bool unsigned_val)3881 type_conversion_status Field_medium::store(longlong nr, bool unsigned_val)
3882 {
3883   ASSERT_COLUMN_MARKED_FOR_WRITE;
3884   type_conversion_status error= TYPE_OK;
3885 
3886   if (unsigned_flag)
3887   {
3888     if (nr < 0 && !unsigned_val)
3889     {
3890       int3store(ptr,0);
3891       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3892       error= TYPE_WARN_OUT_OF_RANGE;
3893     }
3894     else if ((ulonglong) nr >= (ulonglong) (long) (1L << 24))
3895     {
3896       long tmp= (long) (1L << 24)-1L;
3897       int3store(ptr,tmp);
3898       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3899       error= TYPE_WARN_OUT_OF_RANGE;
3900     }
3901     else
3902       int3store(ptr,(uint32) nr);
3903   }
3904   else
3905   {
3906     if (nr < 0 && unsigned_val)
3907       nr= (ulonglong) (long) (1L << 24);        // Generate overflow
3908 
3909     if (nr < (longlong) INT_MIN24)
3910     {
3911       long tmp= (long) INT_MIN24;
3912       int3store(ptr,tmp);
3913       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3914       error= TYPE_WARN_OUT_OF_RANGE;
3915     }
3916     else if (nr > (longlong) INT_MAX24)
3917     {
3918       long tmp=(long) INT_MAX24;
3919       int3store(ptr,tmp);
3920       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
3921       error= TYPE_WARN_OUT_OF_RANGE;
3922     }
3923     else
3924       int3store(ptr,(long) nr);
3925   }
3926   return error;
3927 }
3928 
3929 
val_real(void)3930 double Field_medium::val_real(void)
3931 {
3932   ASSERT_COLUMN_MARKED_FOR_READ;
3933   long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
3934   return (double) j;
3935 }
3936 
3937 
val_int(void)3938 longlong Field_medium::val_int(void)
3939 {
3940   ASSERT_COLUMN_MARKED_FOR_READ;
3941   long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
3942   return (longlong) j;
3943 }
3944 
3945 
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))3946 String *Field_medium::val_str(String *val_buffer,
3947 			      String *val_ptr MY_ATTRIBUTE((unused)))
3948 {
3949   ASSERT_COLUMN_MARKED_FOR_READ;
3950   const CHARSET_INFO *cs= &my_charset_numeric;
3951   uint length;
3952   uint mlength=max(field_length+1,10*cs->mbmaxlen);
3953   val_buffer->alloc(mlength);
3954   char *to=(char*) val_buffer->ptr();
3955   long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
3956 
3957   length=(uint) cs->cset->long10_to_str(cs,to,mlength,-10,j);
3958   val_buffer->length(length);
3959   if (zerofill)
3960     prepend_zeros(val_buffer); /* purecov: inspected */
3961   val_buffer->set_charset(cs);
3962   return val_buffer;
3963 }
3964 
3965 
send_binary(Protocol * protocol)3966 bool Field_medium::send_binary(Protocol *protocol)
3967 {
3968   ASSERT_COLUMN_MARKED_FOR_READ;
3969   if (is_null())
3970     return protocol->store_null();
3971   return protocol->store_long(Field_medium::val_int());
3972 }
3973 
3974 
cmp(const uchar * a_ptr,const uchar * b_ptr)3975 int Field_medium::cmp(const uchar *a_ptr, const uchar *b_ptr)
3976 {
3977   long a,b;
3978   if (unsigned_flag)
3979   {
3980     a=uint3korr(a_ptr);
3981     b=uint3korr(b_ptr);
3982   }
3983   else
3984   {
3985     a=sint3korr(a_ptr);
3986     b=sint3korr(b_ptr);
3987   }
3988   return (a < b) ? -1 : (a > b) ? 1 : 0;
3989 }
3990 
make_sort_key(uchar * to,size_t length)3991 void Field_medium::make_sort_key(uchar *to, size_t length)
3992 {
3993   DBUG_ASSERT(length >= 3);
3994   if (unsigned_flag)
3995     to[0] = ptr[2];
3996   else
3997     to[0] = (uchar) (ptr[2] ^ 128);		/* Revers signbit */
3998   to[1] = ptr[1];
3999   to[2] = ptr[0];
4000 }
4001 
4002 
sql_type(String & res) const4003 void Field_medium::sql_type(String &res) const
4004 {
4005   const CHARSET_INFO *cs=res.charset();
4006   res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
4007 			  "mediumint(%d)",(int) field_length));
4008   add_zerofill_and_unsigned(res);
4009 }
4010 
4011 /****************************************************************************
4012 ** long int
4013 ****************************************************************************/
4014 
store(const char * from,size_t len,const CHARSET_INFO * cs)4015 type_conversion_status Field_long::store(const char *from, size_t len,
4016                                          const CHARSET_INFO *cs)
4017 {
4018   ASSERT_COLUMN_MARKED_FOR_WRITE;
4019   long store_tmp;
4020   longlong rnd;
4021 
4022   const type_conversion_status error=
4023     get_int(cs, from, len, &rnd, UINT_MAX32, INT_MIN32, INT_MAX32);
4024   store_tmp= unsigned_flag ? (long) (ulonglong) rnd : (long) rnd;
4025 #ifdef WORDS_BIGENDIAN
4026   if (table->s->db_low_byte_first)
4027   {
4028     int4store(ptr, store_tmp);
4029   }
4030   else
4031 #endif
4032     longstore(ptr, store_tmp);
4033   return error;
4034 }
4035 
4036 
store(double nr)4037 type_conversion_status Field_long::store(double nr)
4038 {
4039   ASSERT_COLUMN_MARKED_FOR_WRITE;
4040   type_conversion_status error= TYPE_OK;
4041   int32 res;
4042   nr=rint(nr);
4043   if (unsigned_flag)
4044   {
4045     if (nr < 0)
4046     {
4047       res=0;
4048       error= TYPE_WARN_OUT_OF_RANGE;
4049     }
4050     else if (nr > (double) UINT_MAX32)
4051     {
4052       res= UINT_MAX32;
4053       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
4054       error= TYPE_WARN_OUT_OF_RANGE;
4055     }
4056     else
4057       res=(int32) (ulong) nr;
4058   }
4059   else
4060   {
4061     if (nr < (double) INT_MIN32)
4062     {
4063       res=(int32) INT_MIN32;
4064       error= TYPE_WARN_OUT_OF_RANGE;
4065     }
4066     else if (nr > (double) INT_MAX32)
4067     {
4068       res=(int32) INT_MAX32;
4069       error= TYPE_WARN_OUT_OF_RANGE;
4070     }
4071     else
4072       res=(int32) (longlong) nr;
4073   }
4074   if (error)
4075     set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
4076 
4077 #ifdef WORDS_BIGENDIAN
4078   if (table->s->db_low_byte_first)
4079   {
4080     int4store(ptr,res);
4081   }
4082   else
4083 #endif
4084     longstore(ptr,res);
4085   return error;
4086 }
4087 
4088 
4089 /**
4090   Store a longlong in the field
4091 
4092   @param nr            the value to store
4093   @param unsigned_val  whether or not 'nr' should be interpreted as
4094                        signed or unsigned. E.g., if 'nr' has all bits
4095                        set it is interpreted as -1 if unsigned_val is
4096                        false and ULLONG_MAX if unsigned_val is true.
4097 */
store(longlong nr,bool unsigned_val)4098 type_conversion_status Field_long::store(longlong nr, bool unsigned_val)
4099 {
4100   ASSERT_COLUMN_MARKED_FOR_WRITE;
4101   type_conversion_status error= TYPE_OK;
4102   int32 res;
4103 
4104   if (unsigned_flag)
4105   {
4106     if (nr < 0 && !unsigned_val)
4107     {
4108       res=0;
4109       error= TYPE_WARN_OUT_OF_RANGE;
4110     }
4111     else if ((ulonglong) nr >= (1LL << 32))
4112     {
4113       res=(int32) (uint32) ~0L;
4114       error= TYPE_WARN_OUT_OF_RANGE;
4115     }
4116     else
4117       res=(int32) (uint32) nr;
4118   }
4119   else
4120   {
4121     if (nr < 0 && unsigned_val)
4122     {
4123       nr= ((longlong) INT_MAX32) + 1;           // Generate overflow
4124       error= TYPE_WARN_OUT_OF_RANGE;
4125     }
4126     if (nr < (longlong) INT_MIN32)
4127     {
4128       res=(int32) INT_MIN32;
4129       error= TYPE_WARN_OUT_OF_RANGE;
4130     }
4131     else if (nr > (longlong) INT_MAX32)
4132     {
4133       res=(int32) INT_MAX32;
4134       error= TYPE_WARN_OUT_OF_RANGE;
4135     }
4136     else
4137       res=(int32) nr;
4138   }
4139   if (error)
4140     set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
4141 
4142 #ifdef WORDS_BIGENDIAN
4143   if (table->s->db_low_byte_first)
4144   {
4145     int4store(ptr,res);
4146   }
4147   else
4148 #endif
4149     longstore(ptr,res);
4150   return error;
4151 }
4152 
4153 
val_real(void)4154 double Field_long::val_real(void)
4155 {
4156   ASSERT_COLUMN_MARKED_FOR_READ;
4157   int32 j;
4158 #ifdef WORDS_BIGENDIAN
4159   if (table->s->db_low_byte_first)
4160     j=sint4korr(ptr);
4161   else
4162 #endif
4163     longget(&j, ptr);
4164   return unsigned_flag ? (double) (uint32) j : (double) j;
4165 }
4166 
val_int(void)4167 longlong Field_long::val_int(void)
4168 {
4169   ASSERT_COLUMN_MARKED_FOR_READ;
4170   int32 j;
4171   /* See the comment in Field_long::store(long long) */
4172   DBUG_ASSERT(table->in_use == current_thd);
4173 #ifdef WORDS_BIGENDIAN
4174   if (table->s->db_low_byte_first)
4175     j=sint4korr(ptr);
4176   else
4177 #endif
4178     longget(&j, ptr);
4179   return unsigned_flag ? (longlong) (uint32) j : (longlong) j;
4180 }
4181 
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))4182 String *Field_long::val_str(String *val_buffer,
4183 			    String *val_ptr MY_ATTRIBUTE((unused)))
4184 {
4185   ASSERT_COLUMN_MARKED_FOR_READ;
4186   const CHARSET_INFO *cs= &my_charset_numeric;
4187   size_t length;
4188   uint mlength=max(field_length+1,12*cs->mbmaxlen);
4189   val_buffer->alloc(mlength);
4190   char *to=(char*) val_buffer->ptr();
4191   int32 j;
4192 #ifdef WORDS_BIGENDIAN
4193   if (table->s->db_low_byte_first)
4194     j=sint4korr(ptr);
4195   else
4196 #endif
4197     longget(&j, ptr);
4198 
4199   if (unsigned_flag)
4200     length=cs->cset->long10_to_str(cs,to,mlength, 10,(long) (uint32)j);
4201   else
4202     length=cs->cset->long10_to_str(cs,to,mlength,-10,(long) j);
4203   val_buffer->length(length);
4204   if (zerofill)
4205     prepend_zeros(val_buffer);
4206   val_buffer->set_charset(cs);
4207   return val_buffer;
4208 }
4209 
4210 
send_binary(Protocol * protocol)4211 bool Field_long::send_binary(Protocol *protocol)
4212 {
4213   ASSERT_COLUMN_MARKED_FOR_READ;
4214   if (is_null())
4215     return protocol->store_null();
4216   return protocol->store_long(Field_long::val_int());
4217 }
4218 
cmp(const uchar * a_ptr,const uchar * b_ptr)4219 int Field_long::cmp(const uchar *a_ptr, const uchar *b_ptr)
4220 {
4221   int32 a,b;
4222 #ifdef WORDS_BIGENDIAN
4223   if (table->s->db_low_byte_first)
4224   {
4225     a=sint4korr(a_ptr);
4226     b=sint4korr(b_ptr);
4227   }
4228   else
4229 #endif
4230   {
4231     longget(&a, a_ptr);
4232     longget(&b, b_ptr);
4233   }
4234   if (unsigned_flag)
4235     return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
4236   return (a < b) ? -1 : (a > b) ? 1 : 0;
4237 }
4238 
make_sort_key(uchar * to,size_t length)4239 void Field_long::make_sort_key(uchar *to, size_t length)
4240 {
4241   DBUG_ASSERT(length >= 4);
4242 #ifdef WORDS_BIGENDIAN
4243   if (!table->s->db_low_byte_first)
4244   {
4245     if (unsigned_flag)
4246       to[0] = ptr[0];
4247     else
4248       to[0] = (char) (ptr[0] ^ 128);		/* Revers signbit */
4249     to[1]   = ptr[1];
4250     to[2]   = ptr[2];
4251     to[3]   = ptr[3];
4252   }
4253   else
4254 #endif
4255   {
4256     if (unsigned_flag)
4257       to[0] = ptr[3];
4258     else
4259       to[0] = (char) (ptr[3] ^ 128);		/* Revers signbit */
4260     to[1]   = ptr[2];
4261     to[2]   = ptr[1];
4262     to[3]   = ptr[0];
4263   }
4264 }
4265 
4266 
sql_type(String & res) const4267 void Field_long::sql_type(String &res) const
4268 {
4269   const CHARSET_INFO *cs=res.charset();
4270   res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
4271 			  "int(%d)",(int) field_length));
4272   add_zerofill_and_unsigned(res);
4273 }
4274 
4275 /****************************************************************************
4276  Field type longlong int (8 bytes)
4277 ****************************************************************************/
4278 
4279 type_conversion_status
store(const char * from,size_t len,const CHARSET_INFO * cs)4280 Field_longlong::store(const char *from, size_t len, const CHARSET_INFO *cs)
4281 {
4282   ASSERT_COLUMN_MARKED_FOR_WRITE;
4283   int conv_err= 0;
4284   type_conversion_status error= TYPE_OK;
4285   char *end;
4286   ulonglong tmp;
4287 
4288   tmp= cs->cset->strntoull10rnd(cs,from,len,unsigned_flag,&end,&conv_err);
4289   if (conv_err == MY_ERRNO_ERANGE)
4290   {
4291     set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
4292     error= TYPE_WARN_OUT_OF_RANGE;
4293   }
4294   else if (table->in_use->count_cuted_fields &&
4295            check_int(cs, from, len, end, conv_err))
4296     error= TYPE_WARN_OUT_OF_RANGE;
4297   else
4298     error= TYPE_OK;
4299 
4300 #ifdef WORDS_BIGENDIAN
4301   if (table->s->db_low_byte_first)
4302   {
4303     int8store(ptr,tmp);
4304   }
4305   else
4306 #endif
4307     longlongstore(ptr,tmp);
4308   return error;
4309 }
4310 
4311 
store(double nr)4312 type_conversion_status Field_longlong::store(double nr)
4313 {
4314   ASSERT_COLUMN_MARKED_FOR_WRITE;
4315   type_conversion_status error= TYPE_OK;
4316   longlong res;
4317 
4318   nr= rint(nr);
4319   if (unsigned_flag)
4320   {
4321     if (nr < 0)
4322     {
4323       res=0;
4324       error= TYPE_WARN_OUT_OF_RANGE;
4325     }
4326     else if (nr >= (double) ULLONG_MAX)
4327     {
4328       res= ~(longlong) 0;
4329       error= TYPE_WARN_OUT_OF_RANGE;
4330     }
4331     else
4332       res=(longlong) double2ulonglong(nr);
4333   }
4334   else
4335   {
4336     if (nr <= (double) LLONG_MIN)
4337     {
4338       res= LLONG_MIN;
4339       if (nr < (double) LLONG_MIN)
4340         error= TYPE_WARN_OUT_OF_RANGE;
4341     }
4342     else if (nr >= (double) (ulonglong) LLONG_MAX)
4343     {
4344       res= LLONG_MAX;
4345       if (nr > (double) LLONG_MAX)
4346         error= TYPE_WARN_OUT_OF_RANGE;
4347     }
4348     else
4349       res=(longlong) nr;
4350   }
4351   if (error)
4352     set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
4353 
4354 #ifdef WORDS_BIGENDIAN
4355   if (table->s->db_low_byte_first)
4356   {
4357     int8store(ptr,res);
4358   }
4359   else
4360 #endif
4361     longlongstore(ptr,res);
4362   return error;
4363 }
4364 
4365 
store(longlong nr,bool unsigned_val)4366 type_conversion_status Field_longlong::store(longlong nr, bool unsigned_val)
4367 {
4368   ASSERT_COLUMN_MARKED_FOR_WRITE;
4369   type_conversion_status error= TYPE_OK;
4370 
4371   if (nr < 0)                                   // Only possible error
4372   {
4373     /*
4374       if field is unsigned and value is signed (< 0) or
4375       if field is signed and value is unsigned we have an overflow
4376     */
4377     if (unsigned_flag != unsigned_val)
4378     {
4379       nr= unsigned_flag ? (ulonglong) 0 : (ulonglong) LLONG_MAX;
4380       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
4381       error= TYPE_WARN_OUT_OF_RANGE;
4382     }
4383   }
4384 
4385 #ifdef WORDS_BIGENDIAN
4386   if (table->s->db_low_byte_first)
4387   {
4388     int8store(ptr,nr);
4389   }
4390   else
4391 #endif
4392     longlongstore(ptr,nr);
4393   return error;
4394 }
4395 
4396 
val_real(void)4397 double Field_longlong::val_real(void)
4398 {
4399   ASSERT_COLUMN_MARKED_FOR_READ;
4400   longlong j;
4401 #ifdef WORDS_BIGENDIAN
4402   if (table->s->db_low_byte_first)
4403   {
4404     j=sint8korr(ptr);
4405   }
4406   else
4407 #endif
4408     longlongget(&j, ptr);
4409   /* The following is open coded to avoid a bug in gcc 3.3 */
4410   if (unsigned_flag)
4411   {
4412     ulonglong tmp= (ulonglong) j;
4413     return ulonglong2double(tmp);
4414   }
4415   return (double) j;
4416 }
4417 
4418 
val_int(void)4419 longlong Field_longlong::val_int(void)
4420 {
4421   ASSERT_COLUMN_MARKED_FOR_READ;
4422   longlong j;
4423 #ifdef WORDS_BIGENDIAN
4424   if (table->s->db_low_byte_first)
4425     j=sint8korr(ptr);
4426   else
4427 #endif
4428     longlongget(&j, ptr);
4429   return j;
4430 }
4431 
4432 
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))4433 String *Field_longlong::val_str(String *val_buffer,
4434 				String *val_ptr MY_ATTRIBUTE((unused)))
4435 {
4436   const CHARSET_INFO *cs= &my_charset_numeric;
4437   uint length;
4438   uint mlength=max(field_length+1,22*cs->mbmaxlen);
4439   val_buffer->alloc(mlength);
4440   char *to=(char*) val_buffer->ptr();
4441   longlong j;
4442 #ifdef WORDS_BIGENDIAN
4443   if (table->s->db_low_byte_first)
4444     j=sint8korr(ptr);
4445   else
4446 #endif
4447     longlongget(&j, ptr);
4448 
4449   length=(uint) (cs->cset->longlong10_to_str)(cs,to,mlength,
4450 					unsigned_flag ? 10 : -10, j);
4451   val_buffer->length(length);
4452   if (zerofill)
4453     prepend_zeros(val_buffer);
4454   val_buffer->set_charset(cs);
4455   return val_buffer;
4456 }
4457 
4458 
send_binary(Protocol * protocol)4459 bool Field_longlong::send_binary(Protocol *protocol)
4460 {
4461   ASSERT_COLUMN_MARKED_FOR_READ;
4462   if (is_null())
4463     return protocol->store_null();
4464   return protocol->store_longlong(Field_longlong::val_int(), unsigned_flag);
4465 }
4466 
4467 
cmp(const uchar * a_ptr,const uchar * b_ptr)4468 int Field_longlong::cmp(const uchar *a_ptr, const uchar *b_ptr)
4469 {
4470   longlong a,b;
4471 #ifdef WORDS_BIGENDIAN
4472   if (table->s->db_low_byte_first)
4473   {
4474     a=sint8korr(a_ptr);
4475     b=sint8korr(b_ptr);
4476   }
4477   else
4478 #endif
4479   {
4480     longlongget(&a, a_ptr);
4481     longlongget(&b, b_ptr);
4482   }
4483   if (unsigned_flag)
4484     return ((ulonglong) a < (ulonglong) b) ? -1 :
4485     ((ulonglong) a > (ulonglong) b) ? 1 : 0;
4486   return (a < b) ? -1 : (a > b) ? 1 : 0;
4487 }
4488 
4489 
make_sort_key(uchar * to,size_t length)4490 void Field_longlong::make_sort_key(uchar *to, size_t length)
4491 {
4492   const size_t from_length= PACK_LENGTH;
4493   const size_t to_length= min(from_length, length);
4494 #ifdef WORDS_BIGENDIAN
4495   if (table == NULL || !table->s->db_low_byte_first)
4496     copy_integer<true>(to, to_length, ptr, from_length, unsigned_flag);
4497   else
4498 #endif
4499     copy_integer<false>(to, to_length, ptr, from_length, unsigned_flag);
4500 }
4501 
4502 
sql_type(String & res) const4503 void Field_longlong::sql_type(String &res) const
4504 {
4505   const CHARSET_INFO *cs=res.charset();
4506   res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
4507 			  "bigint(%d)",(int) field_length));
4508   add_zerofill_and_unsigned(res);
4509 }
4510 
4511 
4512 /*
4513   Floating-point numbers
4514  */
4515 
4516 uchar *
pack(uchar * to,const uchar * from,uint max_length,bool low_byte_first)4517 Field_real::pack(uchar *to, const uchar *from,
4518                  uint max_length, bool low_byte_first)
4519 {
4520   DBUG_ENTER("Field_real::pack");
4521   DBUG_ASSERT(max_length >= pack_length());
4522 #ifdef WORDS_BIGENDIAN
4523   if (low_byte_first != table->s->db_low_byte_first)
4524   {
4525     const uchar *dptr= from + pack_length();
4526     while (dptr-- > from)
4527       *to++ = *dptr;
4528     DBUG_RETURN(to);
4529   }
4530   else
4531 #endif
4532     DBUG_RETURN(Field::pack(to, from, max_length, low_byte_first));
4533 }
4534 
4535 const uchar *
unpack(uchar * to,const uchar * from,uint param_data,bool low_byte_first)4536 Field_real::unpack(uchar *to, const uchar *from,
4537                    uint param_data, bool low_byte_first)
4538 {
4539   DBUG_ENTER("Field_real::unpack");
4540 #ifdef WORDS_BIGENDIAN
4541   if (low_byte_first != table->s->db_low_byte_first)
4542   {
4543     const uchar *dptr= from + pack_length();
4544     while (dptr-- > from)
4545       *to++ = *dptr;
4546     DBUG_RETURN(from + pack_length());
4547   }
4548   else
4549 #endif
4550     DBUG_RETURN(Field::unpack(to, from, param_data, low_byte_first));
4551 }
4552 
4553 
4554 type_conversion_status
store_time(MYSQL_TIME * ltime,uint8 dec_arg MY_ATTRIBUTE ((unused)))4555 Field_real::store_time(MYSQL_TIME *ltime,
4556                        uint8 dec_arg MY_ATTRIBUTE((unused)))
4557 {
4558   double nr= TIME_to_double(ltime);
4559   return store(ltime->neg ? -nr : nr);
4560 }
4561 
4562 
4563 /****************************************************************************
4564   single precision float
4565 ****************************************************************************/
4566 
4567 type_conversion_status
store(const char * from,size_t len,const CHARSET_INFO * cs)4568 Field_float::store(const char *from, size_t len, const CHARSET_INFO *cs)
4569 {
4570   int conv_error;
4571   type_conversion_status err= TYPE_OK;
4572   char *end;
4573   double nr= my_strntod(cs,(char*) from,len,&end,&conv_error);
4574   if (conv_error || (!len || ((uint) (end-from) != len &&
4575                               table->in_use->count_cuted_fields)))
4576   {
4577     set_warning(Sql_condition::SL_WARNING,
4578                 (conv_error ? ER_WARN_DATA_OUT_OF_RANGE
4579                             : WARN_DATA_TRUNCATED),
4580                 1);
4581     err= conv_error ? TYPE_WARN_OUT_OF_RANGE : TYPE_WARN_TRUNCATED;
4582   }
4583   Field_float::store(nr);
4584   return err;
4585 }
4586 
4587 
store(double nr)4588 type_conversion_status Field_float::store(double nr)
4589 {
4590   ASSERT_COLUMN_MARKED_FOR_WRITE;
4591   const type_conversion_status error=
4592     truncate(&nr, FLT_MAX) ? TYPE_WARN_OUT_OF_RANGE : TYPE_OK;
4593 
4594   float j= (float)nr;
4595 
4596 #ifdef WORDS_BIGENDIAN
4597   if (table->s->db_low_byte_first)
4598   {
4599     float4store(ptr,j);
4600   }
4601   else
4602 #endif
4603     memcpy(ptr, &j, sizeof(j));
4604   return error;
4605 }
4606 
4607 
store(longlong nr,bool unsigned_val)4608 type_conversion_status Field_float::store(longlong nr, bool unsigned_val)
4609 {
4610   return Field_float::store(unsigned_val ? ulonglong2double((ulonglong) nr) :
4611                             (double) nr);
4612 }
4613 
4614 
val_real(void)4615 double Field_float::val_real(void)
4616 {
4617   ASSERT_COLUMN_MARKED_FOR_READ;
4618   float j;
4619 #ifdef WORDS_BIGENDIAN
4620   if (table->s->db_low_byte_first)
4621   {
4622     float4get(&j,ptr);
4623   }
4624   else
4625 #endif
4626     memcpy(&j, ptr, sizeof(j));
4627   return ((double) j);
4628 }
4629 
val_int(void)4630 longlong Field_float::val_int(void)
4631 {
4632   float j;
4633 #ifdef WORDS_BIGENDIAN
4634   if (table->s->db_low_byte_first)
4635   {
4636     float4get(&j,ptr);
4637   }
4638   else
4639 #endif
4640     memcpy(&j, ptr, sizeof(j));
4641   return (longlong) rint(j);
4642 }
4643 
4644 
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))4645 String *Field_float::val_str(String *val_buffer,
4646 			     String *val_ptr MY_ATTRIBUTE((unused)))
4647 {
4648   ASSERT_COLUMN_MARKED_FOR_READ;
4649   DBUG_ASSERT(!zerofill || field_length <= MAX_FIELD_CHARLENGTH);
4650   float nr;
4651 #ifdef WORDS_BIGENDIAN
4652   if (table->s->db_low_byte_first)
4653   {
4654     float4get(&nr,ptr);
4655   }
4656   else
4657 #endif
4658     memcpy(&nr, ptr, sizeof(nr));
4659 
4660   uint to_length= 70;
4661   if (val_buffer->alloc(to_length))
4662   {
4663     my_error(ER_OUT_OF_RESOURCES, MYF(0));
4664     return val_buffer;
4665   }
4666 
4667   char *to=(char*) val_buffer->ptr();
4668   size_t len;
4669 
4670   if (dec >= NOT_FIXED_DEC)
4671     len= my_gcvt(nr, MY_GCVT_ARG_FLOAT, to_length - 1, to, NULL);
4672   else
4673   {
4674     /*
4675       We are safe here because the buffer length is 70, and
4676       fabs(float) < 10^39, dec < NOT_FIXED_DEC. So the resulting string
4677       will be not longer than 69 chars + terminating '\0'.
4678     */
4679     len= my_fcvt(nr, dec, to, NULL);
4680   }
4681   val_buffer->length((uint) len);
4682   if (zerofill)
4683     prepend_zeros(val_buffer);
4684   val_buffer->set_charset(&my_charset_numeric);
4685   return val_buffer;
4686 }
4687 
4688 
cmp(const uchar * a_ptr,const uchar * b_ptr)4689 int Field_float::cmp(const uchar *a_ptr, const uchar *b_ptr)
4690 {
4691   float a,b;
4692 #ifdef WORDS_BIGENDIAN
4693   if (table->s->db_low_byte_first)
4694   {
4695     float4get(&a,a_ptr);
4696     float4get(&b,b_ptr);
4697   }
4698   else
4699 #endif
4700   {
4701     memcpy(&a, a_ptr, sizeof(float));
4702     memcpy(&b, b_ptr, sizeof(float));
4703   }
4704   return (a < b) ? -1 : (a > b) ? 1 : 0;
4705 }
4706 
4707 #define FLT_EXP_DIG (sizeof(float)*8-FLT_MANT_DIG)
4708 
make_sort_key(uchar * to,size_t length)4709 void Field_float::make_sort_key(uchar *to, size_t length)
4710 {
4711   DBUG_ASSERT(length >= 4);
4712   float nr;
4713 #ifdef WORDS_BIGENDIAN
4714   if (table->s->db_low_byte_first)
4715   {
4716     float4get(&nr,ptr);
4717   }
4718   else
4719 #endif
4720     memcpy(&nr, ptr, min(length, sizeof(float)));
4721 
4722   uchar *tmp= to;
4723   if (nr == (float) 0.0)
4724   {						/* Change to zero string */
4725     tmp[0]=(uchar) 128;
4726     memset(tmp + 1, 0, min(length, sizeof(nr) - 1));
4727   }
4728   else
4729   {
4730 #ifdef WORDS_BIGENDIAN
4731     memcpy(tmp, &nr, sizeof(nr));
4732 #else
4733     tmp[0]= ptr[3]; tmp[1]=ptr[2]; tmp[2]= ptr[1]; tmp[3]=ptr[0];
4734 #endif
4735     if (tmp[0] & 128)				/* Negative */
4736     {						/* make complement */
4737       uint i;
4738       for (i=0 ; i < sizeof(nr); i++)
4739 	tmp[i]= (uchar) (tmp[i] ^ (uchar) 255);
4740     }
4741     else
4742     {
4743       ushort exp_part=(((ushort) tmp[0] << 8) | (ushort) tmp[1] |
4744 		       (ushort) 32768);
4745       exp_part+= (ushort) 1 << (16-1-FLT_EXP_DIG);
4746       tmp[0]= (uchar) (exp_part >> 8);
4747       tmp[1]= (uchar) exp_part;
4748     }
4749   }
4750 }
4751 
4752 
send_binary(Protocol * protocol)4753 bool Field_float::send_binary(Protocol *protocol)
4754 {
4755   ASSERT_COLUMN_MARKED_FOR_READ;
4756   if (is_null())
4757     return protocol->store_null();
4758   return protocol->store((float) Field_float::val_real(), dec, (String*) 0);
4759 }
4760 
4761 
4762 /**
4763    Save the field metadata for float fields.
4764 
4765    Saves the pack length in the first byte.
4766 
4767    @param   metadata_ptr   First byte of field metadata
4768 
4769    @returns number of bytes written to metadata_ptr
4770 */
do_save_field_metadata(uchar * metadata_ptr)4771 int Field_float::do_save_field_metadata(uchar *metadata_ptr)
4772 {
4773   *metadata_ptr= pack_length();
4774   return 1;
4775 }
4776 
4777 
sql_type(String & res) const4778 void Field_float::sql_type(String &res) const
4779 {
4780   if (dec == NOT_FIXED_DEC)
4781   {
4782     res.set_ascii(STRING_WITH_LEN("float"));
4783   }
4784   else
4785   {
4786     const CHARSET_INFO *cs= res.charset();
4787     res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
4788 			    "float(%d,%d)",(int) field_length,dec));
4789   }
4790   add_zerofill_and_unsigned(res);
4791 }
4792 
4793 
4794 /****************************************************************************
4795   double precision floating point numbers
4796 ****************************************************************************/
4797 
4798 type_conversion_status
store(const char * from,size_t len,const CHARSET_INFO * cs)4799 Field_double::store(const char *from, size_t len, const CHARSET_INFO *cs)
4800 {
4801   int conv_error;
4802   type_conversion_status error= TYPE_OK;
4803   char *end;
4804   double nr= my_strntod(cs,(char*) from, len, &end, &conv_error);
4805   if ((conv_error != 0) || (!len || ((uint) (end-from) != len &&
4806                                      table->in_use->count_cuted_fields)))
4807   {
4808     set_warning(Sql_condition::SL_WARNING,
4809                 (conv_error ? ER_WARN_DATA_OUT_OF_RANGE
4810                             : WARN_DATA_TRUNCATED),
4811                 1);
4812     error= conv_error ? TYPE_WARN_OUT_OF_RANGE : TYPE_WARN_TRUNCATED;
4813   }
4814   Field_double::store(nr);
4815   return error;
4816 }
4817 
4818 
store(double nr)4819 type_conversion_status Field_double::store(double nr)
4820 {
4821   ASSERT_COLUMN_MARKED_FOR_WRITE;
4822   const type_conversion_status error=
4823     truncate(&nr, DBL_MAX) ? TYPE_WARN_OUT_OF_RANGE : TYPE_OK;
4824 
4825 #ifdef WORDS_BIGENDIAN
4826   if (table->s->db_low_byte_first)
4827   {
4828     float8store(ptr,nr);
4829   }
4830   else
4831 #endif
4832     doublestore(ptr,nr);
4833   return error;
4834 }
4835 
4836 
store(longlong nr,bool unsigned_val)4837 type_conversion_status Field_double::store(longlong nr, bool unsigned_val)
4838 {
4839   return Field_double::store(unsigned_val ? ulonglong2double((ulonglong) nr) :
4840                              (double) nr);
4841 }
4842 
4843 /*
4844   If a field has fixed length, truncate the double argument pointed to by 'nr'
4845   appropriately.
4846   Also ensure that the argument is within [-max_value; max_value] range.
4847 */
4848 
truncate(double * nr,double max_value)4849 bool Field_real::truncate(double *nr, double max_value)
4850 {
4851   if (my_isnan(*nr))
4852   {
4853     *nr= 0;
4854     set_null();
4855     set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
4856     return true;
4857   }
4858   else if (unsigned_flag && *nr < 0)
4859   {
4860     *nr= 0;
4861     set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
4862     return true;
4863   }
4864 
4865   if (!not_fixed)
4866   {
4867     uint order= field_length - dec;
4868     uint step= array_elements(log_10) - 1;
4869     max_value= 1.0;
4870     for (; order > step; order-= step)
4871       max_value*= log_10[step];
4872     max_value*= log_10[order];
4873     max_value-= 1.0 / log_10[dec];
4874 
4875     /* Check for infinity so we don't get NaN in calculations */
4876     if (!my_isinf(*nr))
4877     {
4878       double tmp= rint((*nr - floor(*nr)) * log_10[dec]) / log_10[dec];
4879       *nr= floor(*nr) + tmp;
4880     }
4881   }
4882 
4883   if (*nr < -max_value)
4884   {
4885     *nr= -max_value;
4886     set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
4887     return true;
4888   }
4889   else if (*nr > max_value)
4890   {
4891     *nr= max_value;
4892     set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
4893     return true;
4894   }
4895 
4896   return false;
4897 }
4898 
4899 
store_decimal(const my_decimal * dm)4900 type_conversion_status Field_real::store_decimal(const my_decimal *dm)
4901 {
4902   double dbl;
4903   my_decimal2double(E_DEC_FATAL_ERROR, dm, &dbl);
4904   return store(dbl);
4905 }
4906 
val_real(void)4907 double Field_double::val_real(void)
4908 {
4909   ASSERT_COLUMN_MARKED_FOR_READ;
4910   double j;
4911 #ifdef WORDS_BIGENDIAN
4912   if (table->s->db_low_byte_first)
4913   {
4914     float8get(&j,ptr);
4915   }
4916   else
4917 #endif
4918     doubleget(&j,ptr);
4919   return j;
4920 }
4921 
val_int(void)4922 longlong Field_double::val_int(void)
4923 {
4924   ASSERT_COLUMN_MARKED_FOR_READ;
4925   double j;
4926   longlong res;
4927 #ifdef WORDS_BIGENDIAN
4928   if (table->s->db_low_byte_first)
4929   {
4930     float8get(&j,ptr);
4931   }
4932   else
4933 #endif
4934     doubleget(&j,ptr);
4935   /* Check whether we fit into longlong range */
4936   if (j <= (double) LLONG_MIN)
4937   {
4938     res= (longlong) LLONG_MIN;
4939     goto warn;
4940   }
4941   if (j >= (double) (ulonglong) LLONG_MAX)
4942   {
4943     res= (longlong) LLONG_MAX;
4944     goto warn;
4945   }
4946   return (longlong) rint(j);
4947 
4948 warn:
4949   {
4950     char buf[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
4951     String tmp(buf, sizeof(buf), &my_charset_latin1), *str;
4952     str= val_str(&tmp, 0);
4953     ErrConvString err(str);
4954     push_warning_printf(current_thd, Sql_condition::SL_WARNING,
4955                         ER_TRUNCATED_WRONG_VALUE,
4956                         ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
4957                         err.ptr());
4958   }
4959   return res;
4960 }
4961 
4962 
val_decimal(my_decimal * decimal_value)4963 my_decimal *Field_real::val_decimal(my_decimal *decimal_value)
4964 {
4965   ASSERT_COLUMN_MARKED_FOR_READ;
4966   double2my_decimal(E_DEC_FATAL_ERROR, val_real(), decimal_value);
4967   return decimal_value;
4968 }
4969 
4970 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)4971 bool Field_real::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
4972 {
4973   return my_double_to_datetime_with_warn(val_real(), ltime, fuzzydate);
4974 }
4975 
4976 
get_time(MYSQL_TIME * ltime)4977 bool Field_real::get_time(MYSQL_TIME *ltime)
4978 {
4979   return my_double_to_time_with_warn(val_real(), ltime);
4980 }
4981 
4982 
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))4983 String *Field_double::val_str(String *val_buffer,
4984 			      String *val_ptr MY_ATTRIBUTE((unused)))
4985 {
4986   ASSERT_COLUMN_MARKED_FOR_READ;
4987   DBUG_ASSERT(!zerofill || field_length <= MAX_FIELD_CHARLENGTH);
4988   double nr;
4989 #ifdef WORDS_BIGENDIAN
4990   if (table->s->db_low_byte_first)
4991   {
4992     float8get(&nr,ptr);
4993   }
4994   else
4995 #endif
4996     doubleget(&nr,ptr);
4997   uint to_length= DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE;
4998   if (val_buffer->alloc(to_length))
4999   {
5000     my_error(ER_OUT_OF_RESOURCES, MYF(0));
5001     return val_buffer;
5002   }
5003 
5004   char *to=(char*) val_buffer->ptr();
5005   size_t len;
5006 
5007   if (dec >= NOT_FIXED_DEC)
5008     len= my_gcvt(nr, MY_GCVT_ARG_DOUBLE, to_length - 1, to, NULL);
5009   else
5010     len= my_fcvt(nr, dec, to, NULL);
5011 
5012   val_buffer->length((uint) len);
5013   if (zerofill)
5014     prepend_zeros(val_buffer);
5015   val_buffer->set_charset(&my_charset_numeric);
5016   return val_buffer;
5017 }
5018 
send_binary(Protocol * protocol)5019 bool Field_double::send_binary(Protocol *protocol)
5020 {
5021   if (is_null())
5022     return protocol->store_null();
5023   String buf;
5024   return protocol->store(Field_double::val_real(), dec, &buf);
5025 }
5026 
5027 
cmp(const uchar * a_ptr,const uchar * b_ptr)5028 int Field_double::cmp(const uchar *a_ptr, const uchar *b_ptr)
5029 {
5030   double a,b;
5031 #ifdef WORDS_BIGENDIAN
5032   if (table->s->db_low_byte_first)
5033   {
5034     float8get(&a,a_ptr);
5035     float8get(&b,b_ptr);
5036   }
5037   else
5038 #endif
5039   {
5040     doubleget(&a, a_ptr);
5041     doubleget(&b, b_ptr);
5042   }
5043   return (a < b) ? -1 : (a > b) ? 1 : 0;
5044 }
5045 
5046 
5047 #define DBL_EXP_DIG (sizeof(double)*8-DBL_MANT_DIG)
5048 
5049 /* The following should work for IEEE */
5050 
make_sort_key(uchar * to,size_t length)5051 void Field_double::make_sort_key(uchar *to, size_t length)
5052 {
5053   double nr;
5054 #ifdef WORDS_BIGENDIAN
5055   if (table->s->db_low_byte_first)
5056   {
5057     float8get(&nr, ptr);
5058   }
5059   else
5060 #endif
5061     doubleget(&nr, ptr);
5062   if (length < 8)
5063   {
5064     uchar buff[8];
5065     change_double_for_sort(nr, buff);
5066     memcpy(to, buff, length);
5067   }
5068   else
5069     change_double_for_sort(nr, to);
5070 }
5071 
5072 
5073 /**
5074    Save the field metadata for double fields.
5075 
5076    Saves the pack length in the first byte of the field metadata array
5077    at index of *metadata_ptr.
5078 
5079    @param   metadata_ptr   First byte of field metadata
5080 
5081    @returns number of bytes written to metadata_ptr
5082 */
do_save_field_metadata(uchar * metadata_ptr)5083 int Field_double::do_save_field_metadata(uchar *metadata_ptr)
5084 {
5085   *metadata_ptr= pack_length();
5086   return 1;
5087 }
5088 
5089 
sql_type(String & res) const5090 void Field_double::sql_type(String &res) const
5091 {
5092   const CHARSET_INFO *cs=res.charset();
5093   if (dec == NOT_FIXED_DEC)
5094   {
5095     res.set_ascii(STRING_WITH_LEN("double"));
5096   }
5097   else
5098   {
5099     res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
5100 			    "double(%d,%d)",(int) field_length,dec));
5101   }
5102   add_zerofill_and_unsigned(res);
5103 }
5104 
5105 
5106 /****************************************************************************
5107 ** Common code for all temporal data types: DATE, DATETIME, TIMESTAMP, TIME
5108 *****************************************************************************/
5109 
is_equal(Create_field * new_field)5110 uint Field_temporal::is_equal(Create_field *new_field)
5111 {
5112   return new_field->sql_type == real_type() &&
5113          new_field->decimals == decimals();
5114 }
5115 
5116 
val_decimal(my_decimal * decimal_value)5117 my_decimal *Field_temporal::val_decimal(my_decimal *decimal_value)
5118 {
5119   ASSERT_COLUMN_MARKED_FOR_READ;
5120   DBUG_ASSERT(decimals() == 0);
5121   int2my_decimal(E_DEC_FATAL_ERROR, val_int(), 0, decimal_value);
5122   return decimal_value;
5123 }
5124 
5125 
5126 /**
5127   Set warnings from a warning vector.
5128   Note, multiple warnings can be set at the same time.
5129 
5130   @param str       Value.
5131   @param warnings  Warning vector.
5132 */
5133 void
set_warnings(ErrConvString str,int warnings)5134 Field_temporal::set_warnings(ErrConvString str, int warnings)
5135 {
5136   int cut_incremented= 0;
5137   timestamp_type ts_type= field_type_to_timestamp_type(type());
5138 
5139   if (warnings & MYSQL_TIME_WARN_TRUNCATED)
5140   {
5141     set_datetime_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED,
5142                          str, ts_type, !cut_incremented);
5143     cut_incremented= 1;
5144   }
5145   if (warnings & (MYSQL_TIME_WARN_OUT_OF_RANGE | MYSQL_TIME_WARN_ZERO_DATE |
5146                   MYSQL_TIME_WARN_ZERO_IN_DATE))
5147   {
5148     set_datetime_warning(Sql_condition::SL_WARNING,
5149                          ER_WARN_DATA_OUT_OF_RANGE,
5150                          str, ts_type, !cut_incremented);
5151     cut_incremented= 1;
5152   }
5153   if (warnings & MYSQL_TIME_WARN_INVALID_TIMESTAMP)
5154   {
5155     set_datetime_warning(Sql_condition::SL_WARNING,
5156                          ER_WARN_INVALID_TIMESTAMP,
5157                          str, ts_type, !cut_incremented);
5158     cut_incremented= 1;
5159   }
5160   if ((warnings & MYSQL_TIME_NOTE_TRUNCATED) &&
5161       !(warnings & MYSQL_TIME_WARN_TRUNCATED))
5162   {
5163     set_datetime_warning(Sql_condition::SL_NOTE, WARN_DATA_TRUNCATED,
5164                          str, ts_type, !cut_incremented);
5165   }
5166 }
5167 
5168 
store(longlong nr,bool unsigned_val)5169 type_conversion_status Field_temporal::store(longlong nr, bool unsigned_val)
5170 {
5171   ASSERT_COLUMN_MARKED_FOR_WRITE;
5172   int warnings= 0;
5173   MYSQL_TIME ltime;
5174   type_conversion_status error= convert_number_to_TIME(nr, unsigned_val, 0,
5175                                                        &ltime, &warnings);
5176   if (error == TYPE_OK || error == TYPE_NOTE_TRUNCATED)
5177     error= store_internal(&ltime, &warnings);
5178   else
5179   {
5180     DBUG_ASSERT(warnings != 0); // Must be set by convert_number_to_TIME
5181 
5182     if (warnings & (MYSQL_TIME_WARN_ZERO_DATE |
5183                     MYSQL_TIME_WARN_ZERO_IN_DATE) &&
5184         !current_thd->is_strict_mode())
5185       error= TYPE_NOTE_TIME_TRUNCATED;
5186   }
5187   if (warnings)
5188     set_warnings(ErrConvString(nr, unsigned_val), warnings);
5189   return error;
5190 }
5191 
5192 
5193 type_conversion_status
store_lldiv_t(const lldiv_t * lld,int * warnings)5194 Field_temporal::store_lldiv_t(const lldiv_t *lld, int *warnings)
5195 {
5196   ASSERT_COLUMN_MARKED_FOR_WRITE;
5197   type_conversion_status error;
5198   MYSQL_TIME ltime;
5199   error= convert_number_to_TIME(lld->quot, 0, static_cast<int>(lld->rem),
5200                                 &ltime, warnings);
5201   if (error == TYPE_OK || error == TYPE_NOTE_TRUNCATED)
5202     error= store_internal_with_round(&ltime, warnings);
5203   else if (!*warnings)
5204   {
5205     DBUG_ASSERT(warnings != 0); // Must be set by convert_number_to_TIME
5206     if (((*warnings & MYSQL_TIME_WARN_ZERO_DATE) != 0 ||
5207          (*warnings & MYSQL_TIME_WARN_ZERO_IN_DATE) != 0) &&
5208         !current_thd->is_strict_mode())
5209       error= TYPE_NOTE_TIME_TRUNCATED;
5210   }
5211 
5212   return error;
5213 }
5214 
5215 
store_decimal(const my_decimal * decimal)5216 type_conversion_status Field_temporal::store_decimal(const my_decimal *decimal)
5217 {
5218   ASSERT_COLUMN_MARKED_FOR_WRITE;
5219   lldiv_t lld;
5220   int warnings= 0;
5221   /* Pass 0 in the first argument, not to produce warnings automatically */
5222   my_decimal2lldiv_t(0, decimal, &lld);
5223   const type_conversion_status error= store_lldiv_t(&lld, &warnings);
5224   if (warnings)
5225     set_warnings(ErrConvString(decimal), warnings);
5226   return error;
5227 }
5228 
5229 
store(double nr)5230 type_conversion_status Field_temporal::store(double nr)
5231 {
5232   ASSERT_COLUMN_MARKED_FOR_WRITE;
5233   int warnings= 0;
5234   lldiv_t lld;
5235   double2lldiv_t(nr, &lld);
5236   const type_conversion_status error= store_lldiv_t(&lld, &warnings);
5237   if (warnings)
5238     set_warnings(ErrConvString(nr), warnings);
5239    return error;
5240 }
5241 
5242 
5243 /**
5244   Store string into a date/time/datetime field.
5245 
5246   @param from     Date/time string
5247   @param  len     Length of the string
5248   @param  cs      Character set of the string
5249 
5250   @retval TYPE_OK   Storage of value went fine without warnings or errors
5251   @retval !TYPE_OK  Warning/error as indicated by type_conversion_status enum
5252                     value
5253 */
5254 type_conversion_status
store(const char * str,size_t len,const CHARSET_INFO * cs)5255 Field_temporal::store(const char *str, size_t len, const CHARSET_INFO *cs)
5256 {
5257   ASSERT_COLUMN_MARKED_FOR_WRITE;
5258   type_conversion_status error= TYPE_OK;
5259   MYSQL_TIME ltime;
5260   MYSQL_TIME_STATUS status;
5261   if (convert_str_to_TIME(str, len, cs, &ltime, &status))
5262   {
5263     /*
5264       When convert_str_to_TIME() returns error, ltime has been set to
5265       0 so there's nothing to store in the field.
5266     */
5267     reset();
5268     if (status.warnings & (MYSQL_TIME_WARN_ZERO_DATE |
5269                            MYSQL_TIME_WARN_ZERO_IN_DATE) &&
5270         !current_thd->is_strict_mode())
5271       error= TYPE_NOTE_TIME_TRUNCATED;
5272     else
5273       error= TYPE_ERR_BAD_VALUE;
5274   }
5275   else
5276   {
5277     error= time_warning_to_type_conversion_status(status.warnings);
5278 
5279     const type_conversion_status tmp_error= store_internal_with_round(&ltime,
5280                                                            &status.warnings);
5281 
5282     // Return the most serious error of the two, see type_conversion_status
5283     if (tmp_error > error)
5284       error= tmp_error;
5285   }
5286   if (status.warnings)
5287     set_warnings(ErrConvString(str, len, cs), status.warnings);
5288   return error;
5289 }
5290 
5291 
5292 /**
5293   @retval -1              Timestamp with wrong values
5294   @retval anything else   DATETIME as integer in YYYYMMDDHHMMSS format
5295 */
5296 longlong
convert_number_to_datetime(longlong nr,bool unsigned_val,MYSQL_TIME * ltime,int * warnings)5297 Field_temporal::convert_number_to_datetime(longlong nr, bool unsigned_val,
5298                                            MYSQL_TIME *ltime, int *warnings)
5299 {
5300   /*
5301     Note, number_to_datetime can return a result different from nr:
5302     e.g. 111111 -> 20111111000000
5303   */
5304   longlong tmp= number_to_datetime(nr, ltime, date_flags(), warnings);
5305   if (tmp == -1LL)
5306     reset();
5307   return tmp;
5308 }
5309 
5310 
5311 /****************************************************************************
5312 ** Common code for temporal data types with date: DATE, DATETIME, TIMESTAMP
5313 *****************************************************************************/
5314 
5315 
5316 bool
get_internal_check_zero(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)5317 Field_temporal_with_date::get_internal_check_zero(MYSQL_TIME *ltime,
5318                                                   my_time_flags_t fuzzydate)
5319 {
5320   if (get_date_internal(ltime)) /* '0000-00-00' */
5321   {
5322     DBUG_ASSERT(type() == MYSQL_TYPE_TIMESTAMP);
5323     if (fuzzydate & TIME_NO_ZERO_DATE)
5324       return true;
5325     set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME);
5326   }
5327   return false;
5328 }
5329 
5330 
val_date_temporal()5331 longlong Field_temporal_with_date::val_date_temporal()
5332 {
5333   ASSERT_COLUMN_MARKED_FOR_READ;
5334   MYSQL_TIME ltime;
5335   return get_date_internal(&ltime) ?
5336          0 : TIME_to_longlong_datetime_packed(&ltime);
5337 }
5338 
5339 
val_time_temporal()5340 longlong Field_temporal_with_date::val_time_temporal()
5341 {
5342   /*
5343     There are currently no tests covering this method,
5344     as DATETIME seems to always superseed over TIME in comparison.
5345   */
5346   ASSERT_COLUMN_MARKED_FOR_READ;
5347   MYSQL_TIME ltime;
5348   return get_date_internal(&ltime) ? 0 : TIME_to_longlong_time_packed(&ltime);
5349 }
5350 
5351 
5352 /**
5353   Convert a number in format YYMMDDhhmmss to string.
5354   Straight coded to avoid problem with slow longlong arithmetic and sprintf.
5355 
5356   @param[out] pos      pointer to convert to.
5357   @param      tmp      number with datetime value.
5358 */
5359 static inline int
my_datetime_number_to_str(char * pos,longlong tmp)5360 my_datetime_number_to_str(char *pos, longlong tmp)
5361 {
5362   long part1= (long) (tmp / 1000000LL);
5363   long part2= (long) (tmp - (ulonglong) part1 * 1000000LL);
5364   int part3;
5365   pos+= MAX_DATETIME_WIDTH; /* Start from the end */
5366   *pos--= 0;
5367   *pos--= (char) ('0' + (char) (part2 % 10));  /* Seconds */
5368   part2 /= 10;
5369   *pos--= (char) ('0' + (char) (part2 % 10));
5370   part3= (int) (part2 / 10);
5371   *pos--= ':';
5372   *pos--= (char) ('0' + (char) (part3 % 10)); /* Minutes */
5373   part3 /= 10;
5374   *pos--= (char) ('0' + (char) (part3 % 10));
5375   part3 /= 10;
5376   *pos--= ':';
5377   *pos--= (char) ('0' + (char) (part3 % 10)); /* Hours */
5378   part3 /= 10;
5379   *pos--= (char) ('0' + (char) part3);
5380   *pos--= ' ';
5381   *pos--= (char) ('0' + (char) (part1 % 10)); /* Day */
5382   part1 /= 10;
5383   *pos--= (char) ('0' + (char) (part1 % 10));
5384   part1 /= 10;
5385   *pos--= '-';
5386   *pos--= (char) ('0' + (char) (part1 % 10)); /* Month */
5387   part1 /= 10;
5388   *pos--= (char) ('0' + (char) (part1 % 10));
5389   part3= (int) (part1 / 10);
5390   *pos--= '-';
5391   *pos--= (char) ('0' + (char) (part3 % 10)); /* Year */
5392   part3 /= 10;
5393   *pos--= (char) ('0' + (char) (part3 % 10));
5394   part3 /= 10;
5395   *pos--= (char) ('0' + (char) (part3 % 10));
5396   part3 /= 10;
5397   *pos= (char) ('0'+ (char) part3);
5398   return MAX_DATETIME_WIDTH;
5399 }
5400 
5401 
val_str(String * val_buffer,String * val_ptr)5402 String *Field_temporal_with_date::val_str(String *val_buffer, String *val_ptr)
5403 {
5404   ASSERT_COLUMN_MARKED_FOR_READ;
5405   MYSQL_TIME ltime;
5406   val_buffer->alloc(field_length + 1);
5407   val_buffer->set_charset(&my_charset_numeric);
5408   if (get_date_internal(&ltime))
5409   {
5410     val_buffer->set_ascii(my_zero_datetime6, field_length);
5411     return val_buffer;
5412   }
5413   make_datetime((Date_time_format *) 0, &ltime, val_buffer, dec);
5414   return val_buffer;
5415 }
5416 
5417 
5418 type_conversion_status
convert_number_to_TIME(longlong nr,bool unsigned_val,int nanoseconds,MYSQL_TIME * ltime,int * warnings)5419 Field_temporal_with_date::convert_number_to_TIME(longlong nr,
5420                                                  bool unsigned_val,
5421                                                  int nanoseconds,
5422                                                  MYSQL_TIME *ltime,
5423                                                  int *warnings)
5424 {
5425   if (nr < 0 || nanoseconds < 0)
5426   {
5427     reset();
5428     *warnings|= MYSQL_TIME_WARN_OUT_OF_RANGE;
5429     return TYPE_WARN_OUT_OF_RANGE;
5430   }
5431 
5432   if (convert_number_to_datetime(nr, unsigned_val, ltime, warnings) == -1LL)
5433     return TYPE_ERR_BAD_VALUE;
5434 
5435   if (ltime->time_type == MYSQL_TIMESTAMP_DATE && nanoseconds)
5436   {
5437     *warnings|= MYSQL_TIME_WARN_TRUNCATED;
5438     return TYPE_NOTE_TRUNCATED;
5439   }
5440 
5441   ltime->second_part= 0;
5442   if (datetime_add_nanoseconds_with_round(ltime, nanoseconds, warnings))
5443   {
5444     reset();
5445     return TYPE_WARN_OUT_OF_RANGE;
5446   }
5447   return TYPE_OK;
5448 }
5449 
5450 
5451 type_conversion_status
store_time(MYSQL_TIME * ltime,uint8 dec_arg MY_ATTRIBUTE ((unused)))5452 Field_temporal_with_date::store_time(MYSQL_TIME *ltime,
5453                                      uint8 dec_arg MY_ATTRIBUTE((unused)))
5454 {
5455   ASSERT_COLUMN_MARKED_FOR_WRITE;
5456   type_conversion_status error;
5457   int warnings= 0;
5458 
5459   switch (ltime->time_type) // TS-TODO: split into separate methods?
5460   {
5461   case MYSQL_TIMESTAMP_DATETIME:
5462   case MYSQL_TIMESTAMP_DATE:
5463     if (check_date(ltime, non_zero_date(ltime), date_flags(), &warnings))
5464     {
5465       DBUG_ASSERT(warnings &
5466                   (MYSQL_TIME_WARN_OUT_OF_RANGE |
5467                    MYSQL_TIME_WARN_ZERO_DATE |
5468                    MYSQL_TIME_WARN_ZERO_IN_DATE));
5469 
5470       error= time_warning_to_type_conversion_status(warnings);
5471       reset();
5472     }
5473     else
5474       error= store_internal_with_round(ltime, &warnings);
5475     break;
5476   case MYSQL_TIMESTAMP_TIME:
5477   {
5478     /* Convert TIME to DATETIME */
5479     THD *thd= table ? table->in_use : current_thd;
5480     MYSQL_TIME ltime2;
5481     time_to_datetime(thd, ltime, &ltime2);
5482     error= store_internal_with_round(&ltime2, &warnings);
5483     break;
5484   }
5485   case MYSQL_TIMESTAMP_NONE:
5486   case  MYSQL_TIMESTAMP_ERROR:
5487   default:
5488     warnings|= MYSQL_TIME_WARN_TRUNCATED;
5489     reset();
5490     error= TYPE_WARN_TRUNCATED;
5491   }
5492 
5493   if (warnings)
5494     set_warnings(ErrConvString(ltime, decimals()), warnings);
5495   return error;
5496 }
5497 
5498 
5499 bool
convert_str_to_TIME(const char * str,size_t len,const CHARSET_INFO * cs,MYSQL_TIME * ltime,MYSQL_TIME_STATUS * status)5500 Field_temporal_with_date::convert_str_to_TIME(const char *str, size_t len,
5501                                               const CHARSET_INFO *cs,
5502                                               MYSQL_TIME *ltime,
5503                                               MYSQL_TIME_STATUS *status)
5504 {
5505   return str_to_datetime(cs, str, len, ltime, date_flags(), status);
5506 }
5507 
5508 
send_binary(Protocol * protocol)5509 bool Field_temporal_with_date::send_binary(Protocol *protocol)
5510 {
5511   MYSQL_TIME ltime;
5512   if (is_null())
5513     return protocol->store_null();
5514   if (get_date_internal(&ltime))
5515   {
5516     // Only MYSQL_TYPE_TIMESTAMP can return an error in get_date_internal()
5517     DBUG_ASSERT(type() == MYSQL_TYPE_TIMESTAMP);
5518     set_zero_time(&ltime, MYSQL_TIMESTAMP_DATETIME);
5519   }
5520   return protocol->store(&ltime, 0);
5521 }
5522 
5523 
5524 type_conversion_status
store_internal_with_round(MYSQL_TIME * ltime,int * warnings)5525 Field_temporal_with_date::store_internal_with_round(MYSQL_TIME *ltime,
5526                                                     int *warnings)
5527 {
5528   if (my_datetime_round(ltime, dec, warnings))
5529   {
5530     reset();
5531     return time_warning_to_type_conversion_status(*warnings);
5532   }
5533   else
5534     return store_internal(ltime, warnings);
5535 }
5536 
5537 
5538 /**
5539   Validate date value stored in the field.
5540 
5541   Now we check whether date value is zero or has zero in date or not and sets
5542   warning/error message appropriately(depending on the sql_mode).
5543 */
validate_stored_val(THD * thd)5544 type_conversion_status Field_temporal_with_date::validate_stored_val(THD *thd)
5545 {
5546   MYSQL_TIME ltime;
5547   type_conversion_status error= TYPE_OK;
5548   int warnings= 0;
5549 
5550   if (is_real_null())
5551     return error;
5552 
5553   memset(&ltime, 0, sizeof(MYSQL_TIME));
5554   get_date_internal(&ltime);
5555   if (check_date(&ltime, non_zero_date(&ltime), date_flags(), &warnings))
5556     error= time_warning_to_type_conversion_status(warnings);
5557 
5558   if (warnings)
5559   {
5560     ltime.time_type = field_type_to_timestamp_type(type());
5561     set_warnings(ErrConvString(&ltime, dec), warnings);
5562   }
5563 
5564   return error;
5565 }
5566 
5567 
5568 /****************************************************************************
5569 ** Common code for data types with date and time: DATETIME, TIMESTAMP
5570 *****************************************************************************/
5571 
5572 
store_timestamp(const struct timeval * tm)5573 void Field_temporal_with_date_and_time::store_timestamp(const struct timeval *tm)
5574 {
5575   ASSERT_COLUMN_MARKED_FOR_WRITE;
5576   if (!my_time_fraction_remainder(tm->tv_usec, decimals()))
5577   {
5578     store_timestamp_internal(tm);
5579     return;
5580   }
5581   struct timeval tm2= *tm;
5582   my_timeval_round(&tm2, decimals());
5583   store_timestamp_internal(&tm2);
5584 }
5585 
5586 
5587 bool
convert_TIME_to_timestamp(THD * thd,const MYSQL_TIME * ltime,struct timeval * tm,int * warnings)5588 Field_temporal_with_date_and_time::convert_TIME_to_timestamp(THD *thd,
5589                                                              const MYSQL_TIME *ltime,
5590                                                              struct timeval *tm,
5591                                                              int *warnings)
5592 {
5593   /*
5594     No need to do check_date(TIME_NO_ZERO_IN_DATE),
5595     because it has been done earlier in
5596     store_time(), number_to_datetime() or str_to_datetime().
5597   */
5598   if (datetime_with_no_zero_in_date_to_timeval(thd, ltime, tm, warnings))
5599   {
5600     tm->tv_sec= tm->tv_usec= 0;
5601     return true;
5602   }
5603   return false;
5604 }
5605 
5606 
init_timestamp_flags()5607 void Field_temporal_with_date_and_time::init_timestamp_flags()
5608 {
5609   if (unireg_check != NONE)
5610   {
5611     /*
5612       This TIMESTAMP column is hereby quietly assumed to have an insert or
5613       update default function.
5614     */
5615     flags|= TIMESTAMP_FLAG;
5616     if (unireg_check != TIMESTAMP_DN_FIELD)
5617       flags|= ON_UPDATE_NOW_FLAG;
5618   }
5619 }
5620 
5621 /****************************************************************************
5622 ** Common code for DATETIME(N) and TIMESTAMP(N)
5623 *****************************************************************************/
5624 
val_real()5625 double Field_temporal_with_date_and_timef::val_real()
5626 {
5627   ASSERT_COLUMN_MARKED_FOR_READ;
5628   MYSQL_TIME ltime;
5629   return get_date_internal(&ltime) ? 0 : TIME_to_double_datetime(&ltime);
5630 }
5631 
5632 
val_int()5633 longlong Field_temporal_with_date_and_timef::val_int()
5634 {
5635   ASSERT_COLUMN_MARKED_FOR_READ;
5636   MYSQL_TIME ltime;
5637   return get_date_internal(&ltime) ?
5638          0 : TIME_to_ulonglong_datetime_round(&ltime);
5639 }
5640 
5641 
val_decimal(my_decimal * dec_arg)5642 my_decimal *Field_temporal_with_date_and_timef::val_decimal(my_decimal *dec_arg)
5643 {
5644   ASSERT_COLUMN_MARKED_FOR_READ;
5645   MYSQL_TIME ltime;
5646   if (get_date_internal(&ltime))
5647   {
5648     // Only MYSQL_TYPE_TIMESTAMP can return an error in get_date_internal()
5649     DBUG_ASSERT(type() == MYSQL_TYPE_TIMESTAMP);
5650     set_zero_time(&ltime, MYSQL_TIMESTAMP_DATETIME);
5651   }
5652   return date2my_decimal(&ltime, dec_arg);
5653 }
5654 
5655 
5656 /**
5657   TIMESTAMP type columns hold date and time values in the range 1970-01-01
5658   00:00:01 UTC to 2038-01-01 00:00:00 UTC, stored as number of seconds since
5659   the start of the Unix Epoch (1970-01-01 00:00:01 UTC.)
5660 
5661   TIMESTAMP columns can be automatically set on row updates to and/or have
5662   CURRENT_TIMESTAMP as default value for inserts.
5663 
5664   The implementation of function defaults is heavily entangled with the binary
5665   .frm file format. The @c utype @c enum is part of the file format
5666   specification but is declared a member of the Field class. This constructor
5667   accepts a unireg_check value to initialize the column default expression.
5668 
5669   Five distinct unireg_check values are used for TIMESTAMP columns to
5670   distinguish various cases of DEFAULT or ON UPDATE values. These values are:
5671 
5672   - TIMESTAMP_OLD_FIELD - old timestamp, this has no significance when
5673     creating a the Field_timestamp.
5674 
5675   - TIMESTAMP_DN_FIELD - means TIMESTAMP DEFAULT CURRENT_TIMESTAMP.
5676 
5677   - TIMESTAMP_UN_FIELD - means TIMESTAMP DEFAULT <default value> ON UPDATE
5678     CURRENT_TIMESTAMP, where <default value> is an implicit or explicit
5679     expression other than CURRENT_TIMESTAMP or any synonym thereof
5680     (e.g. NOW().)
5681 
5682   - TIMESTAMP_DNUN_FIELD - means DEFAULT CURRENT_TIMESTAMP ON UPDATE
5683     CURRENT_TIMESTAMP.
5684 
5685   - NONE - means that the column has neither DEFAULT CURRENT_TIMESTAMP, nor ON
5686     UPDATE CURRENT_TIMESTAMP
5687 
5688   Note that columns with TIMESTAMP_OLD_FIELD are no longer created explicitly,
5689   the value is meant to preserve the ability to read tables from old
5690   databases. Such columns are replaced with their newer counterparts by CREATE
5691   TABLE and SHOW CREATE TABLE. This is because we want to prefer NONE
5692   unireg_check over TIMESTAMP_OLD_FIELD for "TIMESTAMP DEFAULT 'Const'"
5693   field. (Old TIMESTAMP columns allowed such definitions as well but ignored
5694   the default value for first the TIMESTAMP column. This is, of course,
5695   non-standard.)  In most cases a user won't notice any change, only exception
5696   being different behavior of old/new TIMESTAMPS columns during ALTER TABLE.
5697  */
Field_timestamp(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const char * field_name_arg)5698 Field_timestamp::Field_timestamp(uchar *ptr_arg, uint32 len_arg,
5699                                  uchar *null_ptr_arg, uchar null_bit_arg,
5700 				 enum utype unireg_check_arg,
5701 				 const char *field_name_arg)
5702   :Field_temporal_with_date_and_time(ptr_arg, null_ptr_arg, null_bit_arg,
5703                                      unireg_check_arg, field_name_arg, 0)
5704 {
5705   init_timestamp_flags();
5706    /* For 4.0 MYD and 4.0 InnoDB compatibility */
5707   flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
5708 }
5709 
5710 
Field_timestamp(bool maybe_null_arg,const char * field_name_arg)5711 Field_timestamp::Field_timestamp(bool maybe_null_arg,
5712                                  const char *field_name_arg)
5713   :Field_temporal_with_date_and_time((uchar *) 0,
5714                                      maybe_null_arg ? (uchar *) "" : 0, 0,
5715                                      NONE, field_name_arg, 0)
5716 {
5717   init_timestamp_flags();
5718   /* For 4.0 MYD and 4.0 InnoDB compatibility */
5719   flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
5720 }
5721 
5722 
date_flags(const THD * thd)5723 my_time_flags_t Field_timestamp::date_flags(const THD *thd)
5724 {
5725   /* We don't want to store invalid or fuzzy datetime values in TIMESTAMP */
5726   my_time_flags_t date_flags= TIME_NO_ZERO_IN_DATE;
5727   if (thd->variables.sql_mode & MODE_NO_ZERO_DATE)
5728     date_flags|= TIME_NO_ZERO_DATE;
5729   return date_flags;
5730 }
5731 
5732 
5733 type_conversion_status
store_internal(const MYSQL_TIME * ltime,int * warnings)5734 Field_timestamp::store_internal(const MYSQL_TIME *ltime, int *warnings)
5735 {
5736   THD *thd= table ? table->in_use : current_thd;
5737   struct timeval tm;
5738   convert_TIME_to_timestamp(thd, ltime, &tm, warnings);
5739   const type_conversion_status error=
5740     time_warning_to_type_conversion_status(*warnings);
5741   store_timestamp_internal(&tm);
5742   return error;
5743 }
5744 
5745 
5746 /**
5747   Get a value from record, without checking fuzzy date flags.
5748   @retval true  - if timestamp is 0, ltime is not touched in this case.
5749   @retval false - if timestamp is non-zero.
5750 */
get_date_internal(MYSQL_TIME * ltime)5751 bool Field_timestamp::get_date_internal(MYSQL_TIME *ltime)
5752 {
5753   ASSERT_COLUMN_MARKED_FOR_READ;
5754   uint32 temp;
5755   THD  *thd= table ? table->in_use : current_thd;
5756 #ifdef WORDS_BIGENDIAN
5757   if (table && table->s->db_low_byte_first)
5758     temp= uint4korr(ptr);
5759   else
5760 #endif
5761     ulongget(&temp, ptr);
5762   if (!temp)
5763     return true;
5764   thd->time_zone()->gmt_sec_to_TIME(ltime, (my_time_t) temp);
5765   return false;
5766 }
5767 
5768 
5769 /**
5770    Get TIMESTAMP field value as seconds since begging of Unix Epoch
5771 */
get_timestamp(struct timeval * tm,int * warnings)5772 bool Field_timestamp::get_timestamp(struct timeval *tm, int *warnings)
5773 {
5774   if (is_null())
5775     return true;
5776   tm->tv_usec= 0;
5777 #ifdef WORDS_BIGENDIAN
5778   if (table && table->s->db_low_byte_first)
5779   {
5780     tm->tv_sec= sint4korr(ptr);
5781     return false;
5782   }
5783 #endif
5784   int32 tmp;
5785   longget(&tmp, ptr);
5786   tm->tv_sec= tmp;
5787   return false;
5788 }
5789 
5790 
store_timestamp_internal(const struct timeval * tm)5791 void Field_timestamp::store_timestamp_internal(const struct timeval *tm)
5792 {
5793 #ifdef WORDS_BIGENDIAN
5794   if (table && table->s->db_low_byte_first)
5795   {
5796     int4store(ptr, tm->tv_sec);
5797   }
5798   else
5799 #endif
5800     longstore(ptr, (uint32) tm->tv_sec);
5801 }
5802 
5803 
store_packed(longlong nr)5804 type_conversion_status Field_timestamp::store_packed(longlong nr)
5805 {
5806   /* Make sure the stored value was previously properly rounded or truncated */
5807   DBUG_ASSERT((MY_PACKED_TIME_GET_FRAC_PART(nr) %
5808               (int) log_10_int[DATETIME_MAX_DECIMALS - decimals()]) == 0);
5809   MYSQL_TIME ltime;
5810   TIME_from_longlong_datetime_packed(&ltime, nr);
5811   return Field_timestamp::store_time(&ltime, 0);
5812 }
5813 
5814 
val_int()5815 longlong Field_timestamp::val_int()
5816 {
5817   ASSERT_COLUMN_MARKED_FOR_READ;
5818   MYSQL_TIME ltime;
5819   return get_date_internal(&ltime) ? 0 : TIME_to_ulonglong_datetime(&ltime);
5820 }
5821 
5822 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)5823 bool Field_timestamp::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
5824 {
5825   /* Don't do check_fuzzy_date() as month and year are never 0 for timestamp */
5826   return get_internal_check_zero(ltime, fuzzydate);
5827 }
5828 
5829 
cmp(const uchar * a_ptr,const uchar * b_ptr)5830 int Field_timestamp::cmp(const uchar *a_ptr, const uchar *b_ptr)
5831 {
5832   int32 a,b;
5833 #ifdef WORDS_BIGENDIAN
5834   if (table && table->s->db_low_byte_first)
5835   {
5836     a=sint4korr(a_ptr);
5837     b=sint4korr(b_ptr);
5838   }
5839   else
5840 #endif
5841   {
5842   longget(&a, a_ptr);
5843   longget(&b, b_ptr);
5844   }
5845   return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
5846 }
5847 
5848 
make_sort_key(uchar * to,size_t length MY_ATTRIBUTE ((unused)))5849 void Field_timestamp::make_sort_key(uchar *to, size_t length MY_ATTRIBUTE((unused)))
5850 {
5851 #ifdef WORDS_BIGENDIAN
5852   if (!table || !table->s->db_low_byte_first)
5853   {
5854     to[0] = ptr[0];
5855     to[1] = ptr[1];
5856     to[2] = ptr[2];
5857     to[3] = ptr[3];
5858   }
5859   else
5860 #endif
5861   {
5862     to[0] = ptr[3];
5863     to[1] = ptr[2];
5864     to[2] = ptr[1];
5865     to[3] = ptr[0];
5866   }
5867 }
5868 
5869 
sql_type(String & res) const5870 void Field_timestamp::sql_type(String &res) const
5871 {
5872   res.set_ascii(STRING_WITH_LEN("timestamp"));
5873 }
5874 
5875 
validate_stored_val(THD * thd)5876 type_conversion_status Field_timestamp::validate_stored_val(THD *thd)
5877 {
5878   /*
5879     While deprecating "TIMESTAMP with implicit DEFAULT value", we can
5880     remove this function implementation and depend directly on
5881     "Field_temporal_with_date::validate_stored_val"
5882   */
5883   if (!thd->variables.explicit_defaults_for_timestamp)
5884     return TYPE_OK;
5885 
5886   return (Field_temporal_with_date::validate_stored_val(thd));
5887 }
5888 
5889 
5890 /****************************************************************************
5891 ** timestamp(N) type
5892 ** In string context: YYYY-MM-DD HH:MM:SS.FFFFFF
5893 ** In number context: YYYYMMDDHHMMSS.FFFFFF
5894 ** Stored as a 7 byte value
5895 ****************************************************************************/
Field_timestampf(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const char * field_name_arg,uint8 dec_arg)5896 Field_timestampf::Field_timestampf(uchar *ptr_arg,
5897                                    uchar *null_ptr_arg, uchar null_bit_arg,
5898                                    enum utype unireg_check_arg,
5899                                    const char *field_name_arg,
5900                                    uint8 dec_arg)
5901   :Field_temporal_with_date_and_timef(ptr_arg, null_ptr_arg, null_bit_arg,
5902                                       unireg_check_arg, field_name_arg,
5903                                       dec_arg)
5904 {
5905   init_timestamp_flags();
5906 }
5907 
5908 
Field_timestampf(bool maybe_null_arg,const char * field_name_arg,uint8 dec_arg)5909 Field_timestampf::Field_timestampf(bool maybe_null_arg,
5910                                    const char *field_name_arg,
5911                                    uint8 dec_arg)
5912   :Field_temporal_with_date_and_timef((uchar*) 0,
5913                                       maybe_null_arg ? (uchar*) "": 0, 0,
5914                                       NONE, field_name_arg, dec_arg)
5915 {
5916   if (unireg_check != TIMESTAMP_DN_FIELD)
5917     flags|= ON_UPDATE_NOW_FLAG;
5918 }
5919 
5920 
date_flags(const THD * thd)5921 my_time_flags_t Field_timestampf::date_flags(const THD *thd)
5922 {
5923   /* We don't want to store invalid or fuzzy datetime values in TIMESTAMP */
5924   my_time_flags_t date_flags= TIME_NO_ZERO_IN_DATE;
5925   if (thd->variables.sql_mode & MODE_NO_ZERO_DATE)
5926     date_flags|= TIME_NO_ZERO_DATE;
5927   return date_flags;
5928 }
5929 
5930 
reset()5931 type_conversion_status Field_timestampf::reset()
5932 {
5933   memset(ptr, 0, pack_length());
5934   return TYPE_OK;
5935 }
5936 
5937 
store_timestamp_internal(const struct timeval * tm)5938 void Field_timestampf::store_timestamp_internal(const struct timeval *tm)
5939 {
5940   my_timestamp_to_binary(tm, ptr, dec);
5941 }
5942 
5943 
5944 type_conversion_status
store_internal(const MYSQL_TIME * ltime,int * warnings)5945 Field_timestampf::store_internal(const MYSQL_TIME *ltime, int *warnings)
5946 {
5947   THD *thd= table ? table->in_use : current_thd;
5948   struct timeval tm;
5949   convert_TIME_to_timestamp(thd, ltime, &tm, warnings);
5950   const type_conversion_status error=
5951     time_warning_to_type_conversion_status(*warnings);
5952   store_timestamp_internal(&tm);
5953   return error;
5954 }
5955 
5956 
store_packed(longlong nr)5957 type_conversion_status Field_timestampf::store_packed(longlong nr)
5958 {
5959   MYSQL_TIME ltime;
5960   TIME_from_longlong_datetime_packed(&ltime, nr);
5961   return Field_timestampf::store_time(&ltime, dec);
5962 }
5963 
5964 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)5965 bool Field_timestampf::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
5966 {
5967   /* Don't do check_fuzzy_date() as month and year are never 0 for timestamp */
5968   return get_internal_check_zero(ltime, fuzzydate);
5969 }
5970 
5971 
sql_type(String & res) const5972 void Field_timestampf::sql_type(String &res) const
5973 {
5974   if (dec == 0)
5975   {
5976     res.set_ascii(STRING_WITH_LEN("timestamp"));
5977     return;
5978   }
5979   const CHARSET_INFO *cs= res.charset();
5980   res.length(cs->cset->snprintf(cs, (char *) res.ptr(), res.alloced_length(),
5981                                 "timestamp(%d)", dec));
5982 }
5983 
5984 
5985 bool
get_date_internal(MYSQL_TIME * ltime)5986 Field_timestampf::get_date_internal(MYSQL_TIME *ltime)
5987 {
5988   THD *thd= table ? table->in_use : current_thd;
5989   struct timeval tm;
5990   my_timestamp_from_binary(&tm, ptr, dec);
5991   if (tm.tv_sec == 0)
5992     return true;
5993   thd->time_zone()->gmt_sec_to_TIME(ltime, tm);
5994   return false;
5995 }
5996 
5997 
get_timestamp(struct timeval * tm,int * warnings)5998 bool Field_timestampf::get_timestamp(struct timeval *tm, int *warnings)
5999 {
6000   THD *thd= table ? table->in_use : current_thd;
6001   thd->time_zone_used= 1;
6002   DBUG_ASSERT(!is_null());
6003   my_timestamp_from_binary(tm, ptr, dec);
6004   return false;
6005 }
6006 
6007 
validate_stored_val(THD * thd)6008 type_conversion_status Field_timestampf::validate_stored_val(THD *thd)
6009 {
6010   /*
6011     While deprecating "TIMESTAMP with implicit DEFAULT value", we can
6012     remove this function implementation and depend directly on
6013     "Field_temporal_with_date::validate_stored_val"
6014   */
6015   if (!thd->variables.explicit_defaults_for_timestamp)
6016     return TYPE_OK;
6017 
6018   return (Field_temporal_with_date::validate_stored_val(thd));
6019 }
6020 
6021 
6022 /****************************************************************************
6023 ** TIME and TIME(N) common methods
6024 ****************************************************************************/
6025 
6026 
6027 bool
convert_str_to_TIME(const char * str,size_t len,const CHARSET_INFO * cs,MYSQL_TIME * ltime,MYSQL_TIME_STATUS * status)6028 Field_time_common::convert_str_to_TIME(const char *str, size_t len,
6029                                        const CHARSET_INFO *cs,
6030                                        MYSQL_TIME *ltime,
6031                                        MYSQL_TIME_STATUS *status)
6032 {
6033   return str_to_time(cs, str, len, ltime, 0, status);
6034 }
6035 
6036 
6037 type_conversion_status
convert_number_to_TIME(longlong nr,bool unsigned_val,int nanoseconds,MYSQL_TIME * ltime,int * warnings)6038 Field_time_common::convert_number_to_TIME(longlong nr, bool unsigned_val,
6039                                           int nanoseconds,
6040                                           MYSQL_TIME *ltime, int *warnings)
6041 {
6042   if (unsigned_val && nr < 0)
6043   {
6044     *warnings|= MYSQL_TIME_WARN_OUT_OF_RANGE;
6045     set_max_time(ltime, 0);
6046     store_internal(ltime, warnings);
6047     return TYPE_WARN_OUT_OF_RANGE;
6048   }
6049   if (number_to_time(nr, ltime, warnings))
6050   {
6051     store_internal(ltime, warnings);
6052     return TYPE_WARN_OUT_OF_RANGE;
6053   }
6054   /*
6055     Both number_to_time() call and negative nanoseconds value
6056     affect ltime->neg, hence "|=" to combine them:
6057   */
6058   if ((ltime->neg|= (nanoseconds < 0)))
6059     nanoseconds= -nanoseconds;
6060   ltime->second_part= 0;
6061   bool round_error= time_add_nanoseconds_with_round(ltime, nanoseconds,
6062                                                     warnings);
6063 
6064   return round_error ? time_warning_to_type_conversion_status(*warnings)
6065                      : TYPE_OK;
6066 }
6067 
6068 
6069 type_conversion_status
store_time(MYSQL_TIME * ltime,uint8 dec_arg MY_ATTRIBUTE ((unused)))6070 Field_time_common::store_time(MYSQL_TIME *ltime,
6071                               uint8 dec_arg MY_ATTRIBUTE((unused)))
6072 {
6073   /* Check if seconds or minutes are out of range */
6074   if (ltime->second >= 60 || ltime->minute >= 60)
6075   {
6076     set_warnings(ErrConvString(ltime, decimals()),
6077                  MYSQL_TIME_WARN_OUT_OF_RANGE);
6078     reset();
6079     return TYPE_WARN_OUT_OF_RANGE;
6080   }
6081   int warnings= 0;
6082   return store_internal_with_round(ltime, &warnings);
6083 }
6084 
6085 
6086 type_conversion_status
store_internal_with_round(MYSQL_TIME * ltime,int * warnings)6087 Field_time_common::store_internal_with_round(MYSQL_TIME *ltime, int *warnings)
6088 {
6089   if (my_time_round(ltime, dec))
6090     return TYPE_WARN_OUT_OF_RANGE;
6091 
6092   return store_internal(ltime, warnings);
6093 }
6094 
6095 
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))6096 String *Field_time_common::val_str(String *val_buffer,
6097                                    String *val_ptr MY_ATTRIBUTE((unused)))
6098 {
6099   ASSERT_COLUMN_MARKED_FOR_READ;
6100   MYSQL_TIME ltime;
6101   val_buffer->alloc(MAX_DATE_STRING_REP_LENGTH);
6102   val_buffer->set_charset(&my_charset_numeric);
6103   if (get_time(&ltime))
6104   {
6105     DBUG_ASSERT(0);
6106     set_zero_time(&ltime, MYSQL_TIMESTAMP_TIME);
6107   }
6108   make_time((Date_time_format *) 0, &ltime, val_buffer, dec);
6109   return val_buffer;
6110 }
6111 
6112 
6113 /**
6114   For a column for TIME type, get_date() takes the time
6115   value of the field, adds current date to it and returns
6116   the result as a DATETIME value.
6117 */
6118 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)6119 bool Field_time_common::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
6120 {
6121   ASSERT_COLUMN_MARKED_FOR_READ;
6122   MYSQL_TIME tm;
6123   if (get_time(&tm))
6124   {
6125     DBUG_ASSERT(0);
6126     set_zero_time(ltime, MYSQL_TIMESTAMP_TIME);
6127   }
6128   time_to_datetime(table ? table->in_use : current_thd, &tm, ltime);
6129   return false;
6130 }
6131 
6132 
val_date_temporal()6133 longlong Field_time_common::val_date_temporal()
6134 {
6135   ASSERT_COLUMN_MARKED_FOR_READ;
6136   MYSQL_TIME time, datetime;
6137   if (get_time(&time))
6138   {
6139     DBUG_ASSERT(0); // Field_time*::get_time should not fail
6140     return 0;
6141   }
6142   time_to_datetime(table ? table->in_use : current_thd, &time, &datetime);
6143   return TIME_to_longlong_datetime_packed(&datetime);
6144 }
6145 
6146 
send_binary(Protocol * protocol)6147 bool Field_time_common::send_binary(Protocol *protocol)
6148 {
6149   MYSQL_TIME ltime;
6150   if (is_null())
6151     return protocol->store_null();
6152   if (get_time(&ltime))
6153   {
6154     DBUG_ASSERT(0);
6155     set_zero_time(&ltime, MYSQL_TIMESTAMP_TIME);
6156   }
6157   ltime.day= ltime.hour / 24;         // Move hours to days
6158   ltime.hour-= ltime.day * 24;
6159   return protocol->store_time(&ltime, 0);
6160 }
6161 
6162 
6163 /****************************************************************************
6164 ** time type
6165 ** In string context: HH:MM:SS
6166 ** In number context: HHMMSS
6167 ** Stored as a 3 byte unsigned int
6168 ****************************************************************************/
6169 
6170 type_conversion_status
store_internal(const MYSQL_TIME * ltime,int * warnings)6171 Field_time::store_internal(const MYSQL_TIME *ltime, int *warnings)
6172 {
6173   long tmp= ((ltime->month ? 0 : ltime->day * 24L) + ltime->hour) * 10000L +
6174             (ltime->minute * 100 + ltime->second);
6175   if (ltime->neg)
6176     tmp= -tmp;
6177   int3store(ptr, tmp);
6178   return TYPE_OK;
6179 }
6180 
6181 
store_packed(longlong nr)6182 type_conversion_status Field_time::store_packed(longlong nr)
6183 {
6184   MYSQL_TIME ltime;
6185   TIME_from_longlong_time_packed(&ltime, nr);
6186   return Field_time::store_time(&ltime, 0);
6187 }
6188 
6189 
val_time_temporal()6190 longlong Field_time::val_time_temporal()
6191 {
6192   ASSERT_COLUMN_MARKED_FOR_READ;
6193   MYSQL_TIME ltime;
6194   return get_time(&ltime) ? 0 : TIME_to_longlong_time_packed(&ltime);
6195 }
6196 
6197 
val_int()6198 longlong Field_time::val_int()
6199 {
6200   ASSERT_COLUMN_MARKED_FOR_READ;
6201   return (longlong) sint3korr(ptr);
6202 }
6203 
6204 
get_time(MYSQL_TIME * ltime)6205 bool Field_time::get_time(MYSQL_TIME *ltime)
6206 {
6207   long tmp=(long) sint3korr(ptr);
6208   if ((ltime->neg= tmp < 0))
6209     tmp= -tmp;
6210   ltime->year= ltime->month= ltime->day= 0;
6211   TIME_set_hhmmss(ltime, tmp);
6212   ltime->second_part=0;
6213   ltime->time_type= MYSQL_TIMESTAMP_TIME;
6214   return false;
6215 }
6216 
6217 
cmp(const uchar * a_ptr,const uchar * b_ptr)6218 int Field_time::cmp(const uchar *a_ptr, const uchar *b_ptr)
6219 {
6220   int32 a,b;
6221   a= sint3korr(a_ptr);
6222   b= sint3korr(b_ptr);
6223   return (a < b) ? -1 : (a > b) ? 1 : 0;
6224 }
6225 
6226 
make_sort_key(uchar * to,size_t length)6227 void Field_time::make_sort_key(uchar *to, size_t length)
6228 {
6229   DBUG_ASSERT(length >= 3);
6230   to[0] = (uchar) (ptr[2] ^ 128);
6231   to[1] = ptr[1];
6232   to[2] = ptr[0];
6233 }
6234 
6235 
sql_type(String & res) const6236 void Field_time::sql_type(String &res) const
6237 {
6238   res.set_ascii(STRING_WITH_LEN("time"));
6239 }
6240 
6241 
6242 /****************************************************************************
6243 ** time type with fsp
6244 ** In string context: HH:MM:SS.FFFFFF
6245 ** In number context: HHMMSS.FFFFFF
6246 ****************************************************************************/
6247 
6248 
val_int()6249 longlong Field_timef::val_int()
6250 {
6251   ASSERT_COLUMN_MARKED_FOR_READ;
6252   MYSQL_TIME ltime;
6253   if (get_time(&ltime))
6254   {
6255     DBUG_ASSERT(0);
6256     set_zero_time(&ltime, MYSQL_TIMESTAMP_TIME);
6257   }
6258   longlong tmp= (longlong) TIME_to_ulonglong_time_round(&ltime);
6259   return ltime.neg ? -tmp : tmp;
6260 }
6261 
6262 
val_decimal(my_decimal * decimal_value)6263 my_decimal *Field_timef::val_decimal(my_decimal *decimal_value)
6264 {
6265   ASSERT_COLUMN_MARKED_FOR_READ;
6266   MYSQL_TIME ltime;
6267   if (get_time(&ltime))
6268   {
6269     DBUG_ASSERT(0);
6270     set_zero_time(&ltime, MYSQL_TIMESTAMP_TIME);
6271   }
6272   return time2my_decimal(&ltime, decimal_value);
6273 }
6274 
6275 
val_real()6276 double Field_timef::val_real()
6277 {
6278   ASSERT_COLUMN_MARKED_FOR_READ;
6279   MYSQL_TIME ltime;
6280   if (get_time(&ltime))
6281   {
6282     DBUG_ASSERT(0);
6283     return 0;
6284   }
6285   double tmp= TIME_to_double_time(&ltime);
6286   return ltime.neg ? -tmp : tmp;
6287 }
6288 
6289 
sql_type(String & res) const6290 void Field_timef::sql_type(String &res) const
6291 {
6292   if (dec == 0)
6293   {
6294     res.set_ascii(STRING_WITH_LEN("time"));
6295     return;
6296   }
6297   const CHARSET_INFO *cs= res.charset();
6298   res.length(cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
6299                                "time(%d)", dec));
6300 }
6301 
6302 
reset()6303 type_conversion_status Field_timef::reset()
6304 {
6305   return store_packed(0);
6306 }
6307 
6308 
store_packed(longlong nr)6309 type_conversion_status Field_timef::store_packed(longlong nr)
6310 {
6311   my_time_packed_to_binary(nr, ptr, dec);
6312   return TYPE_OK;
6313 }
6314 
6315 
val_time_temporal()6316 longlong Field_timef::val_time_temporal()
6317 {
6318   ASSERT_COLUMN_MARKED_FOR_READ;
6319   return my_time_packed_from_binary(ptr, dec);
6320 }
6321 
6322 
6323 type_conversion_status
store_internal(const MYSQL_TIME * ltime,int * warnings)6324 Field_timef::store_internal(const MYSQL_TIME *ltime, int *warnings)
6325 {
6326   type_conversion_status rc= store_packed(TIME_to_longlong_time_packed(ltime));
6327   if (rc == TYPE_OK && non_zero_date(ltime))
6328   {
6329     /*
6330       The DATE part got lost; we warn, like in Field_newdate::store_internal,
6331       and trigger some code in get_mm_leaf()
6332       (see err==TYPE_NOTE_TIME_TRUNCATED there).
6333     */
6334     *warnings|= MYSQL_TIME_NOTE_TRUNCATED;
6335     rc= TYPE_NOTE_TIME_TRUNCATED;
6336   }
6337   return rc;
6338 }
6339 
6340 
get_time(MYSQL_TIME * ltime)6341 bool Field_timef::get_time(MYSQL_TIME *ltime)
6342 {
6343   longlong tmp= val_time_temporal();
6344   TIME_from_longlong_time_packed(ltime, tmp);
6345   return false;
6346 }
6347 
6348 
6349 /****************************************************************************
6350 ** year type
6351 ** Save in a byte the year 0, 1901->2155
6352 ** Can handle 2 byte or 4 byte years!
6353 ****************************************************************************/
6354 
6355 type_conversion_status
store(const char * from,size_t len,const CHARSET_INFO * cs)6356 Field_year::store(const char *from, size_t len,const CHARSET_INFO *cs)
6357 {
6358   ASSERT_COLUMN_MARKED_FOR_WRITE;
6359   char *end;
6360   int conv_error;
6361   type_conversion_status ret= TYPE_OK;
6362   longlong nr= cs->cset->strntoull10rnd(cs, from, len, 0, &end, &conv_error);
6363 
6364   if (nr < 0 || (nr >= 100 && nr <= 1900) || nr > 2155 ||
6365       conv_error == MY_ERRNO_ERANGE)
6366   {
6367     *ptr=0;
6368     set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
6369     return TYPE_WARN_OUT_OF_RANGE;
6370   }
6371 
6372   if (conv_error)
6373     ret= TYPE_ERR_BAD_VALUE;
6374 
6375   if (table->in_use->count_cuted_fields)
6376     ret= check_int(cs, from, len, end, conv_error);
6377 
6378   if (ret != TYPE_OK)
6379   {
6380     if (ret == TYPE_ERR_BAD_VALUE)  /* empty or incorrect string */
6381     {
6382       *ptr= 0; // Invalid date
6383       return ret;
6384     }
6385     ret= TYPE_WARN_OUT_OF_RANGE;
6386   }
6387 
6388   if (nr != 0 || len != 4)
6389   {
6390     if (nr < YY_PART_YEAR)
6391       nr+=100;					// 2000 - 2069
6392     else if (nr > 1900)
6393       nr-= 1900;
6394   }
6395   *ptr= (char) (uchar) nr;
6396   return ret;
6397 }
6398 
6399 
store(double nr)6400 type_conversion_status Field_year::store(double nr)
6401 {
6402   if (nr < 0.0 || nr > 2155.0)
6403   {
6404     (void) Field_year::store((longlong) -1, FALSE);
6405     return TYPE_WARN_OUT_OF_RANGE;
6406   }
6407   return Field_year::store((longlong) nr, FALSE);
6408 }
6409 
6410 
6411 type_conversion_status
store_time(MYSQL_TIME * ltime,uint8 dec_arg MY_ATTRIBUTE ((unused)))6412 Field_year::store_time(MYSQL_TIME *ltime,
6413                        uint8 dec_arg MY_ATTRIBUTE((unused)))
6414 {
6415   if (ltime->time_type != MYSQL_TIMESTAMP_DATETIME &&
6416       ltime->time_type != MYSQL_TIMESTAMP_DATE)
6417   {
6418     /* Convert time to datetime, then store year of the result */
6419     THD *thd= table ? table->in_use : current_thd;
6420     MYSQL_TIME ltime2;
6421     time_to_datetime(thd, ltime, &ltime2);
6422     return store(ltime2.year, 0);
6423   }
6424   return store(ltime->year, 0);
6425 }
6426 
6427 
store(longlong nr,bool unsigned_val)6428 type_conversion_status Field_year::store(longlong nr, bool unsigned_val)
6429 {
6430   ASSERT_COLUMN_MARKED_FOR_WRITE;
6431   if (nr < 0 || (nr >= 100 && nr <= 1900) || nr > 2155)
6432   {
6433     *ptr= 0;
6434     set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
6435     return TYPE_WARN_OUT_OF_RANGE;
6436   }
6437   if (nr != 0 || field_length != 4)		// 0000 -> 0; 00 -> 2000
6438   {
6439     if (nr < YY_PART_YEAR)
6440       nr+=100;					// 2000 - 2069
6441     else if (nr > 1900)
6442       nr-= 1900;
6443   }
6444   *ptr= (char) (uchar) nr;
6445   return TYPE_OK;
6446 }
6447 
6448 
send_binary(Protocol * protocol)6449 bool Field_year::send_binary(Protocol *protocol)
6450 {
6451   ASSERT_COLUMN_MARKED_FOR_READ;
6452   if (is_null())
6453     return protocol->store_null();
6454   ulonglong tmp= Field_year::val_int();
6455   return protocol->store_short(tmp);
6456 }
6457 
6458 
val_real(void)6459 double Field_year::val_real(void)
6460 {
6461   return (double) Field_year::val_int();
6462 }
6463 
6464 
val_int(void)6465 longlong Field_year::val_int(void)
6466 {
6467   ASSERT_COLUMN_MARKED_FOR_READ;
6468   DBUG_ASSERT(field_length == 2 || field_length == 4);
6469   int tmp= (int) ptr[0];
6470   if (field_length != 4)
6471     tmp%=100;					// Return last 2 char
6472   else if (tmp)
6473     tmp+=1900;
6474   return (longlong) tmp;
6475 }
6476 
6477 
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))6478 String *Field_year::val_str(String *val_buffer,
6479 			    String *val_ptr MY_ATTRIBUTE((unused)))
6480 {
6481   DBUG_ASSERT(field_length < 5);
6482   val_buffer->alloc(5);
6483   val_buffer->length(field_length);
6484   char *to=(char*) val_buffer->ptr();
6485   sprintf(to,field_length == 2 ? "%02d" : "%04d",(int) Field_year::val_int());
6486   val_buffer->set_charset(&my_charset_numeric);
6487   return val_buffer;
6488 }
6489 
6490 
sql_type(String & res) const6491 void Field_year::sql_type(String &res) const
6492 {
6493   const CHARSET_INFO *cs=res.charset();
6494   res.length(cs->cset->snprintf(cs,(char*)res.ptr(),res.alloced_length(),
6495 			  "year(%d)",(int) field_length));
6496 }
6497 
6498 
6499 /****************************************************************************
6500 ** The new date type
6501 ** Stored as 3 bytes
6502 ** In number context: YYYYMMDD
6503 ****************************************************************************/
6504 
date_flags(const THD * thd)6505 my_time_flags_t Field_newdate::date_flags(const THD *thd)
6506 {
6507   my_time_flags_t date_flags= TIME_FUZZY_DATE;
6508   if (thd->variables.sql_mode & MODE_NO_ZERO_DATE)
6509     date_flags|= TIME_NO_ZERO_DATE;
6510   if (thd->variables.sql_mode & MODE_NO_ZERO_IN_DATE)
6511     date_flags|= TIME_NO_ZERO_IN_DATE;
6512   if (thd->variables.sql_mode & MODE_INVALID_DATES)
6513     date_flags|= TIME_INVALID_DATES;
6514   return date_flags;
6515 }
6516 
6517 
6518 type_conversion_status
store_internal(const MYSQL_TIME * ltime,int * warnings)6519 Field_newdate::store_internal(const MYSQL_TIME *ltime, int *warnings)
6520 {
6521   long tmp= ltime->day + ltime->month * 32 + ltime->year * 16 * 32;
6522   int3store(ptr, tmp);
6523   if (non_zero_time(ltime))
6524   {
6525     *warnings|= MYSQL_TIME_NOTE_TRUNCATED;
6526     return TYPE_NOTE_TIME_TRUNCATED;
6527   }
6528   return TYPE_OK;
6529 }
6530 
6531 
get_date_internal(MYSQL_TIME * ltime)6532 bool Field_newdate::get_date_internal(MYSQL_TIME *ltime)
6533 {
6534   uint32 tmp= uint3korr(ptr);
6535   ltime->day=   tmp & 31;
6536   ltime->month= (tmp >> 5) & 15;
6537   ltime->year=  (tmp >> 9);
6538   ltime->time_type= MYSQL_TIMESTAMP_DATE;
6539   ltime->hour= ltime->minute= ltime->second= ltime->second_part= ltime->neg= 0;
6540   return false;
6541 }
6542 
6543 
store_packed(longlong nr)6544 type_conversion_status Field_newdate::store_packed(longlong nr)
6545 {
6546   int warnings= 0;
6547   MYSQL_TIME ltime;
6548   TIME_from_longlong_date_packed(&ltime, nr);
6549   return store_internal(&ltime, &warnings);
6550 }
6551 
6552 
send_binary(Protocol * protocol)6553 bool Field_newdate::send_binary(Protocol *protocol)
6554 {
6555   MYSQL_TIME ltime;
6556   if (is_null())
6557     return protocol->store_null();
6558   get_date(&ltime, 0);
6559   return protocol->store_date(&ltime);
6560 }
6561 
6562 
val_int()6563 longlong Field_newdate::val_int()
6564 {
6565   ASSERT_COLUMN_MARKED_FOR_READ;
6566   ulong j= uint3korr(ptr);
6567   j= (j % 32L)+(j / 32L % 16L)*100L + (j/(16L*32L))*10000L;
6568   return (longlong) j;
6569 }
6570 
6571 
val_date_temporal()6572 longlong Field_newdate::val_date_temporal()
6573 {
6574   ASSERT_COLUMN_MARKED_FOR_READ;
6575   MYSQL_TIME ltime;
6576   return get_date_internal(&ltime) ? 0 : TIME_to_longlong_date_packed(&ltime);
6577 }
6578 
6579 
val_time_temporal()6580 longlong Field_newdate::val_time_temporal()
6581 {
6582   ASSERT_COLUMN_MARKED_FOR_READ;
6583   return 0;
6584 }
6585 
6586 
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))6587 String *Field_newdate::val_str(String *val_buffer,
6588 			       String *val_ptr MY_ATTRIBUTE((unused)))
6589 {
6590   ASSERT_COLUMN_MARKED_FOR_READ;
6591   val_buffer->alloc(field_length);
6592   val_buffer->length(field_length);
6593   uint32 tmp= uint3korr(ptr);
6594   int part;
6595   char *pos=(char*) val_buffer->ptr()+10;
6596 
6597   /* Open coded to get more speed */
6598   *pos--=0;					// End NULL
6599   part=(int) (tmp & 31);
6600   *pos--= (char) ('0'+part%10);
6601   *pos--= (char) ('0'+part/10);
6602   *pos--= '-';
6603   part=(int) (tmp >> 5 & 15);
6604   *pos--= (char) ('0'+part%10);
6605   *pos--= (char) ('0'+part/10);
6606   *pos--= '-';
6607   part=(int) (tmp >> 9);
6608   *pos--= (char) ('0'+part%10); part/=10;
6609   *pos--= (char) ('0'+part%10); part/=10;
6610   *pos--= (char) ('0'+part%10); part/=10;
6611   *pos=   (char) ('0'+part);
6612   val_buffer->set_charset(&my_charset_numeric);
6613   return val_buffer;
6614 }
6615 
6616 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)6617 bool Field_newdate::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
6618 {
6619   return get_internal_check_zero(ltime, fuzzydate) ||
6620          check_fuzzy_date(ltime, fuzzydate);
6621 }
6622 
6623 
cmp(const uchar * a_ptr,const uchar * b_ptr)6624 int Field_newdate::cmp(const uchar *a_ptr, const uchar *b_ptr)
6625 {
6626   uint32 a,b;
6627   a= uint3korr(a_ptr);
6628   b= uint3korr(b_ptr);
6629   return (a < b) ? -1 : (a > b) ? 1 : 0;
6630 }
6631 
6632 
make_sort_key(uchar * to,size_t length)6633 void Field_newdate::make_sort_key(uchar *to, size_t length)
6634 {
6635   DBUG_ASSERT(length >= 3);
6636   to[0] = ptr[2];
6637   to[1] = ptr[1];
6638   to[2] = ptr[0];
6639 }
6640 
6641 
sql_type(String & res) const6642 void Field_newdate::sql_type(String &res) const
6643 {
6644   res.set_ascii(STRING_WITH_LEN("date"));
6645 }
6646 
6647 
6648 /****************************************************************************
6649 ** datetime type
6650 ** In string context: YYYY-MM-DD HH:MM:DD
6651 ** In number context: YYYYMMDDHHMMDD
6652 ** Stored as a 8 byte unsigned int. Should sometimes be change to a 6 byte int.
6653 ****************************************************************************/
6654 
6655 
date_flags(const THD * thd)6656 my_time_flags_t Field_datetime::date_flags(const THD *thd)
6657 {
6658   my_time_flags_t date_flags= TIME_FUZZY_DATE;
6659   if (thd->variables.sql_mode & MODE_NO_ZERO_DATE)
6660     date_flags|= TIME_NO_ZERO_DATE;
6661   if (thd->variables.sql_mode & MODE_NO_ZERO_IN_DATE)
6662     date_flags|= TIME_NO_ZERO_IN_DATE;
6663   if (thd->variables.sql_mode & MODE_INVALID_DATES)
6664     date_flags|= TIME_INVALID_DATES;
6665   return date_flags;
6666 }
6667 
6668 
store_timestamp_internal(const timeval * tm)6669 void Field_datetime::store_timestamp_internal(const timeval *tm)
6670 {
6671   MYSQL_TIME mysql_time;
6672   THD *thd= current_thd;
6673   thd->variables.time_zone->gmt_sec_to_TIME(&mysql_time, *tm);
6674   thd->time_zone_used= true;
6675   int error= 0;
6676   store_internal(&mysql_time, &error);
6677 }
6678 
6679 
6680 /**
6681   Store a DATETIME in a 8-byte integer to record.
6682 
6683   @param table  Table
6684   @param tmp    The number, in YYYYMMDDhhmmss format
6685   @param ptr    Where to store to
6686 */
6687 static inline type_conversion_status
datetime_store_internal(TABLE * table,ulonglong tmp,uchar * ptr)6688 datetime_store_internal(TABLE *table, ulonglong tmp, uchar *ptr)
6689 {
6690 #ifdef WORDS_BIGENDIAN
6691   if (table && table->s->db_low_byte_first)
6692   {
6693     int8store(ptr, tmp);
6694   }
6695   else
6696 #endif
6697     longlongstore(ptr, tmp);
6698   return TYPE_OK;
6699 }
6700 
6701 
6702 /**
6703   Read a DATETIME from record to a 8-byte integer
6704 
6705   @param table  Table
6706   @param ptr    Where to read from
6707   @retval       An integer in format YYYYMMDDhhmmss
6708 */
6709 static inline longlong
datetime_get_internal(TABLE * table,uchar * ptr)6710 datetime_get_internal(TABLE *table, uchar *ptr)
6711 {
6712   longlong tmp;
6713 #ifdef WORDS_BIGENDIAN
6714   if (table && table->s->db_low_byte_first)
6715     tmp= sint8korr(ptr);
6716   else
6717 #endif
6718     longlongget(&tmp, ptr);
6719   return tmp;
6720 }
6721 
6722 
get_date_internal(MYSQL_TIME * ltime)6723 bool Field_datetime::get_date_internal(MYSQL_TIME *ltime)
6724 {
6725   longlong tmp= datetime_get_internal(table, ptr);
6726   ltime->time_type= MYSQL_TIMESTAMP_DATETIME;
6727   ltime->neg= 0;
6728   ltime->second_part= 0;
6729   TIME_set_yymmdd(ltime, (uint) (tmp / 1000000LL));
6730   TIME_set_hhmmss(ltime, (uint) (tmp % 1000000LL));
6731   return false;
6732 }
6733 
6734 
6735 type_conversion_status
store_internal(const MYSQL_TIME * ltime,int * warnings)6736 Field_datetime::store_internal(const MYSQL_TIME *ltime, int *warnings)
6737 {
6738   ulonglong tmp= TIME_to_ulonglong_datetime(ltime);
6739   return datetime_store_internal(table, tmp, ptr);
6740 }
6741 
6742 
store(longlong nr,bool unsigned_val)6743 type_conversion_status Field_datetime::store(longlong nr, bool unsigned_val)
6744 {
6745   ASSERT_COLUMN_MARKED_FOR_WRITE;
6746   MYSQL_TIME ltime;
6747   int warnings;
6748   type_conversion_status error= TYPE_OK;
6749   longlong tmp= convert_number_to_datetime(nr, unsigned_val,
6750                                            &ltime, &warnings);
6751   if (tmp == -1LL)
6752     error= TYPE_ERR_BAD_VALUE;
6753   else
6754   {
6755     error= time_warning_to_type_conversion_status(warnings);
6756     datetime_store_internal(table, tmp, ptr);
6757   }
6758   if (warnings)
6759     set_warnings(ErrConvString(nr, unsigned_val), warnings);
6760   return error;
6761 }
6762 
6763 
store_packed(longlong nr)6764 type_conversion_status Field_datetime::store_packed(longlong nr)
6765 {
6766   MYSQL_TIME ltime;
6767   TIME_from_longlong_datetime_packed(&ltime, nr);
6768   return Field_datetime::store_time(&ltime, 0);
6769 }
6770 
6771 
val_int()6772 longlong Field_datetime::val_int()
6773 {
6774   ASSERT_COLUMN_MARKED_FOR_READ;
6775   return datetime_get_internal(table, ptr);
6776 }
6777 
6778 
6779 /*
6780   We don't reuse the parent method for performance purposes,
6781   to avoid convertion from number to MYSQL_TIME.
6782   Using my_datetime_number_to_str() instead of my_datetime_to_str().
6783 */
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))6784 String *Field_datetime::val_str(String *val_buffer,
6785 				String *val_ptr MY_ATTRIBUTE((unused)))
6786 {
6787   ASSERT_COLUMN_MARKED_FOR_READ;
6788   val_buffer->alloc(field_length + 1);
6789   val_buffer->set_charset(&my_charset_numeric);
6790   val_buffer->length(MAX_DATETIME_WIDTH);
6791   longlong tmp= datetime_get_internal(table, ptr);
6792   val_buffer->length(my_datetime_number_to_str((char *) val_buffer->ptr(),
6793                                                tmp));
6794   return val_buffer;
6795 }
6796 
6797 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)6798 bool Field_datetime::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
6799 {
6800   return get_internal_check_zero(ltime, fuzzydate) ||
6801          check_fuzzy_date(ltime, fuzzydate);
6802 }
6803 
6804 
cmp(const uchar * a_ptr,const uchar * b_ptr)6805 int Field_datetime::cmp(const uchar *a_ptr, const uchar *b_ptr)
6806 {
6807   longlong a,b;
6808 #ifdef WORDS_BIGENDIAN
6809   if (table && table->s->db_low_byte_first)
6810   {
6811     a=sint8korr(a_ptr);
6812     b=sint8korr(b_ptr);
6813   }
6814   else
6815 #endif
6816   {
6817     longlongget(&a, a_ptr);
6818     longlongget(&b, b_ptr);
6819   }
6820   return ((ulonglong) a < (ulonglong) b) ? -1 :
6821     ((ulonglong) a > (ulonglong) b) ? 1 : 0;
6822 }
6823 
make_sort_key(uchar * to,size_t length)6824 void Field_datetime::make_sort_key(uchar *to, size_t length)
6825 {
6826   const size_t pack_length= PACK_LENGTH;
6827   const size_t to_length= min(pack_length, length);
6828 #ifdef WORDS_BIGENDIAN
6829   if (!table || !table->s->db_low_byte_first)
6830     copy_integer<true>(to, to_length, ptr, pack_length, true);
6831   else
6832 #endif
6833   copy_integer<false>(to, to_length, ptr, pack_length, true);
6834 }
6835 
6836 
sql_type(String & res) const6837 void Field_datetime::sql_type(String &res) const
6838 {
6839   res.set_ascii(STRING_WITH_LEN("datetime"));
6840 }
6841 
6842 /****************************************************************************
6843 ** datetimef type
6844 ** In string context: YYYY-MM-DD HH:MM:DD.FFFFFF
6845 ** In number context: YYYYMMDDHHMMDD.FFFFFF
6846 ** Stored as a 8 byte value.
6847 ****************************************************************************/
6848 
6849 
date_flags(const THD * thd)6850 my_time_flags_t Field_datetimef::date_flags(const THD *thd)
6851 {
6852   my_time_flags_t date_flags= TIME_FUZZY_DATE;
6853   if (thd->variables.sql_mode & MODE_NO_ZERO_DATE)
6854     date_flags|= TIME_NO_ZERO_DATE;
6855   if (thd->variables.sql_mode & MODE_NO_ZERO_IN_DATE)
6856     date_flags|= TIME_NO_ZERO_IN_DATE;
6857   if (thd->variables.sql_mode & MODE_INVALID_DATES)
6858     date_flags|= TIME_INVALID_DATES;
6859   return date_flags;
6860 }
6861 
6862 
store_timestamp_internal(const timeval * tm)6863 void Field_datetimef::store_timestamp_internal(const timeval *tm)
6864 {
6865   MYSQL_TIME mysql_time;
6866   THD *thd= current_thd;
6867   thd->variables.time_zone->gmt_sec_to_TIME(&mysql_time, *tm);
6868   thd->time_zone_used= true;
6869   int warnings= 0;
6870   store_internal(&mysql_time, &warnings);
6871 }
6872 
6873 
6874 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)6875 bool Field_datetimef::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
6876 {
6877   return get_internal_check_zero(ltime, fuzzydate) ||
6878          check_fuzzy_date(ltime, fuzzydate);
6879 }
6880 
6881 
sql_type(String & res) const6882 void Field_datetimef::sql_type(String &res) const
6883 {
6884   if (dec == 0)
6885   {
6886     res.set_ascii(STRING_WITH_LEN("datetime"));
6887     return;
6888   }
6889   const CHARSET_INFO *cs= res.charset();
6890   res.length(cs->cset->snprintf(cs, (char *) res.ptr(), res.alloced_length(),
6891                                 "datetime(%d)", dec));
6892 }
6893 
6894 
get_date_internal(MYSQL_TIME * ltime)6895 bool Field_datetimef::get_date_internal(MYSQL_TIME *ltime)
6896 {
6897   TIME_from_longlong_datetime_packed(ltime, val_date_temporal());
6898   return false;
6899 }
6900 
6901 
6902 type_conversion_status
store_internal(const MYSQL_TIME * ltime,int * warnings)6903 Field_datetimef::store_internal(const MYSQL_TIME *ltime, int *warnings)
6904 {
6905   store_packed(TIME_to_longlong_datetime_packed(ltime));
6906   return TYPE_OK;
6907 }
6908 
6909 
reset()6910 type_conversion_status Field_datetimef::reset()
6911 {
6912   store_packed(0);
6913   return TYPE_OK;
6914 }
6915 
6916 
val_date_temporal()6917 longlong Field_datetimef::val_date_temporal()
6918 {
6919   return my_datetime_packed_from_binary(ptr, dec);
6920 }
6921 
6922 
store_packed(longlong nr)6923 type_conversion_status Field_datetimef::store_packed(longlong nr)
6924 {
6925   my_datetime_packed_to_binary(nr, ptr, dec);
6926   return TYPE_OK;
6927 }
6928 
6929 
6930 
6931 /****************************************************************************
6932 ** string type
6933 ** A string may be varchar or binary
6934 ****************************************************************************/
6935 
6936 /**
6937   Report "not well formed" or "cannot convert" error
6938   after storing a character string info a field.
6939 
6940   As of version 5.0 both cases return the same error:
6941 
6942       "Invalid string value: 'xxx' for column 't' at row 1"
6943 
6944   Future versions will possibly introduce a new error message:
6945 
6946       "Cannot convert character string: 'xxx' for column 't' at row 1"
6947 
6948   @param  original_string            this is is the original string that was
6949                                      supposed to be copied. Helps in keeping
6950                                      track of whether a value has been
6951                                      completely truncated.
6952   @param  well_formed_error_pos      position of the first non-wellformed
6953                                      character in the source string
6954   @param  cannot_convert_error_pos   position of the first non-convertable
6955                                      character in the source string
6956   @param  from_end_pos               position where conversion stopped in
6957                                      the source string
6958   @param  end                        end of the source string
6959   @param  count_spaces               treat trailing spaces as important data
6960   @param  cs                         character set of the string
6961 
6962   @return TYPE_OK, TYPE_NOTE_TRUNCATED, TYPE_WARN_TRUNCATED,
6963           TYPE_WARN_INVALID_STRING
6964 
6965 */
6966 
6967 type_conversion_status
check_string_copy_error(const char * original_string,const char * well_formed_error_pos,const char * cannot_convert_error_pos,const char * from_end_pos,const char * end,bool count_spaces,const CHARSET_INFO * cs)6968 Field_longstr::check_string_copy_error(const char *original_string,
6969                                        const char *well_formed_error_pos,
6970                                        const char *cannot_convert_error_pos,
6971                                        const char *from_end_pos,
6972                                        const char *end,
6973                                        bool count_spaces,
6974                                        const CHARSET_INFO *cs)
6975 {
6976   const char *pos;
6977   char tmp[32];
6978   THD *thd= table->in_use;
6979 
6980   if (!(pos= well_formed_error_pos) &&
6981       !(pos= cannot_convert_error_pos))
6982     return report_if_important_data(from_end_pos, end, count_spaces);
6983 
6984   convert_to_printable(tmp, sizeof(tmp), pos, (end - pos), cs, 6);
6985 
6986   push_warning_printf(thd,
6987                       Sql_condition::SL_WARNING,
6988                       ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
6989                       ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
6990                       "string", tmp, field_name,
6991                       thd->get_stmt_da()->current_row_for_condition());
6992 
6993   if (well_formed_error_pos != NULL)
6994     return TYPE_WARN_INVALID_STRING;
6995 
6996   return TYPE_WARN_TRUNCATED;
6997 }
6998 
6999 
7000 /*
7001   Check if we lost any important data and send a truncation error/warning
7002 
7003   SYNOPSIS
7004     Field_longstr::report_if_important_data()
7005     pstr                     - Truncated rest of string
7006     end                      - End of truncated string
7007     count_spaces             - Treat traling spaces as important data
7008 
7009   RETURN VALUES
7010     TYPE_OK    - None was truncated
7011     != TYPE_OK - Some bytes were truncated
7012 
7013   NOTE
7014     Check if we lost any important data (anything in a binary string,
7015     or any non-space in others). If only trailing spaces was lost,
7016     send a truncation note, otherwise send a truncation error.
7017     Silently ignore traling spaces if the count_space parameter is FALSE.
7018 */
7019 
7020 type_conversion_status
report_if_important_data(const char * pstr,const char * end,bool count_spaces)7021 Field_longstr::report_if_important_data(const char *pstr, const char *end,
7022                                         bool count_spaces)
7023 {
7024   if (pstr < end)       // String is truncated
7025   {
7026     if (test_if_important_data(field_charset, pstr, end))
7027     {
7028       // Warning should only be written when count_cuted_fields is set
7029       if (table->in_use->count_cuted_fields)
7030       {
7031         if (!table->in_use->lex->is_ignore() && table->in_use->is_strict_mode())
7032           set_warning(Sql_condition::SL_WARNING, ER_DATA_TOO_LONG, 1);
7033         else
7034           set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
7035       }
7036       return TYPE_WARN_TRUNCATED;
7037     }
7038     else if (count_spaces)
7039     { /* If we lost only spaces then produce a NOTE, not a WARNING */
7040       if (table->in_use->count_cuted_fields)
7041       {
7042         set_warning(Sql_condition::SL_NOTE, WARN_DATA_TRUNCATED, 1);
7043       }
7044       return TYPE_NOTE_TRUNCATED;
7045     }
7046   }
7047   return TYPE_OK;
7048 }
7049 
7050 
7051 	/* Copy a string and fill with space */
7052 
7053 type_conversion_status
store(const char * from,size_t length,const CHARSET_INFO * cs)7054 Field_string::store(const char *from, size_t length,const CHARSET_INFO *cs)
7055 {
7056   ASSERT_COLUMN_MARKED_FOR_WRITE;
7057   size_t copy_length;
7058   const char *well_formed_error_pos;
7059   const char *cannot_convert_error_pos;
7060   const char *from_end_pos;
7061 
7062   /* See the comment for Field_long::store(long long) */
7063   DBUG_ASSERT(table->in_use == current_thd);
7064 
7065   copy_length= field_well_formed_copy_nchars(field_charset,
7066                                        (char*) ptr, field_length,
7067                                        cs, from, length,
7068                                        field_length / field_charset->mbmaxlen,
7069                                        &well_formed_error_pos,
7070                                        &cannot_convert_error_pos,
7071                                        &from_end_pos);
7072 
7073   /* Append spaces if the string was shorter than the field. */
7074   if (copy_length < field_length)
7075     field_charset->cset->fill(field_charset,(char*) ptr+copy_length,
7076                               field_length-copy_length,
7077                               field_charset->pad_char);
7078 
7079   return check_string_copy_error(from, well_formed_error_pos,
7080                                  cannot_convert_error_pos, from_end_pos,
7081                                  from + length, false, cs);
7082 }
7083 
7084 
7085 /**
7086   Store double value in Field_string or Field_varstring.
7087 
7088   Pretty prints double number into field_length characters buffer.
7089 
7090   @param nr            number
7091 */
7092 
store(double nr)7093 type_conversion_status Field_str::store(double nr)
7094 {
7095   ASSERT_COLUMN_MARKED_FOR_WRITE;
7096   char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
7097   uint local_char_length= field_length / charset()->mbmaxlen;
7098   size_t length= 0;
7099   my_bool error= (local_char_length == 0);
7100 
7101   // my_gcvt() requires width > 0, and we may have a CHAR(0) column.
7102   if (!error)
7103     length= my_gcvt(nr, MY_GCVT_ARG_DOUBLE, local_char_length, buff, &error);
7104 
7105   if (error)
7106   {
7107     if (!table->in_use->lex->is_ignore() && table->in_use->is_strict_mode())
7108       set_warning(Sql_condition::SL_WARNING, ER_DATA_TOO_LONG, 1);
7109     else
7110       set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
7111   }
7112   return store(buff, length, &my_charset_numeric);
7113 }
7114 
7115 
7116 /**
7117   Check whether generated columns' expressions are the same.
7118 
7119   @param field  An existing field to compare against
7120 
7121   @return true means the same, otherwise not.
7122 */
7123 
gcol_expr_is_equal(const Field * field) const7124 bool Field::gcol_expr_is_equal(const Field *field) const
7125 {
7126   DBUG_ASSERT(is_gcol() && field->is_gcol());
7127 
7128   return gcol_info->expr_item->eq(field->gcol_info->expr_item, true);
7129 }
7130 
7131 
7132 /**
7133   Check whether generated columns' expressions are the same.
7134 
7135   @param field  A new field to compare against
7136 
7137   @return true means the same, otherwise not.
7138 */
7139 
gcol_expr_is_equal(const Create_field * field) const7140 bool Field::gcol_expr_is_equal(const Create_field *field) const
7141 {
7142   DBUG_ASSERT(is_gcol() && field->is_gcol());
7143 
7144   return ::is_equal(&gcol_info->expr_str, &field->gcol_info->expr_str);
7145 }
7146 
7147 
is_equal(Create_field * new_field)7148 uint Field::is_equal(Create_field *new_field)
7149 {
7150   return (new_field->sql_type == real_type());
7151 }
7152 
7153 
is_equal(Create_field * new_field)7154 uint Field_str::is_equal(Create_field *new_field)
7155 {
7156   return ((new_field->sql_type == real_type()) &&
7157 	  new_field->charset == field_charset &&
7158 	  new_field->length == max_display_length());
7159 }
7160 
7161 
store(longlong nr,bool unsigned_val)7162 type_conversion_status Field_string::store(longlong nr, bool unsigned_val)
7163 {
7164   char buff[64];
7165   size_t  l;
7166   const CHARSET_INFO *cs=charset();
7167   l= (cs->cset->longlong10_to_str)(cs,buff,sizeof(buff),
7168                                    unsigned_val ? 10 : -10, nr);
7169   return Field_string::store(buff, l, cs);
7170 }
7171 
7172 
store_decimal(const my_decimal * d)7173 type_conversion_status Field_longstr::store_decimal(const my_decimal *d)
7174 {
7175   char buff[DECIMAL_MAX_STR_LENGTH+1];
7176   String str(buff, sizeof(buff), &my_charset_numeric);
7177   my_decimal2string(E_DEC_FATAL_ERROR, d, 0, 0, 0, &str);
7178   return store(str.ptr(), str.length(), str.charset());
7179 }
7180 
max_data_length() const7181 uint32 Field_longstr::max_data_length() const
7182 {
7183   return field_length + (field_length > 255 ? 2 : 1);
7184 }
7185 
7186 
val_real(void)7187 double Field_string::val_real(void)
7188 {
7189   ASSERT_COLUMN_MARKED_FOR_READ;
7190   int error;
7191   char *end;
7192   const CHARSET_INFO *cs= charset();
7193   double result;
7194 
7195   result=  my_strntod(cs,(char*) ptr,field_length,&end,&error);
7196   if (!table->in_use->no_errors &&
7197       (error || (field_length != (uint32)(end - (char*) ptr) &&
7198                  !check_if_only_end_space(cs, end,
7199                                           (char*) ptr + field_length))))
7200   {
7201     ErrConvString err((char*) ptr, field_length, cs);
7202     push_warning_printf(current_thd, Sql_condition::SL_WARNING,
7203                         ER_TRUNCATED_WRONG_VALUE,
7204                         ER(ER_TRUNCATED_WRONG_VALUE), "DOUBLE",
7205                         err.ptr());
7206   }
7207   return result;
7208 }
7209 
7210 
val_int(void)7211 longlong Field_string::val_int(void)
7212 {
7213   ASSERT_COLUMN_MARKED_FOR_READ;
7214   int error;
7215   char *end;
7216   const CHARSET_INFO *cs= charset();
7217   longlong result;
7218 
7219   result= my_strntoll(cs, (char*) ptr,field_length,10,&end,&error);
7220   if (!table->in_use->no_errors &&
7221       (error || (field_length != (uint32)(end - (char*) ptr) &&
7222                  !check_if_only_end_space(cs, end,
7223                                           (char*) ptr + field_length))))
7224   {
7225     ErrConvString err((char*) ptr, field_length, cs);
7226     push_warning_printf(current_thd, Sql_condition::SL_WARNING,
7227                         ER_TRUNCATED_WRONG_VALUE,
7228                         ER(ER_TRUNCATED_WRONG_VALUE),
7229                         "INTEGER", err.ptr());
7230   }
7231   return result;
7232 }
7233 
7234 
val_str(String * val_buffer MY_ATTRIBUTE ((unused)),String * val_ptr)7235 String *Field_string::val_str(String *val_buffer MY_ATTRIBUTE((unused)),
7236 			      String *val_ptr)
7237 {
7238   ASSERT_COLUMN_MARKED_FOR_READ;
7239   /* See the comment for Field_long::store(long long) */
7240   DBUG_ASSERT(table->in_use == current_thd);
7241   size_t length;
7242   if (table->in_use->variables.sql_mode &
7243       MODE_PAD_CHAR_TO_FULL_LENGTH)
7244     length= my_charpos(field_charset, ptr, ptr + field_length,
7245                        field_length / field_charset->mbmaxlen);
7246   else
7247     length= field_charset->cset->lengthsp(field_charset, (const char*) ptr,
7248                                           field_length);
7249   val_ptr->set((const char*) ptr, length, field_charset);
7250   return val_ptr;
7251 }
7252 
7253 
val_decimal(my_decimal * decimal_value)7254 my_decimal *Field_string::val_decimal(my_decimal *decimal_value)
7255 {
7256   ASSERT_COLUMN_MARKED_FOR_READ;
7257   int err= str2my_decimal(E_DEC_FATAL_ERROR, (char*) ptr, field_length,
7258                           charset(), decimal_value);
7259   if (!table->in_use->no_errors && err)
7260   {
7261     ErrConvString errmsg((char*) ptr, field_length, charset());
7262     push_warning_printf(current_thd, Sql_condition::SL_WARNING,
7263                         ER_TRUNCATED_WRONG_VALUE,
7264                         ER(ER_TRUNCATED_WRONG_VALUE),
7265                         "DECIMAL", errmsg.ptr());
7266   }
7267 
7268   return decimal_value;
7269 }
7270 
7271 
7272 struct Check_field_param {
7273   Field *field;
7274 };
7275 
7276 #ifdef HAVE_REPLICATION
7277 static bool
check_field_for_37426(const void * param_arg)7278 check_field_for_37426(const void *param_arg)
7279 {
7280   Check_field_param *param= (Check_field_param*) param_arg;
7281   DBUG_ASSERT(param->field->real_type() == MYSQL_TYPE_STRING);
7282   DBUG_PRINT("debug", ("Field %s - type: %d, size: %d",
7283                        param->field->field_name,
7284                        param->field->real_type(),
7285                        param->field->row_pack_length()));
7286   return param->field->row_pack_length() > 255;
7287 }
7288 #endif
7289 
7290 bool
compatible_field_size(uint field_metadata,Relay_log_info * rli_arg,uint16 mflags MY_ATTRIBUTE ((unused)),int * order_var)7291 Field_string::compatible_field_size(uint field_metadata,
7292                                     Relay_log_info *rli_arg,
7293                                     uint16 mflags MY_ATTRIBUTE((unused)),
7294                                     int *order_var)
7295 {
7296 #ifdef HAVE_REPLICATION
7297   const Check_field_param check_param = { this };
7298   if (!is_mts_worker(rli_arg->info_thd) && rpl_master_has_bug(rli_arg, 37426, TRUE,
7299                          check_field_for_37426, &check_param))
7300     return FALSE;                        // Not compatible field sizes
7301 #endif
7302   return Field::compatible_field_size(field_metadata, rli_arg, mflags, order_var);
7303 }
7304 
7305 
cmp(const uchar * a_ptr,const uchar * b_ptr)7306 int Field_string::cmp(const uchar *a_ptr, const uchar *b_ptr)
7307 {
7308   size_t a_len, b_len;
7309 
7310   if (field_charset->mbmaxlen != 1)
7311   {
7312     uint char_len= field_length/field_charset->mbmaxlen;
7313     a_len= my_charpos(field_charset, a_ptr, a_ptr + field_length, char_len);
7314     b_len= my_charpos(field_charset, b_ptr, b_ptr + field_length, char_len);
7315   }
7316   else
7317     a_len= b_len= field_length;
7318   /*
7319     We have to remove end space to be able to compare multi-byte-characters
7320     like in latin_de 'ae' and 0xe4
7321   */
7322   return field_charset->coll->strnncollsp(field_charset,
7323                                           a_ptr, a_len,
7324                                           b_ptr, b_len,
7325                                           0);
7326 }
7327 
7328 
make_sort_key(uchar * to,size_t length)7329 void Field_string::make_sort_key(uchar *to, size_t length)
7330 {
7331   size_t tmp MY_ATTRIBUTE((unused))=
7332     field_charset->coll->strnxfrm(field_charset,
7333                                   to, length, char_length(),
7334                                   ptr, field_length,
7335                                   MY_STRXFRM_PAD_WITH_SPACE |
7336                                   MY_STRXFRM_PAD_TO_MAXLEN);
7337   DBUG_ASSERT(tmp == length);
7338 }
7339 
7340 
sql_type(String & res) const7341 void Field_string::sql_type(String &res) const
7342 {
7343   THD *thd= table->in_use;
7344   const CHARSET_INFO *cs=res.charset();
7345   size_t length;
7346 
7347   length= cs->cset->snprintf(cs,(char*) res.ptr(),
7348                              res.alloced_length(), "%s(%d)",
7349                              ((type() == MYSQL_TYPE_VAR_STRING &&
7350                                !thd->variables.new_mode) ?
7351                               (has_charset() ? "varchar" : "varbinary") :
7352 			      (has_charset() ? "char" : "binary")),
7353                              (int) field_length / charset()->mbmaxlen);
7354   res.length(length);
7355   if ((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) &&
7356       has_charset() && (charset()->state & MY_CS_BINSORT))
7357     res.append(STRING_WITH_LEN(" binary"));
7358 }
7359 
7360 
pack(uchar * to,const uchar * from,uint max_length,bool low_byte_first MY_ATTRIBUTE ((unused)))7361 uchar *Field_string::pack(uchar *to, const uchar *from,
7362                           uint max_length,
7363                           bool low_byte_first MY_ATTRIBUTE((unused)))
7364 {
7365   uint length=      min(field_length,max_length);
7366   uint local_char_length= max_length/field_charset->mbmaxlen;
7367   DBUG_PRINT("debug", ("Packing field '%s' - length: %u ", field_name, length));
7368 
7369   if (length > local_char_length)
7370     local_char_length= my_charpos(field_charset, from, from+length,
7371                                   local_char_length);
7372   set_if_smaller(length, local_char_length);
7373 
7374   /*
7375      TODO: change charset interface to add a new function that does
7376            the following or add a flag to lengthsp to do it itself
7377            (this is for not packing padding adding bytes in BINARY
7378            fields).
7379   */
7380   if (field_charset->mbmaxlen == 1)
7381   {
7382     while (length && from[length-1] == field_charset->pad_char)
7383       length --;
7384   }
7385   else
7386     length= field_charset->cset->lengthsp(field_charset, (const char*) from, length);
7387 
7388   // Length always stored little-endian
7389   *to++= (uchar) length;
7390   if (field_length > 255)
7391     *to++= (uchar) (length >> 8);
7392 
7393   // Store the actual bytes of the string
7394   memcpy(to, from, length);
7395   return to+length;
7396 }
7397 
7398 
7399 /**
7400    Unpack a string field from row data.
7401 
7402    This method is used to unpack a string field from a master whose size
7403    of the field is less than that of the slave. Note that there can be a
7404    variety of field types represented with this class. Certain types like
7405    ENUM or SET are processed differently. Hence, the upper byte of the
7406    @c param_data argument contains the result of field->real_type() from
7407    the master.
7408 
7409    @note For information about how the length is packed, see @c
7410    Field_string::do_save_field_metadata
7411 
7412    @param   to         Destination of the data
7413    @param   from       Source of the data
7414    @param   param_data Real type (upper) and length (lower) values
7415 
7416    @return  New pointer into memory based on from + length of the data
7417 */
7418 const uchar *
unpack(uchar * to,const uchar * from,uint param_data,bool low_byte_first MY_ATTRIBUTE ((unused)))7419 Field_string::unpack(uchar *to,
7420                      const uchar *from,
7421                      uint param_data,
7422                      bool low_byte_first MY_ATTRIBUTE((unused)))
7423 {
7424   uint from_length, length;
7425 
7426   /*
7427     Compute the declared length of the field on the master. This is
7428     used to decide if one or two bytes should be read as length.
7429    */
7430   if (param_data)
7431     from_length= (((param_data >> 4) & 0x300) ^ 0x300) + (param_data & 0x00ff);
7432   else
7433     from_length= field_length;
7434 
7435   DBUG_PRINT("debug",
7436              ("param_data: 0x%x, field_length: %u, from_length: %u",
7437               param_data, field_length, from_length));
7438   /*
7439     Compute the actual length of the data by reading one or two bits
7440     (depending on the declared field length on the master).
7441    */
7442   if (from_length > 255)
7443   {
7444     length= uint2korr(from);
7445     from+= 2;
7446   }
7447   else
7448     length= (uint) *from++;
7449 
7450   memcpy(to, from, length);
7451   // Pad the string with the pad character of the fields charset
7452   field_charset->cset->fill(field_charset, (char*) to + length, field_length - length, field_charset->pad_char);
7453   return from+length;
7454 }
7455 
7456 
7457 /**
7458    Save the field metadata for string fields.
7459 
7460    Saves the real type in the first byte and the field length in the
7461    second byte of the field metadata array at index of *metadata_ptr and
7462    *(metadata_ptr + 1).
7463 
7464    @note In order to be able to handle lengths exceeding 255 and be
7465    backwards-compatible with pre-5.1.26 servers, an extra two bits of
7466    the length has been added to the metadata in such a way that if
7467    they are set, a new unrecognized type is generated.  This will
7468    cause pre-5.1-26 servers to stop due to a field type mismatch,
7469    while new servers will be able to extract the extra bits. If the
7470    length is <256, there will be no difference and both a new and an
7471    old server will be able to handle it.
7472 
7473    @note The extra two bits are added to bits 13 and 14 of the
7474    parameter data (with 1 being the least siginficant bit and 16 the
7475    most significant bit of the word) by xoring the extra length bits
7476    with the real type.  Since all allowable types have 0xF as most
7477    significant bits of the metadata word, lengths <256 will not affect
7478    the real type at all, while all other values will result in a
7479    non-existant type in the range 17-244.
7480 
7481    @see Field_string::unpack
7482 
7483    @param   metadata_ptr   First byte of field metadata
7484 
7485    @returns number of bytes written to metadata_ptr
7486 */
do_save_field_metadata(uchar * metadata_ptr)7487 int Field_string::do_save_field_metadata(uchar *metadata_ptr)
7488 {
7489   DBUG_ASSERT(field_length < 1024);
7490   DBUG_ASSERT((real_type() & 0xF0) == 0xF0);
7491   DBUG_PRINT("debug", ("field_length: %u, real_type: %u",
7492                        field_length, real_type()));
7493   *metadata_ptr= (real_type() ^ ((field_length & 0x300) >> 4));
7494   *(metadata_ptr + 1)= field_length & 0xFF;
7495   return 2;
7496 }
7497 
7498 
packed_col_length(const uchar * data_ptr,uint length)7499 uint Field_string::packed_col_length(const uchar *data_ptr, uint length)
7500 {
7501   if (length > 255)
7502     return uint2korr(data_ptr)+2;
7503   return (uint) *data_ptr + 1;
7504 }
7505 
7506 
max_packed_col_length()7507 uint Field_string::max_packed_col_length()
7508 {
7509   const uint max_length= pack_length();
7510   return (max_length > 255 ? 2 : 1) + max_length;
7511 }
7512 
7513 
get_key_image(uchar * buff,size_t length,imagetype type_arg)7514 size_t Field_string::get_key_image(uchar *buff, size_t length, imagetype type_arg)
7515 {
7516   size_t bytes = my_charpos(field_charset, (char*) ptr,
7517                             (char*) ptr + field_length,
7518                             length / field_charset->mbmaxlen);
7519   memcpy(buff, ptr, bytes);
7520   if (bytes < length)
7521     field_charset->cset->fill(field_charset, (char*) buff + bytes,
7522                               length - bytes, field_charset->pad_char);
7523   return bytes;
7524 }
7525 
7526 
new_field(MEM_ROOT * root,TABLE * new_table,bool keep_type)7527 Field *Field_string::new_field(MEM_ROOT *root, TABLE *new_table,
7528                                bool keep_type)
7529 {
7530   Field *field;
7531   if (type() != MYSQL_TYPE_VAR_STRING || keep_type)
7532     field= Field::new_field(root, new_table, keep_type);
7533   else if ((field= new Field_varstring(field_length, maybe_null(), field_name,
7534                                        new_table->s, charset())))
7535   {
7536     /*
7537       Old VARCHAR field which should be modified to a VARCHAR on copy
7538       This is done to ensure that ALTER TABLE will convert old VARCHAR fields
7539       to now VARCHAR fields.
7540     */
7541     field->init(new_table);
7542     /*
7543       Normally orig_table is different from table only if field was created
7544       via ::new_field.  Here we alter the type of field, so ::new_field is
7545       not applicable. But we still need to preserve the original field
7546       metadata for the client-server protocol.
7547     */
7548     field->orig_table= orig_table;
7549   }
7550   return field;
7551 }
7552 
7553 
7554 /****************************************************************************
7555   VARCHAR type
7556   Data in field->ptr is stored as:
7557     1 or 2 bytes length-prefix-header  (from Field_varstring::length_bytes)
7558     data
7559 
7560   NOTE:
7561   When VARCHAR is stored in a key (for handler::index_read() etc) it's always
7562   stored with a 2 byte prefix. (Just like blob keys).
7563 
7564   Normally length_bytes is calculated as (field_length < 256 : 1 ? 2)
7565   The exception is if there is a prefix key field that is part of a long
7566   VARCHAR, in which case field_length for this may be 1 but the length_bytes
7567   is 2.
7568 ****************************************************************************/
7569 
7570 const uint Field_varstring::MAX_SIZE= UINT_MAX16;
7571 
7572 /**
7573    Save the field metadata for varstring fields.
7574 
7575    Saves the field length in the first byte. Note: may consume
7576    2 bytes. Caller must ensure second byte is contiguous with
7577    first byte (e.g. array index 0,1).
7578 
7579    @param   metadata_ptr   First byte of field metadata
7580 
7581    @returns number of bytes written to metadata_ptr
7582 */
do_save_field_metadata(uchar * metadata_ptr)7583 int Field_varstring::do_save_field_metadata(uchar *metadata_ptr)
7584 {
7585   DBUG_ASSERT(field_length <= 65535);
7586   int2store((char*)metadata_ptr, field_length);
7587   return 2;
7588 }
7589 
store(const char * from,size_t length,const CHARSET_INFO * cs)7590 type_conversion_status Field_varstring::store(const char *from, size_t length,
7591                                               const CHARSET_INFO *cs)
7592 {
7593   ASSERT_COLUMN_MARKED_FOR_WRITE;
7594   size_t copy_length;
7595   const char *well_formed_error_pos;
7596   const char *cannot_convert_error_pos;
7597   const char *from_end_pos;
7598 
7599   copy_length= field_well_formed_copy_nchars(field_charset,
7600                                        (char*) ptr + length_bytes,
7601                                        field_length,
7602                                        cs, from, length,
7603                                        field_length / field_charset->mbmaxlen,
7604                                        &well_formed_error_pos,
7605                                        &cannot_convert_error_pos,
7606                                        &from_end_pos);
7607 
7608   if (length_bytes == 1)
7609     *ptr= (uchar) copy_length;
7610   else
7611     int2store(ptr, static_cast<uint16>(copy_length));
7612 
7613   return check_string_copy_error(from, well_formed_error_pos,
7614                                  cannot_convert_error_pos, from_end_pos,
7615                                  from + length, true, cs);
7616 }
7617 
7618 
store(longlong nr,bool unsigned_val)7619 type_conversion_status Field_varstring::store(longlong nr, bool unsigned_val)
7620 {
7621   char buff[64];
7622   uint  length;
7623   length= (uint) (field_charset->cset->longlong10_to_str)(field_charset,
7624                                                           buff,
7625                                                           sizeof(buff),
7626                                                           (unsigned_val ? 10:
7627                                                            -10),
7628                                                            nr);
7629   return Field_varstring::store(buff, length, field_charset);
7630 }
7631 
7632 
val_real(void)7633 double Field_varstring::val_real(void)
7634 {
7635   ASSERT_COLUMN_MARKED_FOR_READ;
7636   int error;
7637   char *end;
7638   double result;
7639   const CHARSET_INFO* cs= charset();
7640 
7641   uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7642   result= my_strntod(cs, (char*)ptr+length_bytes, length, &end, &error);
7643 
7644   if (!table->in_use->no_errors &&
7645        (error || (length != (uint)(end - (char*)ptr+length_bytes) &&
7646          !check_if_only_end_space(cs, end, (char*)ptr+length_bytes+length))))
7647   {
7648     push_numerical_conversion_warning(current_thd, (char*)ptr+length_bytes,
7649                                       length, cs,"DOUBLE",
7650                                       ER_TRUNCATED_WRONG_VALUE);
7651   }
7652   return result;
7653 }
7654 
7655 
val_int(void)7656 longlong Field_varstring::val_int(void)
7657 {
7658   ASSERT_COLUMN_MARKED_FOR_READ;
7659   int error;
7660   char *end;
7661   const CHARSET_INFO *cs= charset();
7662 
7663   uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7664   longlong result= my_strntoll(cs, (char*) ptr+length_bytes, length, 10,
7665                      &end, &error);
7666 
7667   if (!table->in_use->no_errors &&
7668        (error || (length != (uint)(end - (char*)ptr+length_bytes) &&
7669          !check_if_only_end_space(cs, end, (char*)ptr+length_bytes+length))))
7670   {
7671     push_numerical_conversion_warning(current_thd, (char*)ptr+length_bytes,
7672                                       length, cs, "INTEGER",
7673                                       ER_TRUNCATED_WRONG_VALUE);
7674   }
7675   return result;
7676 }
7677 
val_str(String * val_buffer MY_ATTRIBUTE ((unused)),String * val_ptr)7678 String *Field_varstring::val_str(String *val_buffer MY_ATTRIBUTE((unused)),
7679 				 String *val_ptr)
7680 {
7681   ASSERT_COLUMN_MARKED_FOR_READ;
7682   uint length=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7683   val_ptr->set((const char*) ptr+length_bytes, length, field_charset);
7684   return val_ptr;
7685 }
7686 
7687 
val_decimal(my_decimal * decimal_value)7688 my_decimal *Field_varstring::val_decimal(my_decimal *decimal_value)
7689 {
7690   ASSERT_COLUMN_MARKED_FOR_READ;
7691   const CHARSET_INFO *cs= charset();
7692   uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7693   int error= str2my_decimal(E_DEC_FATAL_ERROR, (char*) ptr+length_bytes, length,
7694                  cs, decimal_value);
7695 
7696   if (!table->in_use->no_errors && error)
7697   {
7698     push_numerical_conversion_warning(current_thd, (char*)ptr+length_bytes,
7699                                       length, cs, "DECIMAL",
7700                                       ER_TRUNCATED_WRONG_VALUE);
7701   }
7702   return decimal_value;
7703 }
7704 
7705 
cmp_max(const uchar * a_ptr,const uchar * b_ptr,uint max_len)7706 int Field_varstring::cmp_max(const uchar *a_ptr, const uchar *b_ptr,
7707                              uint max_len)
7708 {
7709   uint a_length, b_length;
7710   int diff;
7711 
7712   if (length_bytes == 1)
7713   {
7714     a_length= (uint) *a_ptr;
7715     b_length= (uint) *b_ptr;
7716   }
7717   else
7718   {
7719     a_length= uint2korr(a_ptr);
7720     b_length= uint2korr(b_ptr);
7721   }
7722   set_if_smaller(a_length, max_len);
7723   set_if_smaller(b_length, max_len);
7724   diff= field_charset->coll->strnncollsp(field_charset,
7725                                          a_ptr+
7726                                          length_bytes,
7727                                          a_length,
7728                                          b_ptr+
7729                                          length_bytes,
7730                                          b_length,0);
7731   return diff;
7732 }
7733 
7734 
7735 /**
7736   @note
7737     varstring and blob keys are ALWAYS stored with a 2 byte length prefix
7738 */
7739 
key_cmp(const uchar * key_ptr,uint max_key_length)7740 int Field_varstring::key_cmp(const uchar *key_ptr, uint max_key_length)
7741 {
7742   uint length=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7743   uint local_char_length= max_key_length / field_charset->mbmaxlen;
7744 
7745   local_char_length= my_charpos(field_charset, ptr + length_bytes,
7746                           ptr + length_bytes + length, local_char_length);
7747   set_if_smaller(length, local_char_length);
7748   return field_charset->coll->strnncollsp(field_charset,
7749                                           ptr + length_bytes,
7750                                           length,
7751                                           key_ptr+
7752                                           HA_KEY_BLOB_LENGTH,
7753                                           uint2korr(key_ptr), 0);
7754 }
7755 
7756 
7757 /**
7758   Compare to key segments (always 2 byte length prefix).
7759 
7760   @note
7761     This is used only to compare key segments created for index_read().
7762     (keys are created and compared in key.cc)
7763 */
7764 
key_cmp(const uchar * a,const uchar * b)7765 int Field_varstring::key_cmp(const uchar *a,const uchar *b)
7766 {
7767   return field_charset->coll->strnncollsp(field_charset,
7768                                           a + HA_KEY_BLOB_LENGTH,
7769                                           uint2korr(a),
7770                                           b + HA_KEY_BLOB_LENGTH,
7771                                           uint2korr(b),
7772                                           0);
7773 }
7774 
7775 
make_sort_key(uchar * to,size_t length)7776 void Field_varstring::make_sort_key(uchar *to, size_t length)
7777 {
7778   size_t tot_length=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7779 
7780   if (field_charset == &my_charset_bin)
7781   {
7782     /* Store length last in high-byte order to sort longer strings first */
7783     if (length_bytes == 1)
7784       to[length-1]= tot_length;
7785     else
7786       mi_int2store(to+length-2, tot_length);
7787     length-= length_bytes;
7788   }
7789 
7790   tot_length= field_charset->coll->strnxfrm(field_charset,
7791                                             to, length, char_length(),
7792                                             ptr + length_bytes, tot_length,
7793                                             MY_STRXFRM_PAD_WITH_SPACE |
7794                                             MY_STRXFRM_PAD_TO_MAXLEN);
7795   DBUG_ASSERT(tot_length == length);
7796 }
7797 
7798 
key_type() const7799 enum ha_base_keytype Field_varstring::key_type() const
7800 {
7801   enum ha_base_keytype res;
7802 
7803   if (binary())
7804     res= length_bytes == 1 ? HA_KEYTYPE_VARBINARY1 : HA_KEYTYPE_VARBINARY2;
7805   else
7806     res= length_bytes == 1 ? HA_KEYTYPE_VARTEXT1 : HA_KEYTYPE_VARTEXT2;
7807   return res;
7808 }
7809 
7810 
sql_type(String & res) const7811 void Field_varstring::sql_type(String &res) const
7812 {
7813   THD *thd= table->in_use;
7814   const CHARSET_INFO *cs=res.charset();
7815   size_t length;
7816 
7817   length= cs->cset->snprintf(cs,(char*) res.ptr(),
7818                              res.alloced_length(), "%s(%d)",
7819                               (has_charset() ? "varchar" : "varbinary"),
7820                              (int) field_length / charset()->mbmaxlen);
7821   res.length(length);
7822   if ((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) &&
7823       has_charset() && (charset()->state & MY_CS_BINSORT))
7824     res.append(STRING_WITH_LEN(" binary"));
7825 }
7826 
7827 
data_length(uint row_offset)7828 uint32 Field_varstring::data_length(uint row_offset)
7829 {
7830   return length_bytes == 1 ?
7831     (uint32) *(ptr + row_offset) : uint2korr(ptr + row_offset);
7832 }
7833 
7834 /*
7835   Functions to create a packed row.
7836   Here the number of length bytes are depending on the given max_length
7837 */
7838 
pack(uchar * to,const uchar * from,uint max_length,bool low_byte_first MY_ATTRIBUTE ((unused)))7839 uchar *Field_varstring::pack(uchar *to, const uchar *from,
7840                              uint max_length,
7841                              bool low_byte_first MY_ATTRIBUTE((unused)))
7842 {
7843   uint length= length_bytes == 1 ? (uint) *from : uint2korr(from);
7844   set_if_smaller(max_length, field_length);
7845   if (length > max_length)
7846     length=max_length;
7847 
7848   /* Length always stored little-endian */
7849   *to++= length & 0xFF;
7850   if (max_length > 255)
7851     *to++= (length >> 8) & 0xFF;
7852 
7853   /* Store bytes of string */
7854   if (length > 0)
7855     memcpy(to, from+length_bytes, length);
7856   return to+length;
7857 }
7858 
7859 
7860 /**
7861    Unpack a varstring field from row data.
7862 
7863    This method is used to unpack a varstring field from a master
7864    whose size of the field is less than that of the slave.
7865 
7866    @note
7867    The string length is always packed little-endian.
7868 
7869    @param   to         Destination of the data
7870    @param   from       Source of the data
7871    @param   param_data Length bytes from the master's field data
7872 
7873    @return  New pointer into memory based on from + length of the data
7874 */
7875 const uchar *
unpack(uchar * to,const uchar * from,uint param_data,bool low_byte_first MY_ATTRIBUTE ((unused)))7876 Field_varstring::unpack(uchar *to, const uchar *from,
7877                         uint param_data,
7878                         bool low_byte_first MY_ATTRIBUTE((unused)))
7879 {
7880   uint length;
7881   uint l_bytes= (param_data && (param_data < field_length)) ?
7882                 (param_data <= 255) ? 1 : 2 : length_bytes;
7883   if (l_bytes == 1)
7884   {
7885     to[0]= *from++;
7886     length= to[0];
7887     if (length_bytes == 2)
7888       to[1]= 0;
7889   }
7890   else /* l_bytes == 2 */
7891   {
7892     length= uint2korr(from);
7893     to[0]= *from++;
7894     to[1]= *from++;
7895   }
7896   if (length)
7897     memcpy(to+ length_bytes, from, length);
7898   return from+length;
7899 }
7900 
7901 
packed_col_length(const uchar * data_ptr,uint length)7902 uint Field_varstring::packed_col_length(const uchar *data_ptr, uint length)
7903 {
7904   if (length > 255)
7905     return uint2korr(data_ptr)+2;
7906   return (uint) *data_ptr + 1;
7907 }
7908 
7909 
get_key_image(uchar * buff,size_t length,imagetype type)7910 size_t Field_varstring::get_key_image(uchar *buff, size_t length, imagetype type)
7911 {
7912   /*
7913     If NULL, data bytes may have been left random by the storage engine, so
7914     don't try to read them.
7915   */
7916   uint f_length= is_null() ? 0 :
7917     (length_bytes == 1 ? (uint) *ptr : uint2korr(ptr));
7918   uint local_char_length= length / field_charset->mbmaxlen;
7919   uchar *pos= ptr+length_bytes;
7920   local_char_length= my_charpos(field_charset, pos, pos + f_length,
7921                                 local_char_length);
7922   set_if_smaller(f_length, local_char_length);
7923   /* Key is always stored with 2 bytes */
7924   int2store(buff,f_length);
7925   memcpy(buff+HA_KEY_BLOB_LENGTH, pos, f_length);
7926   if (f_length < length)
7927   {
7928     /*
7929       Must clear this as we do a memcmp in opt_range.cc to detect
7930       identical keys
7931     */
7932     memset(buff+HA_KEY_BLOB_LENGTH+f_length, 0, (length-f_length));
7933   }
7934   return HA_KEY_BLOB_LENGTH+f_length;
7935 }
7936 
7937 
set_key_image(const uchar * buff,size_t length)7938 void Field_varstring::set_key_image(const uchar *buff, size_t length)
7939 {
7940   length= uint2korr(buff);			// Real length is here
7941   (void) Field_varstring::store((const char*) buff+HA_KEY_BLOB_LENGTH, length,
7942                                 field_charset);
7943 }
7944 
7945 
cmp_binary(const uchar * a_ptr,const uchar * b_ptr,uint32 max_length)7946 int Field_varstring::cmp_binary(const uchar *a_ptr, const uchar *b_ptr,
7947                                 uint32 max_length)
7948 {
7949   uint32 a_length,b_length;
7950 
7951   if (length_bytes == 1)
7952   {
7953     a_length= (uint) *a_ptr;
7954     b_length= (uint) *b_ptr;
7955   }
7956   else
7957   {
7958     a_length= uint2korr(a_ptr);
7959     b_length= uint2korr(b_ptr);
7960   }
7961   set_if_smaller(a_length, max_length);
7962   set_if_smaller(b_length, max_length);
7963   if (a_length != b_length)
7964     return 1;
7965   return memcmp(a_ptr+length_bytes, b_ptr+length_bytes, a_length);
7966 }
7967 
7968 
new_field(MEM_ROOT * root,TABLE * new_table,bool keep_type)7969 Field *Field_varstring::new_field(MEM_ROOT *root, TABLE *new_table,
7970                                   bool keep_type)
7971 {
7972   Field_varstring *res= (Field_varstring*) Field::new_field(root, new_table,
7973                                                             keep_type);
7974   if (res)
7975     res->length_bytes= length_bytes;
7976   return res;
7977 }
7978 
7979 
new_key_field(MEM_ROOT * root,TABLE * new_table,uchar * new_ptr,uchar * new_null_ptr,uint new_null_bit)7980 Field *Field_varstring::new_key_field(MEM_ROOT *root,
7981                                       TABLE *new_table,
7982                                       uchar *new_ptr, uchar *new_null_ptr,
7983                                       uint new_null_bit)
7984 {
7985   Field_varstring *res;
7986   if ((res= (Field_varstring*) Field::new_key_field(root,
7987                                                     new_table,
7988                                                     new_ptr,
7989                                                     new_null_ptr,
7990                                                     new_null_bit)))
7991   {
7992     /* Keys length prefixes are always packed with 2 bytes */
7993     res->length_bytes= 2;
7994   }
7995   return res;
7996 }
7997 
7998 
is_equal(Create_field * new_field)7999 uint Field_varstring::is_equal(Create_field *new_field)
8000 {
8001   if (new_field->sql_type == real_type() &&
8002       new_field->charset == field_charset)
8003   {
8004     if (new_field->length == max_display_length())
8005       return IS_EQUAL_YES;
8006     DBUG_ASSERT(0 == (new_field->length % field_charset->mbmaxlen));
8007     DBUG_ASSERT(0 == (max_display_length() % field_charset->mbmaxlen));
8008     if (new_field->length > max_display_length() &&
8009 	((new_field->length <= 255 && max_display_length() <= 255) ||
8010 	 (new_field->length > 255 && max_display_length() > 255)))
8011       return IS_EQUAL_PACK_LENGTH; // VARCHAR, longer variable length
8012   }
8013   return IS_EQUAL_NO;
8014 }
8015 
8016 
hash(ulong * nr,ulong * nr2)8017 void Field_varstring::hash(ulong *nr, ulong *nr2)
8018 {
8019   if (is_null())
8020   {
8021     *nr^= (*nr << 1) | 1;
8022   }
8023   else
8024   {
8025     uint len=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
8026     const CHARSET_INFO *cs= charset();
8027     cs->coll->hash_sort(cs, ptr + length_bytes, len, nr, nr2);
8028   }
8029 }
8030 
8031 
8032 /****************************************************************************
8033 ** blob type
8034 ** A blob is saved as a length and a pointer. The length is stored in the
8035 ** packlength slot and may be from 1-4.
8036 ****************************************************************************/
8037 
Field_blob(uchar * ptr_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const char * field_name_arg,TABLE_SHARE * share,uint blob_pack_length,const CHARSET_INFO * cs)8038 Field_blob::Field_blob(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
8039 		       enum utype unireg_check_arg, const char *field_name_arg,
8040                        TABLE_SHARE *share, uint blob_pack_length,
8041 		       const CHARSET_INFO *cs)
8042   :Field_longstr(ptr_arg, BLOB_PACK_LENGTH_TO_MAX_LENGH(blob_pack_length),
8043                  null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg,
8044                  cs),
8045    packlength(blob_pack_length), m_keep_old_value(false)
8046 {
8047   DBUG_ASSERT(blob_pack_length <= 4); // Only pack lengths 1-4 supported currently
8048   flags|= BLOB_FLAG;
8049   share->blob_fields++;
8050   /* TODO: why do not fill table->s->blob_field array here? */
8051 }
8052 
8053 
store_length(uchar * i_ptr,uint i_packlength,uint32 i_number,bool low_byte_first)8054 void Field_blob::store_length(uchar *i_ptr,
8055                               uint i_packlength,
8056                               uint32 i_number,
8057                               bool low_byte_first)
8058 {
8059   switch (i_packlength) {
8060   case 1:
8061     i_ptr[0]= (uchar) i_number;
8062     break;
8063   case 2:
8064 #ifdef WORDS_BIGENDIAN
8065     if (low_byte_first)
8066     {
8067       int2store(i_ptr,(unsigned short) i_number);
8068     }
8069     else
8070 #endif
8071       shortstore(i_ptr,(unsigned short) i_number);
8072     break;
8073   case 3:
8074     int3store(i_ptr,i_number);
8075     break;
8076   case 4:
8077 #ifdef WORDS_BIGENDIAN
8078     if (low_byte_first)
8079     {
8080       int4store(i_ptr,i_number);
8081     }
8082     else
8083 #endif
8084       longstore(i_ptr,i_number);
8085   }
8086 }
8087 
8088 
get_length(const uchar * pos,uint packlength_arg,bool low_byte_first)8089 uint32 Field_blob::get_length(const uchar *pos, uint packlength_arg, bool low_byte_first)
8090 {
8091   switch (packlength_arg) {
8092   case 1:
8093     return (uint32) pos[0];
8094   case 2:
8095     {
8096       uint16 tmp;
8097 #ifdef WORDS_BIGENDIAN
8098       if (low_byte_first)
8099 	tmp=sint2korr(pos);
8100       else
8101 #endif
8102 	ushortget(&tmp, pos);
8103       return (uint32) tmp;
8104     }
8105   case 3:
8106     return uint3korr(pos);
8107   case 4:
8108     {
8109       uint32 tmp;
8110 #ifdef WORDS_BIGENDIAN
8111       if (low_byte_first)
8112 	tmp=uint4korr(pos);
8113       else
8114 #endif
8115 	ulongget(&tmp, pos);
8116       return tmp;
8117     }
8118   }
8119   /* When expanding this, see also MAX_FIELD_BLOBLENGTH. */
8120   return 0;					// Impossible
8121 }
8122 
8123 
8124 /**
8125   Put a blob length field into a record buffer.
8126 
8127   Depending on the maximum length of a blob, its length field is
8128   put into 1 to 4 bytes. This is a property of the blob object,
8129   described by 'packlength'.
8130 
8131   @param pos                 Pointer into the record buffer.
8132   @param length              The length value to put.
8133 */
8134 
put_length(uchar * pos,uint32 length)8135 void Field_blob::put_length(uchar *pos, uint32 length)
8136 {
8137   switch (packlength) {
8138   case 1:
8139     *pos= (char) length;
8140     break;
8141   case 2:
8142     int2store(pos, length);
8143     break;
8144   case 3:
8145     int3store(pos, length);
8146     break;
8147   case 4:
8148     int4store(pos, length);
8149     break;
8150   }
8151 }
8152 
8153 
8154 /**
8155   Store a blob value to memory storage.
8156   @param      from         the string value to store.
8157   @param      length       length of the string value.
8158   @param      cs           character set of the string value.
8159   @param      max_length   Cut at this length safely (multibyte aware).
8160   @param[out] blob_storage Memory storage to put value to.
8161 */
8162 type_conversion_status
store_to_mem(const char * from,size_t length,const CHARSET_INFO * cs,size_t max_length,Blob_mem_storage * blob_storage)8163 Field_blob::store_to_mem(const char *from, size_t length,
8164                          const CHARSET_INFO *cs,
8165                          size_t max_length,
8166                          Blob_mem_storage *blob_storage)
8167 {
8168   /*
8169     We don't need to support escaping or character set conversions here,
8170     because store_to_mem() is currently called only when we process
8171     queries having GROUP_CONCAT with ORDER BY or DISTINCT,
8172     hence some assersions:
8173   */
8174   DBUG_ASSERT(field_charset == cs);
8175   DBUG_ASSERT(length <= max_data_length());
8176 
8177   if (length > max_length)
8178   {
8179     int well_formed_error;
8180     length= cs->cset->well_formed_len(cs, from, from + max_length,
8181                                       length, &well_formed_error);
8182     table->blob_storage->set_truncated_value(true);
8183   }
8184   char *tmp;
8185   if (!(tmp= table->blob_storage->store(from, length)))
8186   {
8187     memset(ptr, 0, Field_blob::pack_length());
8188     return TYPE_ERR_OOM;
8189   }
8190   store_ptr_and_length(tmp, length);
8191   return TYPE_OK;
8192 }
8193 
8194 
8195 type_conversion_status
store_internal(const char * from,size_t length,const CHARSET_INFO * cs)8196 Field_blob::store_internal(const char *from, size_t length,
8197                            const CHARSET_INFO *cs)
8198 {
8199   size_t new_length;
8200   char buff[STRING_BUFFER_USUAL_SIZE], *tmp;
8201   String tmpstr(buff,sizeof(buff), &my_charset_bin);
8202 
8203   /*
8204     If the 'from' address is in the range of the temporary 'value'-
8205     object we need to copy the content to a different location or it will be
8206     invalidated when the 'value'-object is reallocated to make room for
8207     the new character set.
8208   */
8209   if (from >= value.ptr() && from <= value.ptr()+value.length())
8210   {
8211     /*
8212       If content of the 'from'-address is cached in the 'value'-object
8213       it is possible that the content needs a character conversion.
8214     */
8215     if (!String::needs_conversion_on_storage(length, cs, field_charset))
8216     {
8217       store_ptr_and_length(from, length);
8218       return TYPE_OK;
8219     }
8220     if (tmpstr.copy(from, length, cs))
8221       goto oom_error;
8222     from= tmpstr.ptr();
8223   }
8224 
8225   new_length= min<size_t>(max_data_length(), field_charset->mbmaxlen * length);
8226 
8227   if (value.alloc(new_length))
8228     goto oom_error;
8229 
8230   tmp= const_cast<char*>(value.ptr());
8231 
8232   {
8233     const char *well_formed_error_pos;
8234     const char *cannot_convert_error_pos;
8235     const char *from_end_pos;
8236     /*
8237       "length" is OK as "nchars" argument to well_formed_copy_nchars as this
8238       is never used to limit the length of the data. The cut of long data
8239       is done with the new_length value.
8240     */
8241     size_t copy_length= field_well_formed_copy_nchars(field_charset,
8242                                                 tmp, new_length,
8243                                                 cs, from, length,
8244                                                 length,
8245                                                 &well_formed_error_pos,
8246                                                 &cannot_convert_error_pos,
8247                                                 &from_end_pos);
8248 
8249     store_ptr_and_length(tmp, copy_length);
8250     return check_string_copy_error(from, well_formed_error_pos,
8251                                    cannot_convert_error_pos, from_end_pos,
8252                                    from + length, true, cs);
8253   }
8254 
8255 oom_error:
8256   /* Fatal OOM error */
8257   memset(ptr, 0, Field_blob::pack_length());
8258   return TYPE_ERR_OOM;
8259 }
8260 
8261 
8262 type_conversion_status
store(const char * from,size_t length,const CHARSET_INFO * cs)8263 Field_blob::store(const char *from, size_t length, const CHARSET_INFO *cs)
8264 {
8265   ASSERT_COLUMN_MARKED_FOR_WRITE;
8266 
8267   if (table->blob_storage)    // GROUP_CONCAT with ORDER BY | DISTINCT
8268     return store_to_mem(from, length, cs,
8269                         table->in_use->variables.group_concat_max_len,
8270                         table->blob_storage);
8271 
8272   return store_internal(from, length, cs);
8273 }
8274 
8275 
store(double nr)8276 type_conversion_status Field_blob::store(double nr)
8277 {
8278   const CHARSET_INFO *cs=charset();
8279   value.set_real(nr, NOT_FIXED_DEC, cs);
8280   return Field_blob::store(value.ptr(), value.length(), cs);
8281 }
8282 
8283 
store(longlong nr,bool unsigned_val)8284 type_conversion_status Field_blob::store(longlong nr, bool unsigned_val)
8285 {
8286   const CHARSET_INFO *cs=charset();
8287   value.set_int(nr, unsigned_val, cs);
8288   return Field_blob::store(value.ptr(), value.length(), cs);
8289 }
8290 
8291 
val_real(void)8292 double Field_blob::val_real(void)
8293 {
8294   ASSERT_COLUMN_MARKED_FOR_READ;
8295   int not_used;
8296   char *end_not_used, *blob;
8297   uint32 length;
8298   const CHARSET_INFO *cs;
8299 
8300   memcpy(&blob, ptr+packlength, sizeof(char*));
8301   if (!blob)
8302     return 0.0;
8303   length= get_length(ptr);
8304   cs= charset();
8305   return my_strntod(cs, blob, length, &end_not_used, &not_used);
8306 }
8307 
8308 
val_int(void)8309 longlong Field_blob::val_int(void)
8310 {
8311   ASSERT_COLUMN_MARKED_FOR_READ;
8312   int not_used;
8313   char *blob;
8314   memcpy(&blob, ptr+packlength, sizeof(char*));
8315   if (!blob)
8316     return 0;
8317   uint32 length=get_length(ptr);
8318   return my_strntoll(charset(),blob,length,10,NULL,&not_used);
8319 }
8320 
val_str(String * val_buffer MY_ATTRIBUTE ((unused)),String * val_ptr)8321 String *Field_blob::val_str(String *val_buffer MY_ATTRIBUTE((unused)),
8322 			    String *val_ptr)
8323 {
8324   ASSERT_COLUMN_MARKED_FOR_READ;
8325   char *blob;
8326   memcpy(&blob, ptr+packlength, sizeof(char*));
8327   if (!blob)
8328     val_ptr->set("",0,charset());	// A bit safer than ->length(0)
8329   else
8330     val_ptr->set((const char*) blob,get_length(ptr),charset());
8331   return val_ptr;
8332 }
8333 
8334 
val_decimal(my_decimal * decimal_value)8335 my_decimal *Field_blob::val_decimal(my_decimal *decimal_value)
8336 {
8337   ASSERT_COLUMN_MARKED_FOR_READ;
8338   const char *blob;
8339   size_t length;
8340   memcpy(&blob, ptr+packlength, sizeof(const uchar*));
8341   if (!blob)
8342   {
8343     blob= "";
8344     length= 0;
8345   }
8346   else
8347     length= get_length(ptr);
8348 
8349   str2my_decimal(E_DEC_FATAL_ERROR, blob, length, charset(),
8350                  decimal_value);
8351   return decimal_value;
8352 }
8353 
8354 
cmp(const uchar * a,uint32 a_length,const uchar * b,uint32 b_length)8355 int Field_blob::cmp(const uchar *a,uint32 a_length, const uchar *b,
8356 		    uint32 b_length)
8357 {
8358   return field_charset->coll->strnncollsp(field_charset,
8359                                           a, a_length, b, b_length,
8360                                           0);
8361 }
8362 
8363 
cmp_max(const uchar * a_ptr,const uchar * b_ptr,uint max_length)8364 int Field_blob::cmp_max(const uchar *a_ptr, const uchar *b_ptr,
8365                         uint max_length)
8366 {
8367   uchar *blob1,*blob2;
8368   memcpy(&blob1, a_ptr+packlength, sizeof(char*));
8369   memcpy(&blob2, b_ptr+packlength, sizeof(char*));
8370   uint a_len= get_length(a_ptr), b_len= get_length(b_ptr);
8371   set_if_smaller(a_len, max_length);
8372   set_if_smaller(b_len, max_length);
8373   return Field_blob::cmp(blob1,a_len,blob2,b_len);
8374 }
8375 
8376 
cmp_binary(const uchar * a_ptr,const uchar * b_ptr,uint32 max_length)8377 int Field_blob::cmp_binary(const uchar *a_ptr, const uchar *b_ptr,
8378 			   uint32 max_length)
8379 {
8380   char *a,*b;
8381   uint diff;
8382   uint32 a_length,b_length;
8383   memcpy(&a, a_ptr+packlength, sizeof(char*));
8384   memcpy(&b, b_ptr+packlength, sizeof(char*));
8385   a_length=get_length(a_ptr);
8386   if (a_length > max_length)
8387     a_length=max_length;
8388   b_length=get_length(b_ptr);
8389   if (b_length > max_length)
8390     b_length=max_length;
8391   diff=memcmp(a,b,min(a_length,b_length));
8392   return diff ? diff : (int) (a_length - b_length);
8393 }
8394 
8395 
8396 /* The following is used only when comparing a key */
8397 
get_key_image(uchar * buff,size_t length,imagetype type_arg)8398 size_t Field_blob::get_key_image(uchar *buff, size_t length, imagetype type_arg)
8399 {
8400   uint32 blob_length= get_length(ptr);
8401   uchar *blob;
8402 
8403   if (type_arg == itMBR)
8404   {
8405     MBR mbr;
8406     Geometry_buffer buffer;
8407     Geometry *gobj;
8408     const uint image_length= SIZEOF_STORED_DOUBLE*4;
8409 
8410     if (blob_length < SRID_SIZE)
8411     {
8412       memset(buff, 0, image_length);
8413       return image_length;
8414     }
8415     get_ptr(&blob);
8416     gobj= Geometry::construct(&buffer, (char*) blob, blob_length);
8417     if (!gobj || gobj->get_mbr(&mbr))
8418       memset(buff, 0, image_length);
8419     else
8420     {
8421       float8store(buff,    mbr.xmin);
8422       float8store(buff+8,  mbr.xmax);
8423       float8store(buff+16, mbr.ymin);
8424       float8store(buff+24, mbr.ymax);
8425     }
8426     return image_length;
8427   }
8428 
8429   get_ptr(&blob);
8430   uint local_char_length= length / field_charset->mbmaxlen;
8431   local_char_length= my_charpos(field_charset, blob, blob + blob_length,
8432                           local_char_length);
8433   set_if_smaller(blob_length, local_char_length);
8434 
8435   if ((uint32) length > blob_length)
8436   {
8437     /*
8438       Must clear this as we do a memcmp in opt_range.cc to detect
8439       identical keys
8440     */
8441     memset(buff+HA_KEY_BLOB_LENGTH+blob_length, 0, (length-blob_length));
8442     length=(uint) blob_length;
8443   }
8444   int2store(buff, static_cast<uint16>(length));
8445   memcpy(buff+HA_KEY_BLOB_LENGTH, blob, length);
8446   return HA_KEY_BLOB_LENGTH+length;
8447 }
8448 
8449 
set_key_image(const uchar * buff,size_t length)8450 void Field_blob::set_key_image(const uchar *buff, size_t length)
8451 {
8452   length= uint2korr(buff);
8453   (void) Field_blob::store((const char*) buff+HA_KEY_BLOB_LENGTH, length,
8454                            field_charset);
8455 }
8456 
8457 
key_cmp(const uchar * key_ptr,uint max_key_length)8458 int Field_blob::key_cmp(const uchar *key_ptr, uint max_key_length)
8459 {
8460   uchar *blob1;
8461   uint blob_length=get_length(ptr);
8462   memcpy(&blob1, ptr+packlength, sizeof(char*));
8463   const CHARSET_INFO *cs= charset();
8464   uint local_char_length= max_key_length / cs->mbmaxlen;
8465   local_char_length= my_charpos(cs, blob1, blob1+blob_length,
8466                                 local_char_length);
8467   set_if_smaller(blob_length, local_char_length);
8468   return Field_blob::cmp(blob1, blob_length,
8469 			 key_ptr+HA_KEY_BLOB_LENGTH,
8470 			 uint2korr(key_ptr));
8471 }
8472 
key_cmp(const uchar * a,const uchar * b)8473 int Field_blob::key_cmp(const uchar *a,const uchar *b)
8474 {
8475   return Field_blob::cmp(a+HA_KEY_BLOB_LENGTH, uint2korr(a),
8476 			 b+HA_KEY_BLOB_LENGTH, uint2korr(b));
8477 }
8478 
8479 
8480 /**
8481    Save the field metadata for blob fields.
8482 
8483    Saves the pack length in the first byte of the field metadata array
8484    at index of *metadata_ptr.
8485 
8486    @param   metadata_ptr   First byte of field metadata
8487 
8488    @returns number of bytes written to metadata_ptr
8489 */
do_save_field_metadata(uchar * metadata_ptr)8490 int Field_blob::do_save_field_metadata(uchar *metadata_ptr)
8491 {
8492   DBUG_ENTER("Field_blob::do_save_field_metadata");
8493   *metadata_ptr= pack_length_no_ptr();
8494   DBUG_PRINT("debug", ("metadata: %u (pack_length_no_ptr)", *metadata_ptr));
8495   DBUG_RETURN(1);
8496 }
8497 
8498 
sort_length() const8499 uint32 Field_blob::sort_length() const
8500 {
8501   return (uint32) (current_thd->variables.max_sort_length +
8502                    (field_charset == &my_charset_bin ? 0 : packlength));
8503 }
8504 
8505 
make_sort_key(uchar * to,size_t length)8506 void Field_blob::make_sort_key(uchar *to, size_t length)
8507 {
8508   uchar *blob;
8509   size_t blob_length=get_length();
8510 
8511   if (!blob_length)
8512     memset(to, 0, length);
8513   else
8514   {
8515     if (field_charset == &my_charset_bin)
8516     {
8517       uchar *pos;
8518 
8519       /*
8520         Store length of blob last in blob to shorter blobs before longer blobs
8521       */
8522       length-= packlength;
8523       pos= to+length;
8524 
8525       switch (packlength) {
8526       case 1:
8527         *pos= (char) blob_length;
8528         break;
8529       case 2:
8530         mi_int2store(pos, blob_length);
8531         break;
8532       case 3:
8533         mi_int3store(pos, blob_length);
8534         break;
8535       case 4:
8536         mi_int4store(pos, blob_length);
8537         break;
8538       }
8539     }
8540     memcpy(&blob, ptr+packlength, sizeof(char*));
8541 
8542     blob_length= field_charset->coll->strnxfrm(field_charset,
8543                                                to, length, length,
8544                                                blob, blob_length,
8545                                                MY_STRXFRM_PAD_WITH_SPACE |
8546                                                MY_STRXFRM_PAD_TO_MAXLEN);
8547     DBUG_ASSERT(blob_length == length);
8548   }
8549 }
8550 
8551 
sql_type(String & res) const8552 void Field_blob::sql_type(String &res) const
8553 {
8554   const char *str;
8555   uint length;
8556   switch (packlength) {
8557   default: str="tiny"; length=4; break;
8558   case 2:  str="";     length=0; break;
8559   case 3:  str="medium"; length= 6; break;
8560   case 4:  str="long";  length=4; break;
8561   }
8562   res.set_ascii(str,length);
8563   if (charset() == &my_charset_bin)
8564     res.append(STRING_WITH_LEN("blob"));
8565   else
8566   {
8567     res.append(STRING_WITH_LEN("text"));
8568   }
8569 }
8570 
pack(uchar * to,const uchar * from,uint max_length,bool low_byte_first)8571 uchar *Field_blob::pack(uchar *to, const uchar *from,
8572                         uint max_length, bool low_byte_first)
8573 {
8574   uchar *save= ptr;
8575   ptr= (uchar*) from;
8576   uint32 length=get_length();			// Length of from string
8577 
8578   /*
8579     Store max length, which will occupy packlength bytes. If the max
8580     length given is smaller than the actual length of the blob, we
8581     just store the initial bytes of the blob.
8582   */
8583   store_length(to, packlength, min(length, max_length), low_byte_first);
8584 
8585   /*
8586     Store the actual blob data, which will occupy 'length' bytes.
8587    */
8588   if (length > 0)
8589   {
8590     get_ptr((uchar**) &from);
8591     memcpy(to+packlength, from,length);
8592   }
8593   ptr=save;					// Restore org row pointer
8594   return to+packlength+length;
8595 }
8596 
8597 
8598 /**
8599    Unpack a blob field from row data.
8600 
8601    This method is used to unpack a blob field from a master whose size of
8602    the field is less than that of the slave. Note: This method is included
8603    to satisfy inheritance rules, but is not needed for blob fields. It
8604    simply is used as a pass-through to the original unpack() method for
8605    blob fields.
8606 
8607    @param   to         Destination of the data
8608    @param   from       Source of the data
8609    @param   param_data @c TRUE if base types should be stored in little-
8610                        endian format, @c FALSE if native format should
8611                        be used.
8612 
8613    @return  New pointer into memory based on from + length of the data
8614 */
unpack(uchar * to,const uchar * from,uint param_data,bool low_byte_first)8615 const uchar *Field_blob::unpack(uchar *to,
8616                                 const uchar *from,
8617                                 uint param_data,
8618                                 bool low_byte_first)
8619 {
8620   DBUG_ENTER("Field_blob::unpack");
8621   DBUG_PRINT("enter", ("to: 0x%lx; from: 0x%lx;"
8622                        " param_data: %u; low_byte_first: %d",
8623                        (ulong) to, (ulong) from, param_data, low_byte_first));
8624   uint const master_packlength=
8625     param_data > 0 ? param_data & 0xFF : packlength;
8626   uint32 const length= get_length(from, master_packlength, low_byte_first);
8627   DBUG_DUMP("packed", from, length + master_packlength);
8628   bitmap_set_bit(table->write_set, field_index);
8629   Field_blob::store(pointer_cast<const char*>(from) + master_packlength,
8630                     length, field_charset);
8631 #ifndef DBUG_OFF
8632   uchar *vptr;
8633   get_ptr(&vptr);
8634   DBUG_DUMP("field", ptr, pack_length() /* len bytes + ptr bytes */);
8635   DBUG_DUMP("value", vptr, length /* the blob value length */);
8636 #endif
8637   DBUG_RETURN(from + master_packlength + length);
8638 }
8639 
packed_col_length(const uchar * data_ptr,uint length)8640 uint Field_blob::packed_col_length(const uchar *data_ptr, uint length)
8641 {
8642   if (length > 255)
8643     return uint2korr(data_ptr)+2;
8644   return (uint) *data_ptr + 1;
8645 }
8646 
8647 
max_packed_col_length()8648 uint Field_blob::max_packed_col_length()
8649 {
8650   // We do not use addon fields for blobs.
8651   DBUG_ASSERT(false);
8652   const uint max_length= pack_length();
8653   return (max_length > 255 ? 2 : 1) + max_length;
8654 }
8655 
8656 
is_equal(Create_field * new_field)8657 uint Field_blob::is_equal(Create_field *new_field)
8658 {
8659   return ((new_field->sql_type == get_blob_type_from_length(max_data_length()))
8660           && new_field->charset == field_charset &&
8661           new_field->pack_length == pack_length());
8662 }
8663 
8664 
sql_type(String & res) const8665 void Field_geom::sql_type(String &res) const
8666 {
8667   const CHARSET_INFO *cs= &my_charset_latin1;
8668   switch (geom_type)
8669   {
8670     case GEOM_POINT:
8671      res.set(STRING_WITH_LEN("point"), cs);
8672      break;
8673     case GEOM_LINESTRING:
8674      res.set(STRING_WITH_LEN("linestring"), cs);
8675      break;
8676     case GEOM_POLYGON:
8677      res.set(STRING_WITH_LEN("polygon"), cs);
8678      break;
8679     case GEOM_MULTIPOINT:
8680      res.set(STRING_WITH_LEN("multipoint"), cs);
8681      break;
8682     case GEOM_MULTILINESTRING:
8683      res.set(STRING_WITH_LEN("multilinestring"), cs);
8684      break;
8685     case GEOM_MULTIPOLYGON:
8686      res.set(STRING_WITH_LEN("multipolygon"), cs);
8687      break;
8688     case GEOM_GEOMETRYCOLLECTION:
8689      res.set(STRING_WITH_LEN("geometrycollection"), cs);
8690      break;
8691     default:
8692      res.set(STRING_WITH_LEN("geometry"), cs);
8693   }
8694 }
8695 
8696 
store(double nr)8697 type_conversion_status Field_geom::store(double nr)
8698 {
8699   my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
8700              ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
8701   return TYPE_ERR_BAD_VALUE;
8702 }
8703 
8704 
store(longlong nr,bool unsigned_val)8705 type_conversion_status Field_geom::store(longlong nr, bool unsigned_val)
8706 {
8707   my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
8708              ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
8709   return TYPE_ERR_BAD_VALUE;
8710 }
8711 
8712 
store_decimal(const my_decimal *)8713 type_conversion_status Field_geom::store_decimal(const my_decimal *)
8714 {
8715   my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
8716              ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
8717   return TYPE_ERR_BAD_VALUE;
8718 }
8719 
8720 
store(const char * from,size_t length,const CHARSET_INFO * cs)8721 type_conversion_status Field_geom::store(const char *from, size_t length,
8722                                          const CHARSET_INFO *cs)
8723 {
8724   if (length < SRID_SIZE + WKB_HEADER_SIZE + sizeof(uint32))
8725   {
8726     memset(ptr, 0, Field_blob::pack_length());
8727     my_error(ER_CANT_CREATE_GEOMETRY_OBJECT, MYF(0));
8728     return TYPE_ERR_BAD_VALUE;
8729   }
8730 
8731   return Field_blob::store(from, length, cs);
8732 }
8733 
8734 
8735 type_conversion_status
store_internal(const char * from,size_t length,const CHARSET_INFO * cs)8736 Field_geom::store_internal(const char *from, size_t length,
8737                            const CHARSET_INFO *cs)
8738 {
8739   // Check that the given WKB
8740   // 1. is at least 13 bytes long (length of GEOMETRYCOLLECTION EMPTY)
8741   // 2. isn't marked as bad geometry data
8742   // 3. isn't shorter than empty geometrycollection
8743   // 4. is a valid geometry type
8744   // 5. is well formed
8745   if (length < 13 ||                                                  // 1
8746       from == Geometry::bad_geometry_data.ptr() ||                    // 2
8747       length < SRID_SIZE + WKB_HEADER_SIZE + sizeof(uint32) ||        // 3
8748       !Geometry::is_valid_geotype(uint4korr(from + SRID_SIZE + 1)) || // 4
8749       !Geometry::is_well_formed(from, length,                         // 5
8750                                 geometry_type_to_wkb_type(geom_type),
8751                                 Geometry::wkb_ndr))
8752   {
8753     memset(ptr, 0, Field_blob::pack_length());
8754     my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
8755                ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
8756     return TYPE_ERR_BAD_VALUE;
8757   }
8758 
8759   if (table->copy_blobs || length <= MAX_FIELD_WIDTH)
8760   {                                                   // Must make a copy
8761     value.copy(from, length, cs);
8762     from= value.ptr();
8763   }
8764 
8765   store_ptr_and_length(from, length);
8766   return TYPE_OK;
8767 }
8768 
8769 
is_equal(Create_field * new_field)8770 uint Field_geom::is_equal(Create_field *new_field)
8771 {
8772   return new_field->sql_type == real_type() &&
8773          new_field->geom_type == get_geometry_type() &&
8774          new_field->charset == field_charset &&
8775          new_field->pack_length == pack_length();
8776 }
8777 
8778 
8779 /**
8780   Get the type of this field (json).
8781   @param str  the string that receives the type
8782 */
sql_type(String & str) const8783 void Field_json::sql_type(String &str) const
8784 {
8785   str.set_ascii(STRING_WITH_LEN("json"));
8786 }
8787 
8788 
8789 /// Create a shallow clone of this field in the specified MEM_ROOT.
clone(MEM_ROOT * mem_root) const8790 Field_json *Field_json::clone(MEM_ROOT *mem_root) const
8791 {
8792   DBUG_ASSERT(type() == MYSQL_TYPE_JSON);
8793   return new (mem_root) Field_json(*this);
8794 }
8795 
8796 
8797 /// Create a shallow clone of this field.
clone() const8798 Field_json *Field_json::clone() const
8799 {
8800   DBUG_ASSERT(type() == MYSQL_TYPE_JSON);
8801   return new Field_json(*this);
8802 }
8803 
8804 
8805 /**
8806   Check if a new field is compatible with this one.
8807   @param new_field  the new field
8808   @return true if new_field is compatible with this field, false otherwise
8809 */
is_equal(Create_field * new_field)8810 uint Field_json::is_equal(Create_field *new_field)
8811 {
8812   // All JSON fields are compatible with each other.
8813   return (new_field->sql_type == real_type());
8814 }
8815 
8816 
8817 /**
8818   Store data in this JSON field.
8819 
8820   JSON data is usually stored using store(Field_json*) or store_json(), so this
8821   function will only be called if non-JSON data is attempted stored in a JSON
8822   field. This results in an error in most cases.
8823 
8824   It will attempt to parse the string (unless it's binary) as JSON text, and
8825   store a binary representation of JSON document if the string could be parsed.
8826 
8827   Note that we override store() and not store_internal() because
8828   Field_blob::store() contains logic that bypasses store_internal() in
8829   some cases we care about. In particular:
8830 
8831   - When supplied an empty string, we want to raise a JSON syntax
8832     error instead of silently inserting an empty byte string.
8833 
8834   - When called from GROUP_CONCAT with ORDER BY or DISTINCT, we want
8835     to do the same data conversion as usual, whereas
8836     Field_blob::store() jumps directly to Field_blob::store_to_mem()
8837     with the unprocessed input data.
8838 
8839   @param from   the start of the data to be stored
8840   @param length the length of the data
8841   @param cs     the character set of the data
8842   @return zero on success, non-zero on failure
8843 */
8844 type_conversion_status
store(const char * from,size_t length,const CHARSET_INFO * cs)8845 Field_json::store(const char *from, size_t length, const CHARSET_INFO *cs)
8846 {
8847   ASSERT_COLUMN_MARKED_FOR_WRITE;
8848 
8849   /*
8850     First clear the field so that it doesn't contain garbage if we
8851     return with an error. Some callers continue for a while even after
8852     an error has been raised, and they could get into trouble if the
8853     field contains garbage.
8854   */
8855   reset();
8856 
8857   const char *s;
8858   size_t ss;
8859   String v(from, length, cs);
8860 
8861   if (ensure_utf8mb4(&v, &value, &s, &ss, true))
8862   {
8863     return TYPE_ERR_BAD_VALUE;
8864   }
8865 
8866   const char *parse_err;
8867   size_t err_offset;
8868   std::auto_ptr<Json_dom> dom(Json_dom::parse(s, ss, &parse_err, &err_offset));
8869 
8870   if (dom.get() == NULL)
8871   {
8872     if (parse_err != NULL)
8873     {
8874       // Syntax error.
8875       invalid_text(parse_err, err_offset);
8876     }
8877     return TYPE_ERR_BAD_VALUE;
8878   }
8879 
8880   if (json_binary::serialize(dom.get(), &value))
8881     return TYPE_ERR_BAD_VALUE;
8882 
8883   return store_binary(value.ptr(), value.length());
8884 }
8885 
8886 
8887 /**
8888   Helper function for raising an error when trying to store a value
8889   into a JSON column, and that value needs to be cast to JSON before
8890   it can be stored.
8891 */
unsupported_conversion()8892 type_conversion_status Field_json::unsupported_conversion()
8893 {
8894   ASSERT_COLUMN_MARKED_FOR_WRITE;
8895   invalid_text("not a JSON text, may need CAST", 0);
8896   return TYPE_ERR_BAD_VALUE;
8897 }
8898 
8899 
8900 /**
8901   Store the provided JSON binary data in this field.
8902 
8903   @param[in] ptr     pointer to JSON binary data
8904   @param[in] length  the length of the binary data
8905   @return zero on success, non-zero on failure
8906 */
store_binary(const char * ptr,size_t length)8907 type_conversion_status Field_json::store_binary(const char *ptr, size_t length)
8908 {
8909   /*
8910     We expect that a valid binary representation of a JSON document is
8911     passed to us.
8912 
8913     We make an exception for the case of an empty binary string. Even
8914     though an empty binary string is not a valid representation of a
8915     JSON document, we might be served one as a result of inserting
8916     NULL or DEFAULT into a not nullable JSON column using INSERT
8917     IGNORE, or inserting DEFAULT into a not nullable JSON column in
8918     non-strict SQL mode.
8919 
8920     We accept an empty binary string in those cases. Such values will
8921     be converted to the JSON null literal when they are read with
8922     Field_json::val_json().
8923   */
8924   DBUG_ASSERT(length == 0 || json_binary::parse_binary(ptr, length).is_valid());
8925 
8926   if (value.length() > UINT_MAX32)
8927   {
8928     /* purecov: begin inspected */
8929     my_error(ER_JSON_VALUE_TOO_BIG, MYF(0));
8930     return TYPE_ERR_BAD_VALUE;
8931     /* purecov: end */
8932   }
8933 
8934   return Field_blob::store(ptr, length, field_charset);
8935 }
8936 
8937 
8938 /// Store a double in a JSON field. Will raise an error for now.
store(double nr)8939 type_conversion_status Field_json::store(double nr)
8940 {
8941   return unsupported_conversion();
8942 }
8943 
8944 
8945 /// Store an integer in a JSON field. Will raise an error for now.
store(longlong nr,bool unsigned_val)8946 type_conversion_status Field_json::store(longlong nr, bool unsigned_val)
8947 {
8948   return unsupported_conversion();
8949 }
8950 
8951 
8952 /// Store a decimal in a JSON field. Will raise an error for now.
store_decimal(const my_decimal *)8953 type_conversion_status Field_json::store_decimal(const my_decimal *)
8954 {
8955   return unsupported_conversion();
8956 }
8957 
8958 
8959 /// Store a TIME value in a JSON field. Will raise an error for now.
store_time(MYSQL_TIME * ltime,uint8 dec_arg)8960 type_conversion_status Field_json::store_time(MYSQL_TIME *ltime, uint8 dec_arg)
8961 {
8962   return unsupported_conversion();
8963 }
8964 
8965 
8966 /**
8967   Store a JSON value as binary.
8968 
8969   @param json  the JSON value to store
8970   @return zero on success, non-zero otherwise
8971 */
store_json(Json_wrapper * json)8972 type_conversion_status Field_json::store_json(Json_wrapper *json)
8973 {
8974   ASSERT_COLUMN_MARKED_FOR_WRITE;
8975 
8976   if (json->to_binary(&value))
8977     return TYPE_ERR_BAD_VALUE;
8978 
8979   return store_binary(value.ptr(), value.length());
8980 }
8981 
8982 
8983 /**
8984   Copy the contents of a non-null JSON field into this field.
8985 
8986   @param[in] field the field to copy data from
8987   @return zero on success, non-zero on failure
8988 */
store(Field_json * field)8989 type_conversion_status Field_json::store(Field_json *field)
8990 {
8991   /*
8992     The callers of this function have already checked for null, so we
8993     don't need to handle it here for now. Assert that field is not
8994     null.
8995   */
8996   DBUG_ASSERT(!field->is_null());
8997 
8998   String tmp;
8999   String *s= field->Field_blob::val_str(&tmp, &tmp);
9000   return store_binary(s->ptr(), s->length());
9001 }
9002 
9003 
val_json(Json_wrapper * wr)9004 bool Field_json::val_json(Json_wrapper *wr)
9005 {
9006   ASSERT_COLUMN_MARKED_FOR_READ;
9007   DBUG_ASSERT(!is_null());
9008 
9009   String tmp;
9010   String *s= Field_blob::val_str(&tmp, &tmp);
9011 
9012   /*
9013     The empty string is not a valid JSON binary representation, so we
9014     should have returned an error. However, sometimes an empty
9015     Field_json object is created in order to retrieve meta-data.
9016     Return a dummy value instead of raising an error. Bug#21104470.
9017 
9018     The field could also contain an empty string after forcing NULL or
9019     DEFAULT into a not nullable JSON column using lax error checking
9020     (such as INSERT IGNORE or non-strict SQL mode). The JSON null
9021     literal is used to represent the empty value in this case.
9022     Bug#21437989.
9023   */
9024   if (s->length() == 0)
9025   {
9026     Json_wrapper w(new (std::nothrow) Json_null());
9027     wr->steal(&w);
9028     return false;
9029   }
9030 
9031   json_binary::Value v(json_binary::parse_binary(s->ptr(), s->length()));
9032   if (v.type() == json_binary::Value::ERROR)
9033   {
9034     /* purecov: begin inspected */
9035     my_error(ER_INVALID_JSON_BINARY_DATA, MYF(0));
9036     return true;
9037     /* purecov: end */
9038   }
9039 
9040   Json_wrapper w(v);
9041   wr->steal(&w);
9042   return false;
9043 }
9044 
val_int()9045 longlong Field_json::val_int()
9046 {
9047   ASSERT_COLUMN_MARKED_FOR_READ;
9048 
9049   Json_wrapper wr;
9050   if (is_null() || val_json(&wr))
9051     return 0;                                   /* purecov: inspected */
9052 
9053   return wr.coerce_int(field_name);
9054 }
9055 
9056 
val_real()9057 double Field_json::val_real()
9058 {
9059   ASSERT_COLUMN_MARKED_FOR_READ;
9060 
9061   Json_wrapper wr;
9062   if (is_null() || val_json(&wr))
9063     return 0.0;                                 /* purecov: inspected */
9064 
9065   return wr.coerce_real(field_name);
9066 }
9067 
9068 
val_str(String * buf1,String * buf2 MY_ATTRIBUTE ((unused)))9069 String *Field_json::val_str(String *buf1, String *buf2 MY_ATTRIBUTE((unused)))
9070 {
9071   ASSERT_COLUMN_MARKED_FOR_READ;
9072 
9073   /*
9074     Per contract of Field::val_str(String*,String*), buf1 should be
9075     used if the value needs to be converted to string, and buf2 should
9076     be used if the string value is already known. We need to convert,
9077     so use buf1.
9078   */
9079   buf1->length(0);
9080 
9081   Json_wrapper wr;
9082   if (is_null() || val_json(&wr) || wr.to_string(buf1, true, field_name))
9083     buf1->length(0);
9084 
9085   return buf1;
9086 }
9087 
val_decimal(my_decimal * decimal_value)9088 my_decimal *Field_json::val_decimal(my_decimal *decimal_value)
9089 {
9090   ASSERT_COLUMN_MARKED_FOR_READ;
9091 
9092   Json_wrapper wr;
9093   if (is_null() || val_json(&wr))
9094   {
9095     /* purecov: begin inspected */
9096     my_decimal_set_zero(decimal_value);
9097     return decimal_value;
9098     /* purecov: end */
9099   }
9100 
9101   return wr.coerce_decimal(decimal_value, field_name);
9102 }
9103 
9104 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)9105 bool Field_json::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
9106 {
9107   bool result= get_time(ltime);
9108   if (!result && ltime->time_type == MYSQL_TIMESTAMP_TIME)
9109   {
9110     MYSQL_TIME tmp= *ltime;
9111     time_to_datetime(current_thd, &tmp, ltime);
9112   }
9113   return result;
9114 }
9115 
9116 
get_time(MYSQL_TIME * ltime)9117 bool Field_json::get_time(MYSQL_TIME *ltime)
9118 {
9119   ASSERT_COLUMN_MARKED_FOR_READ;
9120 
9121   Json_wrapper wr;
9122   bool result= is_null() || val_json(&wr) || wr.coerce_time(ltime, field_name);
9123   if (result)
9124     set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME); /* purecov: inspected */
9125   return result;
9126 }
9127 
9128 
make_sort_key(uchar * to,size_t length)9129 void Field_json::make_sort_key(uchar *to, size_t length)
9130 {
9131   Json_wrapper wr;
9132   if (val_json(&wr))
9133   {
9134     /* purecov: begin inspected */
9135     memset(to, 0, length);
9136     return;
9137     /* purecov: end */
9138   }
9139   wr.make_sort_key(to, length);
9140 }
9141 
9142 
make_hash_key(ulonglong * hash_val)9143 ulonglong Field_json::make_hash_key(ulonglong *hash_val)
9144 {
9145   Json_wrapper wr;
9146   if (val_json(&wr))
9147     return *hash_val;                         /* purecov: inspected */
9148   return wr.make_hash_key(hash_val);
9149 }
9150 
9151 
9152 /****************************************************************************
9153 ** enum type.
9154 ** This is a string which only can have a selection of different values.
9155 ** If one uses this string in a number context one gets the type number.
9156 ****************************************************************************/
9157 
key_type() const9158 enum ha_base_keytype Field_enum::key_type() const
9159 {
9160   switch (packlength) {
9161   default: return HA_KEYTYPE_BINARY;
9162   case 2: return HA_KEYTYPE_USHORT_INT;
9163   case 3: return HA_KEYTYPE_UINT24;
9164   case 4: return HA_KEYTYPE_ULONG_INT;
9165   case 8: return HA_KEYTYPE_ULONGLONG;
9166   }
9167 }
9168 
store_type(ulonglong value)9169 void Field_enum::store_type(ulonglong value)
9170 {
9171   switch (packlength) {
9172   case 1: ptr[0]= (uchar) value;
9173     break;
9174   case 2:
9175 #ifdef WORDS_BIGENDIAN
9176     if (table->s->db_low_byte_first)
9177     {
9178       int2store(ptr,(unsigned short) value);
9179     }
9180     else
9181     {
9182       shortstore(ptr,(unsigned short) value);
9183     }
9184 #else
9185     shortstore(ptr,(unsigned short) value);
9186 #endif
9187     break;
9188   case 3: int3store(ptr,(long) value);
9189     break;
9190   case 4:
9191 #ifdef WORDS_BIGENDIAN
9192     if (table->s->db_low_byte_first)
9193     {
9194       int4store(ptr,value);
9195     }
9196     else
9197     {
9198       longstore(ptr,(long) value);
9199     }
9200 #else
9201     longstore(ptr,(long) value);
9202 #endif
9203     break;
9204   case 8:
9205 #ifdef WORDS_BIGENDIAN
9206     if (table->s->db_low_byte_first)
9207     {
9208       int8store(ptr,value);
9209     }
9210     else
9211     {
9212       longlongstore(ptr,value);
9213     }
9214 #else
9215     longlongstore(ptr,value);
9216 #endif
9217     break;
9218   }
9219 }
9220 
9221 
9222 /**
9223   @note
9224     Storing a empty string in a enum field gives a warning
9225     (if there isn't a empty value in the enum)
9226 */
9227 
9228 type_conversion_status
store(const char * from,size_t length,const CHARSET_INFO * cs)9229 Field_enum::store(const char *from, size_t length,const CHARSET_INFO *cs)
9230 {
9231   ASSERT_COLUMN_MARKED_FOR_WRITE;
9232   int err= 0;
9233   type_conversion_status ret= TYPE_OK;
9234   char buff[STRING_BUFFER_USUAL_SIZE];
9235   String tmpstr(buff,sizeof(buff), &my_charset_bin);
9236 
9237   /* Convert character set if necessary */
9238   if (String::needs_conversion_on_storage(length, cs, field_charset))
9239   {
9240     uint dummy_errors;
9241     tmpstr.copy(from, length, cs, field_charset, &dummy_errors);
9242     from= tmpstr.ptr();
9243     length=  tmpstr.length();
9244   }
9245 
9246   /* Remove end space */
9247   length= field_charset->cset->lengthsp(field_charset, from, length);
9248   uint tmp=find_type2(typelib, from, length, field_charset);
9249   if (!tmp)
9250   {
9251     if (length < 6) // Can't be more than 99999 enums
9252     {
9253       /* This is for reading numbers with LOAD DATA INFILE */
9254       char *end;
9255       tmp=(uint) my_strntoul(cs,from,length,10,&end,&err);
9256       if (err || end != from+length || tmp > typelib->count)
9257       {
9258 	tmp=0;
9259 	set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
9260         ret= TYPE_WARN_TRUNCATED;
9261       }
9262       if (!table->in_use->count_cuted_fields)
9263         ret= TYPE_OK;
9264     }
9265     else
9266       set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
9267   }
9268   store_type((ulonglong) tmp);
9269   return ret;
9270 }
9271 
9272 
store(double nr)9273 type_conversion_status Field_enum::store(double nr)
9274 {
9275   return Field_enum::store((longlong) nr, FALSE);
9276 }
9277 
9278 
store(longlong nr,bool unsigned_val)9279 type_conversion_status Field_enum::store(longlong nr, bool unsigned_val)
9280 {
9281   ASSERT_COLUMN_MARKED_FOR_WRITE;
9282   type_conversion_status error= TYPE_OK;
9283   if ((ulonglong) nr > typelib->count || nr == 0)
9284   {
9285     set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
9286     if (nr != 0 || table->in_use->count_cuted_fields)
9287     {
9288       nr= 0;
9289       error= TYPE_WARN_TRUNCATED;
9290     }
9291   }
9292   store_type((ulonglong) (uint) nr);
9293   return error;
9294 }
9295 
9296 
val_real(void)9297 double Field_enum::val_real(void)
9298 {
9299   return (double) Field_enum::val_int();
9300 }
9301 
9302 
val_decimal(my_decimal * decimal_value)9303 my_decimal *Field_enum::val_decimal(my_decimal *decimal_value)
9304 {
9305   ASSERT_COLUMN_MARKED_FOR_READ;
9306   int2my_decimal(E_DEC_FATAL_ERROR, val_int(), 0, decimal_value);
9307   return decimal_value;
9308 }
9309 
9310 
val_int(void)9311 longlong Field_enum::val_int(void)
9312 {
9313   ASSERT_COLUMN_MARKED_FOR_READ;
9314   switch (packlength) {
9315   case 1:
9316     return (longlong) ptr[0];
9317   case 2:
9318   {
9319     uint16 tmp;
9320 #ifdef WORDS_BIGENDIAN
9321     if (table->s->db_low_byte_first)
9322       tmp=sint2korr(ptr);
9323     else
9324 #endif
9325       ushortget(&tmp, ptr);
9326     return (longlong) tmp;
9327   }
9328   case 3:
9329     return (longlong) uint3korr(ptr);
9330   case 4:
9331   {
9332     uint32 tmp;
9333 #ifdef WORDS_BIGENDIAN
9334     if (table->s->db_low_byte_first)
9335       tmp=uint4korr(ptr);
9336     else
9337 #endif
9338       ulongget(&tmp, ptr);
9339     return (longlong) tmp;
9340   }
9341   case 8:
9342   {
9343     longlong tmp;
9344 #ifdef WORDS_BIGENDIAN
9345     if (table->s->db_low_byte_first)
9346       tmp=sint8korr(ptr);
9347     else
9348 #endif
9349       longlongget(&tmp, ptr);
9350     return tmp;
9351   }
9352   }
9353   return 0;					// impossible
9354 }
9355 
9356 
9357 /**
9358    Save the field metadata for enum fields.
9359 
9360    Saves the real type in the first byte and the pack length in the
9361    second byte of the field metadata array at index of *metadata_ptr and
9362    *(metadata_ptr + 1).
9363 
9364    @param   metadata_ptr   First byte of field metadata
9365 
9366    @returns number of bytes written to metadata_ptr
9367 */
do_save_field_metadata(uchar * metadata_ptr)9368 int Field_enum::do_save_field_metadata(uchar *metadata_ptr)
9369 {
9370   *metadata_ptr= real_type();
9371   *(metadata_ptr + 1)= pack_length();
9372   return 2;
9373 }
9374 
9375 
val_str(String * val_buffer MY_ATTRIBUTE ((unused)),String * val_ptr)9376 String *Field_enum::val_str(String *val_buffer MY_ATTRIBUTE((unused)),
9377 			    String *val_ptr)
9378 {
9379   uint tmp=(uint) Field_enum::val_int();
9380   if (!tmp || tmp > typelib->count)
9381     val_ptr->set("", 0, field_charset);
9382   else
9383     val_ptr->set(typelib->type_names[tmp-1],
9384 		 typelib->type_lengths[tmp-1],
9385 		 field_charset);
9386   return val_ptr;
9387 }
9388 
cmp(const uchar * a_ptr,const uchar * b_ptr)9389 int Field_enum::cmp(const uchar *a_ptr, const uchar *b_ptr)
9390 {
9391   uchar *old= ptr;
9392   ptr= (uchar*) a_ptr;
9393   ulonglong a=Field_enum::val_int();
9394   ptr= (uchar*) b_ptr;
9395   ulonglong b=Field_enum::val_int();
9396   ptr= old;
9397   return (a < b) ? -1 : (a > b) ? 1 : 0;
9398 }
9399 
make_sort_key(uchar * to,size_t length)9400 void Field_enum::make_sort_key(uchar *to, size_t length)
9401 {
9402 #ifdef WORDS_BIGENDIAN
9403   if (!table->s->db_low_byte_first)
9404     copy_integer<true>(to, length, ptr, packlength, true);
9405   else
9406 #endif
9407   copy_integer<false>(to, length, ptr, packlength, true);
9408 }
9409 
9410 
sql_type(String & res) const9411 void Field_enum::sql_type(String &res) const
9412 {
9413   char buffer[255];
9414   String enum_item(buffer, sizeof(buffer), res.charset());
9415 
9416   res.length(0);
9417   res.append(STRING_WITH_LEN("enum("));
9418 
9419   bool flag=0;
9420   uint *len= typelib->type_lengths;
9421   for (const char **pos= typelib->type_names; *pos; pos++, len++)
9422   {
9423     uint dummy_errors;
9424     if (flag)
9425       res.append(',');
9426     /* convert to res.charset() == utf8, then quote */
9427     enum_item.copy(*pos, *len, charset(), res.charset(), &dummy_errors);
9428     append_unescaped(&res, enum_item.ptr(), enum_item.length());
9429     flag= 1;
9430   }
9431   res.append(')');
9432 }
9433 
9434 
new_field(MEM_ROOT * root,TABLE * new_table,bool keep_type)9435 Field *Field_enum::new_field(MEM_ROOT *root, TABLE *new_table,
9436                              bool keep_type)
9437 {
9438   Field_enum *res= (Field_enum*) Field::new_field(root, new_table, keep_type);
9439   if (res)
9440     res->typelib= copy_typelib(root, typelib);
9441   return res;
9442 }
9443 
9444 
9445 /*
9446    set type.
9447    This is a string which can have a collection of different values.
9448    Each string value is separated with a ','.
9449    For example "One,two,five"
9450    If one uses this string in a number context one gets the bits as a longlong
9451    number.
9452 */
9453 
9454 
9455 type_conversion_status
store(const char * from,size_t length,const CHARSET_INFO * cs)9456 Field_set::store(const char *from, size_t length,const CHARSET_INFO *cs)
9457 {
9458   ASSERT_COLUMN_MARKED_FOR_WRITE;
9459   bool got_warning= 0;
9460   int err= 0;
9461   type_conversion_status ret= TYPE_OK;
9462   char *not_used;
9463   uint not_used2;
9464   char buff[STRING_BUFFER_USUAL_SIZE];
9465   String tmpstr(buff,sizeof(buff), &my_charset_bin);
9466 
9467   /* Convert character set if necessary */
9468   if (String::needs_conversion_on_storage(length, cs, field_charset))
9469   {
9470     uint dummy_errors;
9471     tmpstr.copy(from, length, cs, field_charset, &dummy_errors);
9472     from= tmpstr.ptr();
9473     length=  tmpstr.length();
9474   }
9475   ulonglong tmp= find_set(typelib, from, length, field_charset,
9476                           &not_used, &not_used2, &got_warning);
9477   if (!tmp && length && length < 22)
9478   {
9479     /* This is for reading numbers with LOAD DATA INFILE */
9480     char *end;
9481     tmp=my_strntoull(cs,from,length,10,&end,&err);
9482     if (err ||
9483         end != from+length ||
9484         (typelib->count < 64 && tmp >= (1ULL << typelib->count)))
9485     {
9486       tmp=0;
9487       set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
9488       ret= TYPE_WARN_TRUNCATED;
9489     }
9490   }
9491   else if (got_warning)
9492     set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
9493   store_type(tmp);
9494   return ret;
9495 }
9496 
9497 
store(longlong nr,bool unsigned_val)9498 type_conversion_status Field_set::store(longlong nr, bool unsigned_val)
9499 {
9500   ASSERT_COLUMN_MARKED_FOR_WRITE;
9501   type_conversion_status error= TYPE_OK;
9502   ulonglong max_nr;
9503 
9504   if (sizeof(ulonglong)*8 <= typelib->count)
9505     max_nr= ULLONG_MAX;
9506   else
9507     max_nr= (1ULL << typelib->count) - 1;
9508 
9509   if ((ulonglong) nr > max_nr)
9510   {
9511     nr&= max_nr;
9512     set_warning(Sql_condition::SL_WARNING, WARN_DATA_TRUNCATED, 1);
9513     error= TYPE_WARN_TRUNCATED;
9514   }
9515   store_type((ulonglong) nr);
9516   return error;
9517 }
9518 
9519 
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))9520 String *Field_set::val_str(String *val_buffer,
9521 			   String *val_ptr MY_ATTRIBUTE((unused)))
9522 {
9523   ulonglong tmp=(ulonglong) Field_enum::val_int();
9524   uint bitnr=0;
9525 
9526   /*
9527     Some callers expect *val_buffer to contain the result,
9528     so we assign to it, rather than doing 'return &empty_set_string.
9529   */
9530   *val_buffer= empty_set_string;
9531   if (tmp == 0)
9532   {
9533     return val_buffer;
9534   }
9535 
9536   val_buffer->set_charset(field_charset);
9537   val_buffer->length(0);
9538 
9539   while (tmp && bitnr < typelib->count)
9540   {
9541     if (tmp & 1)
9542     {
9543       if (val_buffer->length())
9544 	val_buffer->append(&field_separator, 1, &my_charset_latin1);
9545       String str(typelib->type_names[bitnr],
9546 		 typelib->type_lengths[bitnr],
9547 		 field_charset);
9548       val_buffer->append(str);
9549     }
9550     tmp>>=1;
9551     bitnr++;
9552   }
9553   return val_buffer;
9554 }
9555 
9556 
sql_type(String & res) const9557 void Field_set::sql_type(String &res) const
9558 {
9559   char buffer[255];
9560   String set_item(buffer, sizeof(buffer), res.charset());
9561 
9562   res.length(0);
9563   res.append(STRING_WITH_LEN("set("));
9564 
9565   bool flag=0;
9566   uint *len= typelib->type_lengths;
9567   for (const char **pos= typelib->type_names; *pos; pos++, len++)
9568   {
9569     uint dummy_errors;
9570     if (flag)
9571       res.append(',');
9572     /* convert to res.charset() == utf8, then quote */
9573     set_item.copy(*pos, *len, charset(), res.charset(), &dummy_errors);
9574     append_unescaped(&res, set_item.ptr(), set_item.length());
9575     flag= 1;
9576   }
9577   res.append(')');
9578 }
9579 
9580 /**
9581   @retval
9582     1  if the fields are equally defined
9583   @retval
9584     0  if the fields are unequally defined
9585 */
9586 
eq_def(Field * field)9587 bool Field::eq_def(Field *field)
9588 {
9589   if (real_type() != field->real_type() || charset() != field->charset() ||
9590       pack_length() != field->pack_length())
9591     return 0;
9592   return 1;
9593 }
9594 
9595 
9596 /**
9597   Compare the first t1::count type names.
9598 
9599   @return TRUE if the type names of t1 match those of t2. FALSE otherwise.
9600 */
9601 
compare_type_names(const CHARSET_INFO * charset,TYPELIB * t1,TYPELIB * t2)9602 static bool compare_type_names(const CHARSET_INFO *charset,
9603                                TYPELIB *t1, TYPELIB *t2)
9604 {
9605   for (uint i= 0; i < t1->count; i++)
9606     if (my_strnncoll(charset,
9607                      (const uchar*) t1->type_names[i],
9608                      t1->type_lengths[i],
9609                      (const uchar*) t2->type_names[i],
9610                      t2->type_lengths[i]))
9611       return FALSE;
9612   return TRUE;
9613 }
9614 
9615 /**
9616   @return
9617   returns 1 if the fields are equally defined
9618 */
9619 
eq_def(Field * field)9620 bool Field_enum::eq_def(Field *field)
9621 {
9622   TYPELIB *values;
9623 
9624   if (!Field::eq_def(field))
9625     return FALSE;
9626 
9627   values= ((Field_enum*) field)->typelib;
9628 
9629   /* Definition must be strictly equal. */
9630   if (typelib->count != values->count)
9631     return FALSE;
9632 
9633   return compare_type_names(field_charset, typelib, values);
9634 }
9635 
9636 
9637 /**
9638   Check whether two fields can be considered 'equal' for table
9639   alteration purposes. Fields are equal if they retain the same
9640   pack length and if new members are added to the end of the list.
9641 
9642   @return IS_EQUAL_YES if fields are compatible.
9643           IS_EQUAL_NO otherwise.
9644 */
9645 
is_equal(Create_field * new_field)9646 uint Field_enum::is_equal(Create_field *new_field)
9647 {
9648   TYPELIB *values= new_field->interval;
9649 
9650   /*
9651     The fields are compatible if they have the same flags,
9652     type, charset and have the same underlying length.
9653   */
9654   if (new_field->sql_type != real_type() ||
9655       new_field->charset != field_charset ||
9656       new_field->pack_length != pack_length())
9657     return IS_EQUAL_NO;
9658 
9659   /*
9660     Changing the definition of an ENUM or SET column by adding a new
9661     enumeration or set members to the end of the list of valid member
9662     values only alters table metadata and not table data.
9663   */
9664   if (typelib->count > values->count)
9665     return IS_EQUAL_NO;
9666 
9667   /* Check whether there are modification before the end. */
9668   if (! compare_type_names(field_charset, typelib, new_field->interval))
9669     return IS_EQUAL_NO;
9670 
9671   return IS_EQUAL_YES;
9672 }
9673 
9674 
pack(uchar * to,const uchar * from,uint max_length,bool low_byte_first)9675 uchar *Field_enum::pack(uchar *to, const uchar *from,
9676                         uint max_length, bool low_byte_first)
9677 {
9678   DBUG_ENTER("Field_enum::pack");
9679   DBUG_PRINT("debug", ("packlength: %d", packlength));
9680   DBUG_DUMP("from", from, packlength);
9681 
9682   switch (packlength)
9683   {
9684   case 1:
9685     if (max_length > 0) *to = *from;
9686     DBUG_RETURN(to + 1);
9687   case 2: DBUG_RETURN(pack_int16(to, from, low_byte_first));
9688   case 3: DBUG_RETURN(pack_int24(to, from, low_byte_first));
9689   case 4: DBUG_RETURN(pack_int32(to, from, low_byte_first));
9690   case 8: DBUG_RETURN(pack_int64(to, from, low_byte_first));
9691   default:
9692     DBUG_ASSERT(0);
9693   }
9694   MY_ASSERT_UNREACHABLE();
9695   DBUG_RETURN(NULL);
9696 }
9697 
unpack(uchar * to,const uchar * from,uint param_data,bool low_byte_first)9698 const uchar *Field_enum::unpack(uchar *to, const uchar *from,
9699                                 uint param_data, bool low_byte_first)
9700 {
9701   DBUG_ENTER("Field_enum::unpack");
9702   DBUG_PRINT("debug", ("packlength: %d", packlength));
9703   DBUG_DUMP("from", from, packlength);
9704 
9705   switch (packlength)
9706   {
9707   case 1:
9708     *to = *from;
9709     DBUG_RETURN(from + 1);
9710 
9711   case 2: DBUG_RETURN(unpack_int16(to, from, low_byte_first));
9712   case 3: DBUG_RETURN(unpack_int24(to, from, low_byte_first));
9713   case 4: DBUG_RETURN(unpack_int32(to, from, low_byte_first));
9714   case 8: DBUG_RETURN(unpack_int64(to, from, low_byte_first));
9715   default:
9716     DBUG_ASSERT(0);
9717   }
9718   MY_ASSERT_UNREACHABLE();
9719   DBUG_RETURN(NULL);
9720 }
9721 
9722 
9723 /**
9724   @return
9725   returns 1 if the fields are equally defined
9726 */
eq_def(Field * field)9727 bool Field_num::eq_def(Field *field)
9728 {
9729   if (!Field::eq_def(field))
9730     return 0;
9731   Field_num *from_num= (Field_num*) field;
9732 
9733   if (unsigned_flag != from_num->unsigned_flag ||
9734       (zerofill && !from_num->zerofill && !zero_pack()) ||
9735       dec != from_num->dec)
9736     return 0;
9737   return 1;
9738 }
9739 
9740 
9741 /**
9742   Check whether two numeric fields can be considered 'equal' for table
9743   alteration purposes. Fields are equal if they are of the same type
9744   and retain the same pack length.
9745 */
9746 
is_equal(Create_field * new_field)9747 uint Field_num::is_equal(Create_field *new_field)
9748 {
9749   return ((new_field->sql_type == real_type()) &&
9750           ((new_field->flags & UNSIGNED_FLAG) ==
9751            (uint) (flags & UNSIGNED_FLAG)) &&
9752 	  ((new_field->flags & AUTO_INCREMENT_FLAG) ==
9753 	   (uint) (flags & AUTO_INCREMENT_FLAG)) &&
9754           (new_field->pack_length == pack_length()));
9755 }
9756 
9757 
9758 /*
9759   Bit field.
9760 
9761   We store the first 0 - 6 uneven bits among the null bits
9762   at the start of the record. The rest bytes are stored in
9763   the record itself.
9764 
9765   For example:
9766 
9767   CREATE TABLE t1 (a int, b bit(17), c bit(21) not null, d bit(8));
9768   We would store data  as follows in the record:
9769 
9770   Byte        Bit
9771   1           7 - reserve for delete
9772               6 - null bit for 'a'
9773               5 - null bit for 'b'
9774               4 - first (high) bit of 'b'
9775               3 - first (high) bit of 'c'
9776               2 - second bit of 'c'
9777               1 - third bit of 'c'
9778               0 - forth bit of 'c'
9779   2           7 - firth bit of 'c'
9780               6 - null bit for 'd'
9781   3 - 6       four bytes for 'a'
9782   7 - 8       two bytes for 'b'
9783   9 - 10      two bytes for 'c'
9784   11          one byte for 'd'
9785 */
9786 
Field_bit(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,uchar * bit_ptr_arg,uchar bit_ofs_arg,enum utype unireg_check_arg,const char * field_name_arg)9787 Field_bit::Field_bit(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
9788                      uchar null_bit_arg, uchar *bit_ptr_arg, uchar bit_ofs_arg,
9789                      enum utype unireg_check_arg, const char *field_name_arg)
9790   : Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
9791           unireg_check_arg, field_name_arg),
9792     bit_ptr(bit_ptr_arg), bit_ofs(bit_ofs_arg), bit_len(len_arg & 7),
9793     bytes_in_rec(len_arg / 8)
9794 {
9795   DBUG_ENTER("Field_bit::Field_bit");
9796   DBUG_PRINT("enter", ("ptr_arg: %p, null_ptr_arg: %p, len_arg: %u, bit_len: %u, bytes_in_rec: %u",
9797                        ptr_arg, null_ptr_arg, len_arg, bit_len, bytes_in_rec));
9798   flags|= UNSIGNED_FLAG;
9799   /*
9800     Ensure that Field::eq() can distinguish between two different bit fields.
9801     (two bit fields that are not null, may have same ptr and m_null_ptr)
9802   */
9803   if (!null_ptr_arg)
9804     null_bit= bit_ofs_arg;
9805   DBUG_VOID_RETURN;
9806 }
9807 
9808 
hash(ulong * nr,ulong * nr2)9809 void Field_bit::hash(ulong *nr, ulong *nr2)
9810 {
9811   if (is_null())
9812   {
9813     *nr^= (*nr << 1) | 1;
9814   }
9815   else
9816   {
9817     const CHARSET_INFO *cs= &my_charset_bin;
9818     longlong value= Field_bit::val_int();
9819     uchar tmp[8];
9820     mi_int8store(tmp,value);
9821     cs->coll->hash_sort(cs, tmp, 8, nr, nr2);
9822   }
9823 }
9824 
9825 
9826 size_t
do_last_null_byte() const9827 Field_bit::do_last_null_byte() const
9828 {
9829   /*
9830     Code elsewhere is assuming that bytes are 8 bits, so I'm using
9831     that value instead of the correct one: CHAR_BIT.
9832 
9833     REFACTOR SUGGESTION (Matz): Change to use the correct number of
9834     bits. On systems with CHAR_BIT > 8 (not very common), the storage
9835     will lose the extra bits.
9836   */
9837   DBUG_PRINT("test", ("bit_ofs: %d, bit_len: %d  bit_ptr: 0x%lx",
9838                       bit_ofs, bit_len, (long) bit_ptr));
9839   const uchar *result;
9840   if (bit_len == 0)
9841     result= get_null_ptr();
9842   else if (bit_ofs + bit_len > 8)
9843     result= bit_ptr + 1;
9844   else
9845     result= bit_ptr;
9846 
9847   if (result)
9848     return (size_t) (result - table->record[0]) + 1;
9849   return LAST_NULL_BYTE_UNDEF;
9850 }
9851 
9852 
new_key_field(MEM_ROOT * root,TABLE * new_table,uchar * new_ptr,uchar * new_null_ptr,uint new_null_bit)9853 Field *Field_bit::new_key_field(MEM_ROOT *root,
9854                                 TABLE *new_table,
9855                                 uchar *new_ptr, uchar *new_null_ptr,
9856                                 uint new_null_bit)
9857 {
9858   Field_bit *res;
9859   if ((res= (Field_bit*) Field::new_key_field(root, new_table,
9860                                               new_ptr, new_null_ptr,
9861                                               new_null_bit)))
9862   {
9863     /* Move bits normally stored in null_pointer to new_ptr */
9864     res->bit_ptr= new_ptr;
9865     res->bit_ofs= 0;
9866     if (bit_len)
9867       res->ptr++;                               // Store rest of data here
9868   }
9869   return res;
9870 }
9871 
9872 
is_equal(Create_field * new_field)9873 uint Field_bit::is_equal(Create_field *new_field)
9874 {
9875   return (new_field->sql_type == real_type() &&
9876           new_field->length == max_display_length());
9877 }
9878 
9879 
9880 type_conversion_status
store(const char * from,size_t length,const CHARSET_INFO * cs)9881 Field_bit::store(const char *from, size_t length, const CHARSET_INFO *cs)
9882 {
9883   ASSERT_COLUMN_MARKED_FOR_WRITE;
9884   int delta;
9885 
9886   for (; length && !*from; from++, length--) ;         // skip left 0's
9887   delta= bytes_in_rec - static_cast<int>(length);
9888 
9889   /*
9890     *from should probably be treated like uint here see BUG#13727586
9891   */
9892   if (delta < -1 ||
9893       (delta == -1 && (uchar) *from > ((1 << bit_len) - 1)) ||
9894       (!bit_len && delta < 0))
9895   {
9896     set_rec_bits((1 << bit_len) - 1, bit_ptr, bit_ofs, bit_len);
9897     memset(ptr, 0xff, bytes_in_rec);
9898     if (table->in_use->is_strict_mode())
9899       set_warning(Sql_condition::SL_WARNING, ER_DATA_TOO_LONG, 1);
9900     else
9901       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
9902     return TYPE_WARN_OUT_OF_RANGE;
9903   }
9904   /* delta is >= -1 here */
9905   if (delta > 0)
9906   {
9907     if (bit_len)
9908       clr_rec_bits(bit_ptr, bit_ofs, bit_len);
9909     memset(ptr, 0, delta);
9910     memcpy(ptr + delta, from, length);
9911   }
9912   else if (delta == 0)
9913   {
9914     if (bit_len)
9915       clr_rec_bits(bit_ptr, bit_ofs, bit_len);
9916     memcpy(ptr, from, length);
9917   }
9918   else
9919   {
9920     if (bit_len)
9921     {
9922       set_rec_bits((uchar) *from, bit_ptr, bit_ofs, bit_len);
9923       from++;
9924     }
9925     memcpy(ptr, from, bytes_in_rec);
9926   }
9927   return TYPE_OK;
9928 }
9929 
9930 
store(double nr)9931 type_conversion_status Field_bit::store(double nr)
9932 {
9933   return Field_bit::store((longlong) nr, FALSE);
9934 }
9935 
9936 
store(longlong nr,bool unsigned_val)9937 type_conversion_status Field_bit::store(longlong nr, bool unsigned_val)
9938 {
9939   char buf[8];
9940 
9941   mi_int8store(buf, nr);
9942   return store(buf, 8, NULL);
9943 }
9944 
9945 
store_decimal(const my_decimal * val)9946 type_conversion_status Field_bit::store_decimal(const my_decimal *val)
9947 {
9948   bool has_overflow= false;
9949   longlong i= convert_decimal2longlong(val, 1, &has_overflow);
9950   type_conversion_status res= store(i, TRUE);
9951   return has_overflow ? TYPE_WARN_OUT_OF_RANGE : res;
9952 }
9953 
9954 
val_real(void)9955 double Field_bit::val_real(void)
9956 {
9957   return (double) Field_bit::val_int();
9958 }
9959 
9960 
val_int(void)9961 longlong Field_bit::val_int(void)
9962 {
9963   ASSERT_COLUMN_MARKED_FOR_READ;
9964   ulonglong bits= 0;
9965   if (bit_len)
9966   {
9967     bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
9968     bits<<= (bytes_in_rec * 8);
9969   }
9970 
9971   switch (bytes_in_rec) {
9972   case 0: return bits;
9973   case 1: return bits | (ulonglong) ptr[0];
9974   case 2: return bits | mi_uint2korr(ptr);
9975   case 3: return bits | mi_uint3korr(ptr);
9976   case 4: return bits | mi_uint4korr(ptr);
9977   case 5: return bits | mi_uint5korr(ptr);
9978   case 6: return bits | mi_uint6korr(ptr);
9979   case 7: return bits | mi_uint7korr(ptr);
9980   default: return mi_uint8korr(ptr + bytes_in_rec - sizeof(longlong));
9981   }
9982 }
9983 
9984 
val_str(String * val_buffer,String * val_ptr MY_ATTRIBUTE ((unused)))9985 String *Field_bit::val_str(String *val_buffer,
9986                            String *val_ptr MY_ATTRIBUTE((unused)))
9987 {
9988   ASSERT_COLUMN_MARKED_FOR_READ;
9989   char buff[sizeof(longlong)];
9990   uint length= min<uint>(pack_length(), sizeof(longlong));
9991   ulonglong bits= val_int();
9992   mi_int8store(buff,bits);
9993 
9994   val_buffer->alloc(length);
9995   memcpy((char *) val_buffer->ptr(), buff+8-length, length);
9996   val_buffer->length(length);
9997   val_buffer->set_charset(&my_charset_bin);
9998   return val_buffer;
9999 }
10000 
10001 
val_decimal(my_decimal * deciaml_value)10002 my_decimal *Field_bit::val_decimal(my_decimal *deciaml_value)
10003 {
10004   ASSERT_COLUMN_MARKED_FOR_READ;
10005   int2my_decimal(E_DEC_FATAL_ERROR, val_int(), 1, deciaml_value);
10006   return deciaml_value;
10007 }
10008 
10009 
10010 /*
10011   Compare two bit fields using pointers within the record.
10012   SYNOPSIS
10013     cmp_max()
10014     a                 Pointer to field->ptr in first record
10015     b                 Pointer to field->ptr in second record
10016     max_len           Maximum length used in index
10017   DESCRIPTION
10018     This method is used from key_rec_cmp used by merge sorts used
10019     by partitioned index read and later other similar places.
10020     The a and b pointer must be pointers to the field in a record
10021     (not the table->record[0] necessarily)
10022 */
cmp_max(const uchar * a,const uchar * b,uint max_len)10023 int Field_bit::cmp_max(const uchar *a, const uchar *b, uint max_len)
10024 {
10025   my_ptrdiff_t a_diff= a - ptr;
10026   my_ptrdiff_t b_diff= b - ptr;
10027   if (bit_len)
10028   {
10029     int flag;
10030     uchar bits_a= get_rec_bits(bit_ptr+a_diff, bit_ofs, bit_len);
10031     uchar bits_b= get_rec_bits(bit_ptr+b_diff, bit_ofs, bit_len);
10032     if ((flag= (int) (bits_a - bits_b)))
10033       return flag;
10034   }
10035   return memcmp(a, b, pack_length());
10036 }
10037 
10038 
key_cmp(const uchar * str,uint length)10039 int Field_bit::key_cmp(const uchar *str, uint length)
10040 {
10041   if (bit_len)
10042   {
10043     int flag;
10044     uchar bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
10045     if ((flag= (int) (bits - *str)))
10046       return flag;
10047     str++;
10048     length--;
10049   }
10050   return memcmp(ptr, str, length);
10051 }
10052 
10053 
cmp_offset(uint row_offset)10054 int Field_bit::cmp_offset(uint row_offset)
10055 {
10056   if (bit_len)
10057   {
10058     int flag;
10059     uchar bits_a= get_rec_bits(bit_ptr, bit_ofs, bit_len);
10060     uchar bits_b= get_rec_bits(bit_ptr + row_offset, bit_ofs, bit_len);
10061     if ((flag= (int) (bits_a - bits_b)))
10062       return flag;
10063   }
10064   return memcmp(ptr, ptr + row_offset, bytes_in_rec);
10065 }
10066 
10067 
get_key_image(uchar * buff,size_t length,imagetype type_arg)10068 size_t Field_bit::get_key_image(uchar *buff, size_t length, imagetype type_arg)
10069 {
10070   if (bit_len)
10071   {
10072     uchar bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
10073     *buff++= bits;
10074     length--;
10075   }
10076   size_t data_length = min(length, static_cast<size_t>(bytes_in_rec));
10077   memcpy(buff, ptr, data_length);
10078   return data_length + 1;
10079 }
10080 
10081 
10082 /**
10083    Save the field metadata for bit fields.
10084 
10085    Saves the bit length in the first byte and bytes in record in the
10086    second byte of the field metadata array at index of *metadata_ptr and
10087    *(metadata_ptr + 1).
10088 
10089    @param   metadata_ptr   First byte of field metadata
10090 
10091    @returns number of bytes written to metadata_ptr
10092 */
do_save_field_metadata(uchar * metadata_ptr)10093 int Field_bit::do_save_field_metadata(uchar *metadata_ptr)
10094 {
10095   DBUG_ENTER("Field_bit::do_save_field_metadata");
10096   DBUG_PRINT("debug", ("bit_len: %d, bytes_in_rec: %d",
10097                        bit_len, bytes_in_rec));
10098   /*
10099     Since this class and Field_bit_as_char have different ideas of
10100     what should be stored here, we compute the values of the metadata
10101     explicitly using the field_length.
10102    */
10103   metadata_ptr[0]= field_length % 8;
10104   metadata_ptr[1]= field_length / 8;
10105   DBUG_RETURN(2);
10106 }
10107 
10108 
10109 /**
10110    Returns the number of bytes field uses in row-based replication
10111    row packed size.
10112 
10113    This method is used in row-based replication to determine the number
10114    of bytes that the field consumes in the row record format. This is
10115    used to skip fields in the master that do not exist on the slave.
10116 
10117    @param   field_metadata   Encoded size in field metadata
10118 
10119    @returns The size of the field based on the field metadata.
10120 */
pack_length_from_metadata(uint field_metadata)10121 uint Field_bit::pack_length_from_metadata(uint field_metadata)
10122 {
10123   uint const from_len= (field_metadata >> 8U) & 0x00ff;
10124   uint const from_bit_len= field_metadata & 0x00ff;
10125   uint const source_size= from_len + ((from_bit_len > 0) ? 1 : 0);
10126   return (source_size);
10127 }
10128 
10129 /**
10130    Check to see if field size is compatible with destination.
10131 
10132    This method is used in row-based replication to verify that the slave's
10133    field size is less than or equal to the master's field size. The
10134    encoded field metadata (from the master or source) is decoded and compared
10135    to the size of this field (the slave or destination).
10136 
10137    @param   field_metadata   Encoded size in field metadata
10138    @param   order_var        Pointer to variable where the order
10139                              between the source field and this field
10140                              will be returned.
10141 
10142    @return @c true
10143 */
10144 bool
compatible_field_size(uint field_metadata,Relay_log_info * MY_ATTRIBUTE ((unused)),uint16 mflags,int * order_var)10145 Field_bit::compatible_field_size(uint field_metadata,
10146                                  Relay_log_info * MY_ATTRIBUTE((unused)),
10147                                  uint16 mflags,
10148                                  int *order_var)
10149 {
10150   DBUG_ENTER("Field_bit::compatible_field_size");
10151   DBUG_ASSERT((field_metadata >> 16) == 0);
10152   uint from_bit_len= 8 * (field_metadata >> 8) + (field_metadata & 0xff);
10153   uint to_bit_len= max_display_length();
10154   DBUG_PRINT("debug", ("from_bit_len: %u, to_bit_len: %u",
10155                        from_bit_len, to_bit_len));
10156   /*
10157     If the bit length exact flag is clear, we are dealing with an old
10158     master, so we allow some less strict behaviour if replicating by
10159     moving both bit lengths to an even multiple of 8.
10160 
10161     We do this by computing the number of bytes to store the field
10162     instead, and then compare the result.
10163    */
10164   if (!(mflags & Table_map_log_event::TM_BIT_LEN_EXACT_F)) {
10165     from_bit_len= (from_bit_len + 7) / 8;
10166     to_bit_len= (to_bit_len + 7) / 8;
10167   }
10168 
10169   *order_var= compare(from_bit_len, to_bit_len);
10170   DBUG_RETURN(TRUE);
10171 }
10172 
10173 
10174 
sql_type(String & res) const10175 void Field_bit::sql_type(String &res) const
10176 {
10177   const CHARSET_INFO *cs= res.charset();
10178   size_t length= cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
10179                                    "bit(%d)", (int) field_length);
10180   res.length(length);
10181 }
10182 
10183 
10184 uchar *
pack(uchar * to,const uchar * from,uint max_length,bool low_byte_first MY_ATTRIBUTE ((unused)))10185 Field_bit::pack(uchar *to, const uchar *from, uint max_length,
10186                 bool low_byte_first MY_ATTRIBUTE((unused)))
10187 {
10188   DBUG_ASSERT(max_length > 0);
10189   uint length;
10190   if (bit_len > 0)
10191   {
10192     /*
10193       We have the following:
10194 
10195       ptr        Points into a field in record R1
10196       from       Points to a field in a record R2
10197       bit_ptr    Points to the byte (in the null bytes) that holds the
10198                  odd bits of R1
10199       from_bitp  Points to the byte that holds the odd bits of R2
10200 
10201       We have the following:
10202 
10203           ptr - bit_ptr = from - from_bitp
10204 
10205       We want to isolate 'from_bitp', so this gives:
10206 
10207           ptr - bit_ptr - from = - from_bitp
10208           - ptr + bit_ptr + from = from_bitp
10209           bit_ptr + from - ptr = from_bitp
10210      */
10211     uchar bits= get_rec_bits(bit_ptr + (from - ptr), bit_ofs, bit_len);
10212     *to++= bits;
10213   }
10214   length= min(bytes_in_rec, max_length - (bit_len > 0));
10215   memcpy(to, from, length);
10216   return to + length;
10217 }
10218 
10219 
10220 /**
10221    Unpack a bit field from row data.
10222 
10223    This method is used to unpack a bit field from a master whose size
10224    of the field is less than that of the slave.
10225 
10226    @param   to         Destination of the data
10227    @param   from       Source of the data
10228    @param   param_data Bit length (upper) and length (lower) values
10229 
10230    @return  New pointer into memory based on from + length of the data
10231 */
10232 const uchar *
unpack(uchar * to,const uchar * from,uint param_data,bool low_byte_first MY_ATTRIBUTE ((unused)))10233 Field_bit::unpack(uchar *to, const uchar *from, uint param_data,
10234                   bool low_byte_first MY_ATTRIBUTE((unused)))
10235 {
10236   DBUG_ENTER("Field_bit::unpack");
10237   DBUG_PRINT("enter", ("to: %p, from: %p, param_data: 0x%x",
10238                        to, from, param_data));
10239   DBUG_PRINT("debug", ("bit_ptr: %p, bit_len: %u, bit_ofs: %u",
10240                        bit_ptr, bit_len, bit_ofs));
10241   uint const from_len= (param_data >> 8U) & 0x00ff;
10242   uint const from_bit_len= param_data & 0x00ff;
10243   DBUG_PRINT("debug", ("from_len: %u, from_bit_len: %u",
10244                        from_len, from_bit_len));
10245   /*
10246     If the parameter data is zero (i.e., undefined), or if the master
10247     and slave have the same sizes, then use the old unpack() method.
10248   */
10249   if (param_data == 0 ||
10250       ((from_bit_len == bit_len) && (from_len == bytes_in_rec)))
10251   {
10252     if (bit_len > 0)
10253     {
10254       /*
10255         set_rec_bits is a macro, don't put the post-increment in the
10256         argument since that might cause strange side-effects.
10257 
10258         For the choice of the second argument, see the explanation for
10259         Field_bit::pack().
10260       */
10261       set_rec_bits(*from, bit_ptr + (to - ptr), bit_ofs, bit_len);
10262       from++;
10263     }
10264     memcpy(to, from, bytes_in_rec);
10265     DBUG_RETURN(from + bytes_in_rec);
10266   }
10267 
10268   /*
10269     We are converting a smaller bit field to a larger one here.
10270     To do that, we first need to construct a raw value for the original
10271     bit value stored in the from buffer. Then that needs to be converted
10272     to the larger field then sent to store() for writing to the field.
10273     Lastly the odd bits need to be masked out if the bytes_in_rec > 0.
10274     Otherwise stray bits can cause spurious values.
10275   */
10276   uint new_len= (field_length + 7) / 8;
10277   char *value= (char *)my_alloca(new_len);
10278   memset(value, 0, new_len);
10279   uint len= from_len + ((from_bit_len > 0) ? 1 : 0);
10280   memcpy(value + (new_len - len), from, len);
10281   /*
10282     Mask out the unused bits in the partial byte.
10283     TODO: Add code to the master to always mask these bits and remove
10284           the following.
10285   */
10286   if ((from_bit_len > 0) && (from_len > 0))
10287     value[new_len - len]= value[new_len - len] & ((1U << from_bit_len) - 1);
10288   bitmap_set_bit(table->write_set,field_index);
10289   store(value, new_len, system_charset_info);
10290   DBUG_RETURN(from + len);
10291 }
10292 
10293 
set_default()10294 void Field_bit::set_default()
10295 {
10296   if (bit_len > 0)
10297   {
10298     my_ptrdiff_t offset= table->default_values_offset();
10299     uchar bits= get_rec_bits(bit_ptr + offset, bit_ofs, bit_len);
10300     set_rec_bits(bits, bit_ptr, bit_ofs, bit_len);
10301   }
10302   Field::set_default();
10303 }
10304 
10305 /*
10306   Bit field support for non-MyISAM tables.
10307 */
10308 
Field_bit_as_char(uchar * ptr_arg,uint32 len_arg,uchar * null_ptr_arg,uchar null_bit_arg,enum utype unireg_check_arg,const char * field_name_arg)10309 Field_bit_as_char::Field_bit_as_char(uchar *ptr_arg, uint32 len_arg,
10310                                      uchar *null_ptr_arg, uchar null_bit_arg,
10311                                      enum utype unireg_check_arg,
10312                                      const char *field_name_arg)
10313   :Field_bit(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, 0, 0,
10314              unireg_check_arg, field_name_arg)
10315 {
10316   flags|= UNSIGNED_FLAG;
10317   bit_len= 0;
10318   bytes_in_rec= (len_arg + 7) / 8;
10319 }
10320 
10321 
store(const char * from,size_t length,const CHARSET_INFO * cs)10322 type_conversion_status Field_bit_as_char::store(const char *from, size_t length,
10323                                                 const CHARSET_INFO *cs)
10324 {
10325   ASSERT_COLUMN_MARKED_FOR_WRITE;
10326   int delta;
10327   uchar bits= (uchar) (field_length & 7);
10328 
10329   for (; length && !*from; from++, length--) ;         // skip left 0's
10330   delta= bytes_in_rec - static_cast<int>(length);
10331 
10332   if (delta < 0 ||
10333       (delta == 0 && bits && (uint) (uchar) *from >= (uint) (1 << bits)))
10334   {
10335     memset(ptr, 0xff, bytes_in_rec);
10336     if (bits)
10337       *ptr&= ((1 << bits) - 1); /* set first uchar */
10338     if (table->in_use->is_strict_mode())
10339       set_warning(Sql_condition::SL_WARNING, ER_DATA_TOO_LONG, 1);
10340     else
10341       set_warning(Sql_condition::SL_WARNING, ER_WARN_DATA_OUT_OF_RANGE, 1);
10342     return TYPE_WARN_OUT_OF_RANGE;
10343   }
10344   memset(ptr, 0, delta);
10345   memcpy(ptr + delta, from, length);
10346   return TYPE_OK;
10347 }
10348 
10349 
sql_type(String & res) const10350 void Field_bit_as_char::sql_type(String &res) const
10351 {
10352   const CHARSET_INFO *cs= res.charset();
10353   size_t length= cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
10354                                     "bit(%d)", (int) field_length);
10355   res.length(length);
10356 }
10357 
10358 
10359 /*****************************************************************************
10360   Handling of field and Create_field
10361 *****************************************************************************/
10362 
10363 /**
10364   Convert create_field::length from number of characters to number of bytes.
10365 */
10366 
create_length_to_internal_length(void)10367 void Create_field::create_length_to_internal_length(void)
10368 {
10369   switch (sql_type) {
10370   case MYSQL_TYPE_TINY_BLOB:
10371   case MYSQL_TYPE_MEDIUM_BLOB:
10372   case MYSQL_TYPE_LONG_BLOB:
10373   case MYSQL_TYPE_BLOB:
10374   case MYSQL_TYPE_GEOMETRY:
10375   case MYSQL_TYPE_JSON:
10376   case MYSQL_TYPE_VAR_STRING:
10377   case MYSQL_TYPE_STRING:
10378   case MYSQL_TYPE_VARCHAR:
10379     length*= charset->mbmaxlen;
10380     key_length= length;
10381     pack_length= calc_pack_length(sql_type, length);
10382     break;
10383   case MYSQL_TYPE_ENUM:
10384   case MYSQL_TYPE_SET:
10385     /* Pack_length already calculated in sql_parse.cc */
10386     length*= charset->mbmaxlen;
10387     key_length= pack_length;
10388     break;
10389   case MYSQL_TYPE_BIT:
10390     if (f_bit_as_char(pack_flag))
10391     {
10392       key_length= pack_length= ((length + 7) & ~7) / 8;
10393     }
10394     else
10395     {
10396       pack_length= length / 8;
10397       /* We need one extra byte to store the bits we save among the null bits */
10398       key_length= pack_length + MY_TEST(length & 7);
10399     }
10400     break;
10401   case MYSQL_TYPE_NEWDECIMAL:
10402     key_length= pack_length=
10403       my_decimal_get_binary_size(my_decimal_length_to_precision(length,
10404 								decimals,
10405 								flags &
10406 								UNSIGNED_FLAG),
10407 				 decimals);
10408     break;
10409   default:
10410     key_length= pack_length= calc_pack_length(sql_type, length);
10411     break;
10412   }
10413 }
10414 
10415 
10416 /**
10417   Init for a tmp table field. To be extended if need be.
10418 */
init_for_tmp_table(enum_field_types sql_type_arg,uint32 length_arg,uint32 decimals_arg,bool maybe_null,bool is_unsigned,uint pack_length_arg)10419 void Create_field::init_for_tmp_table(enum_field_types sql_type_arg,
10420                                       uint32 length_arg, uint32 decimals_arg,
10421                                       bool maybe_null, bool is_unsigned,
10422                                       uint pack_length_arg)
10423 {
10424   DBUG_ENTER("Create_field::init_for_tmp_table");
10425 
10426   field_name= "";
10427   sql_type= sql_type_arg;
10428   char_length= length= length_arg;;
10429   unireg_check= Field::NONE;
10430   interval= 0;
10431   charset= &my_charset_bin;
10432   geom_type= Field::GEOM_GEOMETRY;
10433 
10434   DBUG_PRINT("enter", ("sql_type: %d, length: %u, pack_length: %u",
10435                        sql_type_arg, length_arg, pack_length_arg));
10436 
10437   /*
10438     These pack flags are crafted to get it correctly through the
10439     branches of make_field().
10440    */
10441   switch (sql_type_arg)
10442   {
10443   case MYSQL_TYPE_VARCHAR:
10444   case MYSQL_TYPE_VAR_STRING:
10445   case MYSQL_TYPE_STRING:
10446   case MYSQL_TYPE_SET:
10447     pack_flag= 0;
10448     break;
10449 
10450   case MYSQL_TYPE_GEOMETRY:
10451     pack_flag= FIELDFLAG_GEOM;
10452     break;
10453 
10454   case MYSQL_TYPE_JSON:
10455     pack_flag= FIELDFLAG_JSON;
10456     break;
10457 
10458   case MYSQL_TYPE_ENUM:
10459     pack_flag= FIELDFLAG_INTERVAL;
10460     break;
10461 
10462   case MYSQL_TYPE_NEWDECIMAL:
10463     DBUG_ASSERT(decimals_arg <= DECIMAL_MAX_SCALE);
10464   case MYSQL_TYPE_DECIMAL:
10465   case MYSQL_TYPE_FLOAT:
10466   case MYSQL_TYPE_DOUBLE:
10467     pack_flag= FIELDFLAG_NUMBER |
10468       (decimals_arg & FIELDFLAG_MAX_DEC) << FIELDFLAG_DEC_SHIFT;
10469     break;
10470 
10471   case MYSQL_TYPE_TINY_BLOB:
10472   case MYSQL_TYPE_MEDIUM_BLOB:
10473   case MYSQL_TYPE_LONG_BLOB:
10474   case MYSQL_TYPE_BLOB:
10475     pack_flag= FIELDFLAG_BLOB;
10476     break;
10477 
10478   case MYSQL_TYPE_BIT:
10479     pack_flag= FIELDFLAG_NUMBER | FIELDFLAG_TREAT_BIT_AS_CHAR;
10480     break;
10481 
10482   default:
10483     pack_flag= FIELDFLAG_NUMBER;
10484     break;
10485   }
10486 
10487   /*
10488     Set the pack flag correctly for the blob-like types. This sets the
10489     packtype to something that make_field can use. If the pack type is
10490     not set correctly, the packlength will be reeeeally wierd (like
10491     129 or so).
10492    */
10493   switch (sql_type_arg)
10494   {
10495   case MYSQL_TYPE_ENUM:
10496   case MYSQL_TYPE_SET:
10497   case MYSQL_TYPE_TINY_BLOB:
10498   case MYSQL_TYPE_MEDIUM_BLOB:
10499   case MYSQL_TYPE_LONG_BLOB:
10500   case MYSQL_TYPE_BLOB:
10501   case MYSQL_TYPE_GEOMETRY:
10502   case MYSQL_TYPE_JSON:
10503     /*
10504       If you are going to use the above types, you have to pass a
10505       pack_length as parameter. Assert that is really done.
10506     */
10507     DBUG_ASSERT(pack_length_arg != ~0U);
10508     pack_flag|= pack_length_to_packflag(pack_length_arg);
10509     break;
10510   default:
10511     /* Nothing */
10512     break;
10513   }
10514 
10515   pack_flag|=
10516     (maybe_null ? FIELDFLAG_MAYBE_NULL : 0) |
10517     (is_unsigned ? 0 : FIELDFLAG_DECIMAL);
10518 
10519   gcol_info= 0;
10520   stored_in_db= TRUE;
10521 
10522   DBUG_PRINT("debug", ("pack_flag: %s%s%s%s%s%s%s, pack_type: %d",
10523                        FLAGSTR(pack_flag, FIELDFLAG_BINARY),
10524                        FLAGSTR(pack_flag, FIELDFLAG_NUMBER),
10525                        FLAGSTR(pack_flag, FIELDFLAG_INTERVAL),
10526                        FLAGSTR(pack_flag, FIELDFLAG_GEOM),
10527                        FLAGSTR(pack_flag, FIELDFLAG_BLOB),
10528                        FLAGSTR(pack_flag, FIELDFLAG_DECIMAL),
10529                        FLAGSTR(pack_flag, FIELDFLAG_JSON),
10530                        f_packtype(pack_flag)));
10531   DBUG_VOID_RETURN;
10532 }
10533 
10534 
10535 /**
10536   Initialize a column definition object. Column definition objects can be used
10537   to construct Field objects.
10538 
10539   @param thd                   Session/Thread handle.
10540   @param fld_name              Column name.
10541   @param fld_type              Column type.
10542   @param fld_length            Column length.
10543   @param fld_decimals          Number of digits to the right of the decimal
10544                                point (if any.)
10545   @param fld_type_modifier     Additional type information.
10546   @param fld_default_value     Column default expression (if any.)
10547   @param fld_on_update_value   The expression in the ON UPDATE clause.
10548   @param fld_comment           Column comment.
10549   @param fld_change            Column change.
10550   @param fld_interval_list     Interval list (if any.)
10551   @param fld_charset           Column charset.
10552   @param fld_geom_type         Column geometry type (if any.)
10553   @param fld_gcol_info         Generated column data
10554 
10555   @retval
10556     FALSE on success.
10557   @retval
10558     TRUE  on error.
10559 */
10560 
init(THD * thd,const char * fld_name,enum_field_types fld_type,const char * fld_length,const char * fld_decimals,uint fld_type_modifier,Item * fld_default_value,Item * fld_on_update_value,LEX_STRING * fld_comment,const char * fld_change,List<String> * fld_interval_list,const CHARSET_INFO * fld_charset,uint fld_geom_type,Generated_column * fld_gcol_info)10561 bool Create_field::init(THD *thd, const char *fld_name,
10562                         enum_field_types fld_type, const char *fld_length,
10563                         const char *fld_decimals, uint fld_type_modifier,
10564                         Item *fld_default_value, Item *fld_on_update_value,
10565                         LEX_STRING *fld_comment, const char *fld_change,
10566                         List<String> *fld_interval_list,
10567                         const CHARSET_INFO *fld_charset, uint fld_geom_type,
10568                         Generated_column *fld_gcol_info)
10569 {
10570   uint sign_len, allowed_type_modifier= 0;
10571   ulong max_field_charlength= MAX_FIELD_CHARLENGTH;
10572 
10573   DBUG_ENTER("Create_field::init()");
10574 
10575   field= 0;
10576   field_name= fld_name;
10577   flags= fld_type_modifier;
10578   charset= fld_charset;
10579 
10580   const bool on_update_is_function=
10581     (fld_on_update_value != NULL &&
10582      fld_on_update_value->type() == Item::FUNC_ITEM);
10583 
10584   if (fld_default_value != NULL && fld_default_value->type() == Item::FUNC_ITEM)
10585   {
10586     // We have a function default for insertions.
10587     def= NULL;
10588     unireg_check= on_update_is_function ?
10589       Field::TIMESTAMP_DNUN_FIELD : // for insertions and for updates.
10590       Field::TIMESTAMP_DN_FIELD;    // only for insertions.
10591   }
10592   else
10593   {
10594     // No function default for insertions. Either NULL or a constant.
10595     def= fld_default_value;
10596     if (on_update_is_function)
10597       // We have a function default for updates only.
10598       unireg_check= Field::TIMESTAMP_UN_FIELD;
10599     else
10600       // No function defaults.
10601       unireg_check= (fld_type_modifier & AUTO_INCREMENT_FLAG) != 0 ?
10602         Field::NEXT_NUMBER : // Automatic increment.
10603         Field::NONE;
10604   }
10605 
10606   decimals= fld_decimals ? (uint)atoi(fld_decimals) : 0;
10607   if (is_temporal_real_type(fld_type))
10608   {
10609     flags|= BINARY_FLAG;
10610     charset= &my_charset_numeric;
10611     if (decimals > DATETIME_MAX_DECIMALS)
10612     {
10613       my_error(ER_TOO_BIG_PRECISION, MYF(0),
10614                decimals, fld_name, DATETIME_MAX_DECIMALS);
10615       DBUG_RETURN(TRUE);
10616     }
10617   }
10618   else if (decimals >= NOT_FIXED_DEC)
10619   {
10620     my_error(ER_TOO_BIG_SCALE, MYF(0), decimals, fld_name,
10621              static_cast<ulong>(NOT_FIXED_DEC - 1));
10622     DBUG_RETURN(TRUE);
10623   }
10624 
10625   sql_type= fld_type;
10626   length= 0;
10627   change= fld_change;
10628   interval= 0;
10629   pack_length= key_length= 0;
10630   geom_type= (Field::geometry_type) fld_geom_type;
10631   interval_list.empty();
10632 
10633   comment= *fld_comment;
10634   gcol_info= fld_gcol_info;
10635   stored_in_db= TRUE;
10636 
10637   /* Initialize data for a virtual field */
10638   if (gcol_info)
10639   {
10640     DBUG_ASSERT(gcol_info->expr_item);
10641     stored_in_db= gcol_info->get_field_stored();
10642     /*
10643       Perform per item-type checks to determine if the expression is
10644       allowed for a generated column.
10645       Note that validation of the specific function is done later in
10646       procedures open_table_from_share and fix_fields_gcol_func
10647     */
10648     switch (gcol_info->expr_item->type()) {
10649     case Item::FUNC_ITEM:
10650       if (((Item_func *)gcol_info->expr_item)->functype() ==
10651           Item_func::FUNC_SP)
10652       {
10653         my_error(ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED, MYF(0),
10654                  field_name);
10655         DBUG_RETURN(TRUE);
10656       }
10657       break;
10658     case Item::COPY_STR_ITEM:
10659     case Item::FIELD_AVG_ITEM:
10660     case Item::PROC_ITEM:
10661     case Item::REF_ITEM:
10662     case Item::FIELD_STD_ITEM:
10663     case Item::FIELD_VARIANCE_ITEM:
10664     case Item::INSERT_VALUE_ITEM:
10665     case Item::SUBSELECT_ITEM:
10666     case Item::CACHE_ITEM:
10667     case Item::TYPE_HOLDER:
10668     case Item::PARAM_ITEM:
10669     case Item::TRIGGER_FIELD_ITEM:
10670     case Item::XPATH_NODESET:
10671     case Item::XPATH_NODESET_CMP:
10672     case Item::VIEW_FIXER_ITEM:
10673       my_error(ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED, MYF(0),
10674                field_name);
10675       DBUG_RETURN(TRUE);
10676       break;
10677     default:
10678       // Continue with the field creation
10679       break;
10680     }
10681     /*
10682       Make a field created for the real type.
10683       Note that "real" and generated fields differ from each other
10684       only by Field::gcol_info, which is always 0 for normal columns.
10685       gcol_info is updated for fields later in procedure open_binary_frm.
10686     */
10687     sql_type= fld_type= gcol_info->get_real_type();
10688   }
10689 
10690   /*
10691     Set NO_DEFAULT_VALUE_FLAG if this field doesn't have a default value and
10692     it is NOT NULL and not an AUTO_INCREMENT field.
10693   */
10694   if (!fld_default_value &&
10695       (fld_type_modifier & NOT_NULL_FLAG) &&
10696       !(fld_type_modifier & AUTO_INCREMENT_FLAG))
10697   {
10698     /*
10699       TIMESTAMP columns get implicit DEFAULT value when
10700       explicit_defaults_for_timestamp is not set.
10701     */
10702     if (thd->variables.explicit_defaults_for_timestamp ||
10703         !is_timestamp_type(fld_type))
10704     {
10705       flags|= NO_DEFAULT_VALUE_FLAG;
10706     }
10707   }
10708 
10709   if (fld_length != NULL)
10710   {
10711     errno= 0;
10712     length= strtoul(fld_length, NULL, 10);
10713     if ((errno != 0) || (length > MAX_FIELD_BLOBLENGTH))
10714     {
10715       my_error(ER_TOO_BIG_DISPLAYWIDTH, MYF(0), fld_name, MAX_FIELD_BLOBLENGTH);
10716       DBUG_RETURN(TRUE);
10717     }
10718 
10719     if (length == 0)
10720       fld_length= NULL; /* purecov: inspected */
10721   }
10722 
10723   sign_len= fld_type_modifier & UNSIGNED_FLAG ? 0 : 1;
10724 
10725   switch (fld_type) {
10726   case MYSQL_TYPE_TINY:
10727     if (!fld_length)
10728       length= MAX_TINYINT_WIDTH+sign_len;
10729     allowed_type_modifier= AUTO_INCREMENT_FLAG;
10730     break;
10731   case MYSQL_TYPE_SHORT:
10732     if (!fld_length)
10733       length= MAX_SMALLINT_WIDTH+sign_len;
10734     allowed_type_modifier= AUTO_INCREMENT_FLAG;
10735     break;
10736   case MYSQL_TYPE_INT24:
10737     if (!fld_length)
10738       length= MAX_MEDIUMINT_WIDTH+sign_len;
10739     allowed_type_modifier= AUTO_INCREMENT_FLAG;
10740     break;
10741   case MYSQL_TYPE_LONG:
10742     if (!fld_length)
10743       length= MAX_INT_WIDTH+sign_len;
10744     allowed_type_modifier= AUTO_INCREMENT_FLAG;
10745     break;
10746   case MYSQL_TYPE_LONGLONG:
10747     if (!fld_length)
10748       length= MAX_BIGINT_WIDTH;
10749     allowed_type_modifier= AUTO_INCREMENT_FLAG;
10750     break;
10751   case MYSQL_TYPE_NULL:
10752     break;
10753   case MYSQL_TYPE_NEWDECIMAL:
10754     {
10755       ulong precision= static_cast<ulong>(length);
10756       my_decimal_trim(&precision, &decimals);
10757       length= precision;
10758     }
10759     if (length > DECIMAL_MAX_PRECISION)
10760     {
10761       my_error(ER_TOO_BIG_PRECISION, MYF(0), static_cast<int>(length),
10762                fld_name, static_cast<ulong>(DECIMAL_MAX_PRECISION));
10763       DBUG_RETURN(TRUE);
10764     }
10765     if (length < decimals)
10766     {
10767       my_error(ER_M_BIGGER_THAN_D, MYF(0), fld_name);
10768       DBUG_RETURN(TRUE);
10769     }
10770     length=
10771       my_decimal_precision_to_length(length, decimals,
10772                                      fld_type_modifier & UNSIGNED_FLAG);
10773     pack_length=
10774       my_decimal_get_binary_size(length, decimals);
10775     break;
10776   case MYSQL_TYPE_VARCHAR:
10777     /*
10778       Long VARCHAR's are automaticly converted to blobs in mysql_prepare_table
10779       if they don't have a default value
10780     */
10781     max_field_charlength= MAX_FIELD_VARCHARLENGTH;
10782     break;
10783   case MYSQL_TYPE_STRING:
10784     break;
10785   case MYSQL_TYPE_BLOB:
10786   case MYSQL_TYPE_TINY_BLOB:
10787   case MYSQL_TYPE_LONG_BLOB:
10788   case MYSQL_TYPE_MEDIUM_BLOB:
10789   case MYSQL_TYPE_GEOMETRY:
10790   case MYSQL_TYPE_JSON:
10791     if (fld_default_value)
10792     {
10793       /* Allow empty as default value. */
10794       String str,*res;
10795       res= fld_default_value->val_str(&str);
10796       /*
10797         A default other than '' is always an error, and any non-NULL
10798         specified default is an error in strict mode.
10799       */
10800       if (res->length() || thd->is_strict_mode())
10801       {
10802         my_error(ER_BLOB_CANT_HAVE_DEFAULT, MYF(0),
10803                  fld_name); /* purecov: inspected */
10804         DBUG_RETURN(TRUE);
10805       }
10806       else
10807       {
10808         /*
10809           Otherwise a default of '' is just a warning.
10810         */
10811         push_warning_printf(thd, Sql_condition::SL_WARNING,
10812                             ER_BLOB_CANT_HAVE_DEFAULT,
10813                             ER(ER_BLOB_CANT_HAVE_DEFAULT),
10814                             fld_name);
10815       }
10816       def= 0;
10817     }
10818     flags|= BLOB_FLAG;
10819     break;
10820   case MYSQL_TYPE_YEAR:
10821     if (!fld_length || length != 4)
10822       length= 4; /* Default length */
10823     flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
10824     break;
10825   case MYSQL_TYPE_FLOAT:
10826     /* change FLOAT(precision) to FLOAT or DOUBLE */
10827     allowed_type_modifier= AUTO_INCREMENT_FLAG;
10828     if (fld_length && !fld_decimals)
10829     {
10830       size_t tmp_length= length;
10831       if (tmp_length > PRECISION_FOR_DOUBLE)
10832       {
10833         my_error(ER_WRONG_FIELD_SPEC, MYF(0), fld_name);
10834         DBUG_RETURN(TRUE);
10835       }
10836       else if (tmp_length > PRECISION_FOR_FLOAT)
10837       {
10838         sql_type= MYSQL_TYPE_DOUBLE;
10839         length= MAX_DOUBLE_STR_LENGTH;
10840       }
10841       else
10842         length= MAX_FLOAT_STR_LENGTH;
10843       decimals= NOT_FIXED_DEC;
10844       break;
10845     }
10846     if (!fld_length && !fld_decimals)
10847     {
10848       length=  MAX_FLOAT_STR_LENGTH;
10849       decimals= NOT_FIXED_DEC;
10850     }
10851     if (length < decimals &&
10852         decimals != NOT_FIXED_DEC)
10853     {
10854       my_error(ER_M_BIGGER_THAN_D, MYF(0), fld_name);
10855       DBUG_RETURN(TRUE);
10856     }
10857     break;
10858   case MYSQL_TYPE_DOUBLE:
10859     allowed_type_modifier= AUTO_INCREMENT_FLAG;
10860     if (!fld_length && !fld_decimals)
10861     {
10862       length= DBL_DIG+7;
10863       decimals= NOT_FIXED_DEC;
10864     }
10865     if (length < decimals &&
10866         decimals != NOT_FIXED_DEC)
10867     {
10868       my_error(ER_M_BIGGER_THAN_D, MYF(0), fld_name);
10869       DBUG_RETURN(TRUE);
10870     }
10871     break;
10872   case MYSQL_TYPE_TIMESTAMP:
10873     /* Add flags for TIMESTAMP for 4.0 MYD and 4.0 InnoDB compatibility */
10874     flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
10875     /* Fall through */
10876   case MYSQL_TYPE_TIMESTAMP2:
10877     if (fld_length == NULL)
10878     {
10879       length= MAX_DATETIME_WIDTH + (decimals ? (1 + decimals) : 0);
10880     }
10881     else if (length != MAX_DATETIME_WIDTH)
10882     {
10883       /*
10884         We support only even TIMESTAMP lengths less or equal than 14
10885         and 19 as length of 4.1 compatible representation.  Silently
10886         shrink it to MAX_DATETIME_COMPRESSED_WIDTH.
10887       */
10888       DBUG_ASSERT(MAX_DATETIME_COMPRESSED_WIDTH < UINT_MAX);
10889       if (length != UINT_MAX)  /* avoid overflow; is safe because of min() */
10890         length= ((length+1)/2)*2;
10891       length= min<size_t>(length, MAX_DATETIME_COMPRESSED_WIDTH);
10892     }
10893 
10894     /*
10895       Since we silently rewrite down to MAX_DATETIME_COMPRESSED_WIDTH bytes,
10896       the parser should not raise errors unless bizzarely large.
10897      */
10898     max_field_charlength= UINT_MAX;
10899 
10900     break;
10901   case MYSQL_TYPE_DATE:
10902     /* Old date type. */
10903     sql_type= MYSQL_TYPE_NEWDATE;
10904     /* fall through */
10905   case MYSQL_TYPE_NEWDATE:
10906     length= MAX_DATE_WIDTH;
10907     break;
10908   case MYSQL_TYPE_TIME:
10909   case MYSQL_TYPE_TIME2:
10910     length= MAX_TIME_WIDTH + (decimals ? (1 + decimals) : 0);
10911     break;
10912   case MYSQL_TYPE_DATETIME:
10913   case MYSQL_TYPE_DATETIME2:
10914     length= MAX_DATETIME_WIDTH + (decimals ? (1 + decimals) : 0);
10915     break;
10916   case MYSQL_TYPE_SET:
10917     {
10918       pack_length= get_set_pack_length(fld_interval_list->elements);
10919 
10920       List_iterator<String> it(*fld_interval_list);
10921       String *tmp;
10922       while ((tmp= it++))
10923         interval_list.push_back(tmp);
10924       /*
10925         Set fake length to 1 to pass the below conditions.
10926         Real length will be set in mysql_prepare_table()
10927         when we know the character set of the column
10928       */
10929       length= 1;
10930       break;
10931     }
10932   case MYSQL_TYPE_ENUM:
10933     {
10934       /* Should be safe. */
10935       pack_length= get_enum_pack_length(fld_interval_list->elements);
10936 
10937       List_iterator<String> it(*fld_interval_list);
10938       String *tmp;
10939       while ((tmp= it++))
10940         interval_list.push_back(tmp);
10941       length= 1; /* See comment for MYSQL_TYPE_SET above. */
10942       break;
10943    }
10944   case MYSQL_TYPE_VAR_STRING:
10945     DBUG_ASSERT(0);  /* Impossible. */
10946     break;
10947   case MYSQL_TYPE_BIT:
10948     {
10949       if (!fld_length)
10950       {
10951         my_error(ER_INVALID_FIELD_SIZE, MYF(0), fld_name);
10952         DBUG_RETURN(TRUE);
10953       }
10954       if (length > MAX_BIT_FIELD_LENGTH)
10955       {
10956         my_error(ER_TOO_BIG_DISPLAYWIDTH, MYF(0), fld_name,
10957                  static_cast<ulong>(MAX_BIT_FIELD_LENGTH));
10958         DBUG_RETURN(TRUE);
10959       }
10960       pack_length= (length + 7) / 8;
10961       break;
10962     }
10963   case MYSQL_TYPE_DECIMAL:
10964     DBUG_ASSERT(0); /* Was obsolete */
10965  }
10966   /* Remember the value of length */
10967   char_length= length;
10968 
10969   if (!(flags & BLOB_FLAG) &&
10970       ((length > max_field_charlength && fld_type != MYSQL_TYPE_SET &&
10971         fld_type != MYSQL_TYPE_ENUM &&
10972         (fld_type != MYSQL_TYPE_VARCHAR || fld_default_value)) ||
10973        ((length == 0) &&
10974         fld_type != MYSQL_TYPE_STRING &&
10975         fld_type != MYSQL_TYPE_VARCHAR && fld_type != MYSQL_TYPE_GEOMETRY)))
10976   {
10977     my_error((fld_type == MYSQL_TYPE_VAR_STRING ||
10978               fld_type == MYSQL_TYPE_VARCHAR ||
10979               fld_type == MYSQL_TYPE_STRING) ?  ER_TOO_BIG_FIELDLENGTH :
10980                                                 ER_TOO_BIG_DISPLAYWIDTH,
10981               MYF(0),
10982               fld_name, max_field_charlength); /* purecov: inspected */
10983     DBUG_RETURN(TRUE);
10984   }
10985   fld_type_modifier&= AUTO_INCREMENT_FLAG;
10986   if ((~allowed_type_modifier) & fld_type_modifier)
10987   {
10988     my_error(ER_WRONG_FIELD_SPEC, MYF(0), fld_name);
10989     DBUG_RETURN(TRUE);
10990   }
10991 
10992   DBUG_RETURN(FALSE); /* success */
10993 }
10994 
10995 
get_blob_type_from_length(ulong length)10996 enum_field_types get_blob_type_from_length(ulong length)
10997 {
10998   enum_field_types type;
10999   if (length < 256)
11000     type= MYSQL_TYPE_TINY_BLOB;
11001   else if (length < 65536)
11002     type= MYSQL_TYPE_BLOB;
11003   else if (length < 256L*256L*256L)
11004     type= MYSQL_TYPE_MEDIUM_BLOB;
11005   else
11006     type= MYSQL_TYPE_LONG_BLOB;
11007   return type;
11008 }
11009 
11010 
11011 /*
11012   Make a field from the .frm file info
11013 */
11014 
calc_pack_length(enum_field_types type,size_t length)11015 size_t calc_pack_length(enum_field_types type, size_t length)
11016 {
11017   switch (type) {
11018   case MYSQL_TYPE_VAR_STRING:
11019   case MYSQL_TYPE_STRING:
11020   case MYSQL_TYPE_DECIMAL:     return (length);
11021   case MYSQL_TYPE_VARCHAR:     return (length + (length < 256 ? 1: 2));
11022   case MYSQL_TYPE_YEAR:
11023   case MYSQL_TYPE_TINY	: return 1;
11024   case MYSQL_TYPE_SHORT : return 2;
11025   case MYSQL_TYPE_INT24:
11026   case MYSQL_TYPE_NEWDATE: return 3;
11027   case MYSQL_TYPE_TIME: return 3;
11028   case MYSQL_TYPE_TIME2:
11029     return length > MAX_TIME_WIDTH ?
11030            my_time_binary_length(length - MAX_TIME_WIDTH - 1) : 3;
11031   case MYSQL_TYPE_TIMESTAMP: return 4;
11032   case MYSQL_TYPE_TIMESTAMP2:
11033     return length > MAX_DATETIME_WIDTH ?
11034            my_timestamp_binary_length(length - MAX_DATETIME_WIDTH - 1) : 4;
11035   case MYSQL_TYPE_DATE:
11036   case MYSQL_TYPE_LONG	: return 4;
11037   case MYSQL_TYPE_FLOAT : return sizeof(float);
11038   case MYSQL_TYPE_DOUBLE: return sizeof(double);
11039   case MYSQL_TYPE_DATETIME: return 8;
11040   case MYSQL_TYPE_DATETIME2:
11041     return length > MAX_DATETIME_WIDTH ?
11042            my_datetime_binary_length(length - MAX_DATETIME_WIDTH - 1) : 5;
11043   case MYSQL_TYPE_LONGLONG: return 8;	/* Don't crash if no longlong */
11044   case MYSQL_TYPE_NULL	: return 0;
11045   case MYSQL_TYPE_TINY_BLOB:	return 1+portable_sizeof_char_ptr;
11046   case MYSQL_TYPE_BLOB:		return 2+portable_sizeof_char_ptr;
11047   case MYSQL_TYPE_MEDIUM_BLOB:	return 3+portable_sizeof_char_ptr;
11048   case MYSQL_TYPE_LONG_BLOB:	return 4+portable_sizeof_char_ptr;
11049   case MYSQL_TYPE_GEOMETRY:	return 4+portable_sizeof_char_ptr;
11050   case MYSQL_TYPE_JSON:         return 4+portable_sizeof_char_ptr;
11051   case MYSQL_TYPE_SET:
11052   case MYSQL_TYPE_ENUM:
11053   case MYSQL_TYPE_NEWDECIMAL:
11054     abort(); return 0;                          // This shouldn't happen
11055   case MYSQL_TYPE_BIT: return length / 8;
11056   default:
11057     return 0;
11058   }
11059 }
11060 
11061 
pack_length_to_packflag(uint type)11062 uint pack_length_to_packflag(uint type)
11063 {
11064   switch (type) {
11065     case 1: return f_settype((uint) MYSQL_TYPE_TINY);
11066     case 2: return f_settype((uint) MYSQL_TYPE_SHORT);
11067     case 3: return f_settype((uint) MYSQL_TYPE_INT24);
11068     case 4: return f_settype((uint) MYSQL_TYPE_LONG);
11069     case 8: return f_settype((uint) MYSQL_TYPE_LONGLONG);
11070   }
11071   return 0;					// This shouldn't happen
11072 }
11073 
make_field(TABLE_SHARE * share,uchar * ptr,size_t field_length,uchar * null_pos,uchar null_bit,uint pack_flag,enum_field_types field_type,const CHARSET_INFO * field_charset,Field::geometry_type geom_type,Field::utype unireg_check,TYPELIB * interval,const char * field_name)11074 Field *make_field(TABLE_SHARE *share, uchar *ptr, size_t field_length,
11075 		  uchar *null_pos, uchar null_bit,
11076 		  uint pack_flag,
11077 		  enum_field_types field_type,
11078 		  const CHARSET_INFO *field_charset,
11079 		  Field::geometry_type geom_type,
11080 		  Field::utype unireg_check,
11081 		  TYPELIB *interval,
11082 		  const char *field_name)
11083 {
11084   uchar *bit_ptr= NULL;
11085   uchar bit_offset= 0;
11086   if (field_type == MYSQL_TYPE_BIT && !f_bit_as_char(pack_flag))
11087   {
11088     bit_ptr= null_pos;
11089     bit_offset= null_bit;
11090     if (f_maybe_null(pack_flag))         // if null field
11091     {
11092        bit_ptr+= (null_bit == 7);        // shift bit_ptr and bit_offset
11093        bit_offset= (bit_offset + 1) & 7;
11094     }
11095   }
11096 
11097   if (!f_maybe_null(pack_flag))
11098   {
11099     null_pos=0;
11100     null_bit=0;
11101   }
11102   else
11103   {
11104     null_bit= ((uchar) 1) << null_bit;
11105   }
11106 
11107   if (is_temporal_real_type(field_type))
11108     field_charset= &my_charset_numeric;
11109 
11110   DBUG_PRINT("debug", ("field_type: %d, field_length: %zu, "
11111                        "interval: %p, pack_flag: %s%s%s%s%s",
11112                        field_type, field_length, interval,
11113                        FLAGSTR(pack_flag, FIELDFLAG_BINARY),
11114                        FLAGSTR(pack_flag, FIELDFLAG_INTERVAL),
11115                        FLAGSTR(pack_flag, FIELDFLAG_NUMBER),
11116                        FLAGSTR(pack_flag, FIELDFLAG_PACK),
11117                        FLAGSTR(pack_flag, FIELDFLAG_BLOB)));
11118 
11119   if (f_is_alpha(pack_flag))
11120   {
11121     if (!f_is_packed(pack_flag))
11122     {
11123       if (field_type == MYSQL_TYPE_STRING ||
11124           field_type == MYSQL_TYPE_DECIMAL ||   // 3.23 or 4.0 string
11125           field_type == MYSQL_TYPE_VAR_STRING)
11126         return new Field_string(ptr,field_length,null_pos,null_bit,
11127                                 unireg_check, field_name,
11128                                 field_charset);
11129       if (field_type == MYSQL_TYPE_VARCHAR)
11130         return new Field_varstring(ptr,field_length,
11131                                    HA_VARCHAR_PACKLENGTH(field_length),
11132                                    null_pos,null_bit,
11133                                    unireg_check, field_name,
11134                                    share,
11135                                    field_charset);
11136       return 0;                                 // Error
11137     }
11138 
11139     uint pack_length=calc_pack_length((enum_field_types)
11140 				      f_packtype(pack_flag),
11141 				      field_length);
11142 
11143     if (f_is_geom(pack_flag))
11144       return new Field_geom(ptr,null_pos,null_bit,
11145 			    unireg_check, field_name, share,
11146 			    pack_length, geom_type);
11147     if (f_is_json(pack_flag))
11148       return new Field_json(ptr, null_pos, null_bit,
11149                             unireg_check, field_name, share,
11150                             pack_length);
11151     if (f_is_blob(pack_flag))
11152       return new Field_blob(ptr,null_pos,null_bit,
11153 			    unireg_check, field_name, share,
11154 			    pack_length, field_charset);
11155     if (interval)
11156     {
11157       if (f_is_enum(pack_flag))
11158 	return new Field_enum(ptr,field_length,null_pos,null_bit,
11159 				  unireg_check, field_name,
11160 				  pack_length, interval, field_charset);
11161       else
11162 	return new Field_set(ptr,field_length,null_pos,null_bit,
11163 			     unireg_check, field_name,
11164 			     pack_length, interval, field_charset);
11165     }
11166   }
11167 
11168   switch (field_type) {
11169   case MYSQL_TYPE_DECIMAL:
11170     return new Field_decimal(ptr,field_length,null_pos,null_bit,
11171 			     unireg_check, field_name,
11172 			     f_decimals(pack_flag),
11173 			     f_is_zerofill(pack_flag) != 0,
11174 			     f_is_dec(pack_flag) == 0);
11175   case MYSQL_TYPE_NEWDECIMAL:
11176     return new Field_new_decimal(ptr,field_length,null_pos,null_bit,
11177                                  unireg_check, field_name,
11178                                  f_decimals(pack_flag),
11179                                  f_is_zerofill(pack_flag) != 0,
11180                                  f_is_dec(pack_flag) == 0);
11181   case MYSQL_TYPE_FLOAT:
11182     return new Field_float(ptr,field_length,null_pos,null_bit,
11183 			   unireg_check, field_name,
11184 			   f_decimals(pack_flag),
11185 			   f_is_zerofill(pack_flag) != 0,
11186 			   f_is_dec(pack_flag)== 0);
11187   case MYSQL_TYPE_DOUBLE:
11188     return new Field_double(ptr,field_length,null_pos,null_bit,
11189 			    unireg_check, field_name,
11190 			    f_decimals(pack_flag),
11191 			    f_is_zerofill(pack_flag) != 0,
11192 			    f_is_dec(pack_flag)== 0);
11193   case MYSQL_TYPE_TINY:
11194     return new Field_tiny(ptr,field_length,null_pos,null_bit,
11195 			  unireg_check, field_name,
11196 			  f_is_zerofill(pack_flag) != 0,
11197 			  f_is_dec(pack_flag) == 0);
11198   case MYSQL_TYPE_SHORT:
11199     return new Field_short(ptr,field_length,null_pos,null_bit,
11200 			   unireg_check, field_name,
11201 			   f_is_zerofill(pack_flag) != 0,
11202 			   f_is_dec(pack_flag) == 0);
11203   case MYSQL_TYPE_INT24:
11204     return new Field_medium(ptr,field_length,null_pos,null_bit,
11205 			    unireg_check, field_name,
11206 			    f_is_zerofill(pack_flag) != 0,
11207 			    f_is_dec(pack_flag) == 0);
11208   case MYSQL_TYPE_LONG:
11209     return new Field_long(ptr,field_length,null_pos,null_bit,
11210 			   unireg_check, field_name,
11211 			   f_is_zerofill(pack_flag) != 0,
11212 			   f_is_dec(pack_flag) == 0);
11213   case MYSQL_TYPE_LONGLONG:
11214     return new Field_longlong(ptr,field_length,null_pos,null_bit,
11215 			      unireg_check, field_name,
11216 			      f_is_zerofill(pack_flag) != 0,
11217 			      f_is_dec(pack_flag) == 0);
11218   case MYSQL_TYPE_TIMESTAMP:
11219     return new Field_timestamp(ptr, field_length, null_pos, null_bit,
11220                                unireg_check, field_name);
11221   case MYSQL_TYPE_TIMESTAMP2:
11222     return new Field_timestampf(ptr, null_pos, null_bit,
11223                                 unireg_check, field_name,
11224                                 field_length > MAX_DATETIME_WIDTH ?
11225                                 field_length - 1 - MAX_DATETIME_WIDTH : 0);
11226   case MYSQL_TYPE_YEAR:
11227     return new Field_year(ptr,field_length,null_pos,null_bit,
11228 			  unireg_check, field_name);
11229   case MYSQL_TYPE_NEWDATE:
11230     return new Field_newdate(ptr, null_pos, null_bit, unireg_check, field_name);
11231 
11232   case MYSQL_TYPE_TIME:
11233     return new Field_time(ptr, null_pos, null_bit,
11234                           unireg_check, field_name);
11235   case MYSQL_TYPE_TIME2:
11236     return new Field_timef(ptr, null_pos, null_bit,
11237                            unireg_check, field_name,
11238                            (field_length > MAX_TIME_WIDTH) ?
11239                            field_length - 1 - MAX_TIME_WIDTH : 0);
11240   case MYSQL_TYPE_DATETIME:
11241     return new Field_datetime(ptr, null_pos, null_bit,
11242                               unireg_check, field_name);
11243   case MYSQL_TYPE_DATETIME2:
11244     return new Field_datetimef(ptr, null_pos, null_bit,
11245                                unireg_check, field_name,
11246                                (field_length > MAX_DATETIME_WIDTH) ?
11247                                field_length - 1 - MAX_DATETIME_WIDTH : 0);
11248   case MYSQL_TYPE_NULL:
11249     return new Field_null(ptr, field_length, unireg_check, field_name,
11250                           field_charset);
11251   case MYSQL_TYPE_BIT:
11252     return f_bit_as_char(pack_flag) ?
11253            new Field_bit_as_char(ptr, field_length, null_pos, null_bit,
11254                                  unireg_check, field_name) :
11255            new Field_bit(ptr, field_length, null_pos, null_bit, bit_ptr,
11256                          bit_offset, unireg_check, field_name);
11257 
11258   default:					// Impossible (Wrong version)
11259     break;
11260   }
11261   return 0;
11262 }
11263 
11264 
11265 /**
11266     Constructs a column definition from an actual column object. This is a
11267     reverse-engineering procedure that creates a column definition object as
11268     produced by the parser (Create_field) from a resolved column object
11269     (Field).
11270 
11271     @param old_field  The column object from which the column definition is
11272                       constructed.
11273     @param orig_field Used for copying default values. This parameter may be
11274                       NULL, but if present it is used for copying default
11275                       values.
11276 
11277     Default values are copied into an Item_string unless:
11278     @li The default value is a function.
11279     @li There is no default value.
11280     @li old_field is a BLOB column.
11281     @li old_field has its data pointer improperly initialized.
11282 */
11283 
Create_field(Field * old_field,Field * orig_field)11284 Create_field::Create_field(Field *old_field,Field *orig_field) :
11285   field_name(old_field->field_name),
11286   change(NULL),
11287   comment(old_field->comment),
11288   sql_type(old_field->real_type()),
11289   length(old_field->field_length),
11290   decimals(old_field->decimals()),
11291   flags(old_field->flags),
11292   pack_length(old_field->pack_length()),
11293   key_length(old_field->key_length()),
11294   unireg_check(old_field->unireg_check),
11295   charset(old_field->charset()),		// May be NULL ptr
11296   field(old_field),
11297   gcol_info(old_field->gcol_info),
11298   stored_in_db(old_field->stored_in_db)
11299 {
11300 
11301   switch (sql_type) {
11302   case MYSQL_TYPE_BLOB:
11303     switch (pack_length - portable_sizeof_char_ptr) {
11304     case  1: sql_type= MYSQL_TYPE_TINY_BLOB; break;
11305     case  2: sql_type= MYSQL_TYPE_BLOB; break;
11306     case  3: sql_type= MYSQL_TYPE_MEDIUM_BLOB; break;
11307     default: sql_type= MYSQL_TYPE_LONG_BLOB; break;
11308     }
11309     length/= charset->mbmaxlen;
11310     key_length/= charset->mbmaxlen;
11311     break;
11312   case MYSQL_TYPE_STRING:
11313     /* Change CHAR -> VARCHAR if dynamic record length */
11314     if (old_field->type() == MYSQL_TYPE_VAR_STRING)
11315       sql_type= MYSQL_TYPE_VARCHAR;
11316     /* fall through */
11317 
11318   case MYSQL_TYPE_ENUM:
11319   case MYSQL_TYPE_SET:
11320   case MYSQL_TYPE_VARCHAR:
11321   case MYSQL_TYPE_VAR_STRING:
11322     /* This is corrected in create_length_to_internal_length */
11323     length= (length+charset->mbmaxlen-1) / charset->mbmaxlen;
11324     break;
11325   case MYSQL_TYPE_GEOMETRY:
11326     geom_type= ((Field_geom*)old_field)->geom_type;
11327     break;
11328   case MYSQL_TYPE_YEAR:
11329     if (length != 4)
11330       length= 4; //set default value
11331     break;
11332   default:
11333     break;
11334   }
11335 
11336   if (flags & (ENUM_FLAG | SET_FLAG))
11337     interval= ((Field_enum*) old_field)->typelib;
11338   else
11339     interval=0;
11340   def=0;
11341   char_length= length;
11342 
11343   /*
11344     Copy the default (constant/function) from the column object orig_field, if
11345     supplied. We do this if all these conditions are met:
11346 
11347     - The column allows a default.
11348 
11349     - The column type is not a BLOB type.
11350 
11351     - The original column (old_field) was properly initialized with a record
11352       buffer pointer.
11353   */
11354   if (!(flags & (NO_DEFAULT_VALUE_FLAG | BLOB_FLAG)) &&
11355       old_field->ptr != NULL &&
11356       orig_field != NULL)
11357   {
11358     bool default_now= false;
11359     if (real_type_with_now_as_default(sql_type))
11360     {
11361       // The SQL type of the new field allows a function default:
11362       default_now= orig_field->has_insert_default_function();
11363       bool update_now= orig_field->has_update_default_function();
11364 
11365       if (default_now && update_now)
11366         unireg_check= Field::TIMESTAMP_DNUN_FIELD;
11367       else if (default_now)
11368         unireg_check= Field::TIMESTAMP_DN_FIELD;
11369       else if (update_now)
11370         unireg_check= Field::TIMESTAMP_UN_FIELD;
11371     }
11372     if (!default_now)                           // Give a constant default
11373     {
11374       char buff[MAX_FIELD_WIDTH];
11375       String tmp(buff,sizeof(buff), charset);
11376 
11377       /* Get the value from default_values */
11378       my_ptrdiff_t diff= orig_field->table->default_values_offset();
11379       orig_field->move_field_offset(diff);	// Points now at default_values
11380       if (!orig_field->is_real_null())
11381       {
11382         char buff[MAX_FIELD_WIDTH], *pos;
11383         String tmp(buff, sizeof(buff), charset), *res;
11384         res= orig_field->val_str(&tmp);
11385         pos= sql_strmake(res->ptr(), res->length());
11386         def= new Item_string(pos, res->length(), charset);
11387       }
11388       orig_field->move_field_offset(-diff);	// Back to record[0]
11389     }
11390   }
11391 }
11392 
11393 
11394 /**
11395   maximum possible character length for blob.
11396 
11397   This method is used in Item_field::set_field to calculate
11398   max_length for Item.
11399 
11400   For example:
11401     CREATE TABLE t2 SELECT CONCAT(tinyblob_utf8_column) FROM t1;
11402   must create a "VARCHAR(255) CHARACTER SET utf8" column.
11403 
11404   @return
11405     length
11406 */
11407 
char_length()11408 uint32 Field_blob::char_length()
11409 {
11410   switch (packlength)
11411   {
11412   case 1:
11413     return 255;
11414   case 2:
11415     return 65535;
11416   case 3:
11417     return 16777215;
11418   case 4:
11419     return (uint32) 4294967295U;
11420   default:
11421     DBUG_ASSERT(0); // we should never go here
11422     return 0;
11423   }
11424 }
11425 
11426 /**
11427   This function creates a separate copy of blob value.
11428 
11429   @param [in] mem_root
11430     mem_root that is used to allocate memory for 'copy_of_value'.
11431 
11432   @return - Can fail if we are out of memory.
11433     @retval false   Success
11434     @retval true    Failure
11435 */
11436 
copy_blob_value(MEM_ROOT * mem_root)11437 bool Field_blob::copy_blob_value(MEM_ROOT *mem_root)
11438 {
11439   DBUG_ENTER("copy_blob_value");
11440 
11441   // Testing memory allocation failure
11442   DBUG_EXECUTE_IF("simulate_blob_memory_allocation_fail",
11443                   DBUG_SET("+d,simulate_out_of_memory"););
11444 
11445   // Allocate new memory location
11446   size_t ulen= get_length(ptr);
11447 
11448   char *blob_value= (char *) alloc_root(mem_root, ulen);
11449   if (!blob_value)
11450     DBUG_RETURN(true);
11451 
11452   // Copy Data
11453   uchar *temp_ptr;
11454   get_ptr(&temp_ptr);
11455   memcpy(blob_value, temp_ptr, ulen);
11456 
11457   // Set ptr of Field for duplicated data
11458   store_ptr_and_length(blob_value, ulen);
11459 
11460   // Set 'value' with the duplicated data
11461   value.set(blob_value, ulen, value.charset());
11462 
11463   DBUG_RETURN(false);
11464 }
11465 
11466 /**
11467   maximum possible display length for blob.
11468 
11469   @return
11470     length
11471 */
11472 
max_display_length()11473 uint32 Field_blob::max_display_length()
11474 {
11475   switch (packlength)
11476   {
11477   case 1:
11478     return 255 * field_charset->mbmaxlen;
11479   case 2:
11480     return 65535 * field_charset->mbmaxlen;
11481   case 3:
11482     return 16777215 * field_charset->mbmaxlen;
11483   case 4:
11484     return (uint32) 4294967295U;
11485   default:
11486     DBUG_ASSERT(0); // we should never go here
11487     return 0;
11488   }
11489 }
11490 
11491 
11492 /*****************************************************************************
11493  Warning handling
11494 *****************************************************************************/
11495 
11496 
11497 /**
11498   Produce warning or note about data saved into field.
11499 
11500   @param level            - level of message (Note/Warning/Error)
11501   @param code             - error code of message to be produced
11502   @param cut_increment    - whenever we should increase cut fields count
11503   @param view_db_name     - if set this is the database name for view
11504                             that causes the warning
11505   @param view_name        - if set this is the name of view that causes
11506                             the warning
11507 
11508   @note
11509     This function won't produce warning and increase cut fields counter
11510     if count_cuted_fields == CHECK_FIELD_IGNORE for current thread.
11511 
11512     if count_cuted_fields == CHECK_FIELD_IGNORE then we ignore notes.
11513     This allows us to avoid notes in optimisation, like convert_constant_item().
11514 
11515     In case of execution statements INSERT/INSERT SELECT/REPLACE/REPLACE SELECT
11516     the method emits only one warning message for the following
11517     types of warning: ER_BAD_NULL_ERROR, ER_WARN_NULL_TO_NOTNULL,
11518     ER_NO_DEFAULT_FOR_FIELD.
11519   @retval
11520     1 if count_cuted_fields == CHECK_FIELD_IGNORE and error level is not NOTE
11521   @retval
11522     0 otherwise
11523 */
11524 
set_warning(Sql_condition::enum_severity_level level,uint code,int cut_increment,const char * view_db_name,const char * view_name)11525 bool Field::set_warning(Sql_condition::enum_severity_level level,
11526                         uint code,
11527                         int cut_increment,
11528                         const char *view_db_name,
11529                         const char *view_name)
11530 {
11531   /*
11532     If this field was created only for type conversion purposes it
11533     will have table == NULL.
11534   */
11535 
11536   THD *thd= table ? table->in_use : current_thd;
11537 
11538   if (!thd->count_cuted_fields)
11539     return level >= Sql_condition::SL_WARNING;
11540 
11541   thd->cuted_fields+= cut_increment;
11542 
11543   if (thd->lex->sql_command != SQLCOM_INSERT &&
11544       thd->lex->sql_command != SQLCOM_INSERT_SELECT &&
11545       thd->lex->sql_command != SQLCOM_REPLACE &&
11546       thd->lex->sql_command != SQLCOM_REPLACE_SELECT)
11547   {
11548     // We aggregate warnings from only INSERT and REPLACE statements.
11549 
11550     push_warning_printf(thd, level, code, ER(code), field_name,
11551                         thd->get_stmt_da()->current_row_for_condition());
11552 
11553     return 0;
11554   }
11555 
11556   unsigned int current_warning_mask= 0;
11557 
11558   if (code == ER_BAD_NULL_ERROR)
11559     current_warning_mask= BAD_NULL_ERROR_PUSHED;
11560   else if (code == ER_NO_DEFAULT_FOR_FIELD)
11561     current_warning_mask= NO_DEFAULT_FOR_FIELD_PUSHED;
11562 
11563   if (current_warning_mask)
11564   {
11565     if (!(m_warnings_pushed & current_warning_mask))
11566     {
11567       push_warning_printf(thd, level, code, ER(code), field_name,
11568                           thd->get_stmt_da()->current_row_for_condition());
11569       m_warnings_pushed|= current_warning_mask;
11570     }
11571   }
11572   else if (code == ER_NO_DEFAULT_FOR_VIEW_FIELD)
11573   {
11574     if (!(m_warnings_pushed & NO_DEFAULT_FOR_VIEW_FIELD_PUSHED))
11575     {
11576       push_warning_printf(thd, Sql_condition::SL_WARNING,
11577                           ER_NO_DEFAULT_FOR_VIEW_FIELD,
11578                           ER(ER_NO_DEFAULT_FOR_VIEW_FIELD),
11579                           view_db_name,
11580                           view_name);
11581       m_warnings_pushed|= NO_DEFAULT_FOR_VIEW_FIELD_PUSHED;
11582     }
11583   }
11584   else
11585   {
11586     push_warning_printf(thd, level, code, ER(code), field_name,
11587                         thd->get_stmt_da()->current_row_for_condition());
11588   }
11589 
11590   return 0;
11591 }
11592 
11593 
11594 /**
11595   Produce warning or note about double datetime data saved into field.
11596 
11597   @param level            level of message (Note/Warning/Error)
11598   @param code             error code of message to be produced
11599   @param val              error parameter (the value)
11600   @param ts_type          type of datetime value (datetime/date/time)
11601   @param cut_increment    whenever we should increase cut fields count
11602   @note
11603     This function will always produce some warning but won't increase cut
11604     fields counter if count_cuted_fields == FIELD_CHECK_IGNORE for current
11605     thread.
11606 */
11607 void
set_datetime_warning(Sql_condition::enum_severity_level level,uint code,ErrConvString val,timestamp_type ts_type,int cut_increment)11608 Field_temporal::set_datetime_warning(Sql_condition::enum_severity_level level,
11609                                      uint code,
11610                                      ErrConvString val,
11611                                      timestamp_type ts_type,
11612                                      int cut_increment)
11613 {
11614   THD *thd= table ? table->in_use : current_thd;
11615   if ((!thd->lex->is_ignore() &&
11616        ((thd->variables.sql_mode & MODE_STRICT_ALL_TABLES) ||
11617         (thd->variables.sql_mode & MODE_STRICT_TRANS_TABLES &&
11618          !thd->get_transaction()->cannot_safely_rollback(Transaction_ctx::STMT)))) ||
11619       set_warning(level, code, cut_increment))
11620     make_truncated_value_warning(thd, level, val, ts_type, field_name);
11621 }
11622 
is_part_of_actual_key(THD * thd,uint cur_index,KEY * cur_index_info)11623 bool Field::is_part_of_actual_key(THD *thd, uint cur_index, KEY *cur_index_info)
11624 {
11625   return
11626     thd->optimizer_switch_flag(OPTIMIZER_SWITCH_USE_INDEX_EXTENSIONS) &&
11627     !(cur_index_info->flags & HA_NOSAME) ?
11628     part_of_key.is_set(cur_index) :
11629     part_of_key_not_extended.is_set(cur_index);
11630 }
11631