field.cc 312 KB
Newer Older
1
/*
Sergei Golubchik's avatar
Sergei Golubchik committed
2
   Copyright (c) 2000, 2013, Oracle and/or its affiliates.
3
   Copyright (c) 2008, 2013, Monty Program Ab.
unknown's avatar
unknown committed
4

unknown's avatar
unknown committed
5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
unknown's avatar
unknown committed
7
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
8

unknown's avatar
unknown committed
9 10 11 12
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
unknown's avatar
unknown committed
13

unknown's avatar
unknown committed
14 15
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
16 17
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
*/
unknown's avatar
unknown committed
18

19 20 21 22 23 24
/**
  @file

  @brief
  This file implements classes defined in field.h
*/
unknown's avatar
unknown committed
25

26
#ifdef USE_PRAGMA_IMPLEMENTATION
unknown's avatar
unknown committed
27 28 29
#pragma implementation				// gcc: Class implementation
#endif

30
#include <my_global.h>
31
#include "sql_priv.h"
unknown's avatar
unknown committed
32
#include "sql_select.h"
33 34
#include "rpl_rli.h"                            // Pull in Relay_log_info
#include "slave.h"                              // Pull in rpl_master_has_bug()
35 36 37 38 39 40 41 42 43
#include "strfunc.h"                            // find_type2, find_set
#include "sql_time.h"                    // str_to_datetime_with_warn,
                                         // str_to_time_with_warn,
                                         // TIME_to_timestamp,
                                         // make_time, make_date,
                                         // make_truncated_value_warning
#include "tztime.h"                      // struct Time_zone
#include "filesort.h"                    // change_double_for_sort
#include "log_event.h"                   // class Table_map_log_event
unknown's avatar
unknown committed
44 45
#include <m_ctype.h>

unknown's avatar
unknown committed
46 47 48
// Maximum allowed exponent value for converting string to decimal
#define MAX_EXPONENT 1024

unknown's avatar
unknown committed
49
/*****************************************************************************
50
  Instansiate templates and static variables
unknown's avatar
unknown committed
51 52
*****************************************************************************/

Sergei Golubchik's avatar
Sergei Golubchik committed
53 54 55 56 57 58 59 60 61 62 63
static const char *zero_timestamp="0000-00-00 00:00:00.000000";

/* number of bytes to store second_part part of the TIMESTAMP(N) */
static uint sec_part_bytes[MAX_DATETIME_PRECISION+1]= { 0, 1, 1, 2, 2, 3, 3 };

/* number of bytes to store DATETIME(N) */
static uint datetime_hires_bytes[MAX_DATETIME_PRECISION+1]= { 5, 6, 6, 7, 7, 7, 8 };

/* number of bytes to store TIME(N) */
static uint time_hires_bytes[MAX_DATETIME_PRECISION+1]= { 3, 4, 4, 5, 5, 5, 6 };

unknown's avatar
unknown committed
64 65 66
uchar Field_null::null[1]={1};
const char field_separator=',';

67
#define DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE FLOATING_POINT_BUFFER
68 69
#define LONGLONG_TO_STRING_CONVERSION_BUFFER_SIZE 128
#define DECIMAL_TO_STRING_CONVERSION_BUFFER_SIZE 128
70
#define BLOB_PACK_LENGTH_TO_MAX_LENGH(arg) \
Sergei Golubchik's avatar
Sergei Golubchik committed
71
                        ((ulong) ((1LL << MY_MIN(arg, 4) * 8) - 1))
72

unknown's avatar
unknown committed
73
#define ASSERT_COLUMN_MARKED_FOR_READ DBUG_ASSERT(!table || (!table->read_set || bitmap_is_set(table->read_set, field_index)))
74
#define ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED DBUG_ASSERT(is_stat_field || !table || (!table->write_set || bitmap_is_set(table->write_set, field_index) || (table->vcol_set && bitmap_is_set(table->vcol_set, field_index))))
75

76 77
#define FLAGSTR(S,F) ((S) & (F) ? #F " " : "")

78 79 80 81 82
/*
  Rules for merging different types of fields in UNION

  NOTE: to avoid 256*256 table, gap in table types numeration is skiped
  following #defines describe that gap and how to canculate number of fields
83
  and index of field in this array.
84
*/
unknown's avatar
unknown committed
85 86 87
#define FIELDTYPE_TEAR_FROM (MYSQL_TYPE_BIT + 1)
#define FIELDTYPE_TEAR_TO   (MYSQL_TYPE_NEWDECIMAL - 1)
#define FIELDTYPE_NUM (FIELDTYPE_TEAR_FROM + (255 - FIELDTYPE_TEAR_TO))
88
static inline int field_type2index (enum_field_types field_type)
89
{
90
  field_type= real_type_to_type(field_type);
91 92 93 94 95
  return (field_type < FIELDTYPE_TEAR_FROM ?
          field_type :
          ((int)FIELDTYPE_TEAR_FROM) + (field_type - FIELDTYPE_TEAR_TO) - 1);
}

unknown's avatar
unknown committed
96

97 98 99 100 101
static enum_field_types field_types_merge_rules [FIELDTYPE_NUM][FIELDTYPE_NUM]=
{
  /* MYSQL_TYPE_DECIMAL -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
102
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
103
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
unknown's avatar
unknown committed
104
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
105 106 107
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
unknown's avatar
unknown committed
108
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
109 110 111
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_DECIMAL,     MYSQL_TYPE_DECIMAL,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
unknown's avatar
unknown committed
112
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
113
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
114 115 116 117 118 119 120
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
121
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
122
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
123 124 125
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
126
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
127
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
128
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
129 130 131 132
  },
  /* MYSQL_TYPE_TINY -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
133
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_TINY,
134 135 136 137 138
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_SHORT,       MYSQL_TYPE_LONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
unknown's avatar
unknown committed
139
    MYSQL_TYPE_TINY,        MYSQL_TYPE_VARCHAR,
140 141 142
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_INT24,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
unknown's avatar
unknown committed
143
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
144
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
145 146 147 148 149 150 151
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
152
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
153
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
154 155 156
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
157
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
158
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
159
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
160 161 162 163
  },
  /* MYSQL_TYPE_SHORT -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
164
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_SHORT,
165 166 167 168 169
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_SHORT,       MYSQL_TYPE_LONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
unknown's avatar
unknown committed
170
    MYSQL_TYPE_SHORT,       MYSQL_TYPE_VARCHAR,
171 172 173
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_INT24,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
unknown's avatar
unknown committed
174
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
175
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
176 177 178 179 180 181 182
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_SHORT,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
183
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
184
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
185 186 187
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
188
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
189
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
190
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
191 192 193 194
  },
  /* MYSQL_TYPE_LONG -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
195
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_LONG,
196 197 198 199 200
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_LONG,        MYSQL_TYPE_LONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
unknown's avatar
unknown committed
201
    MYSQL_TYPE_LONG,         MYSQL_TYPE_VARCHAR,
202
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
203
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONG,
204
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
unknown's avatar
unknown committed
205
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
206
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
207 208 209 210 211 212 213
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_LONG,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
214
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
215
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
216 217 218
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
219
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
220
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
221
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
222 223 224 225 226 227 228 229 230 231
  },
  /* MYSQL_TYPE_FLOAT -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_FLOAT,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
unknown's avatar
unknown committed
232
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_VARCHAR,
233
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
234
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_FLOAT,
235
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
unknown's avatar
unknown committed
236
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
237
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
238 239 240 241 242 243 244
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_FLOAT,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_VARCHAR,
245
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
246
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
247 248 249
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
250
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
251
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
252
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
253 254 255 256 257 258 259 260 261 262
  },
  /* MYSQL_TYPE_DOUBLE -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
unknown's avatar
unknown committed
263
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_VARCHAR,
264
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
265
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
266
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
unknown's avatar
unknown committed
267
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
268
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
269 270 271 272 273 274 275
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_VARCHAR,
276
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
277
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
278 279 280
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
281
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
282
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
283
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
284 285 286 287
  },
  /* MYSQL_TYPE_NULL -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
288
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_TINY,
289 290 291 292 293 294 295
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_SHORT,       MYSQL_TYPE_LONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_NULL,        MYSQL_TYPE_TIMESTAMP,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
296
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONGLONG,
297 298 299 300
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_TIME,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_YEAR,
unknown's avatar
unknown committed
301 302 303 304 305 306
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_BIT,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_ENUM,
307 308 309 310 311
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_SET,         MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
312
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
313 314 315 316 317 318
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
    MYSQL_TYPE_STRING,      MYSQL_TYPE_GEOMETRY
  },
  /* MYSQL_TYPE_TIMESTAMP -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
319
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
320
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
unknown's avatar
unknown committed
321
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
322
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
unknown's avatar
unknown committed
323
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
324 325 326
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_TIMESTAMP,   MYSQL_TYPE_TIMESTAMP,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
unknown's avatar
unknown committed
327
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
328 329 330
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
331 332 333 334 335 336 337
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
338
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
339
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
340 341 342
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
343
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
344
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
345
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
346 347 348 349
  },
  /* MYSQL_TYPE_LONGLONG -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
350
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_LONGLONG,
351 352 353 354 355
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONGLONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
unknown's avatar
unknown committed
356
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_VARCHAR,
357 358 359
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONG,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
unknown's avatar
unknown committed
360
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
361
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
362 363 364 365 366 367 368
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_LONGLONG,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
369
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
370
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
371 372 373
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
374
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
375
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
376
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
377 378 379 380
  },
  /* MYSQL_TYPE_INT24 -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
381
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_INT24,
382 383 384 385 386
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_INT24,       MYSQL_TYPE_LONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
unknown's avatar
unknown committed
387
    MYSQL_TYPE_INT24,       MYSQL_TYPE_VARCHAR,
388 389 390
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_INT24,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
unknown's avatar
unknown committed
391
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
392
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
393 394 395 396 397 398 399
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_INT24,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL    MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
400
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
401
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
402 403 404
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
405
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
406
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
407
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
408 409 410 411
  },
  /* MYSQL_TYPE_DATE -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
412
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
413
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
unknown's avatar
unknown committed
414
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
415
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
unknown's avatar
unknown committed
416
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
417 418 419
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
unknown's avatar
unknown committed
420
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
421 422 423
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
424 425 426 427 428 429 430
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
431
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
432
    MYSQL_TYPE_VARCHAR,  MYSQL_TYPE_TINY_BLOB,
433 434 435
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
436
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
437
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
438
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
439 440 441 442
  },
  /* MYSQL_TYPE_TIME -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
443
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
444
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
unknown's avatar
unknown committed
445
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
446
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
unknown's avatar
unknown committed
447
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
448 449 450
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_TIME,        MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
unknown's avatar
unknown committed
451
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
452 453 454
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_TIME,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
455 456 457 458 459 460 461
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
462
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
463
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
464 465 466
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
467
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
468
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
469
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
470 471 472 473
  },
  /* MYSQL_TYPE_DATETIME -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
474
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
475
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
unknown's avatar
unknown committed
476
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
477
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
unknown's avatar
unknown committed
478
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
479 480 481
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
unknown's avatar
unknown committed
482
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
483 484 485
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
486 487 488 489 490 491 492
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
493
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
494
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
495 496 497
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
498
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
499
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
500
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
501 502 503 504 505 506 507 508 509 510
  },
  /* MYSQL_TYPE_YEAR -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_DECIMAL,     MYSQL_TYPE_TINY,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_SHORT,       MYSQL_TYPE_LONG,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_FLOAT,       MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
unknown's avatar
unknown committed
511
    MYSQL_TYPE_YEAR,        MYSQL_TYPE_VARCHAR,
512 513 514
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_INT24,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
unknown's avatar
unknown committed
515
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
516
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
517 518 519 520 521 522 523
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_YEAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
524
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
525
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
526 527 528
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
529
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
530
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
531
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
532 533 534 535
  },
  /* MYSQL_TYPE_NEWDATE -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
536
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
537
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
unknown's avatar
unknown committed
538
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
539
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
unknown's avatar
unknown committed
540
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
541 542 543
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
unknown's avatar
unknown committed
544
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
545 546 547
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_DATETIME,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
    MYSQL_TYPE_DATETIME,    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_NEWDATE,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
  },
  /* MYSQL_TYPE_VARCHAR -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR
  },
  /* MYSQL_TYPE_BIT -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_BIT,         MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_BIT,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
  },
  /* MYSQL_TYPE_NEWDECIMAL -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_DOUBLE,      MYSQL_TYPE_DOUBLE,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_NEWDECIMAL,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_NEWDECIMAL,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_NEWDECIMAL,  MYSQL_TYPE_VARCHAR,
648
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
649
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
650 651 652
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
653
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
654
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
655
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
656 657 658 659
  },
  /* MYSQL_TYPE_ENUM -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
660
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
661
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
unknown's avatar
unknown committed
662
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
663
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
unknown's avatar
unknown committed
664
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
665
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
unknown's avatar
unknown committed
666
    MYSQL_TYPE_ENUM,        MYSQL_TYPE_VARCHAR,
667
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
unknown's avatar
unknown committed
668
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
669
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
unknown's avatar
unknown committed
670
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
671
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
672 673 674 675 676 677 678
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
679
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
680
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
681 682 683
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
684
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
685
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
686
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
687 688 689 690
  },
  /* MYSQL_TYPE_SET -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
691
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
692
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
unknown's avatar
unknown committed
693
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
694
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
unknown's avatar
unknown committed
695
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
696
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
unknown's avatar
unknown committed
697
    MYSQL_TYPE_SET,         MYSQL_TYPE_VARCHAR,
698
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
unknown's avatar
unknown committed
699
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
700
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
unknown's avatar
unknown committed
701
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
702
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
703 704 705 706 707 708 709
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
710
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
711
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
712 713 714
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
715
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
716
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
717
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
  },
  /* MYSQL_TYPE_TINY_BLOB -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
unknown's avatar
unknown committed
735 736 737
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_BIT          <16>-<245>
738
    MYSQL_TYPE_TINY_BLOB,
unknown's avatar
unknown committed
739 740
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
    MYSQL_TYPE_TINY_BLOB,   MYSQL_TYPE_TINY_BLOB
  },
  /* MYSQL_TYPE_MEDIUM_BLOB -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
unknown's avatar
unknown committed
766 767 768
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_BIT          <16>-<245>
769
    MYSQL_TYPE_MEDIUM_BLOB,
unknown's avatar
unknown committed
770 771
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_MEDIUM_BLOB
  },
  /* MYSQL_TYPE_LONG_BLOB -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
unknown's avatar
unknown committed
797 798 799
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BIT          <16>-<245>
800
    MYSQL_TYPE_LONG_BLOB,
unknown's avatar
unknown committed
801 802
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
    MYSQL_TYPE_LONG_BLOB,   MYSQL_TYPE_LONG_BLOB
  },
  /* MYSQL_TYPE_BLOB -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
unknown's avatar
unknown committed
828 829 830
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_BIT          <16>-<245>
831
    MYSQL_TYPE_BLOB,
unknown's avatar
unknown committed
832 833
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
834 835 836 837 838 839 840 841 842 843 844 845
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB,
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_BLOB
  },
  /* MYSQL_TYPE_VAR_STRING -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
846
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
847
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
unknown's avatar
unknown committed
848
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
849
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
unknown's avatar
unknown committed
850
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
851
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
unknown's avatar
unknown committed
852
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
853
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
unknown's avatar
unknown committed
854
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
855
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
unknown's avatar
unknown committed
856
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
857
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
858 859 860 861 862 863 864
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
865
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
866
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
867 868 869
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
870
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
871
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
unknown's avatar
unknown committed
872
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
  },
  /* MYSQL_TYPE_STRING -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
unknown's avatar
unknown committed
890 891 892
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_STRING,      MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
893
    MYSQL_TYPE_STRING,
unknown's avatar
unknown committed
894 895
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING,
896 897 898 899 900
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
    MYSQL_TYPE_STRING,      MYSQL_TYPE_TINY_BLOB,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
901
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
902 903 904 905 906 907
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
    MYSQL_TYPE_STRING,      MYSQL_TYPE_STRING
  },
  /* MYSQL_TYPE_GEOMETRY -> */
  {
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
908
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
909
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
unknown's avatar
unknown committed
910
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
911
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
unknown's avatar
unknown committed
912
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
913
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
unknown's avatar
unknown committed
914
    MYSQL_TYPE_GEOMETRY,    MYSQL_TYPE_VARCHAR,
915
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
unknown's avatar
unknown committed
916
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
917
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
unknown's avatar
unknown committed
918
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
919
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
unknown's avatar
unknown committed
920 921 922 923 924 925 926
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_BIT          <16>-<245>
    MYSQL_TYPE_VARCHAR,
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
927
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
unknown's avatar
unknown committed
928
    MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_TINY_BLOB,
929 930 931
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
    MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
unknown's avatar
unknown committed
932
    MYSQL_TYPE_BLOB,        MYSQL_TYPE_VARCHAR,
933 934 935 936 937
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
    MYSQL_TYPE_STRING,      MYSQL_TYPE_GEOMETRY
  }
};

938 939
/**
  Return type of which can carry value of both given types in UNION result.
940

941 942
  @param a  type for merging
  @param b  type for merging
943

944
  @return
945 946 947 948 949 950
    type of field
*/

enum_field_types Field::field_type_merge(enum_field_types a,
                                         enum_field_types b)
{
951 952 953 954
  DBUG_ASSERT(real_type_to_type(a) < FIELDTYPE_TEAR_FROM ||
              real_type_to_type(a) > FIELDTYPE_TEAR_TO);
  DBUG_ASSERT(real_type_to_type(b) < FIELDTYPE_TEAR_FROM ||
              real_type_to_type(b) > FIELDTYPE_TEAR_TO);
955 956 957 958 959 960 961 962
  return field_types_merge_rules[field_type2index(a)]
                                [field_type2index(b)];
}


static Item_result field_types_result_type [FIELDTYPE_NUM]=
{
  //MYSQL_TYPE_DECIMAL      MYSQL_TYPE_TINY
unknown's avatar
unknown committed
963
  DECIMAL_RESULT,           INT_RESULT,
964 965 966 967 968 969 970 971 972 973 974 975
  //MYSQL_TYPE_SHORT        MYSQL_TYPE_LONG
  INT_RESULT,               INT_RESULT,
  //MYSQL_TYPE_FLOAT        MYSQL_TYPE_DOUBLE
  REAL_RESULT,              REAL_RESULT,
  //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
  STRING_RESULT,            STRING_RESULT,
  //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
  INT_RESULT,               INT_RESULT,
  //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
  STRING_RESULT,            STRING_RESULT,
  //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
  STRING_RESULT,            INT_RESULT,
unknown's avatar
unknown committed
976 977 978
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
  STRING_RESULT,            STRING_RESULT,
  //MYSQL_TYPE_BIT          <16>-<245>
979
  STRING_RESULT,
unknown's avatar
unknown committed
980 981
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
  DECIMAL_RESULT,           STRING_RESULT,
982 983 984 985 986 987 988 989 990 991 992
  //MYSQL_TYPE_SET          MYSQL_TYPE_TINY_BLOB
  STRING_RESULT,            STRING_RESULT,
  //MYSQL_TYPE_MEDIUM_BLOB  MYSQL_TYPE_LONG_BLOB
  STRING_RESULT,            STRING_RESULT,
  //MYSQL_TYPE_BLOB         MYSQL_TYPE_VAR_STRING
  STRING_RESULT,            STRING_RESULT,
  //MYSQL_TYPE_STRING       MYSQL_TYPE_GEOMETRY
  STRING_RESULT,            STRING_RESULT
};


unknown's avatar
unknown committed
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
/*
  Test if the given string contains important data:
  not spaces for character string,
  or any data for binary string.

  SYNOPSIS
    test_if_important_data()
    cs          Character set
    str         String to test
    strend      String end

  RETURN
    FALSE - If string does not have important data
    TRUE  - If string has some important data
*/

static bool
test_if_important_data(CHARSET_INFO *cs, const char *str, const char *strend)
{
  if (cs != &my_charset_bin)
    str+= cs->cset->scan(cs, str, strend, MY_SEQ_SPACES);
  return (str < strend);
}


1018
/**
1019 1020 1021
   Function to compare two unsigned integers for their relative order.
   Used below. In an anonymous namespace to not clash with definitions
   in other files.
1022
 */
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032

CPP_UNNAMED_NS_START

int compare(unsigned int a, unsigned int b)
{
  if (a < b)
    return -1;
  if (b < a)
    return 1;
  return 0;
1033 1034
}

1035 1036
CPP_UNNAMED_NS_END

1037 1038
/**
  Detect Item_result by given field type of UNION merge result.
1039

1040
  @param field_type  given field type
1041

1042
  @return
1043 1044 1045 1046 1047
    Item_result (type of internal MySQL expression result)
*/

Item_result Field::result_merge_type(enum_field_types field_type)
{
1048 1049
  DBUG_ASSERT(real_type_to_type(field_type) < FIELDTYPE_TEAR_FROM ||
              real_type_to_type(field_type) > FIELDTYPE_TEAR_TO);
1050 1051 1052
  return field_types_result_type[field_type2index(field_type)];
}

unknown's avatar
unknown committed
1053
/*****************************************************************************
1054
  Static help functions
unknown's avatar
unknown committed
1055 1056
*****************************************************************************/

1057 1058
/**
  Check whether a field type can be partially indexed by a key.
1059 1060 1061 1062

  This is a static method, rather than a virtual function, because we need
  to check the type of a non-Field in mysql_alter_table().

1063
  @param type  field type
1064

1065
  @retval
1066
    TRUE  Type can have a prefixed key
1067
  @retval
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    FALSE Type can not have a prefixed key
*/

bool Field::type_can_have_key_part(enum enum_field_types type)
{
  switch (type) {
  case MYSQL_TYPE_VARCHAR:
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_MEDIUM_BLOB:
  case MYSQL_TYPE_LONG_BLOB:
  case MYSQL_TYPE_BLOB:
  case MYSQL_TYPE_VAR_STRING:
  case MYSQL_TYPE_STRING:
unknown's avatar
unknown committed
1081
  case MYSQL_TYPE_GEOMETRY:
1082 1083 1084 1085 1086 1087 1088
    return TRUE;
  default:
    return FALSE;
  }
}


1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
void Field::make_sort_key(uchar *buff,uint length)
{
  if (maybe_null())
  {
    if (is_null())
    {
      bzero(buff, length + 1);
      return;
    }
    *buff++= 1;
  }
  sort_string(buff, length);
}


1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
/**
  @brief
  Determine the relative position of the field value in a numeric interval

  @details
  The function returns a double number between 0.0 and 1.0 as the relative
  position of the value of the this field in the numeric interval of [min,max].
  If the value is not in the interval the the function returns 0.0 when
  the value is less than min, and, 1.0 when the value is greater than max.

  @param  min  value of the left end of the interval
  @param  max  value of the right end of the interval

  @return
  relative position of the field value in the numeric interval [min,max] 
*/

double Field::pos_in_interval_val_real(Field *min, Field *max)
{
  double n, d;
  n= val_real() - min->val_real();
  if (n < 0)
    return 0.0;
  d= max->val_real() - min->val_real();
  if (d <= 0)
    return 1.0;
Sergei Golubchik's avatar
Sergei Golubchik committed
1130
  return MY_MIN(n/d, 1.0);
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
}


static
inline ulonglong char_prefix_to_ulonglong(uchar *src)
{
  uint sz= sizeof(ulonglong);
  for (uint i= 0; i < sz/2; i++)
  {
    uchar tmp= src[i];
    src[i]= src[sz-1-i];
    src[sz-1-i]= tmp;
  }
  return uint8korr(src); 
}

1147 1148 1149 1150 1151 1152 1153 1154 1155
/*
  Compute res = a - b, without losing precision and taking care that these are
  unsigned numbers.
*/
static inline double safe_substract(ulonglong a, ulonglong b)
{
  return (a > b)? double(a - b) : -double(b - a);
}

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207

/**
  @brief
  Determine the relative position of the field value in a string interval

  @details
  The function returns a double number between 0.0 and 1.0 as the relative
  position of the value of the this field in the string interval of [min,max].
  If the value is not in the interval the the function returns 0.0 when
  the value is less than min, and, 1.0 when the value is greater than max.

  @note
  To calculate the relative position of the string value v in the interval
  [min, max] the function first converts the beginning of these three
  strings v, min, max into the strings that are used for byte comparison.
  For each string not more sizeof(ulonglong) first bytes are taken
  from the result of conversion. Then these bytes are interpreted as the
  big-endian representation of an ulonglong integer. The values of these
  integer numbers obtained for the strings v, min, max are used to calculate
  the position of v in [min,max] in the same way is it's done for numeric
  fields (see Field::pos_in_interval_val_real).

  @todo
  Improve the procedure for the case when min and max have the same
  beginning
     
  @param  min  value of the left end of the interval
  @param  max  value of the right end of the interval

  @return
  relative position of the field value in the string interval [min,max] 
*/

double Field::pos_in_interval_val_str(Field *min, Field *max, uint data_offset)
{
  uchar mp_prefix[sizeof(ulonglong)];
  uchar minp_prefix[sizeof(ulonglong)];
  uchar maxp_prefix[sizeof(ulonglong)];
  ulonglong mp, minp, maxp;
  my_strnxfrm(charset(), mp_prefix, sizeof(mp),
              ptr + data_offset,
              data_length());
  my_strnxfrm(charset(), minp_prefix, sizeof(minp),
              min->ptr + data_offset,
              min->data_length());
  my_strnxfrm(charset(), maxp_prefix, sizeof(maxp),
              max->ptr + data_offset,
              max->data_length());
  mp= char_prefix_to_ulonglong(mp_prefix);
  minp= char_prefix_to_ulonglong(minp_prefix);
  maxp= char_prefix_to_ulonglong(maxp_prefix);
  double n, d;
1208
  n= safe_substract(mp, minp);
1209 1210
  if (n < 0)
    return 0.0;
1211
  d= safe_substract(maxp, minp);
1212 1213
  if (d <= 0)
    return 1.0;
Sergei Golubchik's avatar
Sergei Golubchik committed
1214
  return MY_MIN(n/d, 1.0);
1215 1216 1217
}


1218 1219 1220 1221 1222 1223 1224 1225 1226
bool Field::test_if_equality_guarantees_uniqueness(const Item *item) const
{
  DBUG_ASSERT(cmp_type() != STRING_RESULT); // For STRING_RESULT see Field_str
  /*
    We use result_type() rather than cmp_type() in the below condition,
    because it covers a special case that string literals guarantee uniqueness
    for temporal columns, so the query:
      WHERE temporal_column='string'
    cannot return multiple distinct temporal values.
Monty's avatar
Monty committed
1227 1228

    TODO: perhaps we could allow INT/DECIMAL/DOUBLE types for temporal items.
1229 1230 1231 1232 1233
  */
  return result_type() == item->result_type();
}


1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
/**
  Check whether a field item can be substituted for an equal item

  @details
  The function checks whether a substitution of a field item for
  an equal item is valid.

  @param arg   *arg != NULL <-> the field is in the context
               where substitution for an equal item is valid

  @note
    The following statement is not always true:
  @n
    x=y => F(x)=F(x/y).
  @n
    This means substitution of an item for an equal item not always
    yields an equavalent condition. Here's an example:
    @code
    'a'='a '
    (LENGTH('a')=1) != (LENGTH('a ')=2)
  @endcode
    Such a substitution is surely valid if either the substituted
    field is not of a STRING type or if it is an argument of
    a comparison predicate.

  @retval
    TRUE   substitution is valid
  @retval
    FALSE  otherwise
*/

bool Field::can_be_substituted_to_equal_item(const Context &ctx,
                                             const Item_equal *item_equal)
{
  DBUG_ASSERT(item_equal->compare_type() != STRING_RESULT);
  DBUG_ASSERT(cmp_type() != STRING_RESULT);
  switch (ctx.subst_constraint()) {
  case ANY_SUBST:
    /*
      Disable const propagation for items used in different comparison contexts.
      This must be done because, for example, Item_hex_string->val_int() is not
      the same as (Item_hex_string->val_str() in BINARY column)->val_int().
      We cannot simply disable the replacement in a particular context (
      e.g. <bin_col> = <int_col> AND <bin_col> = <hex_string>) since
      Items don't know the context they are in and there are functions like
      IF (<hex_string>, 'yes', 'no').
    */
    return ctx.compare_type() == item_equal->compare_type();
  case IDENTITY_SUBST:
    return true;
  }
  return false;
}


1289 1290 1291
/*
  This handles all numeric and BIT data types.
*/ 
1292
bool Field::can_optimize_keypart_ref(const Item_bool_func *cond,
1293 1294 1295 1296 1297 1298 1299 1300
                                     const Item *item) const
{
  DBUG_ASSERT(cmp_type() != STRING_RESULT);
  DBUG_ASSERT(cmp_type() != TIME_RESULT);
  return item->cmp_type() != TIME_RESULT;
}


1301 1302 1303
/*
  This handles all numeric and BIT data types.
*/ 
1304
bool Field::can_optimize_group_min_max(const Item_bool_func *cond,
1305
                                       const Item *const_item) const
1306 1307 1308 1309 1310 1311 1312
{
  DBUG_ASSERT(cmp_type() != STRING_RESULT);
  DBUG_ASSERT(cmp_type() != TIME_RESULT);
  return const_item->cmp_type() != TIME_RESULT;
}


1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
/*
  This covers all numeric types, ENUM, SET, BIT
*/
bool Field::can_optimize_range(const Item_bool_func *cond,
                               const Item *item,
                               bool is_eq_func) const
{
  DBUG_ASSERT(cmp_type() != TIME_RESULT);   // Handled in Field_temporal
  DBUG_ASSERT(cmp_type() != STRING_RESULT); // Handled in Field_longstr
  return item->cmp_type() != TIME_RESULT;
}


1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
int Field::store_hex_hybrid(const char *str, uint length)
{
  DBUG_ASSERT(result_type() != STRING_RESULT);
  ulonglong nr;

  if (length > 8)
  {
    nr= flags & UNSIGNED_FLAG ? ULONGLONG_MAX : LONGLONG_MAX;
    goto warn;
  }
  nr= (ulonglong) longlong_from_hex_hybrid(str, length);
  if ((length == 8) && !(flags & UNSIGNED_FLAG) && (nr > LONGLONG_MAX))
  {
    nr= LONGLONG_MAX;
    goto warn;
  }
  return store((longlong) nr, true);  // Assume hex numbers are unsigned

warn:
  if (!store((longlong) nr, true))
    set_warning(Sql_condition::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
  return 1;
}


1351 1352
/**
  Numeric fields base class constructor.
unknown's avatar
unknown committed
1353
*/
1354
Field_num::Field_num(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
unknown's avatar
unknown committed
1355 1356 1357 1358
                     uchar null_bit_arg, utype unireg_check_arg,
                     const char *field_name_arg,
                     uint8 dec_arg, bool zero_arg, bool unsigned_arg)
  :Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
unknown's avatar
unknown committed
1359
         unireg_check_arg, field_name_arg),
unknown's avatar
unknown committed
1360 1361 1362 1363 1364 1365 1366 1367 1368
  dec(dec_arg),zerofill(zero_arg),unsigned_flag(unsigned_arg)
{
  if (zerofill)
    flags|=ZEROFILL_FLAG;
  if (unsigned_flag)
    flags|=UNSIGNED_FLAG;
}


1369
void Field_num::prepend_zeros(String *value) const
unknown's avatar
unknown committed
1370 1371 1372 1373
{
  int diff;
  if ((diff= (int) (field_length - value->length())) > 0)
  {
1374 1375
    bmove_upp((uchar*) value->ptr()+field_length,
              (uchar*) value->ptr()+value->length(),
unknown's avatar
unknown committed
1376
	      value->length());
1377
    bfill((uchar*) value->ptr(),diff,'0');
unknown's avatar
unknown committed
1378 1379 1380 1381 1382
    value->length(field_length);
    (void) value->c_ptr_quick();		// Avoid warnings in purify
  }
}

1383

1384 1385
Item *Field_num::get_equal_zerofill_const_item(THD *thd, const Context &ctx,
                                               Item *const_item)
1386
{
1387 1388
  switch (ctx.subst_constraint()) {
  case IDENTITY_SUBST:
1389
    return NULL; // Not safe to propagate if not in comparison. See MDEV-8369.
1390 1391
  case ANY_SUBST:
    break;
1392
  }
1393 1394
  DBUG_ASSERT(const_item->const_item());
  DBUG_ASSERT(ctx.compare_type() != STRING_RESULT);
1395
  return const_item;
1396 1397 1398
}


1399
/**
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
  Contruct warning parameters using thd->no_errors
  to determine whether to generate or suppress warnings.
  We can get here in a query like this:
    SELECT COUNT(@@basedir);
  from Item_func_get_system_var::update_null_value().
*/
Value_source::Warn_filter::Warn_filter(const THD *thd)
 :m_want_warning_edom(!thd->no_errors),
  m_want_note_truncated_spaces(!thd->no_errors)
{ }
1410 1411


1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
/**
  Check string-to-number conversion and produce a warning if
  - could not convert any digits (EDOM-alike error)
  - found garbage at the end of the string
  - found trailing spaces (a note)
  See also Field_num::check_edom_and_truncation() for a similar function.

  @param thd        - the thread
  @param filter     - which warnings/notes are allowed
  @param type       - name of the data type (e.g. "INTEGER", "DECIMAL", "DOUBLE")
  @param cs         - character set of the original string
  @param str        - the original string
  @param end        - the end of the string

  Unlike Field_num::check_edom_and_truncation(), this function does not
  distinguish between EDOM and truncation and reports the same warning for
  both cases. Perhaps we should eventually print different warnings, to make
  the explicit CAST work closer to the implicit cast in Field_xxx::store().
*/
void
Value_source::Converter_string_to_number::check_edom_and_truncation(THD *thd,
                                                       Warn_filter filter,
                                                       const char *type,
                                                       CHARSET_INFO *cs,
                                                       const char *str,
                                                       size_t length) const
{
  DBUG_ASSERT(str <= m_end_of_num);
  DBUG_ASSERT(m_end_of_num <= str + length);
  if (m_edom || (m_end_of_num < str + length &&
                 !check_if_only_end_space(cs, m_end_of_num, str + length)))
  {
    // EDOM or important trailing data truncation
    if (filter.want_warning_edom())
    {
      /*
        We can use err.ptr() here as ErrConvString is guranteed to put an
        end \0 here.
      */
      THD *wthd= thd ? thd : current_thd;
      push_warning_printf(wthd, Sql_condition::WARN_LEVEL_WARN,
                          ER_TRUNCATED_WRONG_VALUE,
                          ER_THD(wthd, ER_TRUNCATED_WRONG_VALUE), type,
                          ErrConvString(str, length, cs).ptr());
    }
  }
  else if (m_end_of_num < str + length)
  {
    // Unimportant trailing data (spaces) truncation
    if (filter.want_note_truncated_spaces())
    {
      THD *wthd= thd ? thd : current_thd;
      push_warning_printf(wthd, Sql_condition::WARN_LEVEL_NOTE,
                          ER_TRUNCATED_WRONG_VALUE,
                          ER_THD(wthd, ER_TRUNCATED_WRONG_VALUE), type,
                          ErrConvString(str, length, cs).ptr());
    }
  }
}


/**
  Check a string-to-number conversion routine result and generate warnings
  in case when it:
  - could not convert any digits
  - found garbage at the end of the string.

  @param type          Data type name (e.g. "decimal", "integer", "double")
  @param edom          Indicates that the string-to-number routine retuned
                       an error code equivalent to EDOM (value out of domain),
                       i.e. the string fully consisted of garbage and the
                       conversion routine could not get any digits from it.
  @param str           The original string
1485
  @param length        Length of 'str'
1486 1487
  @param cs            Character set
  @param end           Pointer to char after last used digit
1488 1489

  @note
1490 1491 1492 1493
    This is called after one has called one of the following functions:
    - strntoull10rnd()
    - my_strntod()
    - str2my_decimal()
1494

1495
  @retval
1496
    0        OK
1497
  @retval
1498 1499
    1        error: could not scan any digits (EDOM),
             e.g. empty string, or garbage.
1500
  @retval
1501 1502
    2        error: scanned some digits,
             but then found garbage at the end of the string.
unknown's avatar
unknown committed
1503 1504
*/

1505

1506 1507 1508 1509 1510 1511
int Field_num::check_edom_and_important_data_truncation(const char *type,
                                                        bool edom,
                                                        CHARSET_INFO *cs,
                                                        const char *str,
                                                        uint length,
                                                        const char *end)
unknown's avatar
unknown committed
1512
{
1513 1514
  /* Test if we get an empty string or garbage */
  if (edom)
unknown's avatar
unknown committed
1515
  {
1516
    ErrConvString err(str, length, cs);
1517
    set_warning_truncated_wrong_value(type, err.ptr());
unknown's avatar
unknown committed
1518
    return 1;
unknown's avatar
unknown committed
1519
  }
unknown's avatar
unknown committed
1520
  /* Test if we have garbage at the end of the given string. */
1521
  if (test_if_important_data(cs, end, str + length))
unknown's avatar
unknown committed
1522
  {
1523
    set_warning(WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
1524 1525 1526 1527
    return 2;
  }
  return 0;
}
unknown's avatar
unknown committed
1528

unknown's avatar
unknown committed
1529

1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
int Field_num::check_edom_and_truncation(const char *type, bool edom,
                                         CHARSET_INFO *cs,
                                         const char *str, uint length,
                                         const char *end)
{
  int rc= check_edom_and_important_data_truncation(type, edom,
                                                   cs, str, length, end);
  if (!rc && end < str + length)
    set_note(WARN_DATA_TRUNCATED, 1);
  return rc;
}


unknown's avatar
unknown committed
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
/*
  Conver a string to an integer then check bounds.
  
  SYNOPSIS
    Field_num::get_int
    cs            Character set
    from          String to convert
    len           Length of the string
    rnd           OUT longlong value
    unsigned_max  max unsigned value
    signed_min    min signed value
    signed_max    max signed value

  DESCRIPTION
    The function calls strntoull10rnd() to get an integer value then
    check bounds and errors returned. In case of any error a warning
    is raised.

  RETURN
    0   ok
    1   error
*/

bool Field_num::get_int(CHARSET_INFO *cs, const char *from, uint len,
                        longlong *rnd, ulonglong unsigned_max, 
                        longlong signed_min, longlong signed_max)
{
  char *end;
  int error;
  
1573 1574
  *rnd= (longlong) cs->cset->strntoull10rnd(cs, from, len,
                                            unsigned_flag, &end,
unknown's avatar
unknown committed
1575 1576
                                            &error);
  if (unsigned_flag)
unknown's avatar
unknown committed
1577
  {
unknown's avatar
unknown committed
1578

1579 1580
    if ((((ulonglong) *rnd > unsigned_max) &&
         (*rnd= (longlong) unsigned_max)) ||
unknown's avatar
unknown committed
1581 1582 1583 1584
        error == MY_ERRNO_ERANGE)
    {
      goto out_of_range;
    }
1585
  }
unknown's avatar
unknown committed
1586
  else
1587
  {
unknown's avatar
unknown committed
1588
    if (*rnd < signed_min)
unknown's avatar
unknown committed
1589
    {
unknown's avatar
unknown committed
1590 1591 1592 1593 1594 1595 1596
      *rnd= signed_min;
      goto out_of_range;
    }
    else if (*rnd > signed_max)
    {
      *rnd= signed_max;
      goto out_of_range;
unknown's avatar
unknown committed
1597
    }
unknown's avatar
unknown committed
1598
  }
1599
  if (get_thd()->count_cuted_fields &&
1600
      check_int(cs, from, len, end, error))
unknown's avatar
unknown committed
1601
    return 1;
unknown's avatar
unknown committed
1602
  return 0;
unknown's avatar
unknown committed
1603

unknown's avatar
unknown committed
1604
out_of_range:
1605
  set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
1606 1607
  return 1;
}
unknown's avatar
unknown committed
1608

Igor Babaev's avatar
Igor Babaev committed
1609

1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
double Field_real::get_double(const char *str, uint length, CHARSET_INFO *cs,
                              int *error)
{
  char *end;
  double nr= my_strntod(cs,(char*) str, length, &end, error);
  if (*error)
  {
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    *error= 1;
  }
  else if (get_thd()->count_cuted_fields &&
           check_edom_and_truncation("double", str == end,
                                     cs, str, length, end))
    *error= 1;
  return nr;
}


1628
/**
unknown's avatar
unknown committed
1629 1630 1631
  Process decimal library return codes and issue warnings for overflow and
  truncation.

1632
  @param op_result  decimal library return code (E_DEC_* see include/decimal.h)
unknown's avatar
unknown committed
1633

1634
  @retval
unknown's avatar
unknown committed
1635
    1  there was overflow
1636
  @retval
unknown's avatar
unknown committed
1637 1638 1639
    0  no error or some other errors except overflow
*/

unknown's avatar
unknown committed
1640
int Field::warn_if_overflow(int op_result)
unknown's avatar
unknown committed
1641 1642 1643
{
  if (op_result == E_DEC_OVERFLOW)
  {
1644
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
1645 1646
    return 1;
  }
unknown's avatar
unknown committed
1647 1648
  if (op_result == E_DEC_TRUNCATED)
  {
1649
    set_note(WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
1650 1651
    /* We return 0 here as this is not a critical issue */
  }
unknown's avatar
unknown committed
1652 1653 1654
  return 0;
}

unknown's avatar
unknown committed
1655

1656
/**
unknown's avatar
unknown committed
1657 1658
  Interpret field value as an integer but return the result as a string.

1659
  This is used for printing bit_fields as numbers while debugging.
unknown's avatar
unknown committed
1660 1661
*/

1662
String *Field::val_int_as_str(String *val_buffer, bool unsigned_val)
unknown's avatar
unknown committed
1663
{
1664
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
1665
  CHARSET_INFO *cs= &my_charset_bin;
1666
  uint length;
unknown's avatar
unknown committed
1667
  longlong value= val_int();
1668

1669
  if (val_buffer->alloc(MY_INT64_NUM_DECIMAL_DIGITS))
unknown's avatar
unknown committed
1670
    return 0;
unknown's avatar
unknown committed
1671
  length= (uint) (*cs->cset->longlong10_to_str)(cs, (char*) val_buffer->ptr(),
1672
                                                MY_INT64_NUM_DECIMAL_DIGITS,
1673
                                                unsigned_val ? 10 : -10,
unknown's avatar
unknown committed
1674
                                                value);
unknown's avatar
unknown committed
1675 1676 1677 1678 1679
  val_buffer->length(length);
  return val_buffer;
}


1680
/// This is used as a table name when the table structure is not set up
1681
Field::Field(uchar *ptr_arg,uint32 length_arg,uchar *null_ptr_arg,
unknown's avatar
unknown committed
1682
	     uchar null_bit_arg,
unknown's avatar
unknown committed
1683
	     utype unireg_check_arg, const char *field_name_arg)
1684 1685 1686 1687 1688
  :ptr(ptr_arg), null_ptr(null_ptr_arg), table(0), orig_table(0),
  table_name(0), field_name(field_name_arg), option_list(0),
  option_struct(0), key_start(0), part_of_key(0),
  part_of_key_not_clustered(0), part_of_sortkey(0),
  unireg_check(unireg_check_arg), field_length(length_arg),
1689
  null_bit(null_bit_arg), is_created_from_null_item(FALSE),
1690 1691
  read_stats(NULL), collected_stats(0), vcol_info(0), check_constraint(0),
  default_value(0)
unknown's avatar
unknown committed
1692 1693
{
  flags=null_ptr ? 0: NOT_NULL_FLAG;
unknown's avatar
unknown committed
1694 1695
  comment.str= (char*) "";
  comment.length=0;
1696 1697
  field_index= 0;   
  is_stat_field= FALSE;
Igor Babaev's avatar
Igor Babaev committed
1698 1699
  cond_selectivity= 1.0;
  next_equal_field= NULL;
unknown's avatar
unknown committed
1700 1701
}

1702

1703 1704 1705 1706 1707 1708 1709 1710 1711
void Field::hash(ulong *nr, ulong *nr2)
{
  if (is_null())
  {
    *nr^= (*nr << 1) | 1;
  }
  else
  {
    uint len= pack_length();
1712
    CHARSET_INFO *cs= sort_charset();
1713
    cs->coll->hash_sort(cs, ptr, len, nr, nr2);
1714 1715 1716
  }
}

1717
size_t
1718 1719
Field::do_last_null_byte() const
{
1720
  DBUG_ASSERT(null_ptr == NULL || null_ptr >= table->record[0]);
1721
  if (null_ptr)
1722 1723
    return (size_t) (null_ptr - table->record[0]) + 1;
  return LAST_NULL_BYTE_UNDEF;
1724 1725 1726
}


unknown's avatar
unknown committed
1727 1728 1729 1730 1731
void Field::copy_from_tmp(int row_offset)
{
  memcpy(ptr,ptr+row_offset,pack_length());
  if (null_ptr)
  {
unknown's avatar
unknown committed
1732
    *null_ptr= (uchar) ((null_ptr[0] & (uchar) ~(uint) null_bit) |
1733
			(null_ptr[row_offset] & (uchar) null_bit));
unknown's avatar
unknown committed
1734 1735 1736 1737
  }
}


1738
bool Field::send_binary(Protocol *protocol)
unknown's avatar
unknown committed
1739 1740
{
  char buff[MAX_FIELD_WIDTH];
1741
  String tmp(buff,sizeof(buff),charset());
1742
  val_str(&tmp);
1743
  return protocol->store(tmp.ptr(), tmp.length(), tmp.charset());
unknown's avatar
unknown committed
1744 1745 1746
}


1747 1748 1749
/**
   Check to see if field size is compatible with destination.

1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
   This method is used in row-based replication to verify that the
   slave's field size is less than or equal to the master's field
   size. The encoded field metadata (from the master or source) is
   decoded and compared to the size of this field (the slave or
   destination).

   @note

   The comparison is made so that if the source data (from the master)
   is less than the target data (on the slave), -1 is returned in @c
   <code>*order_var</code>. This implies that a conversion is
   necessary, but that it is lossy and can result in truncation of the
   value.

   If the source data is strictly greater than the target data, 1 is
   returned in <code>*order_var</code>. This implies that the source
   type can is contained in the target type and that a conversion is
   necessary but is non-lossy.

   If no conversion is required to fit the source type in the target
   type, 0 is returned in <code>*order_var</code>.
1771 1772

   @param   field_metadata   Encoded size in field metadata
1773
   @param   mflags           Flags from the table map event for the table.
1774 1775 1776
   @param   order_var        Pointer to variable where the order
                             between the source field and this field
                             will be returned.
1777

1778 1779
   @return @c true if this field's size is compatible with the
   master's field size, @c false otherwise.
1780
*/
1781 1782
bool Field::compatible_field_size(uint field_metadata,
                                  Relay_log_info *rli_arg __attribute__((unused)),
1783
                                  uint16 mflags __attribute__((unused)),
1784
                                  int *order_var)
1785 1786 1787
{
  uint const source_size= pack_length_from_metadata(field_metadata);
  uint const destination_size= row_pack_length();
1788 1789 1790 1791
  DBUG_PRINT("debug", ("real_type: %d, source_size: %u, destination_size: %u",
                       real_type(), source_size, destination_size));
  *order_var = compare(source_size, destination_size);
  return true;
1792 1793 1794
}


1795 1796 1797 1798
int Field::store(const char *to, uint length, CHARSET_INFO *cs,
                 enum_check_fields check_level)
{
  int res;
1799 1800 1801
  THD *thd= get_thd();
  enum_check_fields old_check_level= thd->count_cuted_fields;
  thd->count_cuted_fields= check_level;
1802
  res= store(to, length, cs);
1803
  thd->count_cuted_fields= old_check_level;
1804 1805 1806 1807
  return res;
}


1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
/**
   Pack the field into a format suitable for storage and transfer.

   To implement packing functionality, only the virtual function
   should be overridden. The other functions are just convenience
   functions and hence should not be overridden.

   @note The default method for packing fields just copy the raw bytes
   of the record into the destination, but never more than
   <code>max_length</code> characters.

   @param to
   Pointer to memory area where representation of field should be put.

   @param from
   Pointer to memory area where record representation of field is
   stored.

   @param max_length
   Maximum length of the field, as given in the column definition. For
   example, for <code>CHAR(1000)</code>, the <code>max_length</code>
   is 1000. This information is sometimes needed to decide how to pack
   the data.

*/
uchar *
Sergei Golubchik's avatar
Sergei Golubchik committed
1834
Field::pack(uchar *to, const uchar *from, uint max_length)
1835 1836 1837 1838 1839 1840 1841
{
  uint32 length= pack_length();
  set_if_smaller(length, max_length);
  memcpy(to, from, length);
  return to+length;
}

1842 1843 1844
/**
   Unpack a field from row data.

1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
   This method is used to unpack a field from a master whose size of
   the field is less than that of the slave.

   The <code>param_data</code> parameter is a two-byte integer (stored
   in the least significant 16 bits of the unsigned integer) usually
   consisting of two parts: the real type in the most significant byte
   and a original pack length in the least significant byte.

   The exact layout of the <code>param_data</code> field is given by
   the <code>Table_map_log_event::save_field_metadata()</code>.

   This is the default method for unpacking a field. It just copies
   the memory block in byte order (of original pack length bytes or
   length of field, whichever is smaller).

1860 1861
   @param   to         Destination of the data
   @param   from       Source of the data
1862 1863 1864
   @param   param_data Real type and original pack length of the field
                       data

1865
   @return  New pointer into memory based on from + length of the data
1866
   @return  0 if wrong data
1867
*/
1868
const uchar *
1869 1870
Field::unpack(uchar* to, const uchar *from, const uchar *from_end,
              uint param_data)
1871
{
1872
  uint length=pack_length(), len;
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
  int from_type= 0;
  /*
    If from length is > 255, it has encoded data in the upper bits. Need
    to mask it out.
  */
  if (param_data > 255)
  {
    from_type= (param_data & 0xff00) >> 8U;  // real_type.
    param_data= param_data & 0x00ff;        // length.
  }
1883 1884 1885 1886 1887

  if ((param_data == 0) ||
      (length == param_data) ||
      (from_type != real_type()))
  {
1888 1889 1890
    if (from + length > from_end)
      return 0;                                 // Error in data

1891 1892 1893 1894
    memcpy(to, from, length);
    return from+length;
  }

1895
  len= (param_data && (param_data < length)) ? param_data : length;
1896

1897 1898
  if (from + len > from_end)
    return 0;                                   // Error in data
1899

1900
  memcpy(to, from, len);
1901 1902 1903 1904
  return from+len;
}


unknown's avatar
unknown committed
1905 1906 1907 1908 1909 1910 1911 1912
my_decimal *Field::val_decimal(my_decimal *decimal)
{
  /* This never have to be called */
  DBUG_ASSERT(0);
  return 0;
}


unknown's avatar
unknown committed
1913 1914
void Field_num::add_zerofill_and_unsigned(String &res) const
{
1915
  if (unsigned_flag)
1916
    res.append(STRING_WITH_LEN(" unsigned"));
1917
  if (zerofill)
1918
    res.append(STRING_WITH_LEN(" zerofill"));
unknown's avatar
unknown committed
1919 1920
}

unknown's avatar
unknown committed
1921

1922
void Field::make_field(Send_field *field)
unknown's avatar
unknown committed
1923
{
unknown's avatar
unknown committed
1924
  if (orig_table && orig_table->s->db.str && *orig_table->s->db.str)
unknown's avatar
unknown committed
1925
  {
unknown's avatar
unknown committed
1926
    field->db_name= orig_table->s->db.str;
1927 1928 1929 1930 1931 1932
    if (orig_table->pos_in_table_list && 
        orig_table->pos_in_table_list->schema_table)
      field->org_table_name= (orig_table->pos_in_table_list->
                              schema_table->table_name);
    else
      field->org_table_name= orig_table->s->table_name.str;
1933 1934
  }
  else
unknown's avatar
unknown committed
1935
    field->org_table_name= field->db_name= "";
1936
  if (orig_table && orig_table->alias.ptr())
1937
  {
1938
    field->table_name= orig_table->alias.ptr();
1939 1940 1941 1942 1943 1944 1945 1946
    field->org_col_name= field_name;
  }
  else
  {
    field->table_name= "";
    field->org_col_name= "";
  }
  field->col_name= field_name;
1947
  field->charsetnr= charset()->number;
unknown's avatar
unknown committed
1948 1949 1950
  field->length=field_length;
  field->type=type();
  field->flags=table->maybe_null ? (flags & ~NOT_NULL_FLAG) : flags;
1951
  field->decimals= 0;
unknown's avatar
unknown committed
1952 1953 1954
}


1955
/**
unknown's avatar
unknown committed
1956
  Conversion from decimal to longlong with checking overflow and
1957
  setting correct value (min/max) in case of overflow.
unknown's avatar
unknown committed
1958

1959 1960 1961
  @param val             value which have to be converted
  @param unsigned_flag   type of integer in which we convert val
  @param err             variable to pass error code
unknown's avatar
unknown committed
1962

1963
  @return
unknown's avatar
unknown committed
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
    value converted from val
*/
longlong Field::convert_decimal2longlong(const my_decimal *val,
                                         bool unsigned_flag, int *err)
{
  longlong i;
  if (unsigned_flag)
  {
    if (val->sign())
    {
1974
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
1975 1976 1977
      i= 0;
      *err= 1;
    }
1978 1979 1980 1981
    else if (warn_if_overflow(my_decimal2int((E_DEC_ERROR &
                                              ~E_DEC_OVERFLOW &
                                              ~E_DEC_TRUNCATED),
                                             val, TRUE, &i)))
unknown's avatar
unknown committed
1982 1983 1984 1985 1986
    {
      i= ~(longlong) 0;
      *err= 1;
    }
  }
1987 1988 1989 1990
  else if (warn_if_overflow(my_decimal2int((E_DEC_ERROR &
                                            ~E_DEC_OVERFLOW &
                                            ~E_DEC_TRUNCATED),
                                           val, FALSE, &i)))
unknown's avatar
unknown committed
1991 1992 1993 1994 1995 1996 1997 1998
  {
    i= (val->sign() ? LONGLONG_MIN : LONGLONG_MAX);
    *err= 1;
  }
  return i;
}


1999
/**
unknown's avatar
unknown committed
2000 2001
  Storing decimal in integer fields.

2002
  @param val       value for storing
unknown's avatar
unknown committed
2003

2004
  @note
unknown's avatar
unknown committed
2005 2006
    This method is used by all integer fields, real/decimal redefine it

2007
  @retval
unknown's avatar
unknown committed
2008
    0     OK
2009 2010
  @retval
    !=0  error
unknown's avatar
unknown committed
2011 2012 2013 2014
*/

int Field_num::store_decimal(const my_decimal *val)
{
2015
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
2016 2017
  int err= 0;
  longlong i= convert_decimal2longlong(val, unsigned_flag, &err);
2018
  return MY_TEST(err | store(i, unsigned_flag));
unknown's avatar
unknown committed
2019 2020 2021
}


2022 2023
/**
  Return decimal value of integer field.
unknown's avatar
unknown committed
2024

2025
  @param decimal_value     buffer for storing decimal value
unknown's avatar
unknown committed
2026

2027 2028
  @note
    This method is used by all integer fields, real/decimal redefine it.
unknown's avatar
unknown committed
2029 2030 2031
    All longlong values fit in our decimal buffer which cal store 8*9=72
    digits of integer number

2032
  @return
unknown's avatar
unknown committed
2033 2034 2035 2036 2037
    pointer to decimal buffer with value of field
*/

my_decimal* Field_num::val_decimal(my_decimal *decimal_value)
{
2038
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
2039 2040
  DBUG_ASSERT(result_type() == INT_RESULT);
  longlong nr= val_int();
2041
  int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
unknown's avatar
unknown committed
2042 2043 2044 2045
  return decimal_value;
}


2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
bool Field_num::get_date(MYSQL_TIME *ltime,ulonglong fuzzydate)
{
  ASSERT_COLUMN_MARKED_FOR_READ;
  longlong nr= val_int();
  bool neg= !(flags & UNSIGNED_FLAG) && nr < 0;
  return int_to_datetime_with_warn(neg, neg ? -nr : nr, ltime, fuzzydate,
                                   field_name);
}


2056
Field_str::Field_str(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
unknown's avatar
unknown committed
2057
                     uchar null_bit_arg, utype unireg_check_arg,
unknown's avatar
unknown committed
2058
                     const char *field_name_arg, CHARSET_INFO *charset_arg)
unknown's avatar
unknown committed
2059
  :Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
unknown's avatar
unknown committed
2060
         unireg_check_arg, field_name_arg)
unknown's avatar
unknown committed
2061
{
2062 2063
  field_charset= charset_arg;
  if (charset_arg->state & MY_CS_BINSORT)
unknown's avatar
unknown committed
2064
    flags|=BINARY_FLAG;
2065
  field_derivation= DERIVATION_IMPLICIT;
2066
  field_repertoire= my_charset_repertoire(charset_arg);
unknown's avatar
unknown committed
2067 2068 2069
}


2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
bool Field_str::test_if_equality_guarantees_uniqueness(const Item *item) const
{
  /*
    Can't guarantee uniqueness when comparing a CHAR/VARCHAR/TEXT,
    BINARY/VARBINARY/BLOB, ENUM,SET columns to an item with cmp_type()
    of INT_RESULT, DOUBLE_RESULT, DECIMAL_RESULT or TIME_RESULT.
    Example:
      SELECT * FROM t1 WHERE varchar_column=DATE'2001-01-01'
    return non-unuque values, e.g. '2001-01-01' and '2001-01-01x'.
  */
  if (!field_charset->coll->propagate(field_charset, 0, 0) ||
      item->cmp_type() != STRING_RESULT)
    return false;
  /*
    Can't guarantee uniqueness when comparing to
    an item of a different collation.
    Example:
      SELECT * FROM t1
      WHERE latin1_bin_column = _latin1'A' COLLATE latin1_swedish_ci
    return non-unique values 'a' and 'A'.
  */
  DTCollation tmp(field_charset, field_derivation, repertoire());
  return !tmp.aggregate(item->collation) && tmp.collation == field_charset;
}


2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
bool Field_str::can_be_substituted_to_equal_item(const Context &ctx,
                                                  const Item_equal *item_equal)
{
  DBUG_ASSERT(item_equal->compare_type() == STRING_RESULT);
  switch (ctx.subst_constraint()) {
  case ANY_SUBST:
    return ctx.compare_type() == item_equal->compare_type() &&
          (ctx.compare_type() != STRING_RESULT ||
           ctx.compare_collation() == item_equal->compare_collation());
  case IDENTITY_SUBST:
    return ((charset()->state & MY_CS_BINSORT) &&
            (charset()->state & MY_CS_NOPAD));
  }
  return false;
}


2113
void Field_num::make_field(Send_field *field)
unknown's avatar
unknown committed
2114
{
2115 2116
  Field::make_field(field);
  field->decimals= dec;
unknown's avatar
unknown committed
2117 2118
}

2119 2120
/**
  Decimal representation of Field_str.
unknown's avatar
unknown committed
2121

2122
  @param d         value for storing
unknown's avatar
unknown committed
2123

2124 2125 2126 2127 2128
  @note
    Field_str is the base class for fields like Field_enum,
    Field_date and some similar. Some dates use fraction and also
    string value should be converted to floating point value according
    our rules, so we use double to store value of decimal in string.
unknown's avatar
unknown committed
2129

2130 2131 2132 2133
  @todo
    use decimal2string?

  @retval
unknown's avatar
unknown committed
2134
    0     OK
2135 2136
  @retval
    !=0  error
unknown's avatar
unknown committed
2137 2138 2139 2140
*/

int Field_str::store_decimal(const my_decimal *d)
{
2141
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
2142 2143
  double val;
  /* TODO: use decimal2string? */
unknown's avatar
unknown committed
2144
  int err= warn_if_overflow(my_decimal2double(E_DEC_FATAL_ERROR &
unknown's avatar
unknown committed
2145 2146 2147 2148 2149 2150 2151
                                            ~E_DEC_OVERFLOW, d, &val));
  return err | store(val);
}


my_decimal *Field_str::val_decimal(my_decimal *decimal_value)
{
2152
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
2153
  longlong nr= val_int();
2154
  int2my_decimal(E_DEC_FATAL_ERROR, nr, 0, decimal_value);
unknown's avatar
unknown committed
2155 2156 2157
  return decimal_value;
}

2158

unknown's avatar
unknown committed
2159 2160
uint Field::fill_cache_field(CACHE_FIELD *copy)
{
unknown's avatar
unknown committed
2161
  uint store_length;
2162 2163
  copy->str= ptr;
  copy->length= pack_length();
2164
  copy->field= this;
unknown's avatar
unknown committed
2165 2166
  if (flags & BLOB_FLAG)
  {
2167
    copy->type= CACHE_BLOB;
2168
    copy->length-= portable_sizeof_char_ptr;
unknown's avatar
unknown committed
2169 2170
    return copy->length;
  }
2171 2172 2173
  else if (!zero_pack() &&
           (type() == MYSQL_TYPE_STRING && copy->length >= 4 &&
            copy->length < 256))
unknown's avatar
unknown committed
2174
  {
2175
    copy->type= CACHE_STRIPPED;			    /* Remove end space */
unknown's avatar
unknown committed
2176 2177
    store_length= 2;
  }
2178 2179 2180 2181 2182 2183
  else if (type() ==  MYSQL_TYPE_VARCHAR)
  {
    copy->type= pack_length()-row_pack_length() == 1 ? CACHE_VARSTR1:
                                                      CACHE_VARSTR2;
    store_length= 0;
  }
unknown's avatar
unknown committed
2184
  else
unknown's avatar
unknown committed
2185
  {
2186
    copy->type= 0;
unknown's avatar
unknown committed
2187 2188
    store_length= 0;
  }
2189
  return copy->length + store_length;
unknown's avatar
unknown committed
2190 2191
}

2192

2193
bool Field::get_date(MYSQL_TIME *ltime,ulonglong fuzzydate)
unknown's avatar
unknown committed
2194 2195
{
  char buff[40];
2196 2197
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
  if (!(res=val_str(&tmp)) ||
2198
      str_to_datetime_with_warn(res->charset(), res->ptr(), res->length(),
2199
                                ltime, fuzzydate))
unknown's avatar
unknown committed
2200 2201 2202 2203
    return 1;
  return 0;
}

2204 2205
/**
  This is called when storing a date in a string.
2206

2207 2208
  @note
    Needs to be changed if/when we want to support different time formats.
2209
*/
unknown's avatar
unknown committed
2210

2211
int Field::store_time_dec(MYSQL_TIME *ltime, uint dec)
unknown's avatar
unknown committed
2212
{
2213
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
2214
  char buff[MAX_DATE_STRING_REP_LENGTH];
2215
  uint length= (uint) my_TIME_to_str(ltime, buff, dec);
2216 2217 2218
  /* Avoid conversion when field character set is ASCII compatible */
  return store(buff, length, (charset()->state & MY_CS_NONASCII) ?
                              &my_charset_latin1 : charset());
unknown's avatar
unknown committed
2219 2220 2221
}


2222
bool Field::optimize_range(uint idx, uint part)
unknown's avatar
unknown committed
2223
{
2224
  return MY_TEST(table->file->index_flags(idx, part, 1) & HA_READ_RANGE);
unknown's avatar
unknown committed
2225 2226
}

2227

2228 2229
Field *Field::make_new_field(MEM_ROOT *root, TABLE *new_table,
                             bool keep_type __attribute__((unused)))
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
{
  Field *tmp;
  if (!(tmp= (Field*) memdup_root(root,(char*) this,size_of())))
    return 0;

  if (tmp->table->maybe_null)
    tmp->flags&= ~NOT_NULL_FLAG;
  tmp->table= new_table;
  tmp->key_start.init(0);
  tmp->part_of_key.init(0);
  tmp->part_of_sortkey.init(0);
2241 2242 2243 2244
  /*
    TODO: it is not clear why this method needs to reset unireg_check.
    Try not to reset it, or explain why it needs to be reset.
  */
unknown's avatar
unknown committed
2245
  tmp->unireg_check= Field::NONE;
2246 2247 2248 2249 2250 2251
  tmp->flags&= (NOT_NULL_FLAG | BLOB_FLAG | UNSIGNED_FLAG |
                ZEROFILL_FLAG | BINARY_FLAG | ENUM_FLAG | SET_FLAG);
  tmp->reset_fields();
  return tmp;
}

unknown's avatar
unknown committed
2252

Konstantin Osipov's avatar
Konstantin Osipov committed
2253
Field *Field::new_key_field(MEM_ROOT *root, TABLE *new_table,
2254 2255
                            uchar *new_ptr, uint32 length,
                            uchar *new_null_ptr, uint new_null_bit)
unknown's avatar
unknown committed
2256 2257
{
  Field *tmp;
2258
  if ((tmp= make_new_field(root, new_table, table == new_table)))
unknown's avatar
unknown committed
2259 2260 2261 2262 2263 2264 2265 2266
  {
    tmp->ptr=      new_ptr;
    tmp->null_ptr= new_null_ptr;
    tmp->null_bit= new_null_bit;
  }
  return tmp;
}

2267

unknown's avatar
unknown committed
2268 2269
/* This is used to generate a field in TABLE from TABLE_SHARE */

Konstantin Osipov's avatar
Konstantin Osipov committed
2270
Field *Field::clone(MEM_ROOT *root, TABLE *new_table)
unknown's avatar
unknown committed
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282
{
  Field *tmp;
  if ((tmp= (Field*) memdup_root(root,(char*) this,size_of())))
  {
    tmp->init(new_table);
    tmp->move_field_offset((my_ptrdiff_t) (new_table->record[0] -
                                           new_table->s->default_values));
  }
  return tmp;
}


2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297

Field *Field::clone(MEM_ROOT *root, TABLE *new_table, my_ptrdiff_t diff,
                    bool stat_flag)
{
  Field *tmp;
  if ((tmp= (Field*) memdup_root(root,(char*) this,size_of())))
  {
    tmp->init(new_table);
    tmp->move_field_offset(diff);
  }
  tmp->is_stat_field= stat_flag;
  return tmp;
}


2298
Field *Field::clone(MEM_ROOT *root, my_ptrdiff_t diff)
2299 2300 2301 2302 2303 2304 2305 2306 2307
{
  Field *tmp;
  if ((tmp= (Field*) memdup_root(root,(char*) this,size_of())))
  {
    tmp->move_field_offset(diff);
  }
  return tmp;
}

Sergei Golubchik's avatar
Sergei Golubchik committed
2308
void Field::set_default()
2309
{
Sergei Golubchik's avatar
Sergei Golubchik committed
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
  if (default_value)
  {
    table->in_use->reset_arena_for_cached_items(table->expr_arena);
    (void) default_value->expr_item->save_in_field(this, 0);
    table->in_use->reset_arena_for_cached_items(0);
    return;
  }
  /* Copy constant value stored in s->default_values */
  my_ptrdiff_t l_offset= (my_ptrdiff_t) (table->s->default_values -
                                        table->record[0]);
  memcpy(ptr, ptr + l_offset, pack_length());
  if (maybe_null_in_table())
    *null_ptr= ((*null_ptr & (uchar) ~null_bit) |
                (null_ptr[l_offset] & null_bit));
2324 2325
}

2326

2327
/****************************************************************************
2328
  Field_null, a field that always return NULL
2329 2330 2331 2332
****************************************************************************/

void Field_null::sql_type(String &res) const
{
2333
  res.set_ascii(STRING_WITH_LEN("null"));
2334 2335 2336
}


unknown's avatar
unknown committed
2337
/****************************************************************************
unknown's avatar
unknown committed
2338 2339
  Functions for the Field_decimal class
  This is an number stored as a pre-space (or pre-zero) string
unknown's avatar
unknown committed
2340 2341
****************************************************************************/

2342
int
unknown's avatar
unknown committed
2343 2344
Field_decimal::reset(void)
{
2345
  Field_decimal::store(STRING_WITH_LEN("0"),&my_charset_bin);
2346
  return 0;
unknown's avatar
unknown committed
2347 2348 2349 2350 2351
}

void Field_decimal::overflow(bool negative)
{
  uint len=field_length;
2352
  uchar *to=ptr, filler= '9';
unknown's avatar
unknown committed
2353

2354
  set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
2355
  if (negative)
unknown's avatar
unknown committed
2356
  {
2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
    if (!unsigned_flag)
    {
      /* Put - sign as a first digit so we'll have -999..999 or 999..999 */
      *to++ = '-';
      len--;
    }
    else
    {
      filler= '0';				// Fill up with 0
      if (!zerofill)
      {
	/*
	  Handle unsigned integer without zerofill, in which case
	  the number should be of format '   0' or '   0.000'
	*/
	uint whole_part=field_length- (dec ? dec+2 : 1);
	// Fill with spaces up to the first digit
	bfill(to, whole_part, ' ');
	to+=  whole_part;
	len-= whole_part;
	// The main code will also handle the 0 before the decimal point
      }
    }
unknown's avatar
unknown committed
2380
  }
2381
  bfill(to, len, filler);
unknown's avatar
unknown committed
2382 2383 2384 2385 2386 2387
  if (dec)
    ptr[field_length-dec-1]='.';
  return;
}


2388
int Field_decimal::store(const char *from_arg, uint len, CHARSET_INFO *cs)
unknown's avatar
unknown committed
2389
{
2390
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
2391
  char buff[STRING_BUFFER_USUAL_SIZE];
unknown's avatar
unknown committed
2392
  String tmp(buff,sizeof(buff), &my_charset_bin);
2393
  const uchar *from= (uchar*) from_arg;
2394

2395
  /* Convert character set if the old one is multi uchar */
2396 2397
  if (cs->mbmaxlen > 1)
  { 
2398
    uint dummy_errors;
2399 2400
    tmp.copy((char*) from, len, cs, &my_charset_bin, &dummy_errors);
    from= (uchar*) tmp.ptr();
2401 2402
    len=  tmp.length();
  }
2403

2404
  const uchar *end= from+len;
2405
  /* The pointer where the field value starts (i.e., "where to write") */
2406
  uchar *to= ptr;
2407 2408 2409 2410 2411
  uint tmp_dec, tmp_uint;
  /*
    The sign of the number : will be 0 (means positive but sign not
    specified), '+' or '-'
  */
2412
  uchar sign_char=0;
unknown's avatar
unknown committed
2413
  /* The pointers where prezeros start and stop */
2414
  const uchar *pre_zeros_from, *pre_zeros_end;
unknown's avatar
unknown committed
2415
  /* The pointers where digits at the left of '.' start and stop */
2416
  const uchar *int_digits_from, *int_digits_end;
unknown's avatar
unknown committed
2417
  /* The pointers where digits at the right of '.' start and stop */
2418
  const uchar *frac_digits_from, *frac_digits_end;
unknown's avatar
unknown committed
2419
  /* The sign of the exponent : will be 0 (means no exponent), '+' or '-' */
2420
  char expo_sign_char=0;
unknown's avatar
unknown committed
2421
  uint exponent=0;                                // value of the exponent
2422 2423 2424 2425
  /*
    Pointers used when digits move from the left of the '.' to the
    right of the '.' (explained below)
  */
Staale Smedseng's avatar
Staale Smedseng committed
2426
  const uchar *UNINIT_VAR(int_digits_tail_from);
2427
  /* Number of 0 that need to be added at the left of the '.' (1E3: 3 zeros) */
2428
  uint UNINIT_VAR(int_digits_added_zeros);
unknown's avatar
unknown committed
2429 2430 2431 2432
  /*
    Pointer used when digits move from the right of the '.' to the left
    of the '.'
  */
Staale Smedseng's avatar
Staale Smedseng committed
2433
  const uchar *UNINIT_VAR(frac_digits_head_end);
unknown's avatar
unknown committed
2434
  /* Number of 0 that need to be added at the right of the '.' (for 1E-3) */
2435
  uint UNINIT_VAR(frac_digits_added_zeros);
2436
  uchar *pos,*tmp_left_pos,*tmp_right_pos;
2437
  /* Pointers that are used as limits (begin and end of the field buffer) */
2438 2439
  uchar *left_wall,*right_wall;
  uchar tmp_char;
unknown's avatar
unknown committed
2440
  /*
2441
    To remember if get_thd()->cuted_fields has already been incremented,
unknown's avatar
unknown committed
2442 2443
    to do that only once
  */
2444 2445 2446 2447
  bool is_cuted_fields_incr=0;

  /*
    There are three steps in this function :
unknown's avatar
unknown committed
2448 2449
    - parse the input string
    - modify the position of digits around the decimal dot '.' 
2450
      according to the exponent value (if specified)
unknown's avatar
unknown committed
2451
    - write the formatted number
2452 2453 2454 2455 2456
  */

  if ((tmp_dec=dec))
    tmp_dec++;

unknown's avatar
unknown committed
2457
  /* skip pre-space */
unknown's avatar
unknown committed
2458
  while (from != end && my_isspace(&my_charset_bin,*from))
unknown's avatar
unknown committed
2459
    from++;
2460
  if (from == end)
unknown's avatar
unknown committed
2461
  {
2462
    set_warning(WARN_DATA_TRUNCATED, 1);
2463
    is_cuted_fields_incr=1;
unknown's avatar
unknown committed
2464
  }
2465
  else if (*from == '+' || *from == '-')	// Found some sign ?
unknown's avatar
unknown committed
2466
  {
2467
    sign_char= *from++;
unknown's avatar
unknown committed
2468
    /*
2469 2470 2471
      We allow "+" for unsigned decimal unless defined different
      Both options allowed as one may wish not to have "+" for unsigned numbers
      because of data processing issues
2472 2473 2474 2475
    */ 
    if (unsigned_flag)  
    { 
      if (sign_char=='-')
2476
      {
2477
        Field_decimal::overflow(1);
unknown's avatar
unknown committed
2478
        return 1;
2479
      }
2480
      /* 
unknown's avatar
unknown committed
2481 2482
	 Defining this will not store "+" for unsigned decimal type even if
	 it is passed in numeric string. This will make some tests to fail
2483 2484
      */	 
#ifdef DONT_ALLOW_UNSIGNED_PLUS      
2485 2486
      else 
        sign_char=0;
2487
#endif 	
unknown's avatar
unknown committed
2488
    }
2489
  }
unknown's avatar
unknown committed
2490

2491 2492 2493 2494
  pre_zeros_from= from;
  for (; from!=end && *from == '0'; from++) ;	// Read prezeros
  pre_zeros_end=int_digits_from=from;      
  /* Read non zero digits at the left of '.'*/
unknown's avatar
unknown committed
2495
  for (; from != end && my_isdigit(&my_charset_bin, *from) ; from++) ;
2496 2497 2498 2499 2500
  int_digits_end=from;
  if (from!=end && *from == '.')		// Some '.' ?
    from++;
  frac_digits_from= from;
  /* Read digits at the right of '.' */
unknown's avatar
unknown committed
2501
  for (;from!=end && my_isdigit(&my_charset_bin, *from); from++) ;
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
  frac_digits_end=from;
  // Some exponentiation symbol ?
  if (from != end && (*from == 'e' || *from == 'E'))
  {   
    from++;
    if (from != end && (*from == '+' || *from == '-'))  // Some exponent sign ?
      expo_sign_char= *from++;
    else
      expo_sign_char= '+';
    /*
2512 2513 2514 2515
      Read digits of the exponent and compute its value.  We must care about
      'exponent' overflow, because as unsigned arithmetic is "modulo", big 
      exponents will become small (e.g. 1e4294967296 will become 1e0, and the 
      field will finally contain 1 instead of its max possible value).
2516
    */
unknown's avatar
unknown committed
2517
    for (;from!=end && my_isdigit(&my_charset_bin, *from); from++)
2518
    {
2519
      exponent=10*exponent+(*from-'0');
unknown's avatar
unknown committed
2520
      if (exponent>MAX_EXPONENT)
2521 2522
        break;
    }
unknown's avatar
unknown committed
2523
  }
2524
  
unknown's avatar
unknown committed
2525
  /*
2526 2527
    We only have to generate warnings if count_cuted_fields is set.
    This is to avoid extra checks of the number when they are not needed.
unknown's avatar
unknown committed
2528
    Even if this flag is not set, it's OK to increment warnings, if
2529
    it makes the code easer to read.
unknown's avatar
unknown committed
2530
  */
2531

2532
  if (get_thd()->count_cuted_fields)
unknown's avatar
unknown committed
2533
  {
2534
    // Skip end spaces
unknown's avatar
unknown committed
2535
    for (;from != end && my_isspace(&my_charset_bin, *from); from++) ;
2536
    if (from != end)                     // If still something left, warn
unknown's avatar
unknown committed
2537
    {
2538
      set_warning(WARN_DATA_TRUNCATED, 1);
2539
      is_cuted_fields_incr=1;
unknown's avatar
unknown committed
2540
    }
2541 2542 2543 2544 2545 2546
  }
  
  /*
    Now "move" digits around the decimal dot according to the exponent value,
    and add necessary zeros.
    Examples :
unknown's avatar
unknown committed
2547 2548 2549
    - 1E+3 : needs 3 more zeros at the left of '.' (int_digits_added_zeros=3)
    - 1E-3 : '1' moves at the right of '.', and 2 more zeros are needed
    between '.' and '1'
2550
    - 1234.5E-3 : '234' moves at the right of '.'
unknown's avatar
unknown committed
2551 2552
    These moves are implemented with pointers which point at the begin
    and end of each moved segment. Examples :
2553
    - 1234.5E-3 : before the code below is executed, the int_digits part is
unknown's avatar
unknown committed
2554 2555 2556
    from '1' to '4' and the frac_digits part from '5' to '5'. After the code
    below, the int_digits part is from '1' to '1', the frac_digits_head
    part is from '2' to '4', and the frac_digits part from '5' to '5'.
2557
    - 1234.5E3 : before the code below is executed, the int_digits part is
unknown's avatar
unknown committed
2558 2559 2560 2561
    from '1' to '4' and the frac_digits part from '5' to '5'. After the code
    below, the int_digits part is from '1' to '4', the int_digits_tail
    part is from '5' to '5', the frac_digits part is empty, and
    int_digits_added_zeros=2 (to make 1234500).
2562 2563
  */
  
2564
  /* 
unknown's avatar
unknown committed
2565
     Below tmp_uint cannot overflow with small enough MAX_EXPONENT setting,
2566
     as int_digits_added_zeros<=exponent<4G and 
2567 2568
     (int_digits_end-int_digits_from)<=max_allowed_packet<=2G and
     (frac_digits_from-int_digits_tail_from)<=max_allowed_packet<=2G
2569 2570
  */

2571 2572 2573 2574
  if (!expo_sign_char)
    tmp_uint=tmp_dec+(uint)(int_digits_end-int_digits_from);
  else if (expo_sign_char == '-') 
  {
2575
    tmp_uint=MY_MIN(exponent,(uint)(int_digits_end-int_digits_from));
2576 2577 2578
    frac_digits_added_zeros=exponent-tmp_uint;
    int_digits_end -= tmp_uint;
    frac_digits_head_end=int_digits_end+tmp_uint;
unknown's avatar
unknown committed
2579
    tmp_uint=tmp_dec+(uint)(int_digits_end-int_digits_from);     
2580 2581 2582
  }
  else // (expo_sign_char=='+') 
  {
2583
    tmp_uint=MY_MIN(exponent,(uint)(frac_digits_end-frac_digits_from));
2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604
    int_digits_added_zeros=exponent-tmp_uint;
    int_digits_tail_from=frac_digits_from;
    frac_digits_from=frac_digits_from+tmp_uint;
    /*
      We "eat" the heading zeros of the 
      int_digits.int_digits_tail.int_digits_added_zeros concatenation
      (for example 0.003e3 must become 3 and not 0003)
    */
    if (int_digits_from == int_digits_end) 
    {
      /*
	There was nothing in the int_digits part, so continue
	eating int_digits_tail zeros
      */
      for (; int_digits_tail_from != frac_digits_from &&
	     *int_digits_tail_from == '0'; int_digits_tail_from++) ;
      if (int_digits_tail_from == frac_digits_from) 
      {
	// there were only zeros in int_digits_tail too
	int_digits_added_zeros=0;
      }
unknown's avatar
unknown committed
2605
    }
2606
    tmp_uint= (uint) (tmp_dec+(int_digits_end-int_digits_from)+
2607 2608
               (uint)(frac_digits_from-int_digits_tail_from)+
               int_digits_added_zeros);
2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
  }
  
  /*
    Now write the formated number
    
    First the digits of the int_% parts.
    Do we have enough room to write these digits ?
    If the sign is defined and '-', we need one position for it
  */

2619
  if (field_length < tmp_uint + (int) (sign_char == '-')) 
2620
  {
unknown's avatar
unknown committed
2621
    // too big number, change to max or min number
2622
    Field_decimal::overflow(sign_char == '-');
2623
    return 1;
unknown's avatar
unknown committed
2624
  }
2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641
 
  /*
    Tmp_left_pos is the position where the leftmost digit of
    the int_% parts will be written
  */
  tmp_left_pos=pos=to+(uint)(field_length-tmp_uint);
  
  // Write all digits of the int_% parts
  while (int_digits_from != int_digits_end)
    *pos++ = *int_digits_from++ ;

  if (expo_sign_char == '+')
  {    
    while (int_digits_tail_from != frac_digits_from)
      *pos++= *int_digits_tail_from++;
    while (int_digits_added_zeros-- >0)
      *pos++= '0';  
unknown's avatar
unknown committed
2642
  }
2643 2644 2645 2646 2647 2648
  /*
    Note the position where the rightmost digit of the int_% parts has been
    written (this is to later check if the int_% parts contained nothing,
    meaning an extra 0 is needed).
  */
  tmp_right_pos=pos;
unknown's avatar
unknown committed
2649 2650

  /*
2651 2652
    Step back to the position of the leftmost digit of the int_% parts,
    to write sign and fill with zeros or blanks or prezeros.
unknown's avatar
unknown committed
2653
  */
2654 2655 2656 2657
  pos=tmp_left_pos-1;
  if (zerofill)
  {
    left_wall=to-1;
2658
    while (pos > left_wall)			// Fill with zeros
2659 2660 2661 2662
      *pos--='0';
  }
  else
  {
unknown's avatar
unknown committed
2663
    left_wall=to+(sign_char != 0)-1;
2664 2665
    if (!expo_sign_char)	// If exponent was specified, ignore prezeros
    {
2666
      for (;pos > left_wall && pre_zeros_from !=pre_zeros_end;
2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
	   pre_zeros_from++)
	*pos--= '0';
    }
    if (pos == tmp_right_pos-1)
      *pos--= '0';		// no 0 has ever been written, so write one
    left_wall= to-1;
    if (sign_char && pos != left_wall)
    {
      /* Write sign if possible (it is if sign is '-') */
      *pos--= sign_char;
    }
    while (pos != left_wall)
      *pos--=' ';  //fill with blanks
  }
  
2682 2683
  /*
    Write digits of the frac_% parts ;
2684
    Depending on get_thd()->count_cutted_fields, we may also want
2685 2686 2687 2688 2689
    to know if some non-zero tail of these parts will
    be truncated (for example, 0.002->0.00 will generate a warning,
    while 0.000->0.00 will not)
    (and 0E1000000000 will not, while 1E-1000000000 will)
  */
2690
      
2691 2692 2693
  pos=to+(uint)(field_length-tmp_dec);	// Calculate post to '.'
  right_wall=to+field_length;
  if (pos != right_wall) 
2694 2695
    *pos++='.';

2696 2697 2698
  if (expo_sign_char == '-')
  {
    while (frac_digits_added_zeros-- > 0)
unknown's avatar
unknown committed
2699
    {
2700
      if (pos == right_wall) 
2701
      {
2702
        if (get_thd()->count_cuted_fields && !is_cuted_fields_incr) 
2703
          break; // Go on below to see if we lose non zero digits
unknown's avatar
unknown committed
2704
        return 0;
2705
      }
2706 2707 2708 2709 2710 2711
      *pos++='0';
    }
    while (int_digits_end != frac_digits_head_end)
    {
      tmp_char= *int_digits_end++;
      if (pos == right_wall)
unknown's avatar
unknown committed
2712
      {
2713 2714 2715
        if (tmp_char != '0')			// Losing a non zero digit ?
        {
          if (!is_cuted_fields_incr)
2716
            set_warning(WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
2717
          return 0;
2718 2719
        }
        continue;
unknown's avatar
unknown committed
2720
      }
2721
      *pos++= tmp_char;
unknown's avatar
unknown committed
2722
    }
2723
  }
2724

2725 2726 2727 2728
  for (;frac_digits_from!=frac_digits_end;) 
  {
    tmp_char= *frac_digits_from++;
    if (pos == right_wall)
2729
    {
2730
      if (tmp_char != '0')			// Losing a non zero digit ?
2731
      {
2732
        if (!is_cuted_fields_incr)
unknown's avatar
unknown committed
2733 2734 2735 2736 2737
        {
          /*
            This is a note, not a warning, as we don't want to abort
            when we cut decimals in strict mode
          */
2738
	  set_note(WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
2739
        }
unknown's avatar
unknown committed
2740
        return 0;
2741
      }
2742
      continue;
2743
    }
2744
    *pos++= tmp_char;
unknown's avatar
unknown committed
2745
  }
2746 2747 2748
      
  while (pos != right_wall)
   *pos++='0';			// Fill with zeros at right of '.'
unknown's avatar
unknown committed
2749
  return 0;
unknown's avatar
unknown committed
2750 2751 2752
}


unknown's avatar
unknown committed
2753
int Field_decimal::store(double nr)
unknown's avatar
unknown committed
2754
{
2755
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
2756 2757 2758
  if (unsigned_flag && nr < 0)
  {
    overflow(1);
2759
    return 1;
unknown's avatar
unknown committed
2760
  }
2761
  
2762
  if (!isfinite(nr)) // Handle infinity as special case
2763 2764
  {
    overflow(nr < 0.0);
unknown's avatar
unknown committed
2765
    return 1;
2766
  }
unknown's avatar
unknown committed
2767

2768 2769 2770
  reg4 uint i;
  size_t length;
  uchar fyllchar,*to;
2771
  char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
unknown's avatar
unknown committed
2772 2773

  fyllchar = zerofill ? (char) '0' : (char) ' ';
2774
  length= my_fcvt(nr, dec, buff, NULL);
unknown's avatar
unknown committed
2775 2776 2777 2778

  if (length > field_length)
  {
    overflow(nr < 0.0);
2779
    return 1;
unknown's avatar
unknown committed
2780 2781 2782 2783 2784 2785 2786
  }
  else
  {
    to=ptr;
    for (i=field_length-length ; i-- > 0 ;)
      *to++ = fyllchar;
    memcpy(to,buff,length);
2787
    return 0;
unknown's avatar
unknown committed
2788 2789 2790 2791
  }
}


2792
int Field_decimal::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
2793
{
2794
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
2795 2796
  char buff[22];
  uint length, int_part;
2797 2798
  char fyllchar;
  uchar *to;
2799 2800

  if (nr < 0 && unsigned_flag && !unsigned_val)
unknown's avatar
unknown committed
2801 2802
  {
    overflow(1);
2803
    return 1;
unknown's avatar
unknown committed
2804
  }
2805 2806
  length= (uint) (longlong10_to_str(nr,buff,unsigned_val ? 10 : -10) - buff);
  int_part= field_length- (dec  ? dec+1 : 0);
unknown's avatar
unknown committed
2807 2808 2809

  if (length > int_part)
  {
2810
    overflow(!unsigned_val && nr < 0L);		/* purecov: inspected */
2811
    return 1;
unknown's avatar
unknown committed
2812
  }
2813 2814 2815 2816 2817 2818 2819

  fyllchar = zerofill ? (char) '0' : (char) ' ';
  to= ptr;
  for (uint i=int_part-length ; i-- > 0 ;)
    *to++ = fyllchar;
  memcpy(to,buff,length);
  if (dec)
unknown's avatar
unknown committed
2820
  {
2821 2822
    to[length]='.';
    bfill(to+length+1,dec,'0');
unknown's avatar
unknown committed
2823
  }
2824
  return 0;
unknown's avatar
unknown committed
2825 2826 2827 2828 2829
}


double Field_decimal::val_real(void)
{
2830
  ASSERT_COLUMN_MARKED_FOR_READ;
2831
  int not_used;
2832
  char *end_not_used;
2833
  return my_strntod(&my_charset_bin, (char*) ptr, field_length, &end_not_used,
2834
                    &not_used);
unknown's avatar
unknown committed
2835 2836 2837 2838
}

longlong Field_decimal::val_int(void)
{
2839
  ASSERT_COLUMN_MARKED_FOR_READ;
2840
  int not_used;
unknown's avatar
unknown committed
2841
  if (unsigned_flag)
2842
    return my_strntoull(&my_charset_bin, (char*) ptr, field_length, 10, NULL,
2843
			&not_used);
2844 2845
  return my_strntoll(&my_charset_bin, (char*) ptr, field_length, 10, NULL,
                     &not_used);
unknown's avatar
unknown committed
2846 2847
}

2848

unknown's avatar
unknown committed
2849 2850 2851
String *Field_decimal::val_str(String *val_buffer __attribute__((unused)),
			       String *val_ptr)
{
2852
  ASSERT_COLUMN_MARKED_FOR_READ;
2853 2854 2855
  uchar *str;
  size_t tmp_length;

unknown's avatar
unknown committed
2856
  for (str=ptr ; *str == ' ' ; str++) ;
2857
  val_ptr->set_charset(&my_charset_numeric);
2858
  tmp_length= (size_t) (str-ptr);
unknown's avatar
unknown committed
2859 2860 2861
  if (field_length < tmp_length)		// Error in data
    val_ptr->length(0);
  else
2862
    val_ptr->set_ascii((const char*) str, field_length-tmp_length);
unknown's avatar
unknown committed
2863 2864 2865
  return val_ptr;
}

2866 2867 2868
/**
  Should be able to handle at least the following fixed decimal formats:
  5.00 , -1.0,  05,  -05, +5 with optional pre/end space
unknown's avatar
unknown committed
2869 2870
*/

2871
int Field_decimal::cmp(const uchar *a_ptr,const uchar *b_ptr)
unknown's avatar
unknown committed
2872
{
2873
  const uchar *end;
2874
  int swap=0;
unknown's avatar
unknown committed
2875 2876 2877 2878
  /* First remove prefixes '0', ' ', and '-' */
  for (end=a_ptr+field_length;
       a_ptr != end &&
	 (*a_ptr == *b_ptr ||
unknown's avatar
unknown committed
2879
	  ((my_isspace(&my_charset_bin,*a_ptr)  || *a_ptr == '+' || 
2880
            *a_ptr == '0') &&
unknown's avatar
unknown committed
2881
	   (my_isspace(&my_charset_bin,*b_ptr) || *b_ptr == '+' || 
2882
            *b_ptr == '0')));
2883 2884 2885 2886 2887
       a_ptr++,b_ptr++)
  {
    if (*a_ptr == '-')				// If both numbers are negative
      swap= -1 ^ 1;				// Swap result      
  }
unknown's avatar
unknown committed
2888 2889 2890
  if (a_ptr == end)
    return 0;
  if (*a_ptr == '-')
2891
    return -1;
2892
  if (*b_ptr == '-')
unknown's avatar
unknown committed
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903
    return 1;

  while (a_ptr != end)
  {
    if (*a_ptr++ != *b_ptr++)
      return swap ^ (a_ptr[-1] < b_ptr[-1] ? -1 : 1); // compare digits
  }
  return 0;
}


2904
void Field_decimal::sort_string(uchar *to,uint length)
unknown's avatar
unknown committed
2905
{
2906
  uchar *str,*end;
unknown's avatar
unknown committed
2907 2908
  for (str=ptr,end=ptr+length;
       str != end &&
unknown's avatar
unknown committed
2909
	 ((my_isspace(&my_charset_bin,*str) || *str == '+' ||
unknown's avatar
unknown committed
2910
	   *str == '0')) ;
unknown's avatar
unknown committed
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920
       str++)
    *to++=' ';
  if (str == end)
    return;					/* purecov: inspected */

  if (*str == '-')
  {
    *to++=1;					// Smaller than any number
    str++;
    while (str != end)
unknown's avatar
unknown committed
2921
      if (my_isdigit(&my_charset_bin,*str))
unknown's avatar
unknown committed
2922 2923 2924 2925 2926 2927 2928
	*to++= (char) ('9' - *str++);
      else
	*to++= *str++;
  }
  else memcpy(to,str,(uint) (end-str));
}

unknown's avatar
unknown committed
2929

unknown's avatar
unknown committed
2930 2931
void Field_decimal::sql_type(String &res) const
{
unknown's avatar
unknown committed
2932
  CHARSET_INFO *cs=res.charset();
unknown's avatar
unknown committed
2933 2934 2935 2936 2937
  uint tmp=field_length;
  if (!unsigned_flag)
    tmp--;
  if (dec)
    tmp--;
2938
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
2939
			  "decimal(%d,%d)/*old*/",tmp,dec));
unknown's avatar
unknown committed
2940 2941 2942 2943
  add_zerofill_and_unsigned(res);
}


unknown's avatar
unknown committed
2944 2945 2946 2947
/****************************************************************************
** Field_new_decimal
****************************************************************************/

2948
Field_new_decimal::Field_new_decimal(uchar *ptr_arg,
unknown's avatar
unknown committed
2949 2950 2951 2952 2953 2954
                                     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)
unknown's avatar
unknown committed
2955 2956
  :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
             unireg_check_arg, field_name_arg, dec_arg, zero_arg, unsigned_arg)
unknown's avatar
unknown committed
2957
{
unknown's avatar
unknown committed
2958
  precision= my_decimal_length_to_precision(len_arg, dec_arg, unsigned_arg);
unknown's avatar
unknown committed
2959
  set_if_smaller(precision, DECIMAL_MAX_PRECISION);
unknown's avatar
unknown committed
2960 2961 2962
  DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION) &&
              (dec <= DECIMAL_MAX_SCALE));
  bin_size= my_decimal_get_binary_size(precision, dec);
unknown's avatar
unknown committed
2963 2964 2965 2966
}


Field_new_decimal::Field_new_decimal(uint32 len_arg,
2967
                                     bool maybe_null_arg,
unknown's avatar
unknown committed
2968
                                     const char *name,
unknown's avatar
unknown committed
2969 2970
                                     uint8 dec_arg,
                                     bool unsigned_arg)
2971
  :Field_num((uchar*) 0, len_arg,
2972
             maybe_null_arg ? (uchar*) "": 0, 0,
unknown's avatar
unknown committed
2973
             NONE, name, dec_arg, 0, unsigned_arg)
unknown's avatar
unknown committed
2974
{
unknown's avatar
unknown committed
2975
  precision= my_decimal_length_to_precision(len_arg, dec_arg, unsigned_arg);
unknown's avatar
unknown committed
2976
  set_if_smaller(precision, DECIMAL_MAX_PRECISION);
unknown's avatar
unknown committed
2977 2978 2979
  DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION) &&
              (dec <= DECIMAL_MAX_SCALE));
  bin_size= my_decimal_get_binary_size(precision, dec);
unknown's avatar
unknown committed
2980 2981 2982
}


2983
Field *Field_new_decimal::create_from_item(MEM_ROOT *mem_root, Item *item)
2984 2985 2986
{
  uint8 dec= item->decimals;
  uint8 intg= item->decimal_precision() - dec;
2987
  uint32 len= item->max_char_length();
2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000

  DBUG_ASSERT (item->result_type() == DECIMAL_RESULT);

  /*
    Trying to put too many digits overall in a DECIMAL(prec,dec)
    will always throw a warning. We must limit dec to
    DECIMAL_MAX_SCALE however to prevent an assert() later.
  */

  if (dec > 0)
  {
    signed int overflow;

3001
    dec= MY_MIN(dec, DECIMAL_MAX_SCALE);
3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016

    /*
      If the value still overflows the field with the corrected dec,
      we'll throw out decimals rather than integers. This is still
      bad and of course throws a truncation warning.
      +1: for decimal point
      */

    const int required_length=
      my_decimal_precision_to_length(intg + dec, dec,
                                     item->unsigned_flag);

    overflow= required_length - len;

    if (overflow > 0)
3017
      dec= MY_MAX(0, dec - overflow);            // too long, discard fract
3018 3019 3020 3021
    else
      /* Corrected value fits. */
      len= required_length;
  }
3022 3023 3024
  return new (mem_root)
    Field_new_decimal(len, item->maybe_null, item->name,
                      dec, item->unsigned_flag);
3025 3026 3027
}


unknown's avatar
unknown committed
3028
int Field_new_decimal::reset(void)
unknown's avatar
unknown committed
3029 3030
{
  store_value(&decimal_zero);
unknown's avatar
unknown committed
3031
  return 0;
unknown's avatar
unknown committed
3032 3033 3034
}


3035
/**
unknown's avatar
unknown committed
3036 3037
  Generate max/min decimal value in case of overflow.

3038 3039
  @param decimal_value     buffer for value
  @param sign              sign of value which caused overflow
unknown's avatar
unknown committed
3040 3041 3042 3043 3044 3045
*/

void Field_new_decimal::set_value_on_overflow(my_decimal *decimal_value,
                                              bool sign)
{
  DBUG_ENTER("Field_new_decimal::set_value_on_overflow");
unknown's avatar
unknown committed
3046
  max_my_decimal(decimal_value, precision, decimals());
unknown's avatar
unknown committed
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057
  if (sign)
  {
    if (unsigned_flag)
      my_decimal_set_zero(decimal_value);
    else
      decimal_value->sign(TRUE);
  }
  DBUG_VOID_RETURN;
}


3058 3059
/**
  Store decimal value in the binary buffer.
unknown's avatar
unknown committed
3060

3061 3062 3063
  Checks if decimal_value fits into field size.
  If it does, stores the decimal in the buffer using binary format.
  Otherwise sets maximal number that can be stored in the field.
unknown's avatar
unknown committed
3064

3065 3066
  @param       decimal_value   my_decimal
  @param [OUT] native_error    the error returned by my_decimal2binary().
unknown's avatar
unknown committed
3067

3068 3069 3070 3071
  @retval
    0 ok
  @retval
    1 error
unknown's avatar
unknown committed
3072 3073
*/

3074 3075
bool Field_new_decimal::store_value(const my_decimal *decimal_value,
                                    int *native_error)
unknown's avatar
unknown committed
3076
{
3077
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
3078 3079
  int error= 0;
  DBUG_ENTER("Field_new_decimal::store_value");
unknown's avatar
unknown committed
3080 3081
#ifndef DBUG_OFF
  {
3082
    char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
unknown's avatar
unknown committed
3083 3084 3085
    DBUG_PRINT("enter", ("value: %s", dbug_decimal_as_string(dbug_buff, decimal_value)));
  }
#endif
unknown's avatar
unknown committed
3086 3087 3088 3089 3090

  /* check that we do not try to write negative value in unsigned field */
  if (unsigned_flag && decimal_value->sign())
  {
    DBUG_PRINT("info", ("unsigned overflow"));
3091
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3092
    error= 1;
unknown's avatar
unknown committed
3093 3094 3095 3096
    decimal_value= &decimal_zero;
  }
#ifndef DBUG_OFF
  {
3097
    char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
3098
    DBUG_PRINT("info", ("saving with precision %d  scale: %d  value %s",
unknown's avatar
unknown committed
3099 3100
                        (int)precision, (int)dec,
                        dbug_decimal_as_string(dbug_buff, decimal_value)));
unknown's avatar
unknown committed
3101
  }
unknown's avatar
unknown committed
3102
#endif
unknown's avatar
unknown committed
3103

3104 3105 3106 3107
  *native_error= my_decimal2binary(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW,
                                   decimal_value, ptr, precision, dec);

  if (*native_error == E_DEC_OVERFLOW)
unknown's avatar
unknown committed
3108 3109 3110
  {
    my_decimal buff;
    DBUG_PRINT("info", ("overflow"));
3111
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3112 3113
    set_value_on_overflow(&buff, decimal_value->sign());
    my_decimal2binary(E_DEC_FATAL_ERROR, &buff, ptr, precision, dec);
3114
    error= 1;
unknown's avatar
unknown committed
3115
  }
3116
  DBUG_EXECUTE("info", print_decimal_buff(decimal_value, (uchar *) ptr,
3117
                                          bin_size););
unknown's avatar
unknown committed
3118
  DBUG_RETURN(error);
unknown's avatar
unknown committed
3119 3120 3121
}


3122 3123 3124 3125 3126 3127 3128 3129 3130 3131
bool Field_new_decimal::store_value(const my_decimal *decimal_value)
{
  int native_error;
  bool rc= store_value(decimal_value, &native_error);
  if (!rc && native_error == E_DEC_TRUNCATED)
    set_note(WARN_DATA_TRUNCATED, 1);
  return rc;
}


unknown's avatar
unknown committed
3132
int Field_new_decimal::store(const char *from, uint length,
3133
                             CHARSET_INFO *charset_arg)
unknown's avatar
unknown committed
3134
{
3135
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
3136
  my_decimal decimal_value;
3137
  THD *thd= get_thd();
unknown's avatar
unknown committed
3138 3139
  DBUG_ENTER("Field_new_decimal::store(char*)");

3140 3141 3142
  const char *end;
  int err= str2my_decimal(E_DEC_FATAL_ERROR &
                          ~(E_DEC_OVERFLOW | E_DEC_BAD_NUM),
3143
                           from, length, charset_arg,
3144 3145 3146
                           &decimal_value, &end);

  if (err == E_DEC_OVERFLOW) // Too many digits (>81) in the integer part
3147
  {
3148 3149 3150 3151 3152 3153 3154
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
    if (!thd->abort_on_warning)
    {
      set_value_on_overflow(&decimal_value, decimal_value.sign());
      store_decimal(&decimal_value);
    }
    DBUG_RETURN(1);
3155 3156
  }

3157 3158
  if (thd->count_cuted_fields)
  {
3159 3160 3161 3162
    if (check_edom_and_important_data_truncation("decimal",
                                                 err && err != E_DEC_TRUNCATED,
                                                 charset_arg,
                                                 from, length, end))
3163
    {
3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183
      if (!thd->abort_on_warning)
      {
        if (err && err != E_DEC_TRUNCATED)
        {
          /*
            If check_decimal() failed because of EDOM-alike error,
            (e.g. E_DEC_BAD_NUM), we have to initialize decimal_value to zero.
            Note: if check_decimal() failed because of truncation,
            decimal_value is alreay properly initialized.
          */
          my_decimal_set_zero(&decimal_value);
          /*
            TODO: check str2my_decimal() with HF. It seems to do
            decimal_make_zero() on fatal errors, so my_decimal_set_zero()
            is probably not needed here.
          */
        }
        store_decimal(&decimal_value);
      }
      DBUG_RETURN(1);
3184
    }
unknown's avatar
unknown committed
3185 3186
  }

unknown's avatar
unknown committed
3187
#ifndef DBUG_OFF
3188
  char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
unknown's avatar
unknown committed
3189 3190 3191
  DBUG_PRINT("enter", ("value: %s",
                       dbug_decimal_as_string(dbug_buff, &decimal_value)));
#endif
3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
  int err2;
  if (store_value(&decimal_value, &err2))
    DBUG_RETURN(1);

  /*
    E_DEC_TRUNCATED means minor truncation, a note should be enough:
    - in err: str2my_decimal() truncated '1e-1000000000000' to 0.0
    - in err2: store_value() truncated 1.123 to 1.12, e.g. for DECIMAL(10,2)
    Also, we send a note if a string had some trailing spaces: '1.12 '
  */
  if (thd->count_cuted_fields &&
      (err == E_DEC_TRUNCATED ||
       err2 == E_DEC_TRUNCATED ||
       end < from + length))
    set_note(WARN_DATA_TRUNCATED, 1);
3207
  DBUG_RETURN(0);
unknown's avatar
unknown committed
3208 3209 3210
}


3211 3212 3213 3214 3215 3216
/**
  @todo
  Fix following when double2my_decimal when double2decimal
  will return E_DEC_TRUNCATED always correctly
*/

unknown's avatar
unknown committed
3217 3218
int Field_new_decimal::store(double nr)
{
3219
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
3220
  my_decimal decimal_value;
unknown's avatar
unknown committed
3221
  int err;
3222
  THD *thd= get_thd();
unknown's avatar
unknown committed
3223 3224 3225 3226 3227 3228 3229 3230 3231
  DBUG_ENTER("Field_new_decimal::store(double)");

  err= double2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW, nr,
                         &decimal_value);
  if (err)
  {
    if (check_overflow(err))
      set_value_on_overflow(&decimal_value, decimal_value.sign());
    /* Only issue a warning if store_value doesn't issue an warning */
3232
    thd->got_warning= 0;
unknown's avatar
unknown committed
3233 3234 3235
  }
  if (store_value(&decimal_value))
    err= 1;
3236
  else if (err && !thd->got_warning)
unknown's avatar
unknown committed
3237 3238
    err= warn_if_overflow(err);
  DBUG_RETURN(err);
unknown's avatar
unknown committed
3239 3240 3241
}


3242
int Field_new_decimal::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
3243
{
3244
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
3245 3246
  my_decimal decimal_value;
  int err;
unknown's avatar
unknown committed
3247 3248

  if ((err= int2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW,
3249
                           nr, unsigned_val, &decimal_value)))
unknown's avatar
unknown committed
3250 3251 3252 3253
  {
    if (check_overflow(err))
      set_value_on_overflow(&decimal_value, decimal_value.sign());
    /* Only issue a warning if store_value doesn't issue an warning */
3254
    get_thd()->got_warning= 0;
unknown's avatar
unknown committed
3255 3256 3257
  }
  if (store_value(&decimal_value))
    err= 1;
3258
  else if (err && !get_thd()->got_warning)
unknown's avatar
unknown committed
3259
    err= warn_if_overflow(err);
unknown's avatar
unknown committed
3260 3261 3262 3263 3264 3265
  return err;
}


int Field_new_decimal::store_decimal(const my_decimal *decimal_value)
{
3266
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
3267 3268 3269 3270
  return store_value(decimal_value);
}


3271
int Field_new_decimal::store_time_dec(MYSQL_TIME *ltime, uint dec_arg)
3272
{
3273 3274
  my_decimal decimal_value;
  return store_value(date2my_decimal(ltime, &decimal_value));
unknown's avatar
unknown committed
3275 3276 3277 3278 3279
}


double Field_new_decimal::val_real(void)
{
3280
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3281 3282 3283 3284 3285 3286 3287 3288 3289
  double dbl;
  my_decimal decimal_value;
  my_decimal2double(E_DEC_FATAL_ERROR, val_decimal(&decimal_value), &dbl);
  return dbl;
}


longlong Field_new_decimal::val_int(void)
{
3290
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3291 3292 3293 3294 3295 3296 3297 3298 3299 3300
  longlong i;
  my_decimal decimal_value;
  my_decimal2int(E_DEC_FATAL_ERROR, val_decimal(&decimal_value),
                 unsigned_flag, &i);
  return i;
}


my_decimal* Field_new_decimal::val_decimal(my_decimal *decimal_value)
{
3301
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3302 3303
  DBUG_ENTER("Field_new_decimal::val_decimal");
  binary2my_decimal(E_DEC_FATAL_ERROR, ptr, decimal_value,
unknown's avatar
unknown committed
3304
                    precision, dec);
3305
  DBUG_EXECUTE("info", print_decimal_buff(decimal_value, (uchar *) ptr,
3306
                                          bin_size););
unknown's avatar
unknown committed
3307 3308 3309 3310 3311
  DBUG_RETURN(decimal_value);
}


String *Field_new_decimal::val_str(String *val_buffer,
unknown's avatar
unknown committed
3312
                                   String *val_ptr __attribute__((unused)))
unknown's avatar
unknown committed
3313
{
3314
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3315
  my_decimal decimal_value;
unknown's avatar
unknown committed
3316
  uint fixed_precision= zerofill ? precision : 0;
unknown's avatar
unknown committed
3317
  my_decimal2string(E_DEC_FATAL_ERROR, val_decimal(&decimal_value),
unknown's avatar
unknown committed
3318
                    fixed_precision, dec, '0', val_buffer);
3319
  val_buffer->set_charset(&my_charset_numeric);
unknown's avatar
unknown committed
3320 3321 3322 3323
  return val_buffer;
}


3324 3325 3326 3327 3328 3329 3330 3331
bool Field_new_decimal::get_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
{
  my_decimal value;
  return decimal_to_datetime_with_warn(val_decimal(&value),
                                       ltime, fuzzydate, field_name);
}


3332
int Field_new_decimal::cmp(const uchar *a,const uchar*b)
unknown's avatar
unknown committed
3333 3334 3335 3336 3337
{
  return memcmp(a, b, bin_size);
}


3338
void Field_new_decimal::sort_string(uchar *buff,
unknown's avatar
unknown committed
3339 3340 3341 3342 3343 3344 3345 3346 3347 3348
                                    uint length __attribute__((unused)))
{
  memcpy(buff, ptr, bin_size);
}


void Field_new_decimal::sql_type(String &str) const
{
  CHARSET_INFO *cs= str.charset();
  str.length(cs->cset->snprintf(cs, (char*) str.ptr(), str.alloced_length(),
unknown's avatar
unknown committed
3349
                                "decimal(%d,%d)", precision, (int)dec));
unknown's avatar
unknown committed
3350 3351 3352
  add_zerofill_and_unsigned(str);
}

unknown's avatar
unknown committed
3353

3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394
/**
   Save the field metadata for new decimal fields.

   Saves the precision in the first byte and decimals() in the second
   byte of the field metadata array at index of *metadata_ptr and 
   *(metadata_ptr + 1).

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/
int Field_new_decimal::do_save_field_metadata(uchar *metadata_ptr)
{
  *metadata_ptr= precision;
  *(metadata_ptr + 1)= decimals();
  return 2;
}


/**
   Returns the number of bytes field uses in row-based replication 
   row packed size.

   This method is used in row-based replication to determine the number
   of bytes that the field consumes in the row record format. This is
   used to skip fields in the master that do not exist on the slave.

   @param   field_metadata   Encoded size in field metadata

   @returns The size of the field based on the field metadata.
*/
uint Field_new_decimal::pack_length_from_metadata(uint field_metadata)
{
  uint const source_precision= (field_metadata >> 8U) & 0x00ff;
  uint const source_decimal= field_metadata & 0x00ff; 
  uint const source_size= my_decimal_get_binary_size(source_precision, 
                                                     source_decimal);
  return (source_size);
}


3395 3396
bool Field_new_decimal::compatible_field_size(uint field_metadata,
                                              Relay_log_info * __attribute__((unused)),
3397
                                              uint16 mflags __attribute__((unused)),
3398
                                              int *order_var)
3399 3400 3401
{
  uint const source_precision= (field_metadata >> 8U) & 0x00ff;
  uint const source_decimal= field_metadata & 0x00ff; 
3402 3403 3404
  int order= compare(source_precision, precision);
  *order_var= order != 0 ? order : compare(source_decimal, dec);
  return true;
3405 3406 3407
}


unknown's avatar
unknown committed
3408
uint Field_new_decimal::is_equal(Create_field *new_field)
3409 3410 3411 3412 3413 3414
{
  return ((new_field->sql_type == real_type()) &&
          ((new_field->flags & UNSIGNED_FLAG) == 
           (uint) (flags & UNSIGNED_FLAG)) &&
          ((new_field->flags & AUTO_INCREMENT_FLAG) ==
           (uint) (flags & AUTO_INCREMENT_FLAG)) &&
unknown's avatar
unknown committed
3415
          (new_field->length == max_display_length()) &&
3416 3417 3418 3419
          (new_field->decimals == dec));
}


3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431
/**
   Unpack a decimal field from row data.

   This method is used to unpack a decimal or numeric field from a master
   whose size of the field is less than that of the slave.
  
   @param   to         Destination of the data
   @param   from       Source of the data
   @param   param_data Precision (upper) and decimal (lower) values

   @return  New pointer into memory based on from + length of the data
*/
3432
const uchar *
3433 3434
Field_new_decimal::unpack(uchar* to, const uchar *from, const uchar *from_end,
                          uint param_data)
3435
{
3436
  if (param_data == 0)
3437
    return Field::unpack(to, from, from_end, param_data);
3438

3439 3440 3441 3442 3443 3444
  uint from_precision= (param_data & 0xff00) >> 8U;
  uint from_decimal= param_data & 0x00ff;
  uint length=pack_length();
  uint from_pack_len= my_decimal_get_binary_size(from_precision, from_decimal);
  uint len= (param_data && (from_pack_len < length)) ?
            from_pack_len : length;
3445 3446 3447
  if ((from_pack_len && (from_pack_len < length)) ||
      (from_precision < precision) ||
      (from_decimal < decimals()))
3448 3449 3450 3451 3452 3453 3454
  {
    /*
      If the master's data is smaller than the slave, we need to convert
      the binary to decimal then resize the decimal converting it back to
      a decimal and write that to the raw data buffer.
    */
    decimal_digit_t dec_buf[DECIMAL_MAX_PRECISION];
3455 3456 3457
    decimal_t dec_val;
    dec_val.len= from_precision;
    dec_val.buf= dec_buf;
3458 3459 3460 3461 3462
    /*
      Note: bin2decimal does not change the length of the field. So it is
      just the first step the resizing operation. The second step does the
      resizing using the precision and decimals from the slave.
    */
3463 3464
    bin2decimal((uchar *)from, &dec_val, from_precision, from_decimal);
    decimal2bin(&dec_val, to, precision, decimals());
3465 3466
  }
  else
3467 3468 3469
  {
    if (from + len > from_end)
      return 0;                                 // Wrong data
3470
    memcpy(to, from, len); // Sizes are the same, just copy the data.
3471
  }
3472 3473 3474
  return from+len;
}

3475 3476 3477 3478 3479

Item *Field_new_decimal::get_equal_const_item(THD *thd, const Context &ctx,
                                              Item *const_item)
{
  if (flags & ZEROFILL_FLAG)
3480
    return Field_num::get_equal_zerofill_const_item(thd, ctx, const_item);
3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491
  switch (ctx.subst_constraint()) {
  case IDENTITY_SUBST:
    if (const_item->field_type() != MYSQL_TYPE_NEWDECIMAL ||
        const_item->decimal_scale() != decimals())
    {
      my_decimal *val, val_buffer, val_buffer2;
      if (!(val= const_item->val_decimal(&val_buffer)))
      {
        DBUG_ASSERT(0);
        return const_item;
      }
3492 3493 3494 3495 3496
      /*
        Truncate or extend the decimal value to the scale of the field.
        See comments about truncation in the same place in
        Field_time::get_equal_const_item().
      */
3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508
      my_decimal_round(E_DEC_FATAL_ERROR, val, decimals(), true, &val_buffer2);
      return new (thd->mem_root) Item_decimal(thd, field_name, &val_buffer2,
                                              decimals(), field_length);
    }
    break;
  case ANY_SUBST:
    break;
  }
  return const_item;
}


3509
int Field_num::store_time_dec(MYSQL_TIME *ltime, uint dec_arg)
3510 3511 3512 3513 3514 3515 3516 3517
{
  longlong v= TIME_to_ulonglong(ltime);
  if (ltime->neg == 0)
    return store(v, true);
  return store(-v, false);
}


unknown's avatar
unknown committed
3518 3519 3520 3521
/****************************************************************************
** tiny int
****************************************************************************/

unknown's avatar
unknown committed
3522
int Field_tiny::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
3523
{
3524
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
3525
  int error;
unknown's avatar
unknown committed
3526 3527 3528 3529
  longlong rnd;
  
  error= get_int(cs, from, len, &rnd, 255, -128, 127);
  ptr[0]= unsigned_flag ? (char) (ulonglong) rnd : (char) rnd;
3530
  return error;
unknown's avatar
unknown committed
3531 3532 3533
}


unknown's avatar
unknown committed
3534
int Field_tiny::store(double nr)
unknown's avatar
unknown committed
3535
{
3536
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
3537
  int error= 0;
unknown's avatar
unknown committed
3538 3539 3540 3541 3542 3543
  nr=rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0.0)
    {
      *ptr=0;
3544
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3545
      error= 1;
unknown's avatar
unknown committed
3546 3547 3548
    }
    else if (nr > 255.0)
    {
3549
      *ptr= (uchar) 255;
3550
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3551
      error= 1;
unknown's avatar
unknown committed
3552 3553
    }
    else
3554
      *ptr= (uchar) nr;
unknown's avatar
unknown committed
3555 3556 3557 3558 3559
  }
  else
  {
    if (nr < -128.0)
    {
3560
      *ptr= (uchar) -128;
3561
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3562
      error= 1;
unknown's avatar
unknown committed
3563 3564 3565 3566
    }
    else if (nr > 127.0)
    {
      *ptr=127;
3567
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3568
      error= 1;
unknown's avatar
unknown committed
3569 3570
    }
    else
3571
      *ptr=(uchar) (int) nr;
unknown's avatar
unknown committed
3572
  }
3573
  return error;
unknown's avatar
unknown committed
3574 3575
}

3576 3577

int Field_tiny::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
3578
{
3579
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
3580
  int error= 0;
3581

unknown's avatar
unknown committed
3582 3583
  if (unsigned_flag)
  {
3584
    if (nr < 0 && !unsigned_val)
unknown's avatar
unknown committed
3585
    {
3586
      *ptr= 0;
3587
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3588
      error= 1;
unknown's avatar
unknown committed
3589
    }
3590
    else if ((ulonglong) nr > (ulonglong) 255)
unknown's avatar
unknown committed
3591 3592
    {
      *ptr= (char) 255;
3593
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3594
      error= 1;
unknown's avatar
unknown committed
3595 3596 3597 3598 3599 3600
    }
    else
      *ptr=(char) nr;
  }
  else
  {
3601 3602 3603
    if (nr < 0 && unsigned_val)
      nr= 256;                                    // Generate overflow
    if (nr < -128)
unknown's avatar
unknown committed
3604 3605
    {
      *ptr= (char) -128;
3606
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3607
      error= 1;
unknown's avatar
unknown committed
3608
    }
3609
    else if (nr > 127)
unknown's avatar
unknown committed
3610 3611
    {
      *ptr=127;
3612
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3613
      error= 1;
unknown's avatar
unknown committed
3614 3615 3616 3617
    }
    else
      *ptr=(char) nr;
  }
3618
  return error;
unknown's avatar
unknown committed
3619 3620 3621 3622 3623
}


double Field_tiny::val_real(void)
{
3624
  ASSERT_COLUMN_MARKED_FOR_READ;
3625
  int tmp= unsigned_flag ? (int) ptr[0] :
unknown's avatar
unknown committed
3626 3627 3628 3629
    (int) ((signed char*) ptr)[0];
  return (double) tmp;
}

3630

unknown's avatar
unknown committed
3631 3632
longlong Field_tiny::val_int(void)
{
3633
  ASSERT_COLUMN_MARKED_FOR_READ;
3634
  int tmp= unsigned_flag ? (int) ptr[0] :
unknown's avatar
unknown committed
3635 3636 3637 3638
    (int) ((signed char*) ptr)[0];
  return (longlong) tmp;
}

3639

unknown's avatar
unknown committed
3640 3641 3642
String *Field_tiny::val_str(String *val_buffer,
			    String *val_ptr __attribute__((unused)))
{
3643
  ASSERT_COLUMN_MARKED_FOR_READ;
3644
  CHARSET_INFO *cs= &my_charset_numeric;
unknown's avatar
unknown committed
3645
  uint length;
3646
  uint mlength=MY_MAX(field_length+1,5*cs->mbmaxlen);
3647
  val_buffer->alloc(mlength);
unknown's avatar
unknown committed
3648
  char *to=(char*) val_buffer->ptr();
3649

unknown's avatar
unknown committed
3650
  if (unsigned_flag)
3651
    length= (uint) cs->cset->long10_to_str(cs,to,mlength, 10,
3652
					   (long) *ptr);
unknown's avatar
unknown committed
3653
  else
3654 3655
    length= (uint) cs->cset->long10_to_str(cs,to,mlength,-10,
					   (long) *((signed char*) ptr));
3656
  
unknown's avatar
unknown committed
3657 3658 3659
  val_buffer->length(length);
  if (zerofill)
    prepend_zeros(val_buffer);
3660
  val_buffer->set_charset(cs);
unknown's avatar
unknown committed
3661 3662 3663
  return val_buffer;
}

3664 3665 3666 3667
bool Field_tiny::send_binary(Protocol *protocol)
{
  return protocol->store_tiny((longlong) (int8) ptr[0]);
}
unknown's avatar
unknown committed
3668

3669
int Field_tiny::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
3670 3671 3672 3673 3674 3675 3676 3677
{
  signed char a,b;
  a=(signed char) a_ptr[0]; b= (signed char) b_ptr[0];
  if (unsigned_flag)
    return ((uchar) a < (uchar) b) ? -1 : ((uchar) a > (uchar) b) ? 1 : 0;
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

3678
void Field_tiny::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
3679 3680 3681 3682
{
  if (unsigned_flag)
    *to= *ptr;
  else
3683
    to[0] = (char) (ptr[0] ^ (uchar) 128);	/* Revers signbit */
unknown's avatar
unknown committed
3684 3685 3686 3687
}

void Field_tiny::sql_type(String &res) const
{
unknown's avatar
unknown committed
3688
  CHARSET_INFO *cs=res.charset();
3689
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
3690
			  "tinyint(%d)",(int) field_length));
unknown's avatar
unknown committed
3691 3692 3693 3694
  add_zerofill_and_unsigned(res);
}

/****************************************************************************
3695
 Field type short int (2 byte)
unknown's avatar
unknown committed
3696 3697
****************************************************************************/

unknown's avatar
unknown committed
3698
int Field_short::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
3699
{
3700
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
3701
  int store_tmp;
3702
  int error;
unknown's avatar
unknown committed
3703 3704 3705 3706
  longlong rnd;
  
  error= get_int(cs, from, len, &rnd, UINT_MAX16, INT_MIN16, INT_MAX16);
  store_tmp= unsigned_flag ? (int) (ulonglong) rnd : (int) rnd;
Sergei Golubchik's avatar
Sergei Golubchik committed
3707
  int2store(ptr, store_tmp);
3708
  return error;
unknown's avatar
unknown committed
3709 3710 3711
}


unknown's avatar
unknown committed
3712
int Field_short::store(double nr)
unknown's avatar
unknown committed
3713
{
3714
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
3715
  int error= 0;
unknown's avatar
unknown committed
3716 3717 3718 3719 3720 3721 3722
  int16 res;
  nr=rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0)
    {
      res=0;
3723
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3724
      error= 1;
unknown's avatar
unknown committed
3725
    }
unknown's avatar
unknown committed
3726
    else if (nr > (double) UINT_MAX16)
unknown's avatar
unknown committed
3727
    {
unknown's avatar
unknown committed
3728
      res=(int16) UINT_MAX16;
3729
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3730
      error= 1;
unknown's avatar
unknown committed
3731 3732 3733 3734 3735 3736 3737 3738 3739
    }
    else
      res=(int16) (uint16) nr;
  }
  else
  {
    if (nr < (double) INT_MIN16)
    {
      res=INT_MIN16;
3740
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3741
      error= 1;
unknown's avatar
unknown committed
3742 3743 3744 3745
    }
    else if (nr > (double) INT_MAX16)
    {
      res=INT_MAX16;
3746
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3747
      error= 1;
unknown's avatar
unknown committed
3748 3749
    }
    else
unknown's avatar
unknown committed
3750
      res=(int16) (int) nr;
unknown's avatar
unknown committed
3751
  }
Sergei Golubchik's avatar
Sergei Golubchik committed
3752
  int2store(ptr,res);
3753
  return error;
unknown's avatar
unknown committed
3754 3755
}

3756 3757

int Field_short::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
3758
{
3759
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
3760
  int error= 0;
unknown's avatar
unknown committed
3761
  int16 res;
3762

unknown's avatar
unknown committed
3763 3764
  if (unsigned_flag)
  {
3765
    if (nr < 0L && !unsigned_val)
unknown's avatar
unknown committed
3766 3767
    {
      res=0;
3768
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3769
      error= 1;
unknown's avatar
unknown committed
3770
    }
3771
    else if ((ulonglong) nr > (ulonglong) UINT_MAX16)
unknown's avatar
unknown committed
3772
    {
unknown's avatar
unknown committed
3773
      res=(int16) UINT_MAX16;
3774
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3775
      error= 1;
unknown's avatar
unknown committed
3776 3777 3778 3779 3780 3781
    }
    else
      res=(int16) (uint16) nr;
  }
  else
  {
3782 3783 3784
    if (nr < 0 && unsigned_val)
      nr= UINT_MAX16+1;                         // Generate overflow

unknown's avatar
unknown committed
3785 3786 3787
    if (nr < INT_MIN16)
    {
      res=INT_MIN16;
3788
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3789
      error= 1;
unknown's avatar
unknown committed
3790
    }
3791
    else if (nr > (longlong) INT_MAX16)
unknown's avatar
unknown committed
3792 3793
    {
      res=INT_MAX16;
3794
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3795
      error= 1;
unknown's avatar
unknown committed
3796 3797 3798 3799
    }
    else
      res=(int16) nr;
  }
Sergei Golubchik's avatar
Sergei Golubchik committed
3800
  int2store(ptr,res);
3801
  return error;
unknown's avatar
unknown committed
3802 3803 3804 3805 3806
}


double Field_short::val_real(void)
{
3807
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3808
  short j;
Sergei Golubchik's avatar
Sergei Golubchik committed
3809
  j=sint2korr(ptr);
unknown's avatar
unknown committed
3810 3811 3812 3813 3814
  return unsigned_flag ? (double) (unsigned short) j : (double) j;
}

longlong Field_short::val_int(void)
{
3815
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3816
  short j;
Sergei Golubchik's avatar
Sergei Golubchik committed
3817
  j=sint2korr(ptr);
unknown's avatar
unknown committed
3818 3819 3820
  return unsigned_flag ? (longlong) (unsigned short) j : (longlong) j;
}

3821

unknown's avatar
unknown committed
3822 3823 3824
String *Field_short::val_str(String *val_buffer,
			     String *val_ptr __attribute__((unused)))
{
3825
  ASSERT_COLUMN_MARKED_FOR_READ;
3826
  CHARSET_INFO *cs= &my_charset_numeric;
unknown's avatar
unknown committed
3827
  uint length;
3828
  uint mlength=MY_MAX(field_length+1,7*cs->mbmaxlen);
3829
  val_buffer->alloc(mlength);
unknown's avatar
unknown committed
3830 3831
  char *to=(char*) val_buffer->ptr();
  short j;
Sergei Golubchik's avatar
Sergei Golubchik committed
3832
  j=sint2korr(ptr);
unknown's avatar
unknown committed
3833 3834

  if (unsigned_flag)
3835 3836
    length=(uint) cs->cset->long10_to_str(cs, to, mlength, 10, 
					  (long) (uint16) j);
unknown's avatar
unknown committed
3837
  else
3838
    length=(uint) cs->cset->long10_to_str(cs, to, mlength,-10, (long) j);
unknown's avatar
unknown committed
3839 3840 3841
  val_buffer->length(length);
  if (zerofill)
    prepend_zeros(val_buffer);
3842
  val_buffer->set_charset(cs);
unknown's avatar
unknown committed
3843 3844 3845 3846
  return val_buffer;
}


3847 3848 3849 3850 3851 3852
bool Field_short::send_binary(Protocol *protocol)
{
  return protocol->store_short(Field_short::val_int());
}


3853
int Field_short::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
3854 3855
{
  short a,b;
Sergei Golubchik's avatar
Sergei Golubchik committed
3856 3857
  a=sint2korr(a_ptr);
  b=sint2korr(b_ptr);
unknown's avatar
unknown committed
3858 3859 3860 3861 3862 3863 3864

  if (unsigned_flag)
    return ((unsigned short) a < (unsigned short) b) ? -1 :
    ((unsigned short) a > (unsigned short) b) ? 1 : 0;
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

3865
void Field_short::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
3866
{
Sergei Golubchik's avatar
Sergei Golubchik committed
3867 3868
  if (unsigned_flag)
    to[0] = ptr[1];
unknown's avatar
unknown committed
3869
  else
Sergei Golubchik's avatar
Sergei Golubchik committed
3870 3871
    to[0] = (char) (ptr[1] ^ 128);              /* Revers signbit */
  to[1]   = ptr[0];
unknown's avatar
unknown committed
3872 3873 3874 3875
}

void Field_short::sql_type(String &res) const
{
unknown's avatar
unknown committed
3876
  CHARSET_INFO *cs=res.charset();
3877
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
3878
			  "smallint(%d)",(int) field_length));
unknown's avatar
unknown committed
3879 3880 3881 3882 3883
  add_zerofill_and_unsigned(res);
}


/****************************************************************************
3884
  Field type medium int (3 byte)
unknown's avatar
unknown committed
3885 3886
****************************************************************************/

unknown's avatar
unknown committed
3887
int Field_medium::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
3888
{
3889
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
3890
  int store_tmp;
3891
  int error;
unknown's avatar
unknown committed
3892 3893 3894 3895 3896
  longlong rnd;
  
  error= get_int(cs, from, len, &rnd, UINT_MAX24, INT_MIN24, INT_MAX24);
  store_tmp= unsigned_flag ? (int) (ulonglong) rnd : (int) rnd;
  int3store(ptr, store_tmp);
3897
  return error;
unknown's avatar
unknown committed
3898 3899 3900
}


unknown's avatar
unknown committed
3901
int Field_medium::store(double nr)
unknown's avatar
unknown committed
3902
{
3903
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
3904
  int error= 0;
unknown's avatar
unknown committed
3905 3906 3907 3908 3909 3910
  nr=rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0)
    {
      int3store(ptr,0);
3911
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3912
      error= 1;
unknown's avatar
unknown committed
3913 3914 3915
    }
    else if (nr >= (double) (long) (1L << 24))
    {
unknown's avatar
unknown committed
3916
      uint32 tmp=(uint32) (1L << 24)-1L;
unknown's avatar
unknown committed
3917
      int3store(ptr,tmp);
3918
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3919
      error= 1;
unknown's avatar
unknown committed
3920 3921
    }
    else
unknown's avatar
unknown committed
3922
      int3store(ptr,(uint32) nr);
unknown's avatar
unknown committed
3923 3924 3925 3926 3927 3928 3929
  }
  else
  {
    if (nr < (double) INT_MIN24)
    {
      long tmp=(long) INT_MIN24;
      int3store(ptr,tmp);
3930
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3931
      error= 1;
unknown's avatar
unknown committed
3932 3933 3934 3935 3936
    }
    else if (nr > (double) INT_MAX24)
    {
      long tmp=(long) INT_MAX24;
      int3store(ptr,tmp);
3937
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3938
      error= 1;
unknown's avatar
unknown committed
3939 3940 3941 3942
    }
    else
      int3store(ptr,(long) nr);
  }
3943
  return error;
unknown's avatar
unknown committed
3944 3945
}

3946 3947

int Field_medium::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
3948
{
3949
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
3950
  int error= 0;
3951

unknown's avatar
unknown committed
3952 3953
  if (unsigned_flag)
  {
3954
    if (nr < 0 && !unsigned_val)
unknown's avatar
unknown committed
3955 3956
    {
      int3store(ptr,0);
3957
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3958
      error= 1;
unknown's avatar
unknown committed
3959
    }
3960
    else if ((ulonglong) nr >= (ulonglong) (long) (1L << 24))
unknown's avatar
unknown committed
3961
    {
3962
      long tmp= (long) (1L << 24)-1L;
unknown's avatar
unknown committed
3963
      int3store(ptr,tmp);
3964
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3965
      error= 1;
unknown's avatar
unknown committed
3966 3967
    }
    else
unknown's avatar
unknown committed
3968
      int3store(ptr,(uint32) nr);
unknown's avatar
unknown committed
3969 3970 3971
  }
  else
  {
3972 3973 3974
    if (nr < 0 && unsigned_val)
      nr= (ulonglong) (long) (1L << 24);        // Generate overflow

unknown's avatar
unknown committed
3975 3976
    if (nr < (longlong) INT_MIN24)
    {
3977
      long tmp= (long) INT_MIN24;
unknown's avatar
unknown committed
3978
      int3store(ptr,tmp);
3979
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3980
      error= 1;
unknown's avatar
unknown committed
3981 3982 3983 3984 3985
    }
    else if (nr > (longlong) INT_MAX24)
    {
      long tmp=(long) INT_MAX24;
      int3store(ptr,tmp);
3986
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3987
      error= 1;
unknown's avatar
unknown committed
3988 3989 3990 3991
    }
    else
      int3store(ptr,(long) nr);
  }
3992
  return error;
unknown's avatar
unknown committed
3993 3994 3995 3996 3997
}


double Field_medium::val_real(void)
{
3998
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3999 4000 4001 4002
  long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
  return (double) j;
}

4003

unknown's avatar
unknown committed
4004 4005
longlong Field_medium::val_int(void)
{
4006
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4007 4008 4009 4010
  long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
  return (longlong) j;
}

4011

unknown's avatar
unknown committed
4012 4013 4014
String *Field_medium::val_str(String *val_buffer,
			      String *val_ptr __attribute__((unused)))
{
4015
  ASSERT_COLUMN_MARKED_FOR_READ;
4016
  CHARSET_INFO *cs= &my_charset_numeric;
unknown's avatar
unknown committed
4017
  uint length;
4018
  uint mlength=MY_MAX(field_length+1,10*cs->mbmaxlen);
4019
  val_buffer->alloc(mlength);
unknown's avatar
unknown committed
4020 4021 4022
  char *to=(char*) val_buffer->ptr();
  long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);

4023
  length=(uint) cs->cset->long10_to_str(cs,to,mlength,-10,j);
unknown's avatar
unknown committed
4024 4025 4026
  val_buffer->length(length);
  if (zerofill)
    prepend_zeros(val_buffer); /* purecov: inspected */
4027
  val_buffer->set_charset(cs);
unknown's avatar
unknown committed
4028 4029 4030 4031
  return val_buffer;
}


4032 4033
bool Field_medium::send_binary(Protocol *protocol)
{
4034
  ASSERT_COLUMN_MARKED_FOR_READ;
4035 4036 4037 4038
  return protocol->store_long(Field_medium::val_int());
}


4039
int Field_medium::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054
{
  long a,b;
  if (unsigned_flag)
  {
    a=uint3korr(a_ptr);
    b=uint3korr(b_ptr);
  }
  else
  {
    a=sint3korr(a_ptr);
    b=sint3korr(b_ptr);
  }
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

4055
void Field_medium::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067
{
  if (unsigned_flag)
    to[0] = ptr[2];
  else
    to[0] = (uchar) (ptr[2] ^ 128);		/* Revers signbit */
  to[1] = ptr[1];
  to[2] = ptr[0];
}


void Field_medium::sql_type(String &res) const
{
unknown's avatar
unknown committed
4068
  CHARSET_INFO *cs=res.charset();
4069
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(), 
4070
			  "mediumint(%d)",(int) field_length));
unknown's avatar
unknown committed
4071 4072 4073 4074 4075 4076 4077
  add_zerofill_and_unsigned(res);
}

/****************************************************************************
** long int
****************************************************************************/

unknown's avatar
unknown committed
4078
int Field_long::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
4079
{
4080
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
4081 4082
  long store_tmp;
  int error;
unknown's avatar
unknown committed
4083 4084 4085 4086
  longlong rnd;
  
  error= get_int(cs, from, len, &rnd, UINT_MAX32, INT_MIN32, INT_MAX32);
  store_tmp= unsigned_flag ? (long) (ulonglong) rnd : (long) rnd;
Sergei Golubchik's avatar
Sergei Golubchik committed
4087
  int4store(ptr, store_tmp);
4088
  return error;
unknown's avatar
unknown committed
4089 4090 4091
}


unknown's avatar
unknown committed
4092
int Field_long::store(double nr)
unknown's avatar
unknown committed
4093
{
4094
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
4095
  int error= 0;
unknown's avatar
unknown committed
4096 4097 4098 4099 4100 4101 4102
  int32 res;
  nr=rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0)
    {
      res=0;
unknown's avatar
unknown committed
4103
      error= 1;
unknown's avatar
unknown committed
4104
    }
4105
    else if (nr > (double) UINT_MAX32)
unknown's avatar
unknown committed
4106
    {
4107
      res= UINT_MAX32;
4108
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
4109
      error= 1;
unknown's avatar
unknown committed
4110 4111 4112 4113 4114 4115 4116 4117 4118
    }
    else
      res=(int32) (ulong) nr;
  }
  else
  {
    if (nr < (double) INT_MIN32)
    {
      res=(int32) INT_MIN32;
unknown's avatar
unknown committed
4119
      error= 1;
unknown's avatar
unknown committed
4120 4121 4122 4123
    }
    else if (nr > (double) INT_MAX32)
    {
      res=(int32) INT_MAX32;
unknown's avatar
unknown committed
4124
      error= 1;
unknown's avatar
unknown committed
4125 4126
    }
    else
unknown's avatar
unknown committed
4127
      res=(int32) (longlong) nr;
unknown's avatar
unknown committed
4128
  }
unknown's avatar
unknown committed
4129
  if (error)
4130
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
4131

Sergei Golubchik's avatar
Sergei Golubchik committed
4132
  int4store(ptr,res);
4133
  return error;
unknown's avatar
unknown committed
4134 4135 4136
}


4137
int Field_long::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
4138
{
4139
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
4140
  int error= 0;
unknown's avatar
unknown committed
4141
  int32 res;
unknown's avatar
unknown committed
4142

unknown's avatar
unknown committed
4143 4144
  if (unsigned_flag)
  {
4145
    if (nr < 0 && !unsigned_val)
unknown's avatar
unknown committed
4146 4147
    {
      res=0;
unknown's avatar
unknown committed
4148
      error= 1;
unknown's avatar
unknown committed
4149
    }
4150
    else if ((ulonglong) nr >= (1LL << 32))
unknown's avatar
unknown committed
4151 4152
    {
      res=(int32) (uint32) ~0L;
unknown's avatar
unknown committed
4153
      error= 1;
unknown's avatar
unknown committed
4154 4155 4156 4157 4158 4159
    }
    else
      res=(int32) (uint32) nr;
  }
  else
  {
4160
    if (nr < 0 && unsigned_val)
4161
      nr= ((longlong) INT_MAX32) + 1;           // Generate overflow
4162
    if (nr < (longlong) INT_MIN32) 
unknown's avatar
unknown committed
4163 4164
    {
      res=(int32) INT_MIN32;
unknown's avatar
unknown committed
4165
      error= 1;
unknown's avatar
unknown committed
4166 4167 4168 4169
    }
    else if (nr > (longlong) INT_MAX32)
    {
      res=(int32) INT_MAX32;
unknown's avatar
unknown committed
4170
      error= 1;
unknown's avatar
unknown committed
4171 4172 4173 4174
    }
    else
      res=(int32) nr;
  }
unknown's avatar
unknown committed
4175
  if (error)
4176
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
4177

Sergei Golubchik's avatar
Sergei Golubchik committed
4178
  int4store(ptr,res);
4179
  return error;
unknown's avatar
unknown committed
4180 4181 4182 4183 4184
}


double Field_long::val_real(void)
{
4185
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4186
  int32 j;
Sergei Golubchik's avatar
Sergei Golubchik committed
4187
  j=sint4korr(ptr);
unknown's avatar
unknown committed
4188 4189 4190 4191 4192
  return unsigned_flag ? (double) (uint32) j : (double) j;
}

longlong Field_long::val_int(void)
{
4193
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4194
  int32 j;
4195
  /* See the comment in Field_long::store(long long) */
4196
  DBUG_ASSERT(!table || table->in_use == current_thd);
Sergei Golubchik's avatar
Sergei Golubchik committed
4197
  j=sint4korr(ptr);
unknown's avatar
unknown committed
4198 4199 4200 4201 4202 4203
  return unsigned_flag ? (longlong) (uint32) j : (longlong) j;
}

String *Field_long::val_str(String *val_buffer,
			    String *val_ptr __attribute__((unused)))
{
4204
  ASSERT_COLUMN_MARKED_FOR_READ;
4205
  CHARSET_INFO *cs= &my_charset_numeric;
unknown's avatar
unknown committed
4206
  uint length;
4207
  uint mlength=MY_MAX(field_length+1,12*cs->mbmaxlen);
4208
  val_buffer->alloc(mlength);
unknown's avatar
unknown committed
4209 4210
  char *to=(char*) val_buffer->ptr();
  int32 j;
Sergei Golubchik's avatar
Sergei Golubchik committed
4211
  j=sint4korr(ptr);
unknown's avatar
unknown committed
4212

4213
  if (unsigned_flag)
4214
    length=cs->cset->long10_to_str(cs,to,mlength, 10,(long) (uint32)j);
4215
  else
4216
    length=cs->cset->long10_to_str(cs,to,mlength,-10,(long) j);
unknown's avatar
unknown committed
4217 4218 4219
  val_buffer->length(length);
  if (zerofill)
    prepend_zeros(val_buffer);
4220
  val_buffer->set_charset(cs);
unknown's avatar
unknown committed
4221 4222 4223 4224
  return val_buffer;
}


4225 4226
bool Field_long::send_binary(Protocol *protocol)
{
4227
  ASSERT_COLUMN_MARKED_FOR_READ;
4228 4229 4230
  return protocol->store_long(Field_long::val_int());
}

4231
int Field_long::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
4232 4233
{
  int32 a,b;
Sergei Golubchik's avatar
Sergei Golubchik committed
4234 4235
  a=sint4korr(a_ptr);
  b=sint4korr(b_ptr);
unknown's avatar
unknown committed
4236
  if (unsigned_flag)
unknown's avatar
unknown committed
4237
    return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
unknown's avatar
unknown committed
4238 4239 4240
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

4241
void Field_long::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
4242
{
Sergei Golubchik's avatar
Sergei Golubchik committed
4243 4244
  if (unsigned_flag)
    to[0] = ptr[3];
unknown's avatar
unknown committed
4245
  else
Sergei Golubchik's avatar
Sergei Golubchik committed
4246 4247 4248 4249
    to[0] = (char) (ptr[3] ^ 128);              /* Revers signbit */
  to[1]   = ptr[2];
  to[2]   = ptr[1];
  to[3]   = ptr[0];
unknown's avatar
unknown committed
4250 4251 4252 4253 4254
}


void Field_long::sql_type(String &res) const
{
unknown's avatar
unknown committed
4255
  CHARSET_INFO *cs=res.charset();
4256
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
4257
			  "int(%d)",(int) field_length));
unknown's avatar
unknown committed
4258 4259 4260 4261
  add_zerofill_and_unsigned(res);
}

/****************************************************************************
4262
 Field type longlong int (8 bytes)
unknown's avatar
unknown committed
4263 4264
****************************************************************************/

unknown's avatar
unknown committed
4265
int Field_longlong::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
4266
{
4267
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
4268
  int error= 0;
4269
  char *end;
4270
  ulonglong tmp;
4271

4272 4273
  tmp= cs->cset->strntoull10rnd(cs,from,len,unsigned_flag,&end,&error);
  if (error == MY_ERRNO_ERANGE)
4274
  {
4275
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
4276 4277
    error= 1;
  }
4278
  else if (get_thd()->count_cuted_fields && 
unknown's avatar
unknown committed
4279
           check_int(cs, from, len, end, error))
4280 4281 4282
    error= 1;
  else
    error= 0;
Sergei Golubchik's avatar
Sergei Golubchik committed
4283
  int8store(ptr,tmp);
4284
  return error;
unknown's avatar
unknown committed
4285 4286 4287
}


unknown's avatar
unknown committed
4288
int Field_longlong::store(double nr)
unknown's avatar
unknown committed
4289
{
4290
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
4291
  Converter_double_to_longlong conv(nr, unsigned_flag);
unknown's avatar
unknown committed
4292

4293
  if (conv.error())
4294
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
4295

4296 4297
  int8store(ptr, conv.result());
  return conv.error();
unknown's avatar
unknown committed
4298 4299 4300
}


4301
int Field_longlong::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
4302
{
4303
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314
  int error= 0;

  if (nr < 0)                                   // Only possible error
  {
    /*
      if field is unsigned and value is signed (< 0) or
      if field is signed and value is unsigned we have an overflow
    */
    if (unsigned_flag != unsigned_val)
    {
      nr= unsigned_flag ? (ulonglong) 0 : (ulonglong) LONGLONG_MAX;
4315
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
4316 4317 4318 4319
      error= 1;
    }
  }

Sergei Golubchik's avatar
Sergei Golubchik committed
4320
  int8store(ptr,nr);
4321
  return error;
unknown's avatar
unknown committed
4322 4323 4324 4325 4326
}


double Field_longlong::val_real(void)
{
4327
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4328
  longlong j;
Sergei Golubchik's avatar
Sergei Golubchik committed
4329
  j=sint8korr(ptr);
4330 4331 4332 4333 4334 4335 4336
  /* The following is open coded to avoid a bug in gcc 3.3 */
  if (unsigned_flag)
  {
    ulonglong tmp= (ulonglong) j;
    return ulonglong2double(tmp);
  }
  return (double) j;
unknown's avatar
unknown committed
4337 4338
}

4339

unknown's avatar
unknown committed
4340 4341
longlong Field_longlong::val_int(void)
{
4342
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4343
  longlong j;
Sergei Golubchik's avatar
Sergei Golubchik committed
4344
  j=sint8korr(ptr);
unknown's avatar
unknown committed
4345 4346 4347 4348 4349 4350 4351
  return j;
}


String *Field_longlong::val_str(String *val_buffer,
				String *val_ptr __attribute__((unused)))
{
4352
  CHARSET_INFO *cs= &my_charset_numeric;
unknown's avatar
unknown committed
4353
  uint length;
4354
  uint mlength=MY_MAX(field_length+1,22*cs->mbmaxlen);
4355
  val_buffer->alloc(mlength);
unknown's avatar
unknown committed
4356 4357
  char *to=(char*) val_buffer->ptr();
  longlong j;
Sergei Golubchik's avatar
Sergei Golubchik committed
4358
  j=sint8korr(ptr);
unknown's avatar
unknown committed
4359

4360
  length=(uint) (cs->cset->longlong10_to_str)(cs,to,mlength,
unknown's avatar
unknown committed
4361
					unsigned_flag ? 10 : -10, j);
unknown's avatar
unknown committed
4362 4363 4364
  val_buffer->length(length);
  if (zerofill)
    prepend_zeros(val_buffer);
4365
  val_buffer->set_charset(cs);
unknown's avatar
unknown committed
4366 4367 4368 4369
  return val_buffer;
}


4370 4371
bool Field_longlong::send_binary(Protocol *protocol)
{
4372
  ASSERT_COLUMN_MARKED_FOR_READ;
4373 4374 4375 4376
  return protocol->store_longlong(Field_longlong::val_int(), unsigned_flag);
}


4377
int Field_longlong::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
4378 4379
{
  longlong a,b;
Sergei Golubchik's avatar
Sergei Golubchik committed
4380 4381
  a=sint8korr(a_ptr);
  b=sint8korr(b_ptr);
unknown's avatar
unknown committed
4382 4383 4384 4385 4386 4387
  if (unsigned_flag)
    return ((ulonglong) a < (ulonglong) b) ? -1 :
    ((ulonglong) a > (ulonglong) b) ? 1 : 0;
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

4388
void Field_longlong::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
4389
{
Sergei Golubchik's avatar
Sergei Golubchik committed
4390 4391
  if (unsigned_flag)
    to[0] = ptr[7];
unknown's avatar
unknown committed
4392
  else
Sergei Golubchik's avatar
Sergei Golubchik committed
4393 4394 4395 4396 4397 4398 4399 4400
    to[0] = (char) (ptr[7] ^ 128);		/* Revers signbit */
  to[1]   = ptr[6];
  to[2]   = ptr[5];
  to[3]   = ptr[4];
  to[4]   = ptr[3];
  to[5]   = ptr[2];
  to[6]   = ptr[1];
  to[7]   = ptr[0];
unknown's avatar
unknown committed
4401 4402 4403 4404 4405
}


void Field_longlong::sql_type(String &res) const
{
unknown's avatar
unknown committed
4406
  CHARSET_INFO *cs=res.charset();
4407
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
4408
			  "bigint(%d)",(int) field_length));
unknown's avatar
unknown committed
4409 4410 4411
  add_zerofill_and_unsigned(res);
}

unknown's avatar
unknown committed
4412

4413 4414 4415 4416
/*
  Floating-point numbers
 */

unknown's avatar
unknown committed
4417
/****************************************************************************
unknown's avatar
unknown committed
4418
  single precision float
unknown's avatar
unknown committed
4419 4420
****************************************************************************/

unknown's avatar
unknown committed
4421
int Field_float::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
4422
{
unknown's avatar
unknown committed
4423
  int error;
4424
  Field_float::store(get_double(from, len, cs, &error));
unknown's avatar
unknown committed
4425
  return error;
unknown's avatar
unknown committed
4426 4427 4428
}


unknown's avatar
unknown committed
4429
int Field_float::store(double nr)
unknown's avatar
unknown committed
4430
{
4431
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
4432 4433 4434 4435
  int error= truncate_double(&nr, field_length,
                             not_fixed ? NOT_FIXED_DEC : dec,
                             unsigned_flag, FLT_MAX);
  if (error)
unknown's avatar
unknown committed
4436
  {
4437
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
4438 4439 4440 4441 4442
    if (error < 0)                                // Wrong double value
    {
      error= 1;
      set_null();
    }
unknown's avatar
unknown committed
4443
  }
4444
  float j= (float)nr;
4445

Sergei Golubchik's avatar
Sergei Golubchik committed
4446
  float4store(ptr,j);
4447
  return error;
unknown's avatar
unknown committed
4448 4449 4450
}


4451
int Field_float::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
4452
{
4453 4454
  return Field_float::store(unsigned_val ? ulonglong2double((ulonglong) nr) :
                            (double) nr);
unknown's avatar
unknown committed
4455 4456
}

4457

unknown's avatar
unknown committed
4458 4459
double Field_float::val_real(void)
{
4460
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4461
  float j;
Sergei Golubchik's avatar
Sergei Golubchik committed
4462
  float4get(j,ptr);
unknown's avatar
unknown committed
4463 4464 4465 4466 4467 4468
  return ((double) j);
}

longlong Field_float::val_int(void)
{
  float j;
Sergei Golubchik's avatar
Sergei Golubchik committed
4469
  float4get(j,ptr);
4470
  return (longlong) rint(j);
unknown's avatar
unknown committed
4471 4472 4473 4474 4475 4476
}


String *Field_float::val_str(String *val_buffer,
			     String *val_ptr __attribute__((unused)))
{
4477
  ASSERT_COLUMN_MARKED_FOR_READ;
4478
  DBUG_ASSERT(!zerofill || field_length <= MAX_FIELD_CHARLENGTH);
unknown's avatar
unknown committed
4479
  float nr;
Sergei Golubchik's avatar
Sergei Golubchik committed
4480
  float4get(nr,ptr);
unknown's avatar
unknown committed
4481

4482 4483 4484 4485 4486 4487 4488
  uint to_length= 70;
  if (val_buffer->alloc(to_length))
  {
    my_error(ER_OUT_OF_RESOURCES, MYF(0));
    return val_buffer;
  }

unknown's avatar
unknown committed
4489
  char *to=(char*) val_buffer->ptr();
4490
  size_t len;
unknown's avatar
unknown committed
4491

4492
  if (dec >= FLOATING_POINT_DECIMALS)
4493
    len= my_gcvt(nr, MY_GCVT_ARG_FLOAT, to_length - 1, to, NULL);
unknown's avatar
unknown committed
4494 4495
  else
  {
4496
    /*
4497
      We are safe here because the buffer length is 70, and
4498
      fabs(float) < 10^39, dec < FLOATING_POINT_DECIMALS. So the resulting string
4499 4500 4501
      will be not longer than 69 chars + terminating '\0'.
    */
    len= my_fcvt(nr, dec, to, NULL);
unknown's avatar
unknown committed
4502
  }
4503
  val_buffer->length((uint) len);
unknown's avatar
unknown committed
4504 4505
  if (zerofill)
    prepend_zeros(val_buffer);
4506
  val_buffer->set_charset(&my_charset_numeric);
unknown's avatar
unknown committed
4507 4508 4509 4510
  return val_buffer;
}


4511
int Field_float::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
4512 4513
{
  float a,b;
Sergei Golubchik's avatar
Sergei Golubchik committed
4514 4515
  float4get(a,a_ptr);
  float4get(b,b_ptr);
unknown's avatar
unknown committed
4516 4517 4518 4519 4520
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

#define FLT_EXP_DIG (sizeof(float)*8-FLT_MANT_DIG)

4521
void Field_float::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
4522 4523
{
  float nr;
Sergei Golubchik's avatar
Sergei Golubchik committed
4524
  float4get(nr,ptr);
unknown's avatar
unknown committed
4525

4526
  uchar *tmp= to;
unknown's avatar
unknown committed
4527 4528 4529 4530 4531 4532 4533 4534
  if (nr == (float) 0.0)
  {						/* Change to zero string */
    tmp[0]=(uchar) 128;
    bzero((char*) tmp+1,sizeof(nr)-1);
  }
  else
  {
#ifdef WORDS_BIGENDIAN
4535
    memcpy(tmp, &nr, sizeof(nr));
unknown's avatar
unknown committed
4536 4537 4538 4539 4540 4541 4542
#else
    tmp[0]= ptr[3]; tmp[1]=ptr[2]; tmp[2]= ptr[1]; tmp[3]=ptr[0];
#endif
    if (tmp[0] & 128)				/* Negative */
    {						/* make complement */
      uint i;
      for (i=0 ; i < sizeof(nr); i++)
unknown's avatar
unknown committed
4543
	tmp[i]= (uchar) (tmp[i] ^ (uchar) 255);
unknown's avatar
unknown committed
4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556
    }
    else
    {
      ushort exp_part=(((ushort) tmp[0] << 8) | (ushort) tmp[1] |
		       (ushort) 32768);
      exp_part+= (ushort) 1 << (16-1-FLT_EXP_DIG);
      tmp[0]= (uchar) (exp_part >> 8);
      tmp[1]= (uchar) exp_part;
    }
  }
}


4557 4558
bool Field_float::send_binary(Protocol *protocol)
{
4559
  ASSERT_COLUMN_MARKED_FOR_READ;
4560 4561 4562 4563
  return protocol->store((float) Field_float::val_real(), dec, (String*) 0);
}


4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579
/**
   Save the field metadata for float fields.

   Saves the pack length in the first byte.

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/
int Field_float::do_save_field_metadata(uchar *metadata_ptr)
{
  *metadata_ptr= pack_length();
  return 1;
}


unknown's avatar
unknown committed
4580 4581
void Field_float::sql_type(String &res) const
{
4582
  if (dec >= FLOATING_POINT_DECIMALS)
4583
  {
4584
    res.set_ascii(STRING_WITH_LEN("float"));
4585
  }
unknown's avatar
unknown committed
4586
  else
4587
  {
4588
    CHARSET_INFO *cs= res.charset();
4589
    res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
4590
			    "float(%d,%d)",(int) field_length,dec));
4591
  }
unknown's avatar
unknown committed
4592 4593 4594
  add_zerofill_and_unsigned(res);
}

unknown's avatar
unknown committed
4595

unknown's avatar
unknown committed
4596
/****************************************************************************
unknown's avatar
unknown committed
4597
  double precision floating point numbers
unknown's avatar
unknown committed
4598 4599
****************************************************************************/

unknown's avatar
unknown committed
4600
int Field_double::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
4601
{
unknown's avatar
unknown committed
4602
  int error;
4603
  Field_double::store(get_double(from, len, cs, &error));
unknown's avatar
unknown committed
4604
  return error;
unknown's avatar
unknown committed
4605 4606 4607
}


unknown's avatar
unknown committed
4608
int Field_double::store(double nr)
unknown's avatar
unknown committed
4609
{
4610
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
4611 4612 4613 4614
  int error= truncate_double(&nr, field_length,
                             not_fixed ? NOT_FIXED_DEC : dec,
                             unsigned_flag, DBL_MAX);
  if (error)
unknown's avatar
unknown committed
4615
  {
4616
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
4617 4618 4619 4620 4621
    if (error < 0)                                // Wrong double value
    {
      error= 1;
      set_null();
    }
unknown's avatar
unknown committed
4622
  }
4623

Sergei Golubchik's avatar
Sergei Golubchik committed
4624
  float8store(ptr,nr);
4625
  return error;
unknown's avatar
unknown committed
4626 4627 4628
}


4629
int Field_double::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
4630
{
4631 4632
  return Field_double::store(unsigned_val ? ulonglong2double((ulonglong) nr) :
                             (double) nr);
unknown's avatar
unknown committed
4633 4634
}

4635 4636 4637 4638
/*
  If a field has fixed length, truncate the double argument pointed to by 'nr'
  appropriately.
  Also ensure that the argument is within [-max_value; max_value] range.
4639 4640 4641 4642 4643

  return
    0   ok
    -1  Illegal double value
    1   Value was truncated
4644 4645
*/

4646 4647
int truncate_double(double *nr, uint field_length, uint dec,
                    bool unsigned_flag, double max_value)
4648
{
4649
  int error= 0;
4650 4651 4652 4653
  double res= *nr;
  
  if (isnan(res))
  {
4654 4655
    *nr= 0;
    return -1;
4656 4657 4658
  }
  else if (unsigned_flag && res < 0)
  {
4659 4660
    *nr= 0;
    return 1;
4661 4662
  }

4663
  if (dec < FLOATING_POINT_DECIMALS)
4664 4665 4666 4667 4668 4669 4670 4671 4672
  {
    uint order= field_length - dec;
    uint step= array_elements(log_10) - 1;
    max_value= 1.0;
    for (; order > step; order-= step)
      max_value*= log_10[step];
    max_value*= log_10[order];
    max_value-= 1.0 / log_10[dec];

4673 4674 4675 4676 4677 4678
    /* Check for infinity so we don't get NaN in calculations */
    if (!my_isinf(res))
    {
      double tmp= rint((res - floor(res)) * log_10[dec]) / log_10[dec];
      res= floor(res) + tmp;
    }
4679 4680 4681 4682
  }
  
  if (res < -max_value)
  {
4683 4684
    res= -max_value;
    error= 1;
4685 4686 4687 4688
  }
  else if (res > max_value)
  {
    res= max_value;
4689
    error= 1;
4690 4691 4692 4693 4694 4695
  }

  *nr= res;
  return error;
}

4696 4697
/*
  Convert double to longlong / ulonglong.
4698 4699
  If double is outside of the supported range,
  adjust m_result and set m_error.
4700

4701 4702
  @param nr             Number to convert
  @param unsigned_flag  true if result is unsigned
4703 4704
*/

4705 4706 4707 4708
Value_source::
Converter_double_to_longlong::Converter_double_to_longlong(double nr,
                                                           bool unsigned_flag)
  :m_error(false)
4709 4710 4711 4712 4713 4714
{
  nr= rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0)
    {
4715 4716
      m_result= 0;
      m_error= true;
4717 4718 4719
    }
    else if (nr >= (double) ULONGLONG_MAX)
    {
4720 4721
      m_result= ~(longlong) 0;
      m_error= true;
4722 4723
    }
    else
4724
      m_result= (longlong) double2ulonglong(nr);
4725 4726 4727 4728 4729
  }
  else
  {
    if (nr <= (double) LONGLONG_MIN)
    {
4730 4731
      m_result= LONGLONG_MIN;
      m_error= (nr < (double) LONGLONG_MIN);
4732 4733 4734
    }
    else if (nr >= (double) (ulonglong) LONGLONG_MAX)
    {
4735 4736
      m_result= LONGLONG_MAX;
      m_error= (nr > (double) LONGLONG_MAX);
4737 4738
    }
    else
4739
      m_result= (longlong) nr;
4740
  }
4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752
}


void Value_source::
Converter_double_to_longlong::push_warning(THD *thd,
                                           double nr,
                                           bool unsigned_flag)
{
  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                      ER_DATA_OVERFLOW, ER_THD(thd, ER_DATA_OVERFLOW),
                      ErrConvDouble(nr).ptr(),
                      unsigned_flag ? "UNSIGNED INT" : "INT");
4753 4754
}

4755

unknown's avatar
unknown committed
4756 4757 4758 4759 4760 4761
int Field_real::store_decimal(const my_decimal *dm)
{
  double dbl;
  my_decimal2double(E_DEC_FATAL_ERROR, dm, &dbl);
  return store(dbl);
}
unknown's avatar
unknown committed
4762

4763
int Field_real::store_time_dec(MYSQL_TIME *ltime, uint dec_arg)
4764 4765 4766 4767 4768
{
  return store(TIME_to_double(ltime));
}


unknown's avatar
unknown committed
4769 4770
double Field_double::val_real(void)
{
4771
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4772
  double j;
Sergei Golubchik's avatar
Sergei Golubchik committed
4773
  float8get(j,ptr);
unknown's avatar
unknown committed
4774 4775 4776 4777
  return j;
}


unknown's avatar
unknown committed
4778 4779
my_decimal *Field_real::val_decimal(my_decimal *decimal_value)
{
4780
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4781 4782 4783 4784 4785
  double2my_decimal(E_DEC_FATAL_ERROR, val_real(), decimal_value);
  return decimal_value;
}


4786
bool Field_real::get_date(MYSQL_TIME *ltime,ulonglong fuzzydate)
4787 4788 4789
{
  ASSERT_COLUMN_MARKED_FOR_READ;
  double nr= val_real();
Sergei Golubchik's avatar
Sergei Golubchik committed
4790
  return double_to_datetime_with_warn(nr, ltime, fuzzydate, field_name);
4791 4792 4793
}


4794 4795 4796 4797
Item *Field_real::get_equal_const_item(THD *thd, const Context &ctx,
                                       Item *const_item)
{
  if (flags & ZEROFILL_FLAG)
4798
    return Field_num::get_equal_zerofill_const_item(thd, ctx, const_item);
4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813
  switch (ctx.subst_constraint()) {
  case IDENTITY_SUBST:
    if (const_item->decimal_scale() != Field_real::decimals())
    {
      double val= const_item->val_real();
      return new (thd->mem_root) Item_float(thd, val, Field_real::decimals());
    }
    break;
  case ANY_SUBST:
    break;
  }
  return const_item;
}


unknown's avatar
unknown committed
4814 4815 4816
String *Field_double::val_str(String *val_buffer,
			      String *val_ptr __attribute__((unused)))
{
4817
  ASSERT_COLUMN_MARKED_FOR_READ;
4818
  DBUG_ASSERT(!zerofill || field_length <= MAX_FIELD_CHARLENGTH);
unknown's avatar
unknown committed
4819
  double nr;
Sergei Golubchik's avatar
Sergei Golubchik committed
4820
  float8get(nr,ptr);
unknown's avatar
unknown committed
4821

4822 4823 4824 4825 4826 4827
  uint to_length= DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE;
  if (val_buffer->alloc(to_length))
  {
    my_error(ER_OUT_OF_RESOURCES, MYF(0));
    return val_buffer;
  }
unknown's avatar
unknown committed
4828 4829

  char *to=(char*) val_buffer->ptr();
4830
  size_t len;
unknown's avatar
unknown committed
4831

4832
  if (dec >= FLOATING_POINT_DECIMALS)
4833
    len= my_gcvt(nr, MY_GCVT_ARG_DOUBLE, to_length - 1, to, NULL);
unknown's avatar
unknown committed
4834
  else
4835
    len= my_fcvt(nr, dec, to, NULL);
unknown's avatar
unknown committed
4836

4837
  val_buffer->length((uint) len);
unknown's avatar
unknown committed
4838 4839
  if (zerofill)
    prepend_zeros(val_buffer);
4840
  val_buffer->set_charset(&my_charset_numeric);
unknown's avatar
unknown committed
4841 4842 4843
  return val_buffer;
}

4844 4845
bool Field_double::send_binary(Protocol *protocol)
{
unknown's avatar
unknown committed
4846
  return protocol->store((double) Field_double::val_real(), dec, (String*) 0);
4847 4848
}

unknown's avatar
unknown committed
4849

4850
int Field_double::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
4851 4852
{
  double a,b;
Sergei Golubchik's avatar
Sergei Golubchik committed
4853 4854
  float8get(a,a_ptr);
  float8get(b,b_ptr);
unknown's avatar
unknown committed
4855 4856 4857 4858 4859 4860 4861 4862
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}


#define DBL_EXP_DIG (sizeof(double)*8-DBL_MANT_DIG)

/* The following should work for IEEE */

4863
void Field_double::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
4864 4865
{
  double nr;
Sergei Golubchik's avatar
Sergei Golubchik committed
4866
  float8get(nr,ptr);
4867
  change_double_for_sort(nr, to);
unknown's avatar
unknown committed
4868 4869 4870
}


4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887
/**
   Save the field metadata for double fields.

   Saves the pack length in the first byte of the field metadata array
   at index of *metadata_ptr.

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/
int Field_double::do_save_field_metadata(uchar *metadata_ptr)
{
  *metadata_ptr= pack_length();
  return 1;
}


unknown's avatar
unknown committed
4888 4889
void Field_double::sql_type(String &res) const
{
unknown's avatar
unknown committed
4890
  CHARSET_INFO *cs=res.charset();
4891
  if (dec >= FLOATING_POINT_DECIMALS)
4892
  {
4893
    res.set_ascii(STRING_WITH_LEN("double"));
4894
  }
unknown's avatar
unknown committed
4895
  else
4896
  {
4897
    res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
4898
			    "double(%d,%d)",(int) field_length,dec));
4899
  }
unknown's avatar
unknown committed
4900 4901 4902 4903
  add_zerofill_and_unsigned(res);
}


4904 4905
/**
  TIMESTAMP type holds datetime values in range from 1970-01-01 00:00:01 UTC to 
4906 4907 4908 4909
  2038-01-01 00:00:00 UTC stored as number of seconds since Unix 
  Epoch in UTC.
  
  Actually SQL-99 says that we should allow niladic functions (like NOW())
4910 4911 4912
  as defaults for any field. The current limitation (only NOW() and only 
  for TIMESTAMP and DATETIME fields) are because of restricted binary .frm
  format and should go away in the future.
4913 4914 4915 4916 4917 4918 4919 4920
  
  Also because of this limitation of binary .frm format we use 5 different
  unireg_check values with TIMESTAMP field to distinguish various cases of
  DEFAULT or ON UPDATE values. These values are:
  
  TIMESTAMP_OLD_FIELD - old timestamp, if there was not any fields with
    auto-set-on-update (or now() as default) in this table before, then this 
    field has NOW() as default and is updated when row changes, else it is 
unknown's avatar
unknown committed
4921
    field which has 0 as default value and is not automatically updated.
4922
  TIMESTAMP_DN_FIELD - field with NOW() as default but not set on update
4923
    automatically (TIMESTAMP DEFAULT NOW()), not used in Field since 10.2.2
4924 4925 4926 4927
  TIMESTAMP_UN_FIELD - field which is set on update automatically but has not 
    NOW() as default (but it may has 0 or some other const timestamp as 
    default) (TIMESTAMP ON UPDATE NOW()).
  TIMESTAMP_DNUN_FIELD - field which has now() as default and is auto-set on 
4928
    update. (TIMESTAMP DEFAULT NOW() ON UPDATE NOW()), not used in Field since 10.2.2
4929 4930 4931
  NONE - field which is not auto-set on update with some other than NOW() 
    default value (TIMESTAMP DEFAULT 0).

4932
  Note that TIMESTAMP_OLD_FIELDs are never created explicitly now, they are 
4933 4934 4935 4936 4937 4938 4939 4940
  left only for preserving ability to read old tables. Such fields replaced 
  with their newer analogs in CREATE TABLE and in SHOW CREATE TABLE. This is 
  because we want to prefer NONE unireg_check before TIMESTAMP_OLD_FIELD for 
  "TIMESTAMP DEFAULT 'Const'" field. (Old timestamps allowed such 
  specification too but ignored default value for first timestamp, which of 
  course is non-standard.) In most cases user won't notice any change, only
  exception is different behavior of old/new timestamps during ALTER TABLE.
 */
unknown's avatar
unknown committed
4941

4942
Field_timestamp::Field_timestamp(uchar *ptr_arg, uint32 len_arg,
4943
                                 uchar *null_ptr_arg, uchar null_bit_arg,
unknown's avatar
unknown committed
4944 4945
				 enum utype unireg_check_arg,
				 const char *field_name_arg,
4946 4947 4948
				 TABLE_SHARE *share)
  :Field_temporal(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
                  unireg_check_arg, field_name_arg)
unknown's avatar
unknown committed
4949
{
unknown's avatar
unknown committed
4950
  /* For 4.0 MYD and 4.0 InnoDB compatibility */
4951
  flags|= UNSIGNED_FLAG;
4952
  if (unireg_check != NONE)
unknown's avatar
unknown committed
4953
  {
4954
    /*
4955 4956
      We mark the flag with TIMESTAMP_FLAG to indicate to the client that
      this field will be automaticly updated on insert.
4957
    */
unknown's avatar
unknown committed
4958
    flags|= TIMESTAMP_FLAG;
4959 4960
    if (unireg_check != TIMESTAMP_DN_FIELD)
      flags|= ON_UPDATE_NOW_FLAG;
unknown's avatar
unknown committed
4961 4962 4963 4964
  }
}


4965 4966
my_time_t Field_timestamp::get_timestamp(const uchar *pos,
                                         ulong *sec_part) const
4967 4968 4969
{
  ASSERT_COLUMN_MARKED_FOR_READ;
  *sec_part= 0;
4970
  return sint4korr(pos);
4971
}
4972 4973


4974
int Field_timestamp::store_TIME_with_warning(THD *thd, MYSQL_TIME *l_time,
Sergei Golubchik's avatar
Sergei Golubchik committed
4975
                                             const ErrConv *str,
4976
                                             int was_cut,
4977
                                             bool have_smth_to_conv)
unknown's avatar
unknown committed
4978
{
4979
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
4980 4981
  uint error = 0;
  my_time_t timestamp;
4982

4983
  if (MYSQL_TIME_WARN_HAVE_WARNINGS(was_cut) || !have_smth_to_conv)
unknown's avatar
unknown committed
4984 4985
  {
    error= 1;
4986
    set_datetime_warning(WARN_DATA_TRUNCATED,
4987
                         str, MYSQL_TIMESTAMP_DATETIME, 1);
unknown's avatar
unknown committed
4988
  }
4989 4990 4991 4992 4993 4994
  else if (MYSQL_TIME_WARN_HAVE_NOTES(was_cut))
  {
    error= 3;
    set_datetime_warning(Sql_condition::WARN_LEVEL_NOTE, WARN_DATA_TRUNCATED,
                         str, MYSQL_TIMESTAMP_DATETIME, 1);
  }
unknown's avatar
unknown committed
4995
  /* Only convert a correct date (not a zero date) */
4996
  if (have_smth_to_conv && l_time->month)
4997
  {
Sergei Golubchik's avatar
Sergei Golubchik committed
4998 4999
    uint conversion_error;
    timestamp= TIME_to_timestamp(thd, l_time, &conversion_error);
5000 5001
    if (timestamp == 0 && l_time->second_part == 0)
      conversion_error= ER_WARN_DATA_OUT_OF_RANGE;
Sergei Golubchik's avatar
Sergei Golubchik committed
5002
    if (conversion_error)
5003
    {
5004
      set_datetime_warning(conversion_error,
5005
                           str, MYSQL_TIMESTAMP_DATETIME, !error);
5006 5007 5008
      error= 1;
    }
  }
5009 5010 5011 5012 5013 5014
  else
  {
    timestamp= 0;
    l_time->second_part= 0;
  }
  store_TIME(timestamp, l_time->second_part);
5015
  return error;
unknown's avatar
unknown committed
5016 5017
}

unknown's avatar
unknown committed
5018

5019 5020 5021 5022 5023 5024 5025 5026 5027 5028
static bool
copy_or_convert_to_datetime(THD *thd, const MYSQL_TIME *from, MYSQL_TIME *to)
{
  if (from->time_type == MYSQL_TIMESTAMP_TIME)
    return time_to_datetime(thd, from, to);
  *to= *from;
  return false;
}


5029
int Field_timestamp::store_time_dec(MYSQL_TIME *ltime, uint dec)
unknown's avatar
unknown committed
5030
{
5031
  int unused;
Sergei Golubchik's avatar
Sergei Golubchik committed
5032
  ErrConvTime str(ltime);
5033
  THD *thd= get_thd();
5034 5035 5036
  MYSQL_TIME l_time;
  bool valid= !copy_or_convert_to_datetime(thd, ltime, &l_time) &&
              !check_date(&l_time, pack_time(&l_time) != 0,
5037 5038 5039 5040
                          (thd->variables.sql_mode & MODE_NO_ZERO_DATE) |
                                       MODE_NO_ZERO_IN_DATE, &unused);

  return store_TIME_with_warning(thd, &l_time, &str, false, valid);
unknown's avatar
unknown committed
5041 5042 5043
}


5044
int Field_timestamp::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
5045
{
5046
  MYSQL_TIME l_time;
5047 5048
  MYSQL_TIME_STATUS status;
  bool have_smth_to_conv;
Sergei Golubchik's avatar
Sergei Golubchik committed
5049
  ErrConvString str(from, len, cs);
5050
  THD *thd= get_thd();
unknown's avatar
unknown committed
5051

5052
  /* We don't want to store invalid or fuzzy datetime values in TIMESTAMP */
5053
  have_smth_to_conv= !str_to_datetime(cs, from, len, &l_time,
5054 5055
                                      (thd->variables.sql_mode &
                                       MODE_NO_ZERO_DATE) |
5056 5057 5058
                                       MODE_NO_ZERO_IN_DATE, &status);
  return store_TIME_with_warning(thd, &l_time, &str,
                                 status.warnings, have_smth_to_conv);
5059 5060
}

unknown's avatar
unknown committed
5061

unknown's avatar
unknown committed
5062
int Field_timestamp::store(double nr)
unknown's avatar
unknown committed
5063
{
5064 5065
  MYSQL_TIME l_time;
  int error;
Sergei Golubchik's avatar
Sergei Golubchik committed
5066
  ErrConvDouble str(nr);
5067
  THD *thd= get_thd();
5068

5069
  longlong tmp= double_to_datetime(nr, &l_time, (thd->variables.sql_mode &
5070 5071
                                                 MODE_NO_ZERO_DATE) |
                                   MODE_NO_ZERO_IN_DATE, &error);
Sergei Golubchik's avatar
Sergei Golubchik committed
5072
  return store_TIME_with_warning(thd, &l_time, &str, error, tmp != -1);
unknown's avatar
unknown committed
5073
}
5074

5075

5076
int Field_timestamp::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
5077
{
5078
  MYSQL_TIME l_time;
5079
  int error;
Alexander Barkov's avatar
Alexander Barkov committed
5080
  ErrConvInteger str(nr, unsigned_val);
5081
  THD *thd= get_thd();
unknown's avatar
unknown committed
5082

5083
  /* We don't want to store invalid or fuzzy datetime values in TIMESTAMP */
5084
  longlong tmp= number_to_datetime(nr, 0, &l_time, (thd->variables.sql_mode &
5085 5086
                                                 MODE_NO_ZERO_DATE) |
                                   MODE_NO_ZERO_IN_DATE, &error);
5087
  return store_TIME_with_warning(thd, &l_time, &str, error, tmp != -1);
unknown's avatar
unknown committed
5088 5089
}

5090

unknown's avatar
unknown committed
5091 5092 5093 5094 5095
double Field_timestamp::val_real(void)
{
  return (double) Field_timestamp::val_int();
}

5096

unknown's avatar
unknown committed
5097 5098
longlong Field_timestamp::val_int(void)
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5099 5100 5101
  MYSQL_TIME ltime;
  if (get_date(&ltime, TIME_NO_ZERO_DATE))
    return 0;
unknown's avatar
unknown committed
5102

Sergei Golubchik's avatar
Sergei Golubchik committed
5103 5104 5105
  return ltime.year * 10000000000LL + ltime.month * 100000000LL +
         ltime.day * 1000000L + ltime.hour * 10000L +
         ltime.minute * 100 + ltime.second;
unknown's avatar
unknown committed
5106 5107 5108
}


unknown's avatar
unknown committed
5109
String *Field_timestamp::val_str(String *val_buffer, String *val_ptr)
unknown's avatar
unknown committed
5110
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5111
  MYSQL_TIME ltime;
5112
  uint32 temp, temp2;
5113
  uint dec;
unknown's avatar
unknown committed
5114
  char *to;
unknown's avatar
unknown committed
5115 5116

  val_buffer->alloc(field_length+1);
unknown's avatar
unknown committed
5117
  to= (char*) val_buffer->ptr();
5118
  val_buffer->length(field_length);
unknown's avatar
unknown committed
5119

Sergei Golubchik's avatar
Sergei Golubchik committed
5120
  if (get_date(&ltime, TIME_NO_ZERO_DATE))
unknown's avatar
unknown committed
5121
  {				      /* Zero time is "000000" */
Sergei Golubchik's avatar
Sergei Golubchik committed
5122
    val_ptr->set(zero_timestamp, field_length, &my_charset_numeric);
5123
    return val_ptr;
unknown's avatar
unknown committed
5124
  }
5125
  val_buffer->set_charset(&my_charset_numeric);	// Safety
Sergei Golubchik's avatar
Sergei Golubchik committed
5126 5127
   
  temp= ltime.year % 100;
5128
  if (temp < YY_PART_YEAR - 1)
5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141
  {
    *to++= '2';
    *to++= '0';
  }
  else
  {
    *to++= '1';
    *to++= '9';
  }
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= '-';
Sergei Golubchik's avatar
Sergei Golubchik committed
5142
  temp=ltime.month;
5143 5144 5145 5146
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= '-';
Sergei Golubchik's avatar
Sergei Golubchik committed
5147
  temp=ltime.day;
5148 5149 5150 5151
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= ' ';
Sergei Golubchik's avatar
Sergei Golubchik committed
5152
  temp=ltime.hour;
5153 5154 5155 5156
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= ':';
Sergei Golubchik's avatar
Sergei Golubchik committed
5157
  temp=ltime.minute;
5158 5159 5160 5161
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= ':';
Sergei Golubchik's avatar
Sergei Golubchik committed
5162
  temp=ltime.second;
5163 5164 5165 5166
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to= 0;
5167
  val_buffer->set_charset(&my_charset_numeric);
5168 5169 5170 5171 5172 5173 5174 5175 5176 5177

  if ((dec= decimals()))
  {
    ulong sec_part= (ulong) sec_part_shift(ltime.second_part, dec);
    char *buf= const_cast<char*>(val_buffer->ptr() + MAX_DATETIME_WIDTH);
    for (int i= dec; i > 0; i--, sec_part/= 10)
    buf[i]= (char)(sec_part % 10) + '0';
    buf[0]= '.';
    buf[dec + 1]= 0;
  }
unknown's avatar
unknown committed
5178 5179 5180
  return val_buffer;
}

5181

5182 5183 5184 5185 5186 5187 5188 5189 5190 5191
bool
Field_timestamp::validate_value_in_record(THD *thd, const uchar *record) const
{
  DBUG_ASSERT(!is_null_in_record(record));
  ulong sec_part;
  return !get_timestamp(ptr_in_record(record), &sec_part) && !sec_part &&
         (sql_mode_for_dates(thd) & TIME_NO_ZERO_DATE) != 0;
}


5192
bool Field_timestamp::get_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
unknown's avatar
unknown committed
5193
{
5194
  THD *thd= get_thd();
5195
  thd->time_zone_used= 1;
5196
  ulong sec_part;
Sergei Golubchik's avatar
Sergei Golubchik committed
5197
  my_time_t temp= get_timestamp(&sec_part);
5198
  if (temp == 0 && sec_part == 0)
unknown's avatar
unknown committed
5199
  {				      /* Zero time is "000000" */
unknown's avatar
unknown committed
5200
    if (fuzzydate & TIME_NO_ZERO_DATE)
unknown's avatar
unknown committed
5201
      return 1;
5202
    set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME);
unknown's avatar
unknown committed
5203 5204 5205
  }
  else
  {
5206
    thd->variables.time_zone->gmt_sec_to_TIME(ltime, (my_time_t)temp);
5207
    ltime->second_part= sec_part;
unknown's avatar
unknown committed
5208 5209 5210 5211
  }
  return 0;
}

5212 5213 5214

bool Field_timestamp::send_binary(Protocol *protocol)
{
5215 5216 5217
  MYSQL_TIME ltime;
  Field_timestamp::get_date(&ltime, 0);
  return protocol->store(&ltime, 0);
5218 5219 5220
}


5221
int Field_timestamp::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
5222 5223
{
  int32 a,b;
Sergei Golubchik's avatar
Sergei Golubchik committed
5224 5225
  a=sint4korr(a_ptr);
  b=sint4korr(b_ptr);
unknown's avatar
unknown committed
5226 5227 5228
  return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
}

5229

5230
void Field_timestamp::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
5231
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5232 5233 5234 5235
  to[0] = ptr[3];
  to[1] = ptr[2];
  to[2] = ptr[1];
  to[3] = ptr[0];
unknown's avatar
unknown committed
5236 5237 5238 5239 5240
}


void Field_timestamp::sql_type(String &res) const
{
5241 5242 5243 5244 5245 5246 5247 5248
  if (!decimals())
  {
    res.set_ascii(STRING_WITH_LEN("timestamp"));
    return;
  }
  CHARSET_INFO *cs=res.charset();
  res.length(cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
                                "timestamp(%u)", decimals()));
unknown's avatar
unknown committed
5249 5250 5251
}


5252
int Field_timestamp::set_time()
unknown's avatar
unknown committed
5253
{
5254
  set_notnull();
5255
  store_TIME(get_thd()->query_start(), 0);
5256
  return 0;
unknown's avatar
unknown committed
5257 5258
}

5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270
/**
  Mark the field as having an explicit default value.

  @param value  if available, the value that the field is being set to

  @note
    Fields that have an explicit default value should not be updated
    automatically via the DEFAULT or ON UPDATE functions. The functions
    that deal with data change functionality (INSERT/UPDATE/LOAD),
    determine if there is an explicit value for each field before performing
    the data change, and call this method to mark the field.

5271 5272 5273 5274 5275
    For timestamp columns, the only case where a column is not marked
    as been given a value are:
    - It's explicitly assigned with DEFAULT
    - We assign NULL to a timestamp field that is defined as NOT NULL.
      This is how MySQL has worked since it's start.
5276 5277
*/

5278 5279
void Field_timestamp::set_explicit_default(Item *value)
{
5280
  if (((value->type() == Item::DEFAULT_VALUE_ITEM &&
5281
        !((Item_default_value*)value)->arg) ||
5282
       (!maybe_null() && value->null_value)))
5283
    return;
5284
  set_has_explicit_value();
5285 5286
}

Sergei Golubchik's avatar
Sergei Golubchik committed
5287
#ifdef NOT_USED
5288
static void store_native(ulonglong num, uchar *to, uint bytes)
unknown's avatar
unknown committed
5289
{
5290 5291 5292 5293 5294 5295 5296
  switch(bytes) {
  case 1: *to= (uchar)num;              break;
  case 2: shortstore(to, (ushort)num);  break;
  case 3: int3store(to, num); /* Sic!*/ break;
  case 4: longstore(to, (ulong)num);    break;
  case 8: longlongstore(to, num);       break;
  default: DBUG_ASSERT(0);
5297
  }
5298
}
5299

5300 5301 5302 5303 5304 5305 5306 5307 5308
static longlong read_native(const uchar *from, uint bytes)
{
  switch(bytes) {
  case 1: return from[0];
  case 2: { uint16 tmp; shortget(tmp, from); return tmp; }
  case 3: return uint3korr(from);
  case 4: { uint32 tmp; longget(tmp, from); return tmp; }
  case 8: { longlong tmp; longlongget(tmp, from); return tmp; }
  default: DBUG_ASSERT(0); return 0;
unknown's avatar
unknown committed
5309 5310
  }
}
Sergei Golubchik's avatar
Sergei Golubchik committed
5311
#endif
unknown's avatar
unknown committed
5312

5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323
static void store_lowendian(ulonglong num, uchar *to, uint bytes)
{
  switch(bytes) {
  case 1: *to= (uchar)num;    break;
  case 2: int2store(to, num); break;
  case 3: int3store(to, num); break;
  case 4: int4store(to, num); break;
  case 8: int8store(to, num); break;
  default: DBUG_ASSERT(0);
  }
}
unknown's avatar
unknown committed
5324

5325
static longlong read_lowendian(const uchar *from, uint bytes)
5326
{
5327 5328 5329 5330 5331 5332 5333 5334
  switch(bytes) {
  case 1: return from[0];
  case 2: return uint2korr(from);
  case 3: return uint3korr(from);
  case 4: return uint4korr(from);
  case 8: return sint8korr(from);
  default: DBUG_ASSERT(0); return 0;
  }
5335 5336
}

5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348
static void store_bigendian(ulonglong num, uchar *to, uint bytes)
{
  switch(bytes) {
  case 1: mi_int1store(to, num); break;
  case 2: mi_int2store(to, num); break;
  case 3: mi_int3store(to, num); break;
  case 4: mi_int4store(to, num); break;
  case 5: mi_int5store(to, num); break;
  case 6: mi_int6store(to, num); break;
  case 7: mi_int7store(to, num); break;
  case 8: mi_int8store(to, num); break;
  default: DBUG_ASSERT(0);
unknown's avatar
unknown committed
5349
  }
5350
}
5351

5352
static longlong read_bigendian(const uchar *from, uint bytes)
unknown's avatar
unknown committed
5353
{
5354 5355 5356 5357 5358 5359 5360 5361 5362 5363
  switch(bytes) {
  case 1: return mi_uint1korr(from);
  case 2: return mi_uint2korr(from);
  case 3: return mi_uint3korr(from);
  case 4: return mi_uint4korr(from);
  case 5: return mi_uint5korr(from);
  case 6: return mi_uint6korr(from);
  case 7: return mi_uint7korr(from);
  case 8: return mi_sint8korr(from);
  default: DBUG_ASSERT(0); return 0;
unknown's avatar
unknown committed
5364
  }
5365 5366 5367 5368 5369 5370 5371 5372
}

void Field_timestamp_hires::store_TIME(my_time_t timestamp, ulong sec_part)
{
  mi_int4store(ptr, timestamp);
  store_bigendian(sec_part_shift(sec_part, dec), ptr+4, sec_part_bytes[dec]);
}

5373 5374
my_time_t Field_timestamp_hires::get_timestamp(const uchar *pos,
                                               ulong *sec_part) const
5375 5376
{
  ASSERT_COLUMN_MARKED_FOR_READ;
5377 5378
  *sec_part= (long)sec_part_unshift(read_bigendian(pos+4, sec_part_bytes[dec]), dec);
  return mi_uint4korr(pos);
5379 5380
}

5381
double Field_timestamp_with_dec::val_real(void)
5382
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5383 5384 5385
  MYSQL_TIME ltime;
  if (get_date(&ltime, TIME_NO_ZERO_DATE))
    return 0;
5386
  
Sergei Golubchik's avatar
Sergei Golubchik committed
5387 5388 5389
  return ltime.year * 1e10 + ltime.month * 1e8 +
         ltime.day * 1e6 + ltime.hour * 1e4 +
         ltime.minute * 1e2 + ltime.second + ltime.second_part*1e-6;
unknown's avatar
unknown committed
5390 5391
}

5392
my_decimal *Field_timestamp_with_dec::val_decimal(my_decimal *d)
5393 5394 5395
{
  MYSQL_TIME ltime;
  get_date(&ltime, 0);
Sergei Golubchik's avatar
Sergei Golubchik committed
5396
  return TIME_to_my_decimal(&ltime, d);
5397 5398
}
 
5399
int Field_timestamp::store_decimal(const my_decimal *d)
5400
{
5401 5402 5403 5404 5405
  ulonglong nr;
  ulong sec_part;
  int error;
  MYSQL_TIME ltime;
  longlong tmp;
5406
  THD *thd= get_thd();
Sergei Golubchik's avatar
Sergei Golubchik committed
5407
  ErrConvDecimal str(d);
5408 5409

  if (my_decimal2seconds(d, &nr, &sec_part))
unknown's avatar
unknown committed
5410
  {
5411 5412
    tmp= -1;
    error= 2;
unknown's avatar
unknown committed
5413
  }
5414 5415
  else
    tmp= number_to_datetime(nr, sec_part, &ltime, TIME_NO_ZERO_IN_DATE |
5416 5417
                            (thd->variables.sql_mode &
                             MODE_NO_ZERO_DATE), &error);
5418 5419

  return store_TIME_with_warning(thd, &ltime, &str, error, tmp != -1);
5420 5421
}

5422
int Field_timestamp_with_dec::set_time()
5423
{
5424
  THD *thd= get_thd();
5425
  set_notnull();
5426 5427
  // Avoid writing microseconds into binlog for FSP=0
  store_TIME(thd->query_start(), decimals() ? thd->query_start_sec_part() : 0);
5428 5429
  return 0;
}
5430

5431
bool Field_timestamp_with_dec::send_binary(Protocol *protocol)
5432 5433 5434 5435
{
  MYSQL_TIME ltime;
  Field_timestamp::get_date(&ltime, 0);
  return protocol->store(&ltime, dec);
unknown's avatar
unknown committed
5436 5437 5438
}


5439 5440 5441 5442 5443
int Field_timestamp_hires::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
  int32 a,b;
  ulong a_sec_part, b_sec_part;
  a= mi_uint4korr(a_ptr);
5444
  a_sec_part= (ulong)read_bigendian(a_ptr+4, sec_part_bytes[dec]);
5445
  b= mi_uint4korr(b_ptr);
5446
  b_sec_part= (ulong)read_bigendian(b_ptr+4, sec_part_bytes[dec]);
5447 5448 5449 5450 5451 5452 5453 5454 5455 5456
  return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 :
          a_sec_part < b_sec_part  ? -1 :  a_sec_part > b_sec_part  ? 1 : 0;
}


uint32 Field_timestamp_hires::pack_length() const
{
  return 4 + sec_part_bytes[dec];
}

5457
void Field_timestamp_with_dec::make_field(Send_field *field)
5458 5459 5460 5461 5462
{
  Field::make_field(field);
  field->decimals= dec;
}

5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477

/*************************************************************
** MySQL-5.6 compatible TIMESTAMP(N)
**************************************************************/

void Field_timestampf::store_TIME(my_time_t timestamp, ulong sec_part)
{
  struct timeval tm;
  tm.tv_sec= timestamp;
  tm.tv_usec= sec_part;
  my_timeval_trunc(&tm, dec);
  my_timestamp_to_binary(&tm, ptr, dec);
}


5478 5479
my_time_t Field_timestampf::get_timestamp(const uchar *pos,
                                          ulong *sec_part) const
5480 5481
{
  struct timeval tm;
5482
  my_timestamp_from_binary(&tm, pos, dec);
5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495
  *sec_part= tm.tv_usec;
  return tm.tv_sec;
}


/*************************************************************/
uint Field_temporal::is_equal(Create_field *new_field)
{
  return new_field->sql_type == real_type() &&
         new_field->length == max_display_length();
}


Sergei Golubchik's avatar
Sergei Golubchik committed
5496
void Field_temporal::set_warnings(Sql_condition::enum_warning_level trunc_level,
5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513
                                  const ErrConv *str, int was_cut,
                                  timestamp_type ts_type)
{
  /*
    error code logic:
    MYSQL_TIME_WARN_TRUNCATED means that the value was not a date/time at all.
      it will be stored as zero date/time.
    MYSQL_TIME_WARN_OUT_OF_RANGE means that the value was a date/time,
      that is, it was parsed as such, but the value was invalid.

    Also, MYSQL_TIME_WARN_TRUNCATED is used when storing a DATETIME in
    a DATE field and non-zero time part is thrown away.
  */
  if (was_cut & MYSQL_TIME_WARN_TRUNCATED)
    set_datetime_warning(trunc_level, WARN_DATA_TRUNCATED,
                         str, mysql_type_to_time_type(type()), 1);
  if (was_cut & MYSQL_TIME_WARN_OUT_OF_RANGE)
5514
    set_datetime_warning(ER_WARN_DATA_OUT_OF_RANGE,
5515 5516 5517 5518
                         str, mysql_type_to_time_type(type()), 1);
}


5519 5520 5521 5522 5523 5524 5525 5526 5527 5528
/*
  Store string into a date/time field

  RETURN
    0  ok
    1  Value was cut during conversion
    2  value was out of range
    3  Datetime value that was cut (warning level NOTE)
       This is used by opt_range.cc:get_mm_leaf().
*/
5529 5530 5531 5532
int Field_temporal_with_date::store_TIME_with_warning(MYSQL_TIME *ltime,
                                                      const ErrConv *str,
                                                      int was_cut,
                                                      int have_smth_to_conv)
5533
{
5534
  Sql_condition::enum_warning_level trunc_level= Sql_condition::WARN_LEVEL_WARN;
5535 5536
  int ret= 2;
  
5537
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
5538

5539 5540
  if (was_cut == 0 && have_smth_to_conv == 0) // special case: zero date
  {
5541
    was_cut= MYSQL_TIME_WARN_OUT_OF_RANGE;
5542 5543
  }
  else if (!have_smth_to_conv)
unknown's avatar
unknown committed
5544
  {
5545 5546 5547
    bzero(ltime, sizeof(*ltime));
    was_cut=  MYSQL_TIME_WARN_TRUNCATED;
    ret= 1;
unknown's avatar
unknown committed
5548
  }
5549 5550 5551 5552
  else if (!MYSQL_TIME_WARN_HAVE_WARNINGS(was_cut) &&
           (MYSQL_TIME_WARN_HAVE_NOTES(was_cut) ||
            (mysql_type_to_time_type(type()) == MYSQL_TIMESTAMP_DATE &&
             (ltime->hour || ltime->minute || ltime->second || ltime->second_part))))
unknown's avatar
unknown committed
5553
  {
5554
    trunc_level= Sql_condition::WARN_LEVEL_NOTE;
5555 5556
    was_cut|=  MYSQL_TIME_WARN_TRUNCATED;
    ret= 3;
unknown's avatar
unknown committed
5557
  }
5558
  set_warnings(trunc_level, str, was_cut, mysql_type_to_time_type(type()));
5559 5560
  store_TIME(ltime);
  return was_cut ? ret : 0;
unknown's avatar
unknown committed
5561 5562 5563
}


5564
int Field_temporal_with_date::store(const char *from, uint len, CHARSET_INFO *cs)
5565 5566
{
  MYSQL_TIME ltime;
5567
  MYSQL_TIME_STATUS status;
5568
  THD *thd= get_thd();
Sergei Golubchik's avatar
Sergei Golubchik committed
5569
  ErrConvString str(from, len, cs);
5570
  bool func_res= !str_to_datetime(cs, from, len, &ltime,
Sergei Golubchik's avatar
Sergei Golubchik committed
5571
                                  sql_mode_for_dates(thd),
5572 5573
                                  &status);
  return store_TIME_with_warning(&ltime, &str, status.warnings, func_res);
5574 5575 5576
}


5577
int Field_temporal_with_date::store(double nr)
unknown's avatar
unknown committed
5578
{
unknown's avatar
unknown committed
5579
  int error= 0;
5580
  MYSQL_TIME ltime;
5581
  THD *thd= get_thd();
Sergei Golubchik's avatar
Sergei Golubchik committed
5582
  ErrConvDouble str(nr);
5583

5584
  longlong tmp= double_to_datetime(nr, &ltime,
Sergei Golubchik's avatar
Sergei Golubchik committed
5585
                                    sql_mode_for_dates(thd), &error);
5586 5587 5588 5589
  return store_TIME_with_warning(&ltime, &str, error, tmp != -1);
}


5590
int Field_temporal_with_date::store(longlong nr, bool unsigned_val)
5591 5592 5593 5594
{
  int error;
  MYSQL_TIME ltime;
  longlong tmp;
5595
  THD *thd= get_thd();
Alexander Barkov's avatar
Alexander Barkov committed
5596
  ErrConvInteger str(nr, unsigned_val);
5597

Sergei Golubchik's avatar
Sergei Golubchik committed
5598
  tmp= number_to_datetime(nr, 0, &ltime, sql_mode_for_dates(thd), &error);
5599 5600 5601 5602 5603

  return store_TIME_with_warning(&ltime, &str, error, tmp != -1);
}


5604
int Field_temporal_with_date::store_time_dec(MYSQL_TIME *ltime, uint dec)
5605
{
5606
  int error= 0, have_smth_to_conv= 1;
Sergei Golubchik's avatar
Sergei Golubchik committed
5607
  ErrConvTime str(ltime);
5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618
  MYSQL_TIME l_time;

  if (copy_or_convert_to_datetime(get_thd(), ltime, &l_time))
  {
    /*
      Set have_smth_to_conv and error in a way to have
      store_TIME_with_warning do bzero().
    */
    have_smth_to_conv= false;
    error= MYSQL_TIME_WARN_OUT_OF_RANGE;
  }
5619 5620 5621 5622 5623 5624 5625 5626 5627
  else
  {
    /*
      We don't perform range checking here since values stored in TIME
      structure always fit into DATETIME range.
    */
    have_smth_to_conv= !check_date(&l_time, pack_time(&l_time) != 0,
                                   sql_mode_for_dates(get_thd()), &error);
  }
5628 5629 5630
  return store_TIME_with_warning(&l_time, &str, error, have_smth_to_conv);
}

5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641

bool
Field_temporal_with_date::validate_value_in_record(THD *thd,
                                                   const uchar *record) const
{
  DBUG_ASSERT(!is_null_in_record(record));
  MYSQL_TIME ltime;
  return get_TIME(&ltime, ptr_in_record(record), sql_mode_for_dates(thd));
}


5642 5643 5644
my_decimal *Field_temporal::val_decimal(my_decimal *d)
{
  MYSQL_TIME ltime;
5645
  if (get_date(&ltime, 0))
unknown's avatar
unknown committed
5646
  {
5647 5648
    bzero(&ltime, sizeof(ltime));
    ltime.time_type= mysql_type_to_time_type(type());
unknown's avatar
unknown committed
5649
  }
Sergei Golubchik's avatar
Sergei Golubchik committed
5650
  return TIME_to_my_decimal(&ltime, d);
5651 5652
}

5653

5654
bool Field_temporal::can_optimize_keypart_ref(const Item_bool_func *cond,
5655 5656 5657 5658 5659 5660
                                              const Item *value) const
{
  return true; // Field is of TIME_RESULT, which supersedes everything else.
}


5661
bool Field_temporal::can_optimize_group_min_max(const Item_bool_func *cond,
5662
                                                const Item *const_item) const
5663 5664 5665 5666 5667
{
  return true; // Field is of TIME_RESULT, which supersedes everything else.
}


5668 5669 5670
Item *Field_temporal::get_equal_const_item_datetime(THD *thd,
                                                    const Context &ctx,
                                                    Item *const_item)
5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682
{
  switch (ctx.subst_constraint()) {
  case IDENTITY_SUBST:
    if ((const_item->field_type() != MYSQL_TYPE_DATETIME &&
         const_item->field_type() != MYSQL_TYPE_TIMESTAMP) ||
        const_item->decimals != decimals())
    {
      MYSQL_TIME ltime;
      if (const_item->field_type() == MYSQL_TYPE_TIME ?
          const_item->get_date_with_conversion(&ltime, 0) :
          const_item->get_date(&ltime, 0))
        return NULL;
5683 5684 5685 5686
      /*
        See comments about truncation in the same place in
        Field_time::get_equal_const_item().
      */
5687 5688 5689 5690 5691
      return new (thd->mem_root) Item_datetime_literal(thd, &ltime,
                                                       decimals());
    }
    break;
  case ANY_SUBST:
5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703
    if (!is_temporal_type_with_date(const_item->field_type()))
    {
      MYSQL_TIME ltime;
      if (const_item->get_date_with_conversion(&ltime,
                                               TIME_FUZZY_DATES |
                                               TIME_INVALID_DATES))
        return NULL;
      return new (thd->mem_root)
        Item_datetime_literal_for_invalid_dates(thd, &ltime,
                                                ltime.second_part ?
                                                TIME_SECOND_PART_DIGITS : 0);
    }
5704 5705 5706 5707 5708 5709
    break;
  }
  return const_item;
}


5710 5711 5712 5713 5714 5715
/****************************************************************************
** time type
** In string context: HH:MM:SS
** In number context: HHMMSS
** Stored as a 3 byte unsigned int
****************************************************************************/
5716 5717 5718 5719 5720
int Field_time::store_TIME_with_warning(MYSQL_TIME *ltime,
                                        const ErrConv *str,
                                        int was_cut,
                                        int have_smth_to_conv)
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5721
  Sql_condition::enum_warning_level trunc_level= Sql_condition::WARN_LEVEL_WARN;
5722 5723 5724 5725 5726 5727 5728 5729 5730
  int ret= 2;
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;

  if (!have_smth_to_conv)
  {
    bzero(ltime, sizeof(*ltime));
    was_cut= MYSQL_TIME_WARN_TRUNCATED;
    ret= 1;
  }
5731 5732 5733
  else if (!MYSQL_TIME_WARN_HAVE_WARNINGS(was_cut) &&
           ((ltime->year || ltime->month) ||
            MYSQL_TIME_WARN_HAVE_NOTES(was_cut)))
5734
  {
5735 5736
    if (ltime->year || ltime->month)
      ltime->year= ltime->month= ltime->day= 0;
Sergei Golubchik's avatar
Sergei Golubchik committed
5737
    trunc_level= Sql_condition::WARN_LEVEL_NOTE;
5738 5739 5740 5741 5742 5743 5744 5745
    was_cut|=  MYSQL_TIME_WARN_TRUNCATED;
    ret= 3;
  }
  set_warnings(trunc_level, str, was_cut, MYSQL_TIMESTAMP_TIME);
  store_TIME(ltime);
  return was_cut ? ret : 0;
}

5746 5747 5748 5749 5750 5751 5752

void Field_time::store_TIME(MYSQL_TIME *ltime)
{
  long tmp= (ltime->day*24L+ltime->hour)*10000L +
            (ltime->minute*100+ltime->second);
  if (ltime->neg)
    tmp= -tmp;
unknown's avatar
unknown committed
5753 5754 5755
  int3store(ptr,tmp);
}

5756 5757 5758
int Field_time::store(const char *from,uint len,CHARSET_INFO *cs)
{
  MYSQL_TIME ltime;
5759
  MYSQL_TIME_STATUS status;
Sergei Golubchik's avatar
Sergei Golubchik committed
5760
  ErrConvString str(from, len, cs);
5761
  bool have_smth_to_conv= 
Sergei Golubchik's avatar
Sergei Golubchik committed
5762
   !str_to_time(cs, from, len, &ltime, sql_mode_for_dates(get_thd()),
5763
                &status);
Sergei Golubchik's avatar
Sergei Golubchik committed
5764

5765 5766
  return store_TIME_with_warning(&ltime, &str,
                                 status.warnings, have_smth_to_conv);
5767 5768 5769
}


5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795
/**
  subtract a given number of days from DATETIME, return TIME

  optimized version of calc_time_diff()

  @note it might generate TIME values outside of the valid TIME range!
*/
static void calc_datetime_days_diff(MYSQL_TIME *ltime, long days)
{
  long daydiff= calc_daynr(ltime->year, ltime->month, ltime->day) - days;
  ltime->year= ltime->month= 0;
  if (daydiff >=0 )
    ltime->day= daydiff;
  else
  {
    longlong timediff= ((((daydiff        * 24LL +
                           ltime->hour)   * 60LL +
                           ltime->minute) * 60LL +
                           ltime->second) * 1000000LL +
                           ltime->second_part);
    unpack_time(timediff, ltime);
  }
  ltime->time_type= MYSQL_TIMESTAMP_TIME;
}


5796
int Field_time::store_time_dec(MYSQL_TIME *ltime, uint dec)
5797 5798
{
  MYSQL_TIME l_time= *ltime;
Sergei Golubchik's avatar
Sergei Golubchik committed
5799
  ErrConvTime str(ltime);
5800 5801
  int was_cut= 0;

5802 5803 5804
  if (curdays && l_time.time_type != MYSQL_TIMESTAMP_TIME)
    calc_datetime_days_diff(&l_time, curdays);

5805
  int have_smth_to_conv= !check_time_range(&l_time, decimals(), &was_cut);
5806 5807 5808 5809 5810 5811 5812
  return store_TIME_with_warning(&l_time, &str, was_cut, have_smth_to_conv);
}


int Field_time::store(double nr)
{
  MYSQL_TIME ltime;
Sergei Golubchik's avatar
Sergei Golubchik committed
5813
  ErrConvDouble str(nr);
5814
  int was_cut;
5815 5816 5817
  bool neg= nr < 0;
  if (neg)
    nr= -nr;
5818
  int have_smth_to_conv= !number_to_time(neg, (ulonglong) nr,
5819
                                         (ulong)((nr - floor(nr)) * TIME_SECOND_PART_FACTOR),
5820
                                         &ltime, &was_cut);
unknown's avatar
unknown committed
5821

5822 5823 5824 5825 5826 5827 5828
  return store_TIME_with_warning(&ltime, &str, was_cut, have_smth_to_conv);
}


int Field_time::store(longlong nr, bool unsigned_val)
{
  MYSQL_TIME ltime;
Alexander Barkov's avatar
Alexander Barkov committed
5829
  ErrConvInteger str(nr, unsigned_val);
5830
  int was_cut;
5831 5832 5833 5834
  if (nr < 0 && unsigned_val)
    nr= 99991231235959LL + 1;
  int have_smth_to_conv= !number_to_time(nr < 0,
                                         (ulonglong) (nr < 0 ? -nr : nr),
5835
                                         0, &ltime, &was_cut);
unknown's avatar
unknown committed
5836

5837
  return store_TIME_with_warning(&ltime, &str, was_cut, have_smth_to_conv);
unknown's avatar
unknown committed
5838
}
5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862


void Field_time::set_curdays(THD *thd)
{
  MYSQL_TIME ltime;
  set_current_date(thd, &ltime);
  curdays= calc_daynr(ltime.year, ltime.month, ltime.day);
}


Field *Field_time::new_key_field(MEM_ROOT *root, TABLE *new_table,
                                 uchar *new_ptr, uint32 length,
                                 uchar *new_null_ptr, uint new_null_bit)
{
  THD *thd= get_thd();
  Field_time *res=
    (Field_time*) Field::new_key_field(root, new_table, new_ptr, length,
                                       new_null_ptr, new_null_bit);
  if (!(thd->variables.old_behavior & OLD_MODE_ZERO_DATE_TIME_CAST) && res)
    res->set_curdays(thd);
  return res;
}


unknown's avatar
unknown committed
5863 5864
double Field_time::val_real(void)
{
5865
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
5866
  uint32 j= (uint32) uint3korr(ptr);
unknown's avatar
unknown committed
5867 5868 5869 5870 5871
  return (double) j;
}

longlong Field_time::val_int(void)
{
5872
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
5873 5874 5875
  return (longlong) sint3korr(ptr);
}

5876

5877 5878
/**
  @note
5879 5880 5881 5882
  This function is multi-byte safe as the result string is always of type
  my_charset_bin
*/

5883 5884
String *Field_time::val_str(String *str,
			    String *unused __attribute__((unused)))
unknown's avatar
unknown committed
5885
{
5886
  ASSERT_COLUMN_MARKED_FOR_READ;
5887
  MYSQL_TIME ltime;
5888 5889 5890 5891 5892
  get_date(&ltime, TIME_TIME_ONLY);
  str->alloc(field_length + 1);
  str->length(my_time_to_str(&ltime, const_cast<char*>(str->ptr()), decimals()));
  str->set_charset(&my_charset_numeric);
  return str;
unknown's avatar
unknown committed
5893 5894
}

5895

5896 5897 5898 5899 5900 5901 5902
bool Field_time::check_zero_in_date_with_warn(ulonglong fuzzydate)
{
  if (!(fuzzydate & TIME_TIME_ONLY) && (fuzzydate & TIME_NO_ZERO_IN_DATE))
  {
    THD *thd= get_thd();
    push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                        ER_WARN_DATA_OUT_OF_RANGE,
5903
                        ER_THD(thd, ER_WARN_DATA_OUT_OF_RANGE), field_name,
5904 5905 5906 5907 5908 5909 5910
                        thd->get_stmt_da()->current_row_for_warning());
    return true;
  }
  return false;
}


5911 5912
/**
  @note
unknown's avatar
unknown committed
5913
  Normally we would not consider 'time' as a valid date, but we allow
unknown's avatar
unknown committed
5914 5915 5916 5917
  get_date() here to be able to do things like
  DATE_FORMAT(time, "%l.%i %p")
*/
 
5918
bool Field_time::get_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
5919
{
5920 5921
  if (check_zero_in_date_with_warn(fuzzydate))
    return true;
unknown's avatar
unknown committed
5922 5923 5924 5925 5926 5927 5928
  long tmp=(long) sint3korr(ptr);
  ltime->neg=0;
  if (tmp < 0)
  {
    ltime->neg= 1;
    tmp=-tmp;
  }
5929
  ltime->year= ltime->month= ltime->day= 0;
unknown's avatar
unknown committed
5930
  ltime->hour=   (int) (tmp/10000);
unknown's avatar
unknown committed
5931
  tmp-=ltime->hour*10000;
unknown's avatar
unknown committed
5932 5933
  ltime->minute= (int) tmp/100;
  ltime->second= (int) tmp % 100;
unknown's avatar
unknown committed
5934
  ltime->second_part=0;
5935
  ltime->time_type= MYSQL_TIMESTAMP_TIME;
unknown's avatar
unknown committed
5936 5937 5938
  return 0;
}

5939 5940 5941

bool Field_time::send_binary(Protocol *protocol)
{
5942
  MYSQL_TIME ltime;
5943 5944
  get_date(&ltime, TIME_TIME_ONLY);
  return protocol->store_time(&ltime, decimals());
5945 5946 5947
}


5948
int Field_time::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
5949
{
unknown's avatar
unknown committed
5950 5951 5952
  int32 a,b;
  a=(int32) sint3korr(a_ptr);
  b=(int32) sint3korr(b_ptr);
unknown's avatar
unknown committed
5953 5954 5955
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

5956
void Field_time::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
5957 5958 5959 5960 5961 5962 5963 5964
{
  to[0] = (uchar) (ptr[2] ^ 128);
  to[1] = ptr[1];
  to[2] = ptr[0];
}

void Field_time::sql_type(String &res) const
{
5965 5966 5967 5968 5969
  if (decimals() == 0)
  {
    res.set_ascii(STRING_WITH_LEN("time"));
    return;
  }
5970
  CHARSET_INFO *cs= res.charset();
5971 5972
  res.length(cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
                               "time(%d)", decimals()));
unknown's avatar
unknown committed
5973 5974
}

5975 5976 5977 5978 5979 5980
int Field_time_hires::reset()
{
  store_bigendian(zero_point, ptr, Field_time_hires::pack_length());
  return 0;
}

Sergei Golubchik's avatar
Sergei Golubchik committed
5981

5982 5983
void Field_time_hires::store_TIME(MYSQL_TIME *ltime)
{
5984
  ulonglong packed= sec_part_shift(pack_time(ltime), dec) + zero_point;
5985 5986 5987
  store_bigendian(packed, ptr, Field_time_hires::pack_length());
}

5988
int Field_time::store_decimal(const my_decimal *d)
5989 5990 5991
{
  ulonglong nr;
  ulong sec_part;
Sergei Golubchik's avatar
Sergei Golubchik committed
5992
  ErrConvDecimal str(d);
5993 5994 5995 5996 5997 5998 5999 6000 6001
  MYSQL_TIME ltime;
  int was_cut;
  bool neg= my_decimal2seconds(d, &nr, &sec_part);

  int have_smth_to_conv= !number_to_time(neg, nr, sec_part, &ltime, &was_cut);

  return store_TIME_with_warning(&ltime, &str, was_cut, have_smth_to_conv);
}

6002 6003 6004 6005 6006

Item *Field_time::get_equal_const_item(THD *thd, const Context &ctx,
                                       Item *const_item)
{
  switch (ctx.subst_constraint()) {
6007 6008 6009 6010 6011
  case ANY_SUBST:
    if (const_item->field_type() != MYSQL_TYPE_TIME)
    {
      MYSQL_TIME ltime;
      // Get the value of const_item with conversion from DATETIME to TIME
6012 6013 6014 6015
      if (const_item->get_time_with_conversion(thd, &ltime,
                                               TIME_TIME_ONLY |
                                               TIME_FUZZY_DATES |
                                               TIME_INVALID_DATES))
6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033
        return NULL;
      /*
        Replace a DATE/DATETIME constant to a TIME constant:
          WHERE LENGTH(time_column)=8
            AND time_column=TIMESTAMP'2015-08-30 10:20:30';
        to:
          WHERE LENGTH(time_column)=10
            AND time_column=TIME'10:20:30'

        (assuming CURRENT_DATE is '2015-08-30'
      */
      return new (thd->mem_root) Item_time_literal(thd, &ltime,
                                                   ltime.second_part ?
                                                   TIME_SECOND_PART_DIGITS :
                                                   0);
    }
    break;
   case IDENTITY_SUBST:
6034 6035 6036 6037
    if (const_item->field_type() != MYSQL_TYPE_TIME ||
        const_item->decimals != decimals())
    {
      MYSQL_TIME ltime;
6038
      if (const_item->get_time_with_conversion(thd, &ltime, TIME_TIME_ONLY))
6039
        return NULL;
6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053
      /*
        Note, the value returned in "ltime" can have more fractional
        digits that decimals(). The Item_time_literal constructor will
        truncate these digits. We could disallow propagation is such
        cases, but it's still useful (and safe) to optimize:
          WHERE time0_column='00:00:00.123' AND LENGTH(a)=12
        to
          WHERE time0_column='00:00:00.123' AND LENGTH(TIME'00:00:00')=12
        and then to
          WHERE FALSE
        The original WHERE would do the full table scan (in case of no keys).
        The optimized WHERE will return with "Impossible WHERE", without
        having to do the full table scan.
      */
6054 6055 6056 6057 6058 6059 6060 6061
      return new (thd->mem_root) Item_time_literal(thd, &ltime, decimals());
    }
    break;
  }
  return const_item;
}


6062 6063
uint32 Field_time_hires::pack_length() const
{
6064
  return time_hires_bytes[dec];
6065 6066
}

6067
longlong Field_time_with_dec::val_int(void)
6068 6069 6070
{
  ASSERT_COLUMN_MARKED_FOR_READ;
  MYSQL_TIME ltime;
6071
  get_date(&ltime, TIME_TIME_ONLY);
6072 6073 6074 6075
  longlong val= TIME_to_ulonglong_time(&ltime);
  return ltime.neg ? -val : val;
}

6076
double Field_time_with_dec::val_real(void)
6077 6078 6079
{
  ASSERT_COLUMN_MARKED_FOR_READ;
  MYSQL_TIME ltime;
6080
  get_date(&ltime, TIME_TIME_ONLY);
6081 6082 6083
  return TIME_to_double(&ltime);
}

6084
bool Field_time_hires::get_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
6085
{
6086 6087
  if (check_zero_in_date_with_warn(fuzzydate))
    return true;
Sergei Golubchik's avatar
Sergei Golubchik committed
6088 6089 6090
  uint32 len= pack_length();
  longlong packed= read_bigendian(ptr, len);

6091
  packed= sec_part_unshift(packed - zero_point, dec);
Sergei Golubchik's avatar
Sergei Golubchik committed
6092

6093
  unpack_time(packed, ltime);
6094 6095
  /*
    unpack_time() returns MYSQL_TIMESTAMP_DATETIME.
Sergei Golubchik's avatar
Sergei Golubchik committed
6096
    To get MYSQL_TIMESTAMP_TIME we need few adjustments
6097 6098 6099 6100
  */
  ltime->time_type= MYSQL_TIMESTAMP_TIME;
  ltime->hour+= (ltime->month*32+ltime->day)*24;
  ltime->month= ltime->day= 0;
6101
  return false;
6102 6103 6104 6105
}


int Field_time_hires::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
6106
{
6107 6108
  ulonglong a=read_bigendian(a_ptr, Field_time_hires::pack_length());
  ulonglong b=read_bigendian(b_ptr, Field_time_hires::pack_length());
unknown's avatar
unknown committed
6109 6110 6111
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

6112
void Field_time_hires::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
6113
{
6114 6115 6116
  DBUG_ASSERT(length == Field_time_hires::pack_length());
  memcpy(to, ptr, length);
  to[0]^= 128;
unknown's avatar
unknown committed
6117 6118
}

6119
void Field_time_with_dec::make_field(Send_field *field)
unknown's avatar
unknown committed
6120
{
6121 6122
  Field::make_field(field);
  field->decimals= dec;
6123 6124
}

6125 6126 6127 6128 6129 6130 6131
/****************************************************************************
** time type with fsp (MySQL-5.6 version)
** In string context: HH:MM:SS.FFFFFF
** In number context: HHMMSS.FFFFFF
****************************************************************************/

int Field_timef::reset()
6132
{
6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145
  my_time_packed_to_binary(0, ptr, dec);
  return 0;
}

void Field_timef::store_TIME(MYSQL_TIME *ltime)
{
  my_time_trunc(ltime, decimals());
  longlong tmp= TIME_to_longlong_time_packed(ltime);
  my_time_packed_to_binary(tmp, ptr, dec);
}

bool Field_timef::get_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
{
6146 6147
  if (check_zero_in_date_with_warn(fuzzydate))
    return true;
6148 6149 6150
  longlong tmp= my_time_packed_from_binary(ptr, dec);
  TIME_from_longlong_time_packed(ltime, tmp);
  return false;
unknown's avatar
unknown committed
6151 6152 6153 6154 6155 6156 6157 6158
}

/****************************************************************************
** year type
** Save in a byte the year 0, 1901->2155
** Can handle 2 byte or 4 byte years!
****************************************************************************/

unknown's avatar
unknown committed
6159
int Field_year::store(const char *from, uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
6160
{
6161
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
6162
  char *end;
unknown's avatar
unknown committed
6163
  int error;
unknown's avatar
unknown committed
6164
  longlong nr= cs->cset->strntoull10rnd(cs, from, len, 0, &end, &error);
unknown's avatar
unknown committed
6165

6166
  if (nr < 0 || (nr >= 100 && nr <= 1900) || nr > 2155 || 
unknown's avatar
unknown committed
6167
      error == MY_ERRNO_ERANGE)
unknown's avatar
unknown committed
6168 6169
  {
    *ptr=0;
6170
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
6171
    return 1;
unknown's avatar
unknown committed
6172
  }
6173
  if (get_thd()->count_cuted_fields && 
unknown's avatar
unknown committed
6174 6175 6176 6177 6178 6179 6180
      (error= check_int(cs, from, len, end, error)))
  {
    if (error == 1)  /* empty or incorrect string */
    {
      *ptr= 0;
      return 1;
    }
unknown's avatar
unknown committed
6181
    error= 1;
unknown's avatar
unknown committed
6182
  }
unknown's avatar
unknown committed
6183

unknown's avatar
unknown committed
6184 6185 6186 6187 6188 6189 6190
  if (nr != 0 || len != 4)
  {
    if (nr < YY_PART_YEAR)
      nr+=100;					// 2000 - 2069
    else if (nr > 1900)
      nr-= 1900;
  }
unknown's avatar
unknown committed
6191
  *ptr= (char) (uchar) nr;
unknown's avatar
unknown committed
6192
  return error;
unknown's avatar
unknown committed
6193 6194
}

unknown's avatar
unknown committed
6195

unknown's avatar
unknown committed
6196
int Field_year::store(double nr)
unknown's avatar
unknown committed
6197
{
6198
  if (nr < 0.0 || nr > 2155.0)
6199
  {
6200
    (void) Field_year::store((longlong) -1, FALSE);
6201 6202
    return 1;
  }
6203
  return Field_year::store((longlong) nr, FALSE);
unknown's avatar
unknown committed
6204 6205
}

6206 6207

int Field_year::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
6208
{
6209
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
6210
  if (nr < 0 || (nr >= 100 && nr <= 1900) || nr > 2155)
unknown's avatar
unknown committed
6211
  {
6212
    *ptr= 0;
6213
    set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
6214
    return 1;
unknown's avatar
unknown committed
6215 6216 6217 6218 6219 6220 6221 6222
  }
  if (nr != 0 || field_length != 4)		// 0000 -> 0; 00 -> 2000
  {
    if (nr < YY_PART_YEAR)
      nr+=100;					// 2000 - 2069
    else if (nr > 1900)
      nr-= 1900;
  }
unknown's avatar
unknown committed
6223
  *ptr= (char) (uchar) nr;
6224
  return 0;
unknown's avatar
unknown committed
6225 6226
}

6227

6228
int Field_year::store_time_dec(MYSQL_TIME *ltime, uint dec_arg)
6229
{
Sergei Golubchik's avatar
Sergei Golubchik committed
6230
  ErrConvTime str(ltime);
6231 6232 6233
  if (Field_year::store(ltime->year, 0))
    return 1;

6234
  set_datetime_warning(WARN_DATA_TRUNCATED, &str, ltime->time_type, 1);
6235 6236 6237
  return 0;
}

unknown's avatar
unknown committed
6238 6239
bool Field_year::send_binary(Protocol *protocol)
{
6240
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
6241
  ulonglong tmp= Field_year::val_int();
6242
  return protocol->store_short(tmp);
unknown's avatar
unknown committed
6243
}
unknown's avatar
unknown committed
6244

6245

unknown's avatar
unknown committed
6246 6247 6248 6249 6250
double Field_year::val_real(void)
{
  return (double) Field_year::val_int();
}

6251

unknown's avatar
unknown committed
6252 6253
longlong Field_year::val_int(void)
{
6254
  ASSERT_COLUMN_MARKED_FOR_READ;
6255
  DBUG_ASSERT(field_length == 2 || field_length == 4);
6256
  int tmp= (int) ptr[0];
unknown's avatar
unknown committed
6257 6258 6259 6260 6261 6262 6263
  if (field_length != 4)
    tmp%=100;					// Return last 2 char
  else if (tmp)
    tmp+=1900;
  return (longlong) tmp;
}

6264

unknown's avatar
unknown committed
6265 6266 6267
String *Field_year::val_str(String *val_buffer,
			    String *val_ptr __attribute__((unused)))
{
6268
  DBUG_ASSERT(field_length < 5);
unknown's avatar
unknown committed
6269 6270 6271 6272
  val_buffer->alloc(5);
  val_buffer->length(field_length);
  char *to=(char*) val_buffer->ptr();
  sprintf(to,field_length == 2 ? "%02d" : "%04d",(int) Field_year::val_int());
6273
  val_buffer->set_charset(&my_charset_numeric);
unknown's avatar
unknown committed
6274 6275 6276
  return val_buffer;
}

6277

6278
bool Field_year::get_date(MYSQL_TIME *ltime,ulonglong fuzzydate)
6279 6280 6281 6282
{
  int tmp= (int) ptr[0];
  if (tmp || field_length != 4)
    tmp+= 1900;
6283 6284
  return int_to_datetime_with_warn(false, tmp * 10000,
                                    ltime, fuzzydate, field_name);
6285 6286 6287
}


unknown's avatar
unknown committed
6288 6289
void Field_year::sql_type(String &res) const
{
unknown's avatar
unknown committed
6290
  CHARSET_INFO *cs=res.charset();
6291
  res.length(cs->cset->snprintf(cs,(char*)res.ptr(),res.alloced_length(),
6292
			  "year(%d)",(int) field_length));
unknown's avatar
unknown committed
6293 6294 6295 6296 6297 6298 6299 6300 6301 6302
}


/****************************************************************************
** date type
** In string context: YYYY-MM-DD
** In number context: YYYYMMDD
** Stored as a 4 byte unsigned int
****************************************************************************/

6303
void Field_date::store_TIME(MYSQL_TIME *ltime)
unknown's avatar
unknown committed
6304
{
6305
  uint tmp= ltime->year*10000L + ltime->month*100+ltime->day;
Sergei Golubchik's avatar
Sergei Golubchik committed
6306
  int4store(ptr,tmp);
unknown's avatar
unknown committed
6307 6308
}

unknown's avatar
unknown committed
6309 6310 6311
bool Field_date::send_binary(Protocol *protocol)
{
  longlong tmp= Field_date::val_int();
6312
  MYSQL_TIME tm;
unknown's avatar
unknown committed
6313 6314 6315 6316 6317 6318
  tm.year= (uint32) tmp/10000L % 10000;
  tm.month= (uint32) tmp/100 % 100;
  tm.day= (uint32) tmp % 100;
  return protocol->store_date(&tm);
}

unknown's avatar
unknown committed
6319 6320 6321

double Field_date::val_real(void)
{
6322
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
6323
  int32 j;
Sergei Golubchik's avatar
Sergei Golubchik committed
6324
  j=sint4korr(ptr);
unknown's avatar
unknown committed
6325 6326 6327
  return (double) (uint32) j;
}

6328

unknown's avatar
unknown committed
6329 6330
longlong Field_date::val_int(void)
{
6331
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
6332
  int32 j;
Sergei Golubchik's avatar
Sergei Golubchik committed
6333
  j=sint4korr(ptr);
unknown's avatar
unknown committed
6334 6335 6336
  return (longlong) (uint32) j;
}

6337

6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351
bool Field_date::get_TIME(MYSQL_TIME *ltime, const uchar *pos,
                          ulonglong fuzzydate) const
{
  ASSERT_COLUMN_MARKED_FOR_READ;
  int32 tmp= sint4korr(pos);
  ltime->year= (int) ((uint32) tmp/10000L % 10000);
  ltime->month= (int) ((uint32) tmp/100 % 100);
  ltime->day= (int) ((uint32) tmp % 100);
  ltime->time_type= MYSQL_TIMESTAMP_DATE;
  ltime->hour= ltime->minute= ltime->second= ltime->second_part= ltime->neg= 0;
  return validate_MMDD(tmp, ltime->month, ltime->day, fuzzydate);
}


unknown's avatar
unknown committed
6352 6353 6354
String *Field_date::val_str(String *val_buffer,
			    String *val_ptr __attribute__((unused)))
{
6355
  MYSQL_TIME ltime;
6356
  get_TIME(&ltime, ptr, 0);
Sergei Golubchik's avatar
Sergei Golubchik committed
6357 6358 6359 6360
  val_buffer->alloc(MAX_DATE_STRING_REP_LENGTH);
  uint length= (uint) my_date_to_str(&ltime,
                                     const_cast<char*>(val_buffer->ptr()));
  val_buffer->length(length);
Sergei Golubchik's avatar
Sergei Golubchik committed
6361
  val_buffer->set_charset(&my_charset_numeric);
6362

unknown's avatar
unknown committed
6363
  return val_buffer;
6364 6365 6366
}


6367
int Field_date::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
6368 6369
{
  int32 a,b;
Sergei Golubchik's avatar
Sergei Golubchik committed
6370 6371
  a=sint4korr(a_ptr);
  b=sint4korr(b_ptr);
unknown's avatar
unknown committed
6372 6373 6374 6375
  return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
}


6376
void Field_date::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
6377
{
Sergei Golubchik's avatar
Sergei Golubchik committed
6378 6379 6380 6381
  to[0] = ptr[3];
  to[1] = ptr[2];
  to[2] = ptr[1];
  to[3] = ptr[0];
unknown's avatar
unknown committed
6382 6383 6384 6385
}

void Field_date::sql_type(String &res) const
{
6386
  res.set_ascii(STRING_WITH_LEN("date"));
unknown's avatar
unknown committed
6387 6388
}

6389

unknown's avatar
unknown committed
6390 6391 6392 6393 6394 6395
/****************************************************************************
** The new date type
** This is identical to the old date type, but stored on 3 bytes instead of 4
** In number context: YYYYMMDD
****************************************************************************/

6396
void Field_newdate::store_TIME(MYSQL_TIME *ltime)
unknown's avatar
unknown committed
6397
{
6398
  uint tmp= ltime->year*16*32 + ltime->month*32+ltime->day;
unknown's avatar
unknown committed
6399 6400 6401
  int3store(ptr,tmp);
}

6402

unknown's avatar
unknown committed
6403 6404
bool Field_newdate::send_binary(Protocol *protocol)
{
6405
  MYSQL_TIME tm;
unknown's avatar
unknown committed
6406 6407 6408
  Field_newdate::get_date(&tm,0);
  return protocol->store_date(&tm);
}
unknown's avatar
unknown committed
6409

6410

unknown's avatar
unknown committed
6411 6412
double Field_newdate::val_real(void)
{
6413
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
6414 6415 6416
  return (double) Field_newdate::val_int();
}

6417

unknown's avatar
unknown committed
6418 6419
longlong Field_newdate::val_int(void)
{
6420
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
6421
  ulong j= uint3korr(ptr);
unknown's avatar
unknown committed
6422 6423 6424 6425
  j= (j % 32L)+(j / 32L % 16L)*100L + (j/(16L*32L))*10000L;
  return (longlong) j;
}

6426

unknown's avatar
unknown committed
6427 6428 6429
String *Field_newdate::val_str(String *val_buffer,
			       String *val_ptr __attribute__((unused)))
{
6430
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
6431 6432
  val_buffer->alloc(field_length);
  val_buffer->length(field_length);
unknown's avatar
unknown committed
6433
  uint32 tmp=(uint32) uint3korr(ptr);
unknown's avatar
unknown committed
6434 6435 6436 6437
  int part;
  char *pos=(char*) val_buffer->ptr()+10;

  /* Open coded to get more speed */
unknown's avatar
unknown committed
6438
  *pos--=0;					// End NULL
unknown's avatar
unknown committed
6439
  part=(int) (tmp & 31);
unknown's avatar
unknown committed
6440 6441 6442
  *pos--= (char) ('0'+part%10);
  *pos--= (char) ('0'+part/10);
  *pos--= '-';
unknown's avatar
unknown committed
6443
  part=(int) (tmp >> 5 & 15);
unknown's avatar
unknown committed
6444 6445 6446
  *pos--= (char) ('0'+part%10);
  *pos--= (char) ('0'+part/10);
  *pos--= '-';
unknown's avatar
unknown committed
6447
  part=(int) (tmp >> 9);
unknown's avatar
unknown committed
6448 6449 6450 6451
  *pos--= (char) ('0'+part%10); part/=10;
  *pos--= (char) ('0'+part%10); part/=10;
  *pos--= (char) ('0'+part%10); part/=10;
  *pos=   (char) ('0'+part);
6452
  val_buffer->set_charset(&my_charset_numeric);
unknown's avatar
unknown committed
6453 6454 6455
  return val_buffer;
}

6456

6457 6458
bool Field_newdate::get_TIME(MYSQL_TIME *ltime, const uchar *pos,
                             ulonglong fuzzydate) const
unknown's avatar
unknown committed
6459
{
6460 6461
  ASSERT_COLUMN_MARKED_FOR_READ;
  uint32 tmp=(uint32) uint3korr(pos);
unknown's avatar
unknown committed
6462 6463 6464
  ltime->day=   tmp & 31;
  ltime->month= (tmp >> 5) & 15;
  ltime->year=  (tmp >> 9);
6465
  ltime->time_type= MYSQL_TIMESTAMP_DATE;
6466
  ltime->hour= ltime->minute= ltime->second= ltime->second_part= ltime->neg= 0;
6467
  return validate_MMDD(tmp, ltime->month, ltime->day, fuzzydate);
unknown's avatar
unknown committed
6468 6469
}

6470

6471
int Field_newdate::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
6472
{
unknown's avatar
unknown committed
6473 6474 6475
  uint32 a,b;
  a=(uint32) uint3korr(a_ptr);
  b=(uint32) uint3korr(b_ptr);
unknown's avatar
unknown committed
6476 6477 6478
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

6479

6480
void Field_newdate::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
6481 6482 6483 6484 6485 6486
{
  to[0] = ptr[2];
  to[1] = ptr[1];
  to[2] = ptr[0];
}

6487

unknown's avatar
unknown committed
6488 6489
void Field_newdate::sql_type(String &res) const
{
6490
  res.set_ascii(STRING_WITH_LEN("date"));
unknown's avatar
unknown committed
6491 6492 6493
}


6494 6495 6496 6497
Item *Field_newdate::get_equal_const_item(THD *thd, const Context &ctx,
                                          Item *const_item)
{
  switch (ctx.subst_constraint()) {
6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526
  case ANY_SUBST:
    if (!is_temporal_type_with_date(const_item->field_type()))
    {
      MYSQL_TIME ltime;
      // Get the value of const_item with conversion from TIME to DATETIME
      if (const_item->get_date_with_conversion(&ltime,
                                        TIME_FUZZY_DATES | TIME_INVALID_DATES))
        return NULL;
      /*
        Replace the constant to a DATE or DATETIME constant.
        Example:
          WHERE LENGTH(date_column)=10
            AND date_column=TIME'10:20:30';
        to:
          WHERE LENGTH(date_column)=10
            AND date_column=TIMESTAMP'2015-08-30 10:20:30'

        (assuming CURRENT_DATE is '2015-08-30'
      */
      if (non_zero_hhmmssuu(&ltime))
        return new (thd->mem_root)
          Item_datetime_literal_for_invalid_dates(thd, &ltime,
                                                  ltime.second_part ?
                                                  TIME_SECOND_PART_DIGITS : 0);
      datetime_to_date(&ltime);
      return new (thd->mem_root)
        Item_date_literal_for_invalid_dates(thd, &ltime);
    }
    break;
6527 6528 6529 6530 6531 6532 6533 6534
  case IDENTITY_SUBST:
    if (const_item->field_type() != MYSQL_TYPE_DATE)
    {
      MYSQL_TIME ltime;
      if (const_item->field_type() == MYSQL_TYPE_TIME ?
          const_item->get_date_with_conversion(&ltime, 0) :
          const_item->get_date(&ltime, 0))
        return NULL;
6535
      datetime_to_date(&ltime);
6536 6537 6538 6539 6540 6541 6542 6543
      return new (thd->mem_root) Item_date_literal(thd, &ltime);
    }
    break;
  }
  return const_item;
}


unknown's avatar
unknown committed
6544 6545 6546 6547 6548 6549 6550
/****************************************************************************
** datetime type
** In string context: YYYY-MM-DD HH:MM:DD
** In number context: YYYYMMDDHHMMDD
** Stored as a 8 byte unsigned int. Should sometimes be change to a 6 byte int.
****************************************************************************/

6551
void Field_datetime::store_TIME(MYSQL_TIME *ltime)
unknown's avatar
unknown committed
6552
{
6553
  ulonglong tmp= TIME_to_ulonglong_datetime(ltime);
Sergei Golubchik's avatar
Sergei Golubchik committed
6554
  int8store(ptr,tmp);
unknown's avatar
unknown committed
6555 6556
}

unknown's avatar
unknown committed
6557 6558
bool Field_datetime::send_binary(Protocol *protocol)
{
6559
  MYSQL_TIME tm;
6560
  Field_datetime::get_date(&tm, 0);
6561
  return protocol->store(&tm, 0);
unknown's avatar
unknown committed
6562
}
6563 6564


unknown's avatar
unknown committed
6565 6566 6567 6568 6569 6570 6571
double Field_datetime::val_real(void)
{
  return (double) Field_datetime::val_int();
}

longlong Field_datetime::val_int(void)
{
6572
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
6573
  longlong j;
Sergei Golubchik's avatar
Sergei Golubchik committed
6574
  j=sint8korr(ptr);
unknown's avatar
unknown committed
6575 6576 6577 6578 6579 6580 6581 6582 6583
  return j;
}


String *Field_datetime::val_str(String *val_buffer,
				String *val_ptr __attribute__((unused)))
{
  val_buffer->alloc(field_length);
  val_buffer->length(field_length);
6584 6585

  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
6586 6587 6588 6589 6590
  ulonglong tmp;
  long part1,part2;
  char *pos;
  int part3;

6591
  tmp= Field_datetime::val_int();
unknown's avatar
unknown committed
6592 6593

  /*
unknown's avatar
unknown committed
6594
    Avoid problem with slow longlong arithmetic and sprintf
unknown's avatar
unknown committed
6595 6596
  */

6597 6598
  part1=(long) (tmp/1000000LL);
  part2=(long) (tmp - (ulonglong) part1*1000000LL);
unknown's avatar
unknown committed
6599

6600
  pos=(char*) val_buffer->ptr() + MAX_DATETIME_WIDTH;
unknown's avatar
unknown committed
6601
  *pos--=0;
unknown's avatar
unknown committed
6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620
  *pos--= (char) ('0'+(char) (part2%10)); part2/=10;
  *pos--= (char) ('0'+(char) (part2%10)); part3= (int) (part2 / 10);
  *pos--= ':';
  *pos--= (char) ('0'+(char) (part3%10)); part3/=10;
  *pos--= (char) ('0'+(char) (part3%10)); part3/=10;
  *pos--= ':';
  *pos--= (char) ('0'+(char) (part3%10)); part3/=10;
  *pos--= (char) ('0'+(char) part3);
  *pos--= ' ';
  *pos--= (char) ('0'+(char) (part1%10)); part1/=10;
  *pos--= (char) ('0'+(char) (part1%10)); part1/=10;
  *pos--= '-';
  *pos--= (char) ('0'+(char) (part1%10)); part1/=10;
  *pos--= (char) ('0'+(char) (part1%10)); part3= (int) (part1/10);
  *pos--= '-';
  *pos--= (char) ('0'+(char) (part3%10)); part3/=10;
  *pos--= (char) ('0'+(char) (part3%10)); part3/=10;
  *pos--= (char) ('0'+(char) (part3%10)); part3/=10;
  *pos=(char) ('0'+(char) part3);
6621
  val_buffer->set_charset(&my_charset_numeric);
unknown's avatar
unknown committed
6622 6623 6624
  return val_buffer;
}

6625 6626
bool Field_datetime::get_TIME(MYSQL_TIME *ltime, const uchar *pos,
                              ulonglong fuzzydate) const
unknown's avatar
unknown committed
6627
{
6628 6629
  ASSERT_COLUMN_MARKED_FOR_READ;
  longlong tmp= sint8korr(pos);
unknown's avatar
unknown committed
6630
  uint32 part1,part2;
6631 6632
  part1=(uint32) (tmp/1000000LL);
  part2=(uint32) (tmp - (ulonglong) part1*1000000LL);
unknown's avatar
unknown committed
6633

6634
  ltime->time_type=	MYSQL_TIMESTAMP_DATETIME;
unknown's avatar
unknown committed
6635 6636 6637 6638 6639 6640 6641 6642
  ltime->neg=		0;
  ltime->second_part=	0;
  ltime->second=	(int) (part2%100);
  ltime->minute=	(int) (part2/100%100);
  ltime->hour=		(int) (part2/10000);
  ltime->day=		(int) (part1%100);
  ltime->month= 	(int) (part1/100%100);
  ltime->year= 		(int) (part1/10000);
6643
  return validate_MMDD(tmp, ltime->month, ltime->day, fuzzydate);
unknown's avatar
unknown committed
6644 6645
}

6646

6647
int Field_datetime::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
6648 6649
{
  longlong a,b;
Sergei Golubchik's avatar
Sergei Golubchik committed
6650 6651
  a=sint8korr(a_ptr);
  b=sint8korr(b_ptr);
unknown's avatar
unknown committed
6652 6653 6654 6655
  return ((ulonglong) a < (ulonglong) b) ? -1 :
    ((ulonglong) a > (ulonglong) b) ? 1 : 0;
}

6656
void Field_datetime::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
6657
{
Sergei Golubchik's avatar
Sergei Golubchik committed
6658 6659 6660 6661 6662 6663 6664 6665
  to[0] = ptr[7];
  to[1] = ptr[6];
  to[2] = ptr[5];
  to[3] = ptr[4];
  to[4] = ptr[3];
  to[5] = ptr[2];
  to[6] = ptr[1];
  to[7] = ptr[0];
unknown's avatar
unknown committed
6666 6667 6668 6669 6670
}


void Field_datetime::sql_type(String &res) const
{
6671 6672 6673 6674 6675 6676 6677 6678
  if (decimals() == 0)
  {
    res.set_ascii(STRING_WITH_LEN("datetime"));
    return;
  }
  CHARSET_INFO *cs= res.charset();
  res.length(cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
                                "datetime(%u)", decimals()));
unknown's avatar
unknown committed
6679 6680
}

6681 6682 6683

int Field_datetime::set_time()
{
6684
  THD *thd= table->in_use;
6685 6686 6687 6688 6689 6690 6691 6692 6693 6694
  MYSQL_TIME now_time;
  thd->variables.time_zone->gmt_sec_to_TIME(&now_time, thd->query_start());
  now_time.second_part= thd->query_start_sec_part();
  set_notnull();
  store_TIME(&now_time);
  thd->time_zone_used= 1;
  return 0;
}


6695 6696 6697
void Field_datetime_hires::store_TIME(MYSQL_TIME *ltime)
{
  ulonglong packed= sec_part_shift(pack_time(ltime), dec);
Sergei Golubchik's avatar
Sergei Golubchik committed
6698
  store_bigendian(packed, ptr, Field_datetime_hires::pack_length());
6699 6700
}

6701
int Field_temporal_with_date::store_decimal(const my_decimal *d)
6702
{
6703 6704 6705 6706 6707
  ulonglong nr;
  ulong sec_part;
  int error;
  MYSQL_TIME ltime;
  longlong tmp;
6708
  THD *thd= get_thd();
Sergei Golubchik's avatar
Sergei Golubchik committed
6709
  ErrConvDecimal str(d);
6710 6711

  if (my_decimal2seconds(d, &nr, &sec_part))
unknown's avatar
unknown committed
6712
  {
6713 6714
    tmp= -1;
    error= 2;
unknown's avatar
unknown committed
6715 6716
  }
  else
Sergei Golubchik's avatar
Sergei Golubchik committed
6717 6718
    tmp= number_to_datetime(nr, sec_part, &ltime, sql_mode_for_dates(thd),
                            &error);
6719 6720

  return store_TIME_with_warning(&ltime, &str, error, tmp != -1);
unknown's avatar
unknown committed
6721 6722
}

6723
bool Field_datetime_with_dec::send_binary(Protocol *protocol)
6724 6725
{
  MYSQL_TIME ltime;
Sergei Golubchik's avatar
Sergei Golubchik committed
6726
  get_date(&ltime, 0);
6727 6728
  return protocol->store(&ltime, dec);
}
unknown's avatar
unknown committed
6729

6730

6731
double Field_datetime_with_dec::val_real(void)
unknown's avatar
unknown committed
6732
{
6733
  MYSQL_TIME ltime;
Sergei Golubchik's avatar
Sergei Golubchik committed
6734
  get_date(&ltime, 0);
6735 6736 6737
  return TIME_to_double(&ltime);
}

6738
longlong Field_datetime_with_dec::val_int(void)
6739 6740
{
  MYSQL_TIME ltime;
Sergei Golubchik's avatar
Sergei Golubchik committed
6741
  get_date(&ltime, 0);
6742 6743 6744 6745
  return TIME_to_ulonglong_datetime(&ltime);
}


6746 6747
String *Field_datetime_with_dec::val_str(String *str,
                                         String *unused __attribute__((unused)))
6748 6749
{
  MYSQL_TIME ltime;
Sergei Golubchik's avatar
Sergei Golubchik committed
6750
  get_date(&ltime, 0);
6751 6752 6753
  str->alloc(field_length+1);
  str->length(field_length);
  my_datetime_to_str(&ltime, (char*) str->ptr(), dec);
6754
  str->set_charset(&my_charset_numeric);
6755 6756 6757
  return str;
}

6758 6759 6760

bool Field_datetime_hires::get_TIME(MYSQL_TIME *ltime, const uchar *pos,
                                    ulonglong fuzzydate) const
6761
{
6762 6763
  ASSERT_COLUMN_MARKED_FOR_READ;
  ulonglong packed= read_bigendian(pos, Field_datetime_hires::pack_length());
6764
  unpack_time(sec_part_unshift(packed, dec), ltime);
6765
  return validate_MMDD(packed, ltime->month, ltime->day, fuzzydate);
6766 6767
}

6768

6769 6770
uint32 Field_datetime_hires::pack_length() const
{
6771
  return datetime_hires_bytes[dec];
6772 6773 6774 6775
}

int Field_datetime_hires::cmp(const uchar *a_ptr, const uchar *b_ptr)
{
Sergei Golubchik's avatar
Sergei Golubchik committed
6776 6777
  ulonglong a=read_bigendian(a_ptr, Field_datetime_hires::pack_length());
  ulonglong b=read_bigendian(b_ptr, Field_datetime_hires::pack_length());
6778 6779 6780
  return a < b ? -1 : a > b ? 1 : 0;
}

6781
void Field_datetime_with_dec::make_field(Send_field *field)
6782
{
6783 6784
  Field::make_field(field);
  field->decimals= dec;
6785 6786 6787
}


6788 6789 6790 6791 6792
/****************************************************************************
** MySQL-5.6 compatible DATETIME(N)
**
****************************************************************************/
int Field_datetimef::reset()
6793
{
6794 6795
  my_datetime_packed_to_binary(0, ptr, dec);
  return 0;
6796 6797
}

6798
void Field_datetimef::store_TIME(MYSQL_TIME *ltime)
6799
{
6800 6801 6802 6803 6804
  my_time_trunc(ltime, decimals());
  longlong tmp= TIME_to_longlong_datetime_packed(ltime);
  my_datetime_packed_to_binary(tmp, ptr, dec);
}

6805 6806
bool Field_datetimef::get_TIME(MYSQL_TIME *ltime, const uchar *pos,
                               ulonglong fuzzydate) const
6807
{
6808 6809
  ASSERT_COLUMN_MARKED_FOR_READ;
  longlong tmp= my_datetime_packed_from_binary(pos, dec);
6810
  TIME_from_longlong_datetime_packed(ltime, tmp);
6811
  return validate_MMDD(tmp, ltime->month, ltime->day, fuzzydate);
unknown's avatar
unknown committed
6812 6813 6814 6815 6816 6817 6818
}

/****************************************************************************
** string type
** A string may be varchar or binary
****************************************************************************/

6819 6820 6821 6822 6823 6824
/*
  Report "not well formed" or "cannot convert" error
  after storing a character string info a field.

  SYNOPSIS
    check_string_copy_error()
6825 6826 6827
    copier                   - the conversion status
    end                      - the very end of the source string
                               that was just copied
6828
    cs                       - character set of the string
6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843

  NOTES
    As of version 5.0 both cases return the same error:
  
      "Invalid string value: 'xxx' for column 't' at row 1"
  
  Future versions will possibly introduce a new error message:

      "Cannot convert character string: 'xxx' for column 't' at row 1"

  RETURN
    FALSE - If errors didn't happen
    TRUE  - If an error happened
*/

6844 6845 6846 6847
bool
Field_longstr::check_string_copy_error(const String_copier *copier,
                                       const char *end,
                                       CHARSET_INFO *cs)
6848
{
6849 6850
  const char *pos;
  char tmp[32];
6851

6852
  if (!(pos= copier->most_important_error_pos()))
6853 6854
    return FALSE;

6855
  convert_to_printable(tmp, sizeof(tmp), pos, (end - pos), cs, 6);
6856
  set_warning_truncated_wrong_value("string", tmp);
6857 6858 6859 6860 6861
  return TRUE;
}


/*
unknown's avatar
unknown committed
6862
  Check if we lost any important data and send a truncation error/warning
6863 6864

  SYNOPSIS
unknown's avatar
unknown committed
6865
    Field_longstr::report_if_important_data()
6866
    pstr                     - Truncated rest of string
unknown's avatar
unknown committed
6867
    end                      - End of truncated string
6868
    count_spaces             - Treat traling spaces as important data
6869

unknown's avatar
unknown committed
6870 6871 6872 6873 6874 6875 6876 6877
  RETURN VALUES
    0   - None was truncated (or we don't count cut fields)
    2   - Some bytes was truncated

  NOTE
    Check if we lost any important data (anything in a binary string,
    or any non-space in others). If only trailing spaces was lost,
    send a truncation note, otherwise send a truncation error.
6878
    Silently ignore traling spaces if the count_space parameter is FALSE.
6879 6880
*/

unknown's avatar
unknown committed
6881
int
6882
Field_longstr::report_if_important_data(const char *pstr, const char *end,
6883
                                        bool count_spaces)
6884
{
6885 6886
  THD *thd= get_thd();
  if ((pstr < end) && thd->count_cuted_fields)
unknown's avatar
unknown committed
6887
  {
6888
    if (test_if_important_data(field_charset, pstr, end))
unknown's avatar
unknown committed
6889
    {
6890
      if (thd->abort_on_warning)
6891
        set_warning(ER_DATA_TOO_LONG, 1);
unknown's avatar
unknown committed
6892
      else
6893
        set_warning(WARN_DATA_TRUNCATED, 1);
6894
      return 2;
unknown's avatar
unknown committed
6895
    }
6896 6897
    else if (count_spaces)
    { /* If we lost only spaces then produce a NOTE, not a WARNING */
6898
      set_note(WARN_DATA_TRUNCATED, 1);
6899 6900
      return 2;
    }
unknown's avatar
unknown committed
6901 6902
  }
  return 0;
6903 6904 6905
}


unknown's avatar
unknown committed
6906 6907
	/* Copy a string and fill with space */

unknown's avatar
unknown committed
6908
int Field_string::store(const char *from,uint length,CHARSET_INFO *cs)
unknown's avatar
unknown committed
6909
{
6910
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
6911
  uint copy_length;
6912
  String_copier copier;
6913

6914
  /* See the comment for Field_long::store(long long) */
6915
  DBUG_ASSERT(!table || table->in_use == current_thd);
6916

6917
  copy_length= copier.well_formed_copy(field_charset,
6918
                                       (char*) ptr, field_length,
6919
                                       cs, from, length,
6920
                                       field_length / field_charset->mbmaxlen);
6921 6922 6923

  /* Append spaces if the string was shorter than the field. */
  if (copy_length < field_length)
6924
    field_charset->cset->fill(field_charset,(char*) ptr+copy_length,
6925
                              field_length-copy_length,
6926
                              field_charset->pad_char);
6927

6928
  return check_conversion_status(&copier, from + length, cs, false);
unknown's avatar
unknown committed
6929 6930 6931
}


6932
/**
6933 6934
  Store double value in Field_string or Field_varstring.

6935
  Pretty prints double number into field_length characters buffer.
6936

6937
  @param nr            number
6938 6939
*/

unknown's avatar
unknown committed
6940
int Field_str::store(double nr)
unknown's avatar
unknown committed
6941
{
6942
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
6943
  char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
6944
  uint local_char_length= field_length / charset()->mbmaxlen;
6945 6946 6947 6948 6949 6950
  size_t length= 0;
  my_bool error= (local_char_length == 0);

  // my_gcvt() requires width > 0, and we may have a CHAR(0) column.
  if (!error)
    length= my_gcvt(nr, MY_GCVT_ARG_DOUBLE, local_char_length, buff, &error);
6951

6952
  if (error)
6953
  {
6954
    if (get_thd()->abort_on_warning)
6955
      set_warning(ER_DATA_TOO_LONG, 1);
6956
    else
6957
      set_warning(WARN_DATA_TRUNCATED, 1);
6958
  }
6959
  return store(buff, length, &my_charset_numeric);
6960 6961
}

unknown's avatar
unknown committed
6962
uint Field::is_equal(Create_field *new_field)
unknown's avatar
unknown committed
6963
{
6964
  return (new_field->sql_type == real_type());
unknown's avatar
unknown committed
6965 6966 6967
}


unknown's avatar
unknown committed
6968
uint Field_str::is_equal(Create_field *new_field)
unknown's avatar
unknown committed
6969
{
6970
  return ((new_field->sql_type == real_type()) &&
unknown's avatar
unknown committed
6971
	  new_field->charset == field_charset &&
unknown's avatar
unknown committed
6972
	  new_field->length == max_display_length());
unknown's avatar
unknown committed
6973 6974 6975
}


6976
int Field_string::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
6977
{
unknown's avatar
unknown committed
6978 6979 6980
  char buff[64];
  int  l;
  CHARSET_INFO *cs=charset();
6981 6982
  l= (cs->cset->longlong10_to_str)(cs,buff,sizeof(buff),
                                   unsigned_val ? 10 : -10, nr);
unknown's avatar
unknown committed
6983
  return Field_string::store(buff,(uint)l,cs);
unknown's avatar
unknown committed
6984 6985
}

6986

unknown's avatar
unknown committed
6987 6988
int Field_longstr::store_decimal(const my_decimal *d)
{
6989
  char buff[DECIMAL_MAX_STR_LENGTH+1];
6990
  String str(buff, sizeof(buff), &my_charset_numeric);
unknown's avatar
unknown committed
6991
  my_decimal2string(E_DEC_FATAL_ERROR, d, 0, 0, 0, &str);
6992
  return store(str.ptr(), str.length(), str.charset());
unknown's avatar
unknown committed
6993
}
unknown's avatar
unknown committed
6994

6995 6996 6997 6998 6999
uint32 Field_longstr::max_data_length() const
{
  return field_length + (field_length > 255 ? 2 : 1);
}

7000

7001
bool
7002
Field_longstr::cmp_to_string_with_same_collation(const Item_bool_func *cond,
7003
                                                 const Item *item) const
7004
{
7005 7006 7007
  return item->cmp_type() == STRING_RESULT &&
         charset() == cond->compare_collation();
}
7008

7009 7010

bool
7011
Field_longstr::cmp_to_string_with_stricter_collation(const Item_bool_func *cond,
7012 7013 7014 7015 7016 7017 7018 7019
                                                     const Item *item) const
{
  return item->cmp_type() == STRING_RESULT &&
         (charset() == cond->compare_collation() ||
          cond->compare_collation()->state & MY_CS_BINSORT);
}


7020
bool Field_longstr::can_optimize_keypart_ref(const Item_bool_func *cond,
7021 7022 7023 7024 7025 7026 7027
                                             const Item *item) const
{
  DBUG_ASSERT(cmp_type() == STRING_RESULT);
  return cmp_to_string_with_stricter_collation(cond, item);
}


7028
bool Field_longstr::can_optimize_hash_join(const Item_bool_func *cond,
7029 7030 7031 7032 7033 7034 7035
                                           const Item *item) const
{
  DBUG_ASSERT(cmp_type() == STRING_RESULT);
  return cmp_to_string_with_same_collation(cond, item);
}


7036
bool Field_longstr::can_optimize_group_min_max(const Item_bool_func *cond,
7037 7038 7039 7040 7041 7042 7043 7044
                                               const Item *const_item) const
{
  /*
    Can't use indexes when comparing a string to a number or a date
    Don't use an index when comparing strings of different collations.
  */
  DBUG_ASSERT(cmp_type() == STRING_RESULT);
  return cmp_to_string_with_same_collation(cond, const_item);
7045 7046 7047
}


7048 7049 7050 7051 7052 7053 7054 7055 7056 7057
bool Field_longstr::can_optimize_range(const Item_bool_func *cond,
                                       const Item *item,
                                       bool is_eq_func) const
{
  return is_eq_func ?
         cmp_to_string_with_stricter_collation(cond, item) :
         cmp_to_string_with_same_collation(cond, item);
}


7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072
/**
  This overrides the default behavior of the parent constructor
  Warn_filter(thd) to suppress notes about trailing spaces in case of CHAR(N),
  as they are truncated during val_str().
  We still do want truncation notes in case of BINARY(N),
  as trailing spaces are not truncated in val_str().
*/
Field_string::Warn_filter_string::Warn_filter_string(const THD *thd,
                                                     const Field_string *field)
  :Warn_filter(!thd->no_errors,
               !thd->no_errors &&
               field->Field_string::charset() == &my_charset_bin)
{ }


unknown's avatar
unknown committed
7073 7074
double Field_string::val_real(void)
{
7075
  ASSERT_COLUMN_MARKED_FOR_READ;
7076
  THD *thd= get_thd();
7077 7078 7079 7080 7081
  return Converter_strntod_with_warn(get_thd(),
                                     Warn_filter_string(thd, this),
                                     Field_string::charset(),
                                     (const char *) ptr,
                                     field_length).result();
unknown's avatar
unknown committed
7082 7083 7084 7085 7086
}


longlong Field_string::val_int(void)
{
7087
  ASSERT_COLUMN_MARKED_FOR_READ;
7088
  THD *thd= get_thd();
7089 7090 7091 7092
  return Converter_strntoll_with_warn(thd, Warn_filter_string(thd, this),
                                      Field_string::charset(),
                                      (const char *) ptr,
                                      field_length).result();
unknown's avatar
unknown committed
7093 7094 7095 7096 7097 7098
}


String *Field_string::val_str(String *val_buffer __attribute__((unused)),
			      String *val_ptr)
{
7099
  ASSERT_COLUMN_MARKED_FOR_READ;
7100
  /* See the comment for Field_long::store(long long) */
7101
  DBUG_ASSERT(!table || table->in_use == current_thd);
7102
  uint length;
7103
  if (get_thd()->variables.sql_mode &
7104
      MODE_PAD_CHAR_TO_FULL_LENGTH)
7105 7106
    length= my_charpos(field_charset, ptr, ptr + field_length,
                       field_length / field_charset->mbmaxlen);
7107
  else
7108 7109
    length= field_charset->cset->lengthsp(field_charset, (const char*) ptr,
                                          field_length);
unknown's avatar
unknown committed
7110
  val_ptr->set((const char*) ptr, length, field_charset);
unknown's avatar
unknown committed
7111 7112 7113 7114
  return val_ptr;
}


7115 7116 7117
my_decimal *Field_string::val_decimal(my_decimal *decimal_value)
{
  ASSERT_COLUMN_MARKED_FOR_READ;
7118 7119 7120 7121 7122 7123 7124 7125
  THD *thd= get_thd();
  Converter_str2my_decimal_with_warn(thd,
                                     Warn_filter_string(thd, this),
                                     E_DEC_FATAL_ERROR,
                                     Field_string::charset(),
                                     (const char *) ptr,
                                     field_length, decimal_value);
  return decimal_value;
7126 7127 7128
}


7129 7130 7131 7132
struct Check_field_param {
  Field *field;
};

7133
#ifdef HAVE_REPLICATION
7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144
static bool
check_field_for_37426(const void *param_arg)
{
  Check_field_param *param= (Check_field_param*) param_arg;
  DBUG_ASSERT(param->field->real_type() == MYSQL_TYPE_STRING);
  DBUG_PRINT("debug", ("Field %s - type: %d, size: %d",
                       param->field->field_name,
                       param->field->real_type(),
                       param->field->row_pack_length()));
  return param->field->row_pack_length() > 255;
}
7145
#endif
7146

7147 7148 7149
bool
Field_string::compatible_field_size(uint field_metadata,
                                    Relay_log_info *rli_arg,
7150
                                    uint16 mflags __attribute__((unused)),
7151
                                    int *order_var)
7152 7153 7154 7155 7156 7157 7158
{
#ifdef HAVE_REPLICATION
  const Check_field_param check_param = { this };
  if (rpl_master_has_bug(rli_arg, 37426, TRUE,
                         check_field_for_37426, &check_param))
    return FALSE;                        // Not compatible field sizes
#endif
7159
  return Field::compatible_field_size(field_metadata, rli_arg, mflags, order_var);
7160 7161 7162
}


7163
int Field_string::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
7164
{
unknown's avatar
unknown committed
7165 7166 7167 7168 7169 7170 7171 7172 7173 7174
  uint a_len, b_len;

  if (field_charset->mbmaxlen != 1)
  {
    uint char_len= field_length/field_charset->mbmaxlen;
    a_len= my_charpos(field_charset, a_ptr, a_ptr + field_length, char_len);
    b_len= my_charpos(field_charset, b_ptr, b_ptr + field_length, char_len);
  }
  else
    a_len= b_len= field_length;
unknown's avatar
unknown committed
7175 7176 7177 7178 7179
  /*
    We have to remove end space to be able to compare multi-byte-characters
    like in latin_de 'ae' and 0xe4
  */
  return field_charset->coll->strnncollsp(field_charset,
7180
                                          a_ptr, a_len,
7181
                                          b_ptr, b_len);
unknown's avatar
unknown committed
7182 7183
}

7184

7185
void Field_string::sort_string(uchar *to,uint length)
unknown's avatar
unknown committed
7186
{
7187
  uint tmp __attribute__((unused))=
7188 7189 7190 7191 7192 7193 7194
    field_charset->coll->strnxfrm(field_charset,
                                  to, length,
                                  char_length() *
                                  field_charset->strxfrm_multiply,
                                  ptr, field_length,
                                  MY_STRXFRM_PAD_WITH_SPACE |
                                  MY_STRXFRM_PAD_TO_MAXLEN);
7195
  DBUG_ASSERT(tmp == length);
unknown's avatar
unknown committed
7196 7197 7198 7199 7200
}


void Field_string::sql_type(String &res) const
{
7201
  THD *thd= table->in_use;
unknown's avatar
unknown committed
7202
  CHARSET_INFO *cs=res.charset();
7203 7204 7205 7206
  ulong length;

  length= cs->cset->snprintf(cs,(char*) res.ptr(),
                             res.alloced_length(), "%s(%d)",
7207
                             (type() == MYSQL_TYPE_VAR_STRING ?
7208
                              (has_charset() ? "varchar" : "varbinary") :
7209
			      (has_charset() ? "char" : "binary")),
7210
                             (int) field_length / charset()->mbmaxlen);
7211
  res.length(length);
7212 7213
  if ((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) &&
      has_charset() && (charset()->state & MY_CS_BINSORT))
7214
    res.append(STRING_WITH_LEN(" binary"));
unknown's avatar
unknown committed
7215 7216
}

7217

Sergei Golubchik's avatar
Sergei Golubchik committed
7218
uchar *Field_string::pack(uchar *to, const uchar *from, uint max_length)
7219
{
7220
  uint length=      MY_MIN(field_length,max_length);
7221
  uint local_char_length= max_length/field_charset->mbmaxlen;
7222 7223
  DBUG_PRINT("debug", ("Packing field '%s' - length: %u ", field_name, length));

7224 7225 7226 7227
  if (length > local_char_length)
    local_char_length= my_charpos(field_charset, from, from+length,
                                  local_char_length);
  set_if_smaller(length, local_char_length);
Luis Soares's avatar
Luis Soares committed
7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241
 
  /*
     TODO: change charset interface to add a new function that does 
           the following or add a flag to lengthsp to do it itself 
           (this is for not packing padding adding bytes in BINARY 
           fields).
  */
  if (field_charset->mbmaxlen == 1)
  {
    while (length && from[length-1] == field_charset->pad_char)
      length --;
  }
  else
    length= field_charset->cset->lengthsp(field_charset, (const char*) from, length);
7242 7243

  // Length always stored little-endian
7244
  *to++= (uchar) length;
7245
  if (field_length > 255)
7246
    *to++= (uchar) (length >> 8);
7247 7248

  // Store the actual bytes of the string
7249 7250
  memcpy(to, from, length);
  return to+length;
7251 7252 7253
}


7254 7255 7256 7257 7258 7259 7260 7261 7262 7263
/**
   Unpack a string field from row data.

   This method is used to unpack a string field from a master whose size 
   of the field is less than that of the slave. Note that there can be a
   variety of field types represented with this class. Certain types like
   ENUM or SET are processed differently. Hence, the upper byte of the 
   @c param_data argument contains the result of field->real_type() from
   the master.

7264 7265 7266
   @note For information about how the length is packed, see @c
   Field_string::do_save_field_metadata

7267 7268 7269 7270 7271 7272
   @param   to         Destination of the data
   @param   from       Source of the data
   @param   param_data Real type (upper) and length (lower) values

   @return  New pointer into memory based on from + length of the data
*/
7273
const uchar *
7274 7275
Field_string::unpack(uchar *to, const uchar *from, const uchar *from_end,
                     uint param_data)
7276
{
7277
  uint from_length, length;
7278

7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294
  /*
    Compute the declared length of the field on the master. This is
    used to decide if one or two bytes should be read as length.
   */
  if (param_data)
    from_length= (((param_data >> 4) & 0x300) ^ 0x300) + (param_data & 0x00ff);
  else
    from_length= field_length;

  DBUG_PRINT("debug",
             ("param_data: 0x%x, field_length: %u, from_length: %u",
              param_data, field_length, from_length));
  /*
    Compute the actual length of the data by reading one or two bits
    (depending on the declared field length on the master).
   */
7295
  if (from_length > 255)
7296
  {
7297 7298
    if (from + 2 > from_end)
      return 0;
7299 7300 7301 7302
    length= uint2korr(from);
    from+= 2;
  }
  else
7303 7304 7305
  {
    if (from + 1 > from_end)
      return 0;
7306
    length= (uint) *from++;
7307 7308 7309
  }
  if (from + length > from_end || length > field_length)
    return 0;
7310 7311 7312

  memcpy(to, from, length);
  // Pad the string with the pad character of the fields charset
7313
  field_charset->cset->fill(field_charset, (char*) to + length, field_length - length, field_charset->pad_char);
unknown's avatar
unknown committed
7314 7315 7316 7317
  return from+length;
}


7318 7319 7320 7321 7322 7323 7324
/**
   Save the field metadata for string fields.

   Saves the real type in the first byte and the field length in the 
   second byte of the field metadata array at index of *metadata_ptr and
   *(metadata_ptr + 1).

7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343
   @note In order to be able to handle lengths exceeding 255 and be
   backwards-compatible with pre-5.1.26 servers, an extra two bits of
   the length has been added to the metadata in such a way that if
   they are set, a new unrecognized type is generated.  This will
   cause pre-5.1-26 servers to stop due to a field type mismatch,
   while new servers will be able to extract the extra bits. If the
   length is <256, there will be no difference and both a new and an
   old server will be able to handle it.

   @note The extra two bits are added to bits 13 and 14 of the
   parameter data (with 1 being the least siginficant bit and 16 the
   most significant bit of the word) by xoring the extra length bits
   with the real type.  Since all allowable types have 0xF as most
   significant bits of the metadata word, lengths <256 will not affect
   the real type at all, while all other values will result in a
   non-existant type in the range 17-244.

   @see Field_string::unpack

7344 7345 7346 7347 7348 7349
   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/
int Field_string::do_save_field_metadata(uchar *metadata_ptr)
{
7350 7351 7352 7353 7354 7355
  DBUG_ASSERT(field_length < 1024);
  DBUG_ASSERT((real_type() & 0xF0) == 0xF0);
  DBUG_PRINT("debug", ("field_length: %u, real_type: %u",
                       field_length, real_type()));
  *metadata_ptr= (real_type() ^ ((field_length & 0x300) >> 4));
  *(metadata_ptr + 1)= field_length & 0xFF;
7356 7357 7358 7359
  return 2;
}


7360
uint Field_string::packed_col_length(const uchar *data_ptr, uint length)
unknown's avatar
unknown committed
7361
{
7362
  if (length > 255)
7363
    return uint2korr(data_ptr)+2;
7364
  return (uint) *data_ptr + 1;
unknown's avatar
unknown committed
7365 7366
}

7367

unknown's avatar
unknown committed
7368 7369
uint Field_string::max_packed_col_length(uint max_length)
{
7370
  return (max_length > 255 ? 2 : 1)+max_length;
unknown's avatar
unknown committed
7371 7372
}

7373 7374

uint Field_string::get_key_image(uchar *buff, uint length, imagetype type_arg)
unknown's avatar
unknown committed
7375
{
7376 7377
  uint bytes = my_charpos(field_charset, (char*) ptr,
                          (char*) ptr + field_length,
unknown's avatar
unknown committed
7378 7379 7380
                          length / field_charset->mbmaxlen);
  memcpy(buff, ptr, bytes);
  if (bytes < length)
7381 7382
    field_charset->cset->fill(field_charset, (char*) buff + bytes,
                              length - bytes, field_charset->pad_char);
unknown's avatar
unknown committed
7383 7384
  return bytes;
}
unknown's avatar
unknown committed
7385

7386

7387 7388
Field *Field_string::make_new_field(MEM_ROOT *root, TABLE *new_table,
                                    bool keep_type)
7389
{
unknown's avatar
unknown committed
7390
  Field *field;
7391
  if (type() != MYSQL_TYPE_VAR_STRING || keep_type)
7392
    field= Field::make_new_field(root, new_table, keep_type);
7393 7394 7395
  else if ((field= new (root) Field_varstring(field_length, maybe_null(),
                                              field_name,
                                              new_table->s, charset())))
7396 7397 7398 7399 7400 7401
  {
    /*
      Old VARCHAR field which should be modified to a VARCHAR on copy
      This is done to ensure that ALTER TABLE will convert old VARCHAR fields
      to now VARCHAR fields.
    */
unknown's avatar
unknown committed
7402
    field->init(new_table);
7403
    /*
7404 7405 7406 7407 7408
      Normally orig_table is different from table only if field was
      created via ::make_new_field.  Here we alter the type of field,
      so ::make_new_field is not applicable. But we still need to
      preserve the original field metadata for the client-server
      protocol.
7409
    */
unknown's avatar
unknown committed
7410
    field->orig_table= orig_table;
7411
  }
unknown's avatar
unknown committed
7412
  return field;
7413 7414
}

unknown's avatar
unknown committed
7415

unknown's avatar
unknown committed
7416
/****************************************************************************
7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429
  VARCHAR type
  Data in field->ptr is stored as:
    1 or 2 bytes length-prefix-header  (from Field_varstring::length_bytes)
    data

  NOTE:
  When VARCHAR is stored in a key (for handler::index_read() etc) it's always
  stored with a 2 byte prefix. (Just like blob keys).

  Normally length_bytes is calculated as (field_length < 256 : 1 ? 2)
  The exception is if there is a prefix key field that is part of a long
  VARCHAR, in which case field_length for this may be 1 but the length_bytes
  is 2.
unknown's avatar
unknown committed
7430 7431
****************************************************************************/

unknown's avatar
unknown committed
7432
const uint Field_varstring::MAX_SIZE= UINT_MAX16;
unknown's avatar
unknown committed
7433

7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446
/**
   Save the field metadata for varstring fields.

   Saves the field length in the first byte. Note: may consume
   2 bytes. Caller must ensure second byte is contiguous with
   first byte (e.g. array index 0,1).

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/
int Field_varstring::do_save_field_metadata(uchar *metadata_ptr)
{
7447
  DBUG_ASSERT(field_length <= 65535);
7448
  int2store((char*)metadata_ptr, field_length);
7449 7450 7451
  return 2;
}

unknown's avatar
unknown committed
7452
int Field_varstring::store(const char *from,uint length,CHARSET_INFO *cs)
unknown's avatar
unknown committed
7453
{
7454
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
7455
  uint copy_length;
7456
  String_copier copier;
7457

7458
  copy_length= copier.well_formed_copy(field_charset,
7459 7460
                                       (char*) ptr + length_bytes,
                                       field_length,
7461
                                       cs, from, length,
7462
                                       field_length / field_charset->mbmaxlen);
7463 7464 7465 7466
  if (length_bytes == 1)
    *ptr= (uchar) copy_length;
  else
    int2store(ptr, copy_length);
7467

7468
  return check_conversion_status(&copier, from + length, cs, true);
unknown's avatar
unknown committed
7469 7470 7471
}


7472
int Field_varstring::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
7473
{
unknown's avatar
unknown committed
7474
  char buff[64];
7475 7476 7477 7478
  uint  length;
  length= (uint) (field_charset->cset->longlong10_to_str)(field_charset,
                                                          buff,
                                                          sizeof(buff),
7479 7480 7481
                                                          (unsigned_val ? 10:
                                                           -10),
                                                           nr);
7482
  return Field_varstring::store(buff, length, field_charset);
unknown's avatar
unknown committed
7483 7484 7485 7486 7487
}


double Field_varstring::val_real(void)
{
7488
  ASSERT_COLUMN_MARKED_FOR_READ;
7489 7490 7491 7492 7493
  THD *thd= get_thd();
  return Converter_strntod_with_warn(thd, Warn_filter(thd),
                                     Field_varstring::charset(),
                                     (const char *) get_data(),
                                     get_length()).result();
unknown's avatar
unknown committed
7494 7495 7496 7497 7498
}


longlong Field_varstring::val_int(void)
{
7499
  ASSERT_COLUMN_MARKED_FOR_READ;
7500 7501 7502 7503 7504
  THD *thd= get_thd();
  return Converter_strntoll_with_warn(thd, Warn_filter(thd),
                                      Field_varstring::charset(),
                                      (const char *) get_data(),
                                      get_length()).result();
unknown's avatar
unknown committed
7505 7506
}

7507

unknown's avatar
unknown committed
7508 7509 7510
String *Field_varstring::val_str(String *val_buffer __attribute__((unused)),
				 String *val_ptr)
{
7511
  ASSERT_COLUMN_MARKED_FOR_READ;
7512
  val_ptr->set((const char*) get_data(), get_length(), field_charset);
unknown's avatar
unknown committed
7513 7514 7515 7516
  return val_ptr;
}


unknown's avatar
unknown committed
7517 7518
my_decimal *Field_varstring::val_decimal(my_decimal *decimal_value)
{
7519
  ASSERT_COLUMN_MARKED_FOR_READ;
7520 7521 7522 7523 7524 7525 7526 7527
  THD *thd= get_thd();
  Converter_str2my_decimal_with_warn(thd, Warn_filter(thd),
                                     E_DEC_FATAL_ERROR,
                                     Field_varstring::charset(),
                                     (const char *) get_data(),
                                     get_length(), decimal_value);
  return decimal_value;

unknown's avatar
unknown committed
7528 7529 7530
}


7531
int Field_varstring::cmp_max(const uchar *a_ptr, const uchar *b_ptr,
7532
                             uint max_len)
unknown's avatar
unknown committed
7533
{
7534
  uint a_length, b_length;
unknown's avatar
unknown committed
7535
  int diff;
7536 7537 7538

  if (length_bytes == 1)
  {
7539 7540
    a_length= (uint) *a_ptr;
    b_length= (uint) *b_ptr;
7541 7542 7543 7544 7545 7546
  }
  else
  {
    a_length= uint2korr(a_ptr);
    b_length= uint2korr(b_ptr);
  }
7547 7548
  set_if_smaller(a_length, max_len);
  set_if_smaller(b_length, max_len);
7549
  diff= field_charset->coll->strnncollsp(field_charset,
7550
                                         a_ptr+
7551
                                         length_bytes,
7552
                                         a_length,
7553
                                         b_ptr+
7554
                                         length_bytes,
7555
                                         b_length);
7556
  return diff;
unknown's avatar
unknown committed
7557 7558
}

7559

7560 7561 7562
/**
  @note
    varstring and blob keys are ALWAYS stored with a 2 byte length prefix
7563 7564
*/

7565
int Field_varstring::key_cmp(const uchar *key_ptr, uint max_key_length)
7566
{
7567
  uint length=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7568
  uint local_char_length= max_key_length / field_charset->mbmaxlen;
7569

7570 7571 7572
  local_char_length= my_charpos(field_charset, ptr + length_bytes,
                          ptr + length_bytes + length, local_char_length);
  set_if_smaller(length, local_char_length);
7573
  return field_charset->coll->strnncollsp(field_charset, 
7574
                                          ptr + length_bytes,
7575
                                          length,
7576
                                          key_ptr+
7577
                                          HA_KEY_BLOB_LENGTH,
7578
                                          uint2korr(key_ptr));
unknown's avatar
unknown committed
7579 7580
}

7581

7582 7583
/**
  Compare to key segments (always 2 byte length prefix).
7584

7585
  @note
7586 7587 7588 7589
    This is used only to compare key segments created for index_read().
    (keys are created and compared in key.cc)
*/

7590
int Field_varstring::key_cmp(const uchar *a,const uchar *b)
7591
{
7592
  return field_charset->coll->strnncollsp(field_charset,
7593
                                          a + HA_KEY_BLOB_LENGTH,
7594
                                          uint2korr(a),
7595
                                          b + HA_KEY_BLOB_LENGTH,
7596
                                          uint2korr(b));
7597 7598 7599
}


7600
void Field_varstring::sort_string(uchar *to,uint length)
unknown's avatar
unknown committed
7601
{
7602
  uint tot_length=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613

  if (field_charset == &my_charset_bin)
  {
    /* Store length last in high-byte order to sort longer strings first */
    if (length_bytes == 1)
      to[length-1]= tot_length;
    else
      mi_int2store(to+length-2, tot_length);
    length-= length_bytes;
  }
 
7614 7615 7616 7617 7618 7619 7620
  tot_length= field_charset->coll->strnxfrm(field_charset,
                                            to, length,
                                            char_length() *
                                            field_charset->strxfrm_multiply,
                                            ptr + length_bytes, tot_length,
                                            MY_STRXFRM_PAD_WITH_SPACE |
                                            MY_STRXFRM_PAD_TO_MAXLEN);
unknown's avatar
unknown committed
7621
  DBUG_ASSERT(tot_length == length);
unknown's avatar
unknown committed
7622 7623 7624
}


7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636
enum ha_base_keytype Field_varstring::key_type() const
{
  enum ha_base_keytype res;

  if (binary())
    res= length_bytes == 1 ? HA_KEYTYPE_VARBINARY1 : HA_KEYTYPE_VARBINARY2;
  else
    res= length_bytes == 1 ? HA_KEYTYPE_VARTEXT1 : HA_KEYTYPE_VARTEXT2;
  return res;
}


unknown's avatar
unknown committed
7637 7638
void Field_varstring::sql_type(String &res) const
{
7639
  THD *thd= table->in_use;
unknown's avatar
unknown committed
7640
  CHARSET_INFO *cs=res.charset();
7641 7642 7643 7644 7645 7646
  ulong length;

  length= cs->cset->snprintf(cs,(char*) res.ptr(),
                             res.alloced_length(), "%s(%d)",
                              (has_charset() ? "varchar" : "varbinary"),
                             (int) field_length / charset()->mbmaxlen);
7647
  res.length(length);
7648 7649
  if ((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) &&
      has_charset() && (charset()->state & MY_CS_BINSORT))
7650
    res.append(STRING_WITH_LEN(" binary"));
unknown's avatar
unknown committed
7651 7652
}

7653

7654
uint32 Field_varstring::data_length()
7655
{
7656
  return length_bytes == 1 ? (uint32) *ptr : uint2korr(ptr);
7657 7658
}

7659 7660 7661 7662 7663
/*
  Functions to create a packed row.
  Here the number of length bytes are depending on the given max_length
*/

Sergei Golubchik's avatar
Sergei Golubchik committed
7664
uchar *Field_varstring::pack(uchar *to, const uchar *from, uint max_length)
unknown's avatar
unknown committed
7665
{
7666
  uint length= length_bytes == 1 ? (uint) *from : uint2korr(from);
7667
  set_if_smaller(max_length, field_length);
unknown's avatar
unknown committed
7668 7669
  if (length > max_length)
    length=max_length;
7670 7671 7672

  /* Length always stored little-endian */
  *to++= length & 0xFF;
unknown's avatar
unknown committed
7673
  if (max_length > 255)
7674 7675 7676 7677
    *to++= (length >> 8) & 0xFF;

  /* Store bytes of string */
  if (length > 0)
7678
    memcpy(to, from+length_bytes, length);
unknown's avatar
unknown committed
7679 7680 7681 7682
  return to+length;
}


7683 7684 7685 7686 7687
/**
   Unpack a varstring field from row data.

   This method is used to unpack a varstring field from a master
   whose size of the field is less than that of the slave.
7688 7689 7690

   @note
   The string length is always packed little-endian.
7691 7692 7693 7694 7695 7696 7697
  
   @param   to         Destination of the data
   @param   from       Source of the data
   @param   param_data Length bytes from the master's field data

   @return  New pointer into memory based on from + length of the data
*/
7698
const uchar *
7699 7700
Field_varstring::unpack(uchar *to, const uchar *from, const uchar *from_end,
                        uint param_data)
7701 7702 7703 7704
{
  uint length;
  uint l_bytes= (param_data && (param_data < field_length)) ? 
                (param_data <= 255) ? 1 : 2 : length_bytes;
7705 7706 7707 7708

  if (from + l_bytes > from_end)
    return 0;                                 // Error in data

7709 7710 7711 7712 7713 7714 7715
  if (l_bytes == 1)
  {
    to[0]= *from++;
    length= to[0];
    if (length_bytes == 2)
      to[1]= 0;
  }
7716
  else /* l_bytes == 2 */
unknown's avatar
unknown committed
7717
  {
7718 7719 7720
    length= uint2korr(from);
    to[0]= *from++;
    to[1]= *from++;
unknown's avatar
unknown committed
7721 7722
  }
  if (length)
7723 7724 7725
  {
    if (from + length > from_end || length > field_length)
      return 0;                                 // Error in data
7726
    memcpy(to+ length_bytes, from, length);
7727
  }
unknown's avatar
unknown committed
7728 7729 7730 7731
  return from+length;
}


7732
uint Field_varstring::packed_col_length(const uchar *data_ptr, uint length)
unknown's avatar
unknown committed
7733
{
7734
  if (length > 255)
7735
    return uint2korr(data_ptr)+2;
7736
  return (uint) *data_ptr + 1;
unknown's avatar
unknown committed
7737 7738
}

7739

unknown's avatar
unknown committed
7740 7741
uint Field_varstring::max_packed_col_length(uint max_length)
{
7742
  return (max_length > 255 ? 2 : 1)+max_length;
unknown's avatar
unknown committed
7743 7744
}

7745 7746
uint Field_varstring::get_key_image(uchar *buff, uint length,
                                    imagetype type_arg)
7747
{
7748
  uint f_length=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7749
  uint local_char_length= length / field_charset->mbmaxlen;
7750
  uchar *pos= ptr+length_bytes;
7751 7752 7753
  local_char_length= my_charpos(field_charset, pos, pos + f_length,
                                local_char_length);
  set_if_smaller(f_length, local_char_length);
7754
  /* Key is always stored with 2 bytes */
7755
  int2store(buff,f_length);
7756
  memcpy(buff+HA_KEY_BLOB_LENGTH, pos, f_length);
7757
  if (f_length < length)
7758 7759 7760 7761 7762
  {
    /*
      Must clear this as we do a memcmp in opt_range.cc to detect
      identical keys
    */
7763
    bzero(buff+HA_KEY_BLOB_LENGTH+f_length, (length-f_length));
7764
  }
unknown's avatar
unknown committed
7765
  return HA_KEY_BLOB_LENGTH+f_length;
7766 7767
}

7768

7769
void Field_varstring::set_key_image(const uchar *buff,uint length)
7770
{
7771
  length= uint2korr(buff);			// Real length is here
7772
  (void) Field_varstring::store((const char*) buff+HA_KEY_BLOB_LENGTH, length,
7773
                                field_charset);
7774 7775 7776
}


7777
int Field_varstring::cmp_binary(const uchar *a_ptr, const uchar *b_ptr,
7778 7779 7780 7781
                                uint32 max_length)
{
  uint32 a_length,b_length;

7782 7783
  if (length_bytes == 1)
  {
7784 7785
    a_length= (uint) *a_ptr;
    b_length= (uint) *b_ptr;
7786 7787 7788 7789 7790 7791
  }
  else
  {
    a_length= uint2korr(a_ptr);
    b_length= uint2korr(b_ptr);
  }
7792 7793 7794 7795
  set_if_smaller(a_length, max_length);
  set_if_smaller(b_length, max_length);
  if (a_length != b_length)
    return 1;
7796 7797 7798 7799
  return memcmp(a_ptr+length_bytes, b_ptr+length_bytes, a_length);
}


7800 7801
Field *Field_varstring::make_new_field(MEM_ROOT *root, TABLE *new_table,
                                       bool keep_type)
7802
{
7803 7804 7805
  Field_varstring *res= (Field_varstring*) Field::make_new_field(root,
                                                                 new_table,
                                                                 keep_type);
7806 7807 7808 7809 7810 7811
  if (res)
    res->length_bytes= length_bytes;
  return res;
}


7812 7813 7814
Field *Field_varstring::new_key_field(MEM_ROOT *root, TABLE *new_table,
                                      uchar *new_ptr, uint32 length,
                                      uchar *new_null_ptr, uint new_null_bit)
unknown's avatar
unknown committed
7815 7816
{
  Field_varstring *res;
7817 7818 7819
  if ((res= (Field_varstring*) Field::new_key_field(root, new_table,
                                                    new_ptr, length,
                                                    new_null_ptr, new_null_bit)))
unknown's avatar
unknown committed
7820 7821
  {
    /* Keys length prefixes are always packed with 2 bytes */
7822
    res->length_bytes= 2;
unknown's avatar
unknown committed
7823
  }
7824
  return res;
7825 7826
}

unknown's avatar
unknown committed
7827
uint Field_varstring::is_equal(Create_field *new_field)
unknown's avatar
unknown committed
7828
{
7829
  if (new_field->sql_type == real_type() &&
unknown's avatar
unknown committed
7830 7831
      new_field->charset == field_charset)
  {
unknown's avatar
unknown committed
7832
    if (new_field->length == max_display_length())
unknown's avatar
unknown committed
7833
      return IS_EQUAL_YES;
unknown's avatar
unknown committed
7834 7835 7836
    if (new_field->length > max_display_length() &&
	((new_field->length <= 255 && max_display_length() <= 255) ||
	 (new_field->length > 255 && max_display_length() > 255)))
unknown's avatar
unknown committed
7837 7838 7839 7840 7841 7842
      return IS_EQUAL_PACK_LENGTH; // VARCHAR, longer variable length
  }
  return IS_EQUAL_NO;
}


7843 7844 7845 7846 7847 7848 7849 7850
void Field_varstring::hash(ulong *nr, ulong *nr2)
{
  if (is_null())
  {
    *nr^= (*nr << 1) | 1;
  }
  else
  {
7851
    uint len=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7852
    CHARSET_INFO *cs= charset();
7853
    cs->coll->hash_sort(cs, ptr + length_bytes, len, nr, nr2);
7854 7855 7856 7857
  }
}


unknown's avatar
unknown committed
7858 7859 7860 7861 7862 7863
/****************************************************************************
** blob type
** A blob is saved as a length and a pointer. The length is stored in the
** packlength slot and may be from 1-4.
****************************************************************************/

7864
Field_blob::Field_blob(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
unknown's avatar
unknown committed
7865
		       enum utype unireg_check_arg, const char *field_name_arg,
unknown's avatar
unknown committed
7866
                       TABLE_SHARE *share, uint blob_pack_length,
7867
		       CHARSET_INFO *cs)
7868
  :Field_longstr(ptr_arg, BLOB_PACK_LENGTH_TO_MAX_LENGH(blob_pack_length),
unknown's avatar
unknown committed
7869 7870
                 null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg,
                 cs),
unknown's avatar
unknown committed
7871
   packlength(blob_pack_length)
unknown's avatar
unknown committed
7872
{
7873
  DBUG_ASSERT(blob_pack_length <= 4); // Only pack lengths 1-4 supported currently
unknown's avatar
unknown committed
7874
  flags|= BLOB_FLAG;
unknown's avatar
unknown committed
7875
  share->blob_fields++;
7876
  /* TODO: why do not fill table->s->blob_field array here? */
unknown's avatar
unknown committed
7877 7878 7879
}


Sergei Golubchik's avatar
Sergei Golubchik committed
7880
void Field_blob::store_length(uchar *i_ptr, uint i_packlength, uint32 i_number)
unknown's avatar
unknown committed
7881
{
Sergei Golubchik's avatar
Sergei Golubchik committed
7882
  store_lowendian(i_number, i_ptr, i_packlength);
unknown's avatar
unknown committed
7883 7884 7885
}


7886
uint32 Field_blob::get_length(const uchar *pos, uint packlength_arg) const
7887
{
Sergei Golubchik's avatar
Sergei Golubchik committed
7888
  return (uint32)read_lowendian(pos, packlength_arg);
7889 7890 7891
}


7892 7893 7894 7895 7896 7897 7898 7899 7900
/**
  Copy a value from another BLOB field of the same character set.
  This method is used by Copy_field, e.g. during ALTER TABLE.
*/
int Field_blob::copy_value(Field_blob *from)
{
  DBUG_ASSERT(field_charset == from->charset());
  int rc= 0;
  uint32 length= from->get_length();
7901
  uchar *data= from->get_ptr();
7902 7903 7904
  if (packlength < from->packlength)
  {
    set_if_smaller(length, Field_blob::max_data_length());
7905 7906
    length= (uint32) Well_formed_prefix(field_charset,
                                        (const char *) data, length).length();
7907 7908 7909 7910 7911 7912 7913
    rc= report_if_important_data((const char *) data + length,
                                 (const char *) data + from->get_length(),
                                 true);
  }
  store_length(length);
  bmove(ptr + packlength, (uchar*) &data, sizeof(char*));
  return rc;
7914 7915 7916
}


unknown's avatar
unknown committed
7917
int Field_blob::store(const char *from,uint length,CHARSET_INFO *cs)
unknown's avatar
unknown committed
7918
{
7919
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
7920
  uint copy_length, new_length;
7921
  String_copier copier;
7922
  char *tmp;
7923 7924 7925
  char buff[STRING_BUFFER_USUAL_SIZE];
  String tmpstr(buff,sizeof(buff), &my_charset_bin);

unknown's avatar
unknown committed
7926
  if (!length)
unknown's avatar
unknown committed
7927 7928
  {
    bzero(ptr,Field_blob::pack_length());
7929
    return 0;
unknown's avatar
unknown committed
7930
  }
unknown's avatar
unknown committed
7931

7932 7933 7934 7935 7936 7937 7938 7939 7940 7941
  if (table->blob_storage)    // GROUP_CONCAT with ORDER BY | DISTINCT
  {
    DBUG_ASSERT(!f_is_hex_escape(flags));
    DBUG_ASSERT(field_charset == cs);
    DBUG_ASSERT(length <= max_data_length());
    
    new_length= length;
    copy_length= table->in_use->variables.group_concat_max_len;
    if (new_length > copy_length)
    {
7942 7943
      new_length= Well_formed_prefix(cs,
                                     from, copy_length, new_length).length();
7944 7945 7946 7947 7948 7949 7950 7951 7952 7953
      table->blob_storage->set_truncated_value(true);
    }
    if (!(tmp= table->blob_storage->store(from, new_length)))
      goto oom_error;

    Field_blob::store_length(new_length);
    bmove(ptr + packlength, (uchar*) &tmp, sizeof(char*));
    return 0;
  }

7954 7955 7956 7957 7958 7959 7960
  /*
    If the 'from' address is in the range of the temporary 'value'-
    object we need to copy the content to a different location or it will be
    invalidated when the 'value'-object is reallocated to make room for
    the new character set.
  */
  if (from >= value.ptr() && from <= value.ptr()+value.length())
7961
  {
7962 7963 7964 7965
    /*
      If content of the 'from'-address is cached in the 'value'-object
      it is possible that the content needs a character conversion.
    */
7966
    if (!String::needs_conversion_on_storage(length, cs, field_charset))
7967 7968
    {
      Field_blob::store_length(length);
7969
      bmove(ptr + packlength, &from, sizeof(char*));
7970
      return 0;
unknown's avatar
unknown committed
7971
    }
7972 7973 7974
    if (tmpstr.copy(from, length, cs))
      goto oom_error;
    from= tmpstr.ptr();
unknown's avatar
unknown committed
7975
  }
7976

7977
  new_length= MY_MIN(max_data_length(), field_charset->mbmaxlen * length);
7978 7979
  if (value.alloc(new_length))
    goto oom_error;
7980
  tmp= const_cast<char*>(value.ptr());
7981 7982 7983 7984

  if (f_is_hex_escape(flags))
  {
    copy_length= my_copy_with_hex_escaping(field_charset,
7985 7986
                                           tmp, new_length,
                                           from, length);
7987 7988 7989 7990
    Field_blob::store_length(copy_length);
    bmove(ptr + packlength, (uchar*) &tmp, sizeof(char*));
    return 0;
  }
7991
  copy_length= copier.well_formed_copy(field_charset,
7992
                                       (char*) value.ptr(), new_length,
7993
                                       cs, from, length);
7994
  Field_blob::store_length(copy_length);
7995
  bmove(ptr+packlength,(uchar*) &tmp,sizeof(char*));
7996

7997
  return check_conversion_status(&copier, from + length, cs, true);
7998 7999 8000 8001 8002

oom_error:
  /* Fatal OOM error */
  bzero(ptr,Field_blob::pack_length());
  return -1; 
unknown's avatar
unknown committed
8003 8004 8005
}


unknown's avatar
unknown committed
8006
int Field_blob::store(double nr)
unknown's avatar
unknown committed
8007
{
8008
  CHARSET_INFO *cs=charset();
8009
  value.set_real(nr, NOT_FIXED_DEC, cs);
8010
  return Field_blob::store(value.ptr(),(uint) value.length(), cs);
unknown's avatar
unknown committed
8011 8012 8013
}


8014
int Field_blob::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
8015
{
8016
  CHARSET_INFO *cs=charset();
8017
  value.set_int(nr, unsigned_val, cs);
8018
  return Field_blob::store(value.ptr(), (uint) value.length(), cs);
unknown's avatar
unknown committed
8019 8020
}

8021

unknown's avatar
unknown committed
8022 8023
double Field_blob::val_real(void)
{
8024
  ASSERT_COLUMN_MARKED_FOR_READ;
8025
  char *blob;
8026
  memcpy(&blob, ptr+packlength, sizeof(char*));
unknown's avatar
unknown committed
8027 8028
  if (!blob)
    return 0.0;
8029 8030 8031 8032
  THD *thd= get_thd();
  return  Converter_strntod_with_warn(thd, Warn_filter(thd),
                                      Field_blob::charset(),
                                      blob, get_length(ptr)).result();
unknown's avatar
unknown committed
8033 8034 8035 8036 8037
}


longlong Field_blob::val_int(void)
{
8038
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
8039
  char *blob;
8040
  memcpy(&blob, ptr+packlength, sizeof(char*));
unknown's avatar
unknown committed
8041 8042
  if (!blob)
    return 0;
8043 8044 8045 8046
  THD *thd= get_thd();
  return Converter_strntoll_with_warn(thd, Warn_filter(thd),
                                      Field_blob::charset(),
                                      blob, get_length(ptr)).result();
unknown's avatar
unknown committed
8047 8048
}

8049

unknown's avatar
unknown committed
8050 8051 8052
String *Field_blob::val_str(String *val_buffer __attribute__((unused)),
			    String *val_ptr)
{
8053
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
8054
  char *blob;
8055
  memcpy(&blob, ptr+packlength, sizeof(char*));
unknown's avatar
unknown committed
8056
  if (!blob)
8057
    val_ptr->set("",0,charset());	// A bit safer than ->length(0)
unknown's avatar
unknown committed
8058
  else
8059
    val_ptr->set((const char*) blob,get_length(ptr),charset());
unknown's avatar
unknown committed
8060 8061 8062 8063
  return val_ptr;
}


unknown's avatar
unknown committed
8064 8065
my_decimal *Field_blob::val_decimal(my_decimal *decimal_value)
{
8066
  ASSERT_COLUMN_MARKED_FOR_READ;
8067
  const char *blob;
8068
  size_t length;
8069
  memcpy(&blob, ptr+packlength, sizeof(const uchar*));
unknown's avatar
unknown committed
8070
  if (!blob)
8071
  {
unknown's avatar
unknown committed
8072
    blob= "";
8073 8074 8075 8076 8077
    length= 0;
  }
  else
    length= get_length(ptr);

8078 8079 8080 8081 8082 8083
  THD *thd= get_thd();
  Converter_str2my_decimal_with_warn(thd, Warn_filter(thd),
                                     E_DEC_FATAL_ERROR,
                                     Field_blob::charset(),
                                     blob, length, decimal_value);
  return decimal_value;
unknown's avatar
unknown committed
8084 8085 8086
}


8087
int Field_blob::cmp(const uchar *a,uint32 a_length, const uchar *b,
unknown's avatar
unknown committed
8088
		    uint32 b_length)
unknown's avatar
unknown committed
8089
{
8090
  return field_charset->coll->strnncollsp(field_charset, 
8091
                                          a, a_length, b, b_length);
unknown's avatar
unknown committed
8092 8093 8094
}


8095
int Field_blob::cmp_max(const uchar *a_ptr, const uchar *b_ptr,
8096
                        uint max_length)
unknown's avatar
unknown committed
8097
{
8098
  uchar *blob1,*blob2;
8099 8100
  memcpy(&blob1, a_ptr+packlength, sizeof(char*));
  memcpy(&blob2, b_ptr+packlength, sizeof(char*));
8101 8102 8103 8104
  uint a_len= get_length(a_ptr), b_len= get_length(b_ptr);
  set_if_smaller(a_len, max_length);
  set_if_smaller(b_len, max_length);
  return Field_blob::cmp(blob1,a_len,blob2,b_len);
unknown's avatar
unknown committed
8105 8106 8107
}


8108
int Field_blob::cmp_binary(const uchar *a_ptr, const uchar *b_ptr,
unknown's avatar
unknown committed
8109
			   uint32 max_length)
unknown's avatar
unknown committed
8110 8111 8112
{
  char *a,*b;
  uint diff;
unknown's avatar
unknown committed
8113
  uint32 a_length,b_length;
8114 8115
  memcpy(&a, a_ptr+packlength, sizeof(char*));
  memcpy(&b, b_ptr+packlength, sizeof(char*));
unknown's avatar
unknown committed
8116 8117 8118 8119 8120 8121
  a_length=get_length(a_ptr);
  if (a_length > max_length)
    a_length=max_length;
  b_length=get_length(b_ptr);
  if (b_length > max_length)
    b_length=max_length;
8122
  diff=memcmp(a,b,MY_MIN(a_length,b_length));
unknown's avatar
unknown committed
8123 8124 8125 8126 8127 8128
  return diff ? diff : (int) (a_length - b_length);
}


/* The following is used only when comparing a key */

8129
uint Field_blob::get_key_image(uchar *buff,uint length, imagetype type_arg)
unknown's avatar
unknown committed
8130
{
unknown's avatar
unknown committed
8131
  uint32 blob_length= get_length(ptr);
8132
  uchar *blob;
unknown's avatar
unknown committed
8133

unknown's avatar
unknown committed
8134
#ifdef HAVE_SPATIAL
8135
  if (type_arg == itMBR)
unknown's avatar
unknown committed
8136
  {
unknown's avatar
unknown committed
8137
    const char *dummy;
unknown's avatar
unknown committed
8138
    MBR mbr;
8139 8140
    Geometry_buffer buffer;
    Geometry *gobj;
unknown's avatar
unknown committed
8141
    const uint image_length= SIZEOF_STORED_DOUBLE*4;
unknown's avatar
unknown committed
8142 8143 8144

    if (blob_length < SRID_SIZE)
    {
unknown's avatar
unknown committed
8145 8146
      bzero(buff, image_length);
      return image_length;
unknown's avatar
unknown committed
8147
    }
8148
    blob= get_ptr();
8149
    gobj= Geometry::construct(&buffer, (char*) blob, blob_length);
8150
    if (!gobj || gobj->get_mbr(&mbr, &dummy))
unknown's avatar
unknown committed
8151
      bzero(buff, image_length);
unknown's avatar
unknown committed
8152 8153 8154 8155 8156 8157 8158
    else
    {
      float8store(buff,    mbr.xmin);
      float8store(buff+8,  mbr.xmax);
      float8store(buff+16, mbr.ymin);
      float8store(buff+24, mbr.ymax);
    }
unknown's avatar
unknown committed
8159
    return image_length;
unknown's avatar
unknown committed
8160
  }
unknown's avatar
unknown committed
8161
#endif /*HAVE_SPATIAL*/
unknown's avatar
unknown committed
8162

8163
  blob= get_ptr();
8164 8165 8166 8167
  uint local_char_length= length / field_charset->mbmaxlen;
  local_char_length= my_charpos(field_charset, blob, blob + blob_length,
                          local_char_length);
  set_if_smaller(blob_length, local_char_length);
8168

unknown's avatar
unknown committed
8169
  if ((uint32) length > blob_length)
unknown's avatar
unknown committed
8170
  {
8171 8172 8173 8174
    /*
      Must clear this as we do a memcmp in opt_range.cc to detect
      identical keys
    */
8175
    bzero(buff+HA_KEY_BLOB_LENGTH+blob_length, (length-blob_length));
unknown's avatar
unknown committed
8176
    length=(uint) blob_length;
unknown's avatar
unknown committed
8177
  }
unknown's avatar
unknown committed
8178
  int2store(buff,length);
8179
  memcpy(buff+HA_KEY_BLOB_LENGTH, blob, length);
unknown's avatar
unknown committed
8180
  return HA_KEY_BLOB_LENGTH+length;
unknown's avatar
unknown committed
8181 8182
}

8183

8184
void Field_blob::set_key_image(const uchar *buff,uint length)
unknown's avatar
unknown committed
8185
{
8186
  length= uint2korr(buff);
8187 8188
  (void) Field_blob::store((const char*) buff+HA_KEY_BLOB_LENGTH, length,
                           field_charset);
unknown's avatar
unknown committed
8189 8190
}

unknown's avatar
unknown committed
8191

8192
int Field_blob::key_cmp(const uchar *key_ptr, uint max_key_length)
unknown's avatar
unknown committed
8193
{
8194
  uchar *blob1;
unknown's avatar
unknown committed
8195
  uint blob_length=get_length(ptr);
8196
  memcpy(&blob1, ptr+packlength, sizeof(char*));
8197
  CHARSET_INFO *cs= charset();
8198 8199 8200 8201
  uint local_char_length= max_key_length / cs->mbmaxlen;
  local_char_length= my_charpos(cs, blob1, blob1+blob_length,
                                local_char_length);
  set_if_smaller(blob_length, local_char_length);
8202
  return Field_blob::cmp(blob1, blob_length,
8203
			 key_ptr+HA_KEY_BLOB_LENGTH,
8204
			 uint2korr(key_ptr));
unknown's avatar
unknown committed
8205 8206
}

8207
int Field_blob::key_cmp(const uchar *a,const uchar *b)
unknown's avatar
unknown committed
8208
{
8209 8210
  return Field_blob::cmp(a+HA_KEY_BLOB_LENGTH, uint2korr(a),
			 b+HA_KEY_BLOB_LENGTH, uint2korr(b));
unknown's avatar
unknown committed
8211 8212 8213
}


8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225
Field *Field_blob::new_key_field(MEM_ROOT *root, TABLE *new_table,
                                 uchar *new_ptr, uint32 length,
                                 uchar *new_null_ptr, uint new_null_bit)
{
  Field_varstring *res= new (root) Field_varstring(new_ptr, length, 2,
                                      new_null_ptr, new_null_bit, Field::NONE,
                                      field_name, table->s, charset());
  res->init(new_table);
  return res;
}


8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237
/**
   Save the field metadata for blob fields.

   Saves the pack length in the first byte of the field metadata array
   at index of *metadata_ptr.

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/
int Field_blob::do_save_field_metadata(uchar *metadata_ptr)
{
8238
  DBUG_ENTER("Field_blob::do_save_field_metadata");
8239
  *metadata_ptr= pack_length_no_ptr();
8240 8241
  DBUG_PRINT("debug", ("metadata: %u (pack_length_no_ptr)", *metadata_ptr));
  DBUG_RETURN(1);
8242 8243 8244
}


8245 8246
uint32 Field_blob::sort_length() const
{
8247
  return (uint32) (get_thd()->variables.max_sort_length + 
8248 8249 8250 8251
                   (field_charset == &my_charset_bin ? 0 : packlength));
}


8252
void Field_blob::sort_string(uchar *to,uint length)
unknown's avatar
unknown committed
8253
{
8254
  uchar *blob;
unknown's avatar
unknown committed
8255
  uint blob_length=get_length();
unknown's avatar
unknown committed
8256

unknown's avatar
unknown committed
8257 8258 8259 8260
  if (!blob_length)
    bzero(to,length);
  else
  {
8261 8262
    if (field_charset == &my_charset_bin)
    {
8263
      uchar *pos;
8264 8265 8266 8267 8268 8269 8270

      /*
        Store length of blob last in blob to shorter blobs before longer blobs
      */
      length-= packlength;
      pos= to+length;

8271
      store_bigendian(blob_length, pos, packlength);
8272
    }
8273
    memcpy(&blob, ptr+packlength, sizeof(char*));
unknown's avatar
unknown committed
8274
    
8275 8276 8277 8278 8279
    blob_length= field_charset->coll->strnxfrm(field_charset,
                                               to, length, length,
                                               blob, blob_length,
                                               MY_STRXFRM_PAD_WITH_SPACE |
                                               MY_STRXFRM_PAD_TO_MAXLEN);
8280
    DBUG_ASSERT(blob_length == length);
unknown's avatar
unknown committed
8281 8282 8283 8284 8285 8286 8287
  }
}


void Field_blob::sql_type(String &res) const
{
  const char *str;
8288
  uint length;
unknown's avatar
unknown committed
8289
  switch (packlength) {
8290 8291 8292 8293 8294
  default: str="tiny"; length=4; break;
  case 2:  str="";     length=0; break;
  case 3:  str="medium"; length= 6; break;
  case 4:  str="long";  length=4; break;
  }
8295
  res.set_ascii(str,length);
8296
  if (charset() == &my_charset_bin)
8297
    res.append(STRING_WITH_LEN("blob"));
8298 8299
  else
  {
8300
    res.append(STRING_WITH_LEN("text"));
unknown's avatar
unknown committed
8301 8302 8303
  }
}

Sergei Golubchik's avatar
Sergei Golubchik committed
8304
uchar *Field_blob::pack(uchar *to, const uchar *from, uint max_length)
8305
{
8306 8307
  uchar *save= ptr;
  ptr= (uchar*) from;
unknown's avatar
unknown committed
8308
  uint32 length=get_length();			// Length of from string
8309 8310 8311 8312 8313 8314

  /*
    Store max length, which will occupy packlength bytes. If the max
    length given is smaller than the actual length of the blob, we
    just store the initial bytes of the blob.
  */
8315
  store_length(to, packlength, MY_MIN(length, max_length));
8316 8317 8318 8319 8320

  /*
    Store the actual blob data, which will occupy 'length' bytes.
   */
  if (length > 0)
8321
  {
8322
    from= get_ptr();
8323 8324 8325
    memcpy(to+packlength, from,length);
  }
  ptr=save;					// Restore org row pointer
8326
  return to+packlength+length;
8327 8328 8329
}


8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340
/**
   Unpack a blob field from row data.

   This method is used to unpack a blob field from a master whose size of 
   the field is less than that of the slave. Note: This method is included
   to satisfy inheritance rules, but is not needed for blob fields. It
   simply is used as a pass-through to the original unpack() method for
   blob fields.

   @param   to         Destination of the data
   @param   from       Source of the data
8341 8342 8343
   @param   param_data @c TRUE if base types should be stored in little-
                       endian format, @c FALSE if native format should
                       be used.
8344 8345 8346

   @return  New pointer into memory based on from + length of the data
*/
8347 8348
const uchar *Field_blob::unpack(uchar *to, const uchar *from,
                                const uchar *from_end, uint param_data)
8349 8350
{
  DBUG_ENTER("Field_blob::unpack");
Sergei Golubchik's avatar
Sergei Golubchik committed
8351 8352
  DBUG_PRINT("enter", ("to: 0x%lx; from: 0x%lx; param_data: %u",
                       (ulong) to, (ulong) from, param_data));
8353 8354
  uint const master_packlength=
    param_data > 0 ? param_data & 0xFF : packlength;
8355 8356
  if (from + master_packlength > from_end)
    DBUG_RETURN(0);                             // Error in data
Sergei Golubchik's avatar
Sergei Golubchik committed
8357
  uint32 const length= get_length(from, master_packlength);
8358
  DBUG_DUMP("packed", from, length + master_packlength);
8359
  bitmap_set_bit(table->write_set, field_index);
8360 8361
  if (from + master_packlength + length > from_end)
    DBUG_RETURN(0);
8362 8363 8364 8365
  store(reinterpret_cast<const char*>(from) + master_packlength,
        length, field_charset);
  DBUG_DUMP("record", to, table->s->reclength);
  DBUG_RETURN(from + master_packlength + length);
8366 8367
}

8368

8369
uint Field_blob::packed_col_length(const uchar *data_ptr, uint length)
8370 8371
{
  if (length > 255)
8372
    return uint2korr(data_ptr)+2;
8373
  return (uint) *data_ptr + 1;
8374 8375
}

8376

8377 8378 8379 8380
uint Field_blob::max_packed_col_length(uint max_length)
{
  return (max_length > 255 ? 2 : 1)+max_length;
}
8381

unknown's avatar
unknown committed
8382

unknown's avatar
unknown committed
8383
uint Field_blob::is_equal(Create_field *new_field)
8384 8385 8386
{
  return ((new_field->sql_type == get_blob_type_from_length(max_data_length()))
          && new_field->charset == field_charset &&
8387
          new_field->pack_length == pack_length());
8388 8389 8390
}


unknown's avatar
unknown committed
8391
#ifdef HAVE_SPATIAL
8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450
/* Values 1-40 reserved for 1-byte options,
   41-80 for 2-byte options,
   81-120 for 4-byte options,
   121-160 for 8-byte options,
   other - varied length in next 1-3 bytes.
*/
enum extra2_gis_field_options {
  FIELDGEOM_END=0,
  FIELDGEOM_STORAGE_MODEL=1,
  FIELDGEOM_PRECISION=2,
  FIELDGEOM_SCALE=3,
  FIELDGEOM_SRID=81,
};


uint gis_field_options_image(uchar *buff, List<Create_field> &create_fields)
{
  uint image_size= 0;
  List_iterator<Create_field> it(create_fields);
  Create_field *field;
  while ((field= it++))
  {
    if (field->sql_type != MYSQL_TYPE_GEOMETRY)
      continue;
   if (buff)
   {
     uchar *cbuf= buff + image_size;

     cbuf[0]= FIELDGEOM_STORAGE_MODEL;
     cbuf[1]= (uchar) Field_geom::GEOM_STORAGE_WKB;

     cbuf[2]= FIELDGEOM_PRECISION;
     cbuf[3]= (uchar) field->length;

     cbuf[4]= FIELDGEOM_SCALE;
     cbuf[5]= (uchar) field->decimals;

     cbuf[6]= FIELDGEOM_SRID;
     int4store(cbuf + 7, ((uint32) field->srid));

     cbuf[11]= FIELDGEOM_END;
   }
   image_size+= 12;
  }

  return image_size;
}


uint gis_field_options_read(const uchar *buf, uint buf_len,
      Field_geom::storage_type *st_type,uint *precision, uint *scale, uint *srid)
{
  const uchar *buf_end= buf + buf_len;
  const uchar *cbuf= buf;
  int option_id;

  *precision= *scale= *srid= 0;
  *st_type= Field_geom::GEOM_STORAGE_WKB;

8451 8452 8453
  if (!buf)  /* can only happen with the old FRM file */
    goto end_of_record;

8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472
  while (cbuf < buf_end)
  {
    switch ((option_id= *(cbuf++)))
    {
    case FIELDGEOM_STORAGE_MODEL:
      *st_type= (Field_geom::storage_type) cbuf[0];
      break;
    case FIELDGEOM_PRECISION:
      *precision= cbuf[0];
      break;
    case FIELDGEOM_SCALE:
      *scale= cbuf[0];
      break;
    case FIELDGEOM_SRID:
      *srid= uint4korr(cbuf);
      break;
    case FIELDGEOM_END:
      goto end_of_record;
    }
8473
    if (option_id > 0 && option_id <= 40)
8474
      cbuf+= 1;
8475
    else if (option_id > 40 && option_id <= 80)
8476
      cbuf+= 2;
8477
    else if (option_id > 80 && option_id <= 120)
8478
      cbuf+= 4;
8479
    else if (option_id > 120 && option_id <= 160)
8480 8481 8482 8483 8484 8485 8486 8487 8488 8489
      cbuf+= 8;
    else /* > 160 and <=255 */
      cbuf+= cbuf[0] ? 1 + cbuf[0] : 3 + uint2korr(cbuf+1);
  }

end_of_record:
  return cbuf - buf;
}


unknown's avatar
unknown committed
8490 8491 8492

void Field_geom::sql_type(String &res) const
{
unknown's avatar
unknown committed
8493 8494 8495 8496
  CHARSET_INFO *cs= &my_charset_latin1;
  switch (geom_type)
  {
    case GEOM_POINT:
8497
     res.set(STRING_WITH_LEN("point"), cs);
unknown's avatar
unknown committed
8498 8499
     break;
    case GEOM_LINESTRING:
8500
     res.set(STRING_WITH_LEN("linestring"), cs);
unknown's avatar
unknown committed
8501 8502
     break;
    case GEOM_POLYGON:
8503
     res.set(STRING_WITH_LEN("polygon"), cs);
unknown's avatar
unknown committed
8504 8505
     break;
    case GEOM_MULTIPOINT:
8506
     res.set(STRING_WITH_LEN("multipoint"), cs);
unknown's avatar
unknown committed
8507 8508
     break;
    case GEOM_MULTILINESTRING:
8509
     res.set(STRING_WITH_LEN("multilinestring"), cs);
unknown's avatar
unknown committed
8510 8511
     break;
    case GEOM_MULTIPOLYGON:
8512
     res.set(STRING_WITH_LEN("multipolygon"), cs);
unknown's avatar
unknown committed
8513 8514
     break;
    case GEOM_GEOMETRYCOLLECTION:
8515
     res.set(STRING_WITH_LEN("geometrycollection"), cs);
unknown's avatar
unknown committed
8516 8517
     break;
    default:
8518
     res.set(STRING_WITH_LEN("geometry"), cs);
unknown's avatar
unknown committed
8519
  }
unknown's avatar
unknown committed
8520 8521 8522
}


8523 8524 8525
int Field_geom::store(double nr)
{
  my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
8526
             ER_THD(get_thd(), ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
8527 8528 8529 8530
  return -1;
}


8531
int Field_geom::store(longlong nr, bool unsigned_val)
8532 8533
{
  my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
8534
             ER_THD(get_thd(), ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
8535 8536 8537 8538 8539 8540 8541
  return -1;
}


int Field_geom::store_decimal(const my_decimal *)
{
  my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
8542
             ER_THD(get_thd(), ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
8543 8544 8545 8546
  return -1;
}


unknown's avatar
unknown committed
8547 8548 8549 8550 8551 8552
int Field_geom::store(const char *from, uint length, CHARSET_INFO *cs)
{
  if (!length)
    bzero(ptr, Field_blob::pack_length());
  else
  {
8553 8554
    if (from == Geometry::bad_geometry_data.ptr())
      goto err;
unknown's avatar
unknown committed
8555 8556
    // Check given WKB
    uint32 wkb_type;
8557
    if (length < SRID_SIZE + WKB_HEADER_SIZE + 4)
unknown's avatar
unknown committed
8558
      goto err;
8559
    wkb_type= uint4korr(from + SRID_SIZE + 1);
8560
    if (wkb_type < (uint32) Geometry::wkb_point ||
8561
	wkb_type > (uint32) Geometry::wkb_last)
8562
      goto err;
8563 8564 8565 8566 8567

    if (geom_type != Field::GEOM_GEOMETRY && 
        geom_type != Field::GEOM_GEOMETRYCOLLECTION &&
        (uint32) geom_type != wkb_type)
    {
8568 8569 8570 8571 8572 8573
      my_error(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD, MYF(0),
               Geometry::ci_collection[geom_type]->m_name.str,
               Geometry::ci_collection[wkb_type]->m_name.str,
               field_name,
               (ulong) table->in_use->get_stmt_da()->
               current_row_for_warning());
8574 8575 8576
      goto err_exit;
    }

unknown's avatar
unknown committed
8577
    Field_blob::store_length(length);
8578 8579
    if ((table->copy_blobs || length <= MAX_FIELD_WIDTH) &&
        from != value.ptr())
unknown's avatar
unknown committed
8580 8581 8582 8583
    {						// Must make a copy
      value.copy(from, length, cs);
      from= value.ptr();
    }
8584
    bmove(ptr + packlength, &from, sizeof(char*));
unknown's avatar
unknown committed
8585 8586
  }
  return 0;
unknown's avatar
unknown committed
8587 8588

err:
8589
  my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
8590
             ER_THD(get_thd(), ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
8591 8592
err_exit:
  bzero(ptr, Field_blob::pack_length());  
unknown's avatar
unknown committed
8593
  return -1;
unknown's avatar
unknown committed
8594 8595
}

8596 8597 8598 8599 8600 8601 8602 8603
Field::geometry_type Field_geom::geometry_type_merge(geometry_type a,
                                                            geometry_type b)
{
  if (a == b)
    return a;
  return Field::GEOM_GEOMETRY;
}

8604

8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617
uint Field_geom::is_equal(Create_field *new_field)
{
  return new_field->sql_type == MYSQL_TYPE_GEOMETRY &&
         /*
           - Allow ALTER..INPLACE to supertype (GEOMETRY),
             e.g. POINT to GEOMETRY or POLYGON to GEOMETRY.
           - Allow ALTER..INPLACE to the same geometry type: POINT -> POINT
         */
         (new_field->geom_type == geom_type ||
          new_field->geom_type == GEOM_GEOMETRY);
}


8618 8619 8620 8621 8622 8623 8624
bool Field_geom::can_optimize_range(const Item_bool_func *cond,
                                    const Item *item,
                                    bool is_eq_func) const
{
  return item->cmp_type() == STRING_RESULT;
}

unknown's avatar
unknown committed
8625
#endif /*HAVE_SPATIAL*/
unknown's avatar
unknown committed
8626

unknown's avatar
unknown committed
8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645
/****************************************************************************
** enum type.
** This is a string which only can have a selection of different values.
** If one uses this string in a number context one gets the type number.
****************************************************************************/

enum ha_base_keytype Field_enum::key_type() const
{
  switch (packlength) {
  default: return HA_KEYTYPE_BINARY;
  case 2: return HA_KEYTYPE_USHORT_INT;
  case 3: return HA_KEYTYPE_UINT24;
  case 4: return HA_KEYTYPE_ULONG_INT;
  case 8: return HA_KEYTYPE_ULONGLONG;
  }
}

void Field_enum::store_type(ulonglong value)
{
Sergei Golubchik's avatar
Sergei Golubchik committed
8646
  store_lowendian(value, ptr, packlength);
unknown's avatar
unknown committed
8647 8648 8649
}


8650 8651 8652 8653
/**
  @note
    Storing a empty string in a enum field gives a warning
    (if there isn't a empty value in the enum)
unknown's avatar
unknown committed
8654 8655
*/

unknown's avatar
unknown committed
8656
int Field_enum::store(const char *from,uint length,CHARSET_INFO *cs)
unknown's avatar
unknown committed
8657
{
8658
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
8659
  int err= 0;
unknown's avatar
unknown committed
8660
  char buff[STRING_BUFFER_USUAL_SIZE];
unknown's avatar
unknown committed
8661
  String tmpstr(buff,sizeof(buff), &my_charset_bin);
unknown's avatar
unknown committed
8662

unknown's avatar
unknown committed
8663
  /* Convert character set if necessary */
8664
  if (String::needs_conversion_on_storage(length, cs, field_charset))
unknown's avatar
unknown committed
8665
  { 
8666 8667
    uint dummy_errors;
    tmpstr.copy(from, length, cs, field_charset, &dummy_errors);
unknown's avatar
unknown committed
8668 8669 8670
    from= tmpstr.ptr();
    length=  tmpstr.length();
  }
8671 8672

  /* Remove end space */
8673
  length= field_charset->cset->lengthsp(field_charset, from, length);
8674
  uint tmp=find_type2(typelib, from, length, field_charset);
unknown's avatar
unknown committed
8675
  if (!tmp)
unknown's avatar
unknown committed
8676
  {
8677
    if (length < 6) // Can't be more than 99999 enums
unknown's avatar
unknown committed
8678
    {
unknown's avatar
unknown committed
8679
      /* This is for reading numbers with LOAD DATA INFILE */
8680
      char *end;
8681 8682
      tmp=(uint) my_strntoul(cs,from,length,10,&end,&err);
      if (err || end != from+length || tmp > typelib->count)
unknown's avatar
unknown committed
8683 8684
      {
	tmp=0;
8685
	set_warning(WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
8686
      }
8687
      if (!get_thd()->count_cuted_fields)
8688
        err= 0;
unknown's avatar
unknown committed
8689 8690
    }
    else
8691
      set_warning(WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
8692
  }
unknown's avatar
unknown committed
8693
  store_type((ulonglong) tmp);
8694
  return err;
unknown's avatar
unknown committed
8695 8696 8697
}


unknown's avatar
unknown committed
8698
int Field_enum::store(double nr)
unknown's avatar
unknown committed
8699
{
8700
  return Field_enum::store((longlong) nr, FALSE);
unknown's avatar
unknown committed
8701 8702 8703
}


8704
int Field_enum::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
8705
{
8706
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
8707
  int error= 0;
8708
  if ((ulonglong) nr > typelib->count || nr == 0)
unknown's avatar
unknown committed
8709
  {
8710
    set_warning(WARN_DATA_TRUNCATED, 1);
8711
    if (nr != 0 || get_thd()->count_cuted_fields)
unknown's avatar
unknown committed
8712 8713 8714 8715
    {
      nr= 0;
      error= 1;
    }
unknown's avatar
unknown committed
8716 8717
  }
  store_type((ulonglong) (uint) nr);
8718
  return error;
unknown's avatar
unknown committed
8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729
}


double Field_enum::val_real(void)
{
  return (double) Field_enum::val_int();
}


longlong Field_enum::val_int(void)
{
8730
  ASSERT_COLUMN_MARKED_FOR_READ;
Sergei Golubchik's avatar
Sergei Golubchik committed
8731
  return read_lowendian(ptr, packlength);
unknown's avatar
unknown committed
8732 8733 8734
}


8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753
/**
   Save the field metadata for enum fields.

   Saves the real type in the first byte and the pack length in the 
   second byte of the field metadata array at index of *metadata_ptr and
   *(metadata_ptr + 1).

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/
int Field_enum::do_save_field_metadata(uchar *metadata_ptr)
{
  *metadata_ptr= real_type();
  *(metadata_ptr + 1)= pack_length();
  return 2;
}


unknown's avatar
unknown committed
8754 8755 8756 8757 8758
String *Field_enum::val_str(String *val_buffer __attribute__((unused)),
			    String *val_ptr)
{
  uint tmp=(uint) Field_enum::val_int();
  if (!tmp || tmp > typelib->count)
unknown's avatar
unknown committed
8759
    val_ptr->set("", 0, field_charset);
unknown's avatar
unknown committed
8760 8761
  else
    val_ptr->set((const char*) typelib->type_names[tmp-1],
8762
		 typelib->type_lengths[tmp-1],
8763
		 field_charset);
unknown's avatar
unknown committed
8764 8765 8766
  return val_ptr;
}

8767
int Field_enum::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
8768
{
8769 8770
  uchar *old= ptr;
  ptr= (uchar*) a_ptr;
unknown's avatar
unknown committed
8771
  ulonglong a=Field_enum::val_int();
8772
  ptr= (uchar*) b_ptr;
unknown's avatar
unknown committed
8773
  ulonglong b=Field_enum::val_int();
8774
  ptr= old;
unknown's avatar
unknown committed
8775 8776 8777
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

8778
void Field_enum::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791
{
  ulonglong value=Field_enum::val_int();
  to+=packlength-1;
  for (uint i=0 ; i < packlength ; i++)
  {
    *to-- = (uchar) (value & 255);
    value>>=8;
  }
}


void Field_enum::sql_type(String &res) const
{
8792 8793 8794
  char buffer[255];
  String enum_item(buffer, sizeof(buffer), res.charset());

unknown's avatar
unknown committed
8795
  res.length(0);
8796
  res.append(STRING_WITH_LEN("enum("));
unknown's avatar
unknown committed
8797 8798

  bool flag=0;
8799 8800
  uint *len= typelib->type_lengths;
  for (const char **pos= typelib->type_names; *pos; pos++, len++)
unknown's avatar
unknown committed
8801
  {
8802
    uint dummy_errors;
unknown's avatar
unknown committed
8803 8804
    if (flag)
      res.append(',');
8805
    /* convert to res.charset() == utf8, then quote */
8806
    enum_item.copy(*pos, *len, charset(), res.charset(), &dummy_errors);
8807 8808
    append_unescaped(&res, enum_item.ptr(), enum_item.length());
    flag= 1;
unknown's avatar
unknown committed
8809 8810 8811 8812 8813
  }
  res.append(')');
}


8814 8815
Field *Field_enum::make_new_field(MEM_ROOT *root, TABLE *new_table,
                                  bool keep_type)
8816
{
8817 8818
  Field_enum *res= (Field_enum*) Field::make_new_field(root, new_table,
                                                       keep_type);
8819 8820 8821 8822 8823 8824
  if (res)
    res->typelib= copy_typelib(root, typelib);
  return res;
}


8825 8826 8827 8828 8829 8830 8831 8832
/*
   set type.
   This is a string which can have a collection of different values.
   Each string value is separated with a ','.
   For example "One,two,five"
   If one uses this string in a number context one gets the bits as a longlong
   number.
*/
unknown's avatar
unknown committed
8833 8834


unknown's avatar
unknown committed
8835
int Field_set::store(const char *from,uint length,CHARSET_INFO *cs)
unknown's avatar
unknown committed
8836
{
8837
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
8838
  bool got_warning= 0;
8839
  int err= 0;
8840 8841
  char *not_used;
  uint not_used2;
unknown's avatar
unknown committed
8842
  char buff[STRING_BUFFER_USUAL_SIZE];
unknown's avatar
unknown committed
8843
  String tmpstr(buff,sizeof(buff), &my_charset_bin);
unknown's avatar
unknown committed
8844

unknown's avatar
unknown committed
8845
  /* Convert character set if necessary */
8846
  if (String::needs_conversion_on_storage(length, cs, field_charset))
unknown's avatar
unknown committed
8847
  { 
8848 8849
    uint dummy_errors;
    tmpstr.copy(from, length, cs, field_charset, &dummy_errors);
unknown's avatar
unknown committed
8850 8851 8852
    from= tmpstr.ptr();
    length=  tmpstr.length();
  }
8853 8854
  ulonglong tmp= find_set(typelib, from, length, field_charset,
                          &not_used, &not_used2, &got_warning);
unknown's avatar
unknown committed
8855 8856 8857
  if (!tmp && length && length < 22)
  {
    /* This is for reading numbers with LOAD DATA INFILE */
8858
    char *end;
8859 8860
    tmp=my_strntoull(cs,from,length,10,&end,&err);
    if (err || end != from+length ||
unknown's avatar
unknown committed
8861
	tmp > (ulonglong) (((longlong) 1 << typelib->count) - (longlong) 1))
8862
    {
8863
      tmp=0;      
8864
      set_warning(WARN_DATA_TRUNCATED, 1);
8865
    }
unknown's avatar
unknown committed
8866
  }
unknown's avatar
unknown committed
8867
  else if (got_warning)
8868
    set_warning(WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
8869
  store_type(tmp);
8870
  return err;
unknown's avatar
unknown committed
8871 8872 8873
}


8874
int Field_set::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
8875
{
8876
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
8877
  int error= 0;
8878 8879 8880 8881 8882
  ulonglong max_nr;

  if (sizeof(ulonglong)*8 <= typelib->count)
    max_nr= ULONGLONG_MAX;
  else
8883
    max_nr= (1ULL << typelib->count) - 1;
8884

8885
  if ((ulonglong) nr > max_nr)
unknown's avatar
unknown committed
8886
  {
8887
    nr&= max_nr;
8888
    set_warning(WARN_DATA_TRUNCATED, 1);
8889
    error=1;
unknown's avatar
unknown committed
8890 8891
  }
  store_type((ulonglong) nr);
8892
  return error;
unknown's avatar
unknown committed
8893 8894 8895 8896 8897 8898 8899 8900 8901
}


String *Field_set::val_str(String *val_buffer,
			   String *val_ptr __attribute__((unused)))
{
  ulonglong tmp=(ulonglong) Field_enum::val_int();
  uint bitnr=0;

8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914
  if (tmp == 0)
  {
    /*
      Some callers expect *val_buffer to contain the result,
      so we assign to it, rather than doing 'return &empty_set_string.
     */
    *val_buffer= empty_set_string;
    return val_buffer;
  }

  val_buffer->set_charset(field_charset);
  val_buffer->length(0);

unknown's avatar
unknown committed
8915 8916 8917 8918 8919
  while (tmp && bitnr < (uint) typelib->count)
  {
    if (tmp & 1)
    {
      if (val_buffer->length())
8920
	val_buffer->append(&field_separator, 1, &my_charset_latin1);
unknown's avatar
unknown committed
8921
      String str(typelib->type_names[bitnr],
8922
		 typelib->type_lengths[bitnr],
8923
		 field_charset);
unknown's avatar
unknown committed
8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934
      val_buffer->append(str);
    }
    tmp>>=1;
    bitnr++;
  }
  return val_buffer;
}


void Field_set::sql_type(String &res) const
{
8935 8936 8937
  char buffer[255];
  String set_item(buffer, sizeof(buffer), res.charset());

unknown's avatar
unknown committed
8938
  res.length(0);
8939
  res.append(STRING_WITH_LEN("set("));
unknown's avatar
unknown committed
8940 8941

  bool flag=0;
8942 8943
  uint *len= typelib->type_lengths;
  for (const char **pos= typelib->type_names; *pos; pos++, len++)
unknown's avatar
unknown committed
8944
  {
8945
    uint dummy_errors;
unknown's avatar
unknown committed
8946 8947
    if (flag)
      res.append(',');
8948
    /* convert to res.charset() == utf8, then quote */
8949
    set_item.copy(*pos, *len, charset(), res.charset(), &dummy_errors);
8950 8951
    append_unescaped(&res, set_item.ptr(), set_item.length());
    flag= 1;
unknown's avatar
unknown committed
8952 8953 8954 8955
  }
  res.append(')');
}

8956 8957 8958 8959 8960 8961
/**
  @retval
    1  if the fields are equally defined
  @retval
    0  if the fields are unequally defined
*/
unknown's avatar
unknown committed
8962

8963
bool Field::eq_def(const Field *field) const
unknown's avatar
unknown committed
8964
{
8965
  if (real_type() != field->real_type() || charset() != field->charset() ||
unknown's avatar
unknown committed
8966 8967 8968 8969 8970
      pack_length() != field->pack_length())
    return 0;
  return 1;
}

8971

8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989
/**
  Compare the first t1::count type names.

  @return TRUE if the type names of t1 match those of t2. FALSE otherwise.
*/

static bool compare_type_names(CHARSET_INFO *charset, TYPELIB *t1, TYPELIB *t2)
{
  for (uint i= 0; i < t1->count; i++)
    if (my_strnncoll(charset,
                     (const uchar*) t1->type_names[i],
                     t1->type_lengths[i],
                     (const uchar*) t2->type_names[i],
                     t2->type_lengths[i]))
      return FALSE;
  return TRUE;
}

8990 8991 8992 8993
/**
  @return
  returns 1 if the fields are equally defined
*/
8994

8995
bool Field_enum::eq_def(const Field *field) const
unknown's avatar
unknown committed
8996
{
8997 8998
  TYPELIB *values;

unknown's avatar
unknown committed
8999
  if (!Field::eq_def(field))
9000
    return FALSE;
unknown's avatar
unknown committed
9001

9002
  values= ((Field_enum*) field)->typelib;
9003

9004
  /* Definition must be strictly equal. */
9005 9006
  if (typelib->count != values->count)
    return FALSE;
9007 9008

  return compare_type_names(field_charset, typelib, values);
9009 9010 9011
}


9012 9013 9014 9015 9016 9017 9018 9019 9020
/**
  Check whether two fields can be considered 'equal' for table
  alteration purposes. Fields are equal if they retain the same
  pack length and if new members are added to the end of the list.

  @return IS_EQUAL_YES if fields are compatible.
          IS_EQUAL_NO otherwise.
*/

9021 9022
uint Field_enum::is_equal(Create_field *new_field)
{
9023 9024 9025 9026 9027 9028
  TYPELIB *values= new_field->interval;

  /*
    The fields are compatible if they have the same flags,
    type, charset and have the same underlying length.
  */
9029
  if (new_field->sql_type != real_type() ||
9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046
      new_field->charset != field_charset ||
      new_field->pack_length != pack_length())
    return IS_EQUAL_NO;

  /*
    Changing the definition of an ENUM or SET column by adding a new
    enumeration or set members to the end of the list of valid member
    values only alters table metadata and not table data.
  */
  if (typelib->count > values->count)
    return IS_EQUAL_NO;

  /* Check whether there are modification before the end. */
  if (! compare_type_names(field_charset, typelib, new_field->interval))
    return IS_EQUAL_NO;

  return IS_EQUAL_YES;
unknown's avatar
unknown committed
9047 9048
}

9049

Sergei Golubchik's avatar
Sergei Golubchik committed
9050
uchar *Field_enum::pack(uchar *to, const uchar *from, uint max_length)
9051 9052 9053 9054
{
  DBUG_ENTER("Field_enum::pack");
  DBUG_PRINT("debug", ("packlength: %d", packlength));
  DBUG_DUMP("from", from, packlength);
Sergei Golubchik's avatar
Sergei Golubchik committed
9055
  DBUG_RETURN(pack_int(to, from, packlength));
9056 9057
}

Igor Babaev's avatar
Igor Babaev committed
9058 9059
const uchar *Field_enum::unpack(uchar *to, const uchar *from, 
                                const uchar *from_end, uint param_data)
9060 9061 9062 9063
{
  DBUG_ENTER("Field_enum::unpack");
  DBUG_PRINT("debug", ("packlength: %d", packlength));
  DBUG_DUMP("from", from, packlength);
Igor Babaev's avatar
Igor Babaev committed
9064
  DBUG_RETURN(unpack_int(to, from, from_end, packlength));
9065 9066 9067
}


9068 9069 9070 9071
/**
  @return
  returns 1 if the fields are equally defined
*/
9072
bool Field_num::eq_def(const Field *field) const
unknown's avatar
unknown committed
9073
{
unknown's avatar
unknown committed
9074 9075 9076 9077 9078
  if (!Field::eq_def(field))
    return 0;
  Field_num *from_num= (Field_num*) field;

  if (unsigned_flag != from_num->unsigned_flag ||
9079
      (zerofill && !from_num->zerofill && !zero_pack()) ||
unknown's avatar
unknown committed
9080 9081 9082 9083 9084 9085
      dec != from_num->dec)
    return 0;
  return 1;
}


9086 9087 9088 9089 9090 9091
/**
  Check whether two numeric fields can be considered 'equal' for table
  alteration purposes. Fields are equal if they are of the same type
  and retain the same pack length.
*/

unknown's avatar
unknown committed
9092
uint Field_num::is_equal(Create_field *new_field)
unknown's avatar
unknown committed
9093
{
9094
  return ((new_field->sql_type == real_type()) &&
9095 9096
          ((new_field->flags & UNSIGNED_FLAG) == 
           (uint) (flags & UNSIGNED_FLAG)) &&
unknown's avatar
unknown committed
9097 9098
	  ((new_field->flags & AUTO_INCREMENT_FLAG) ==
	   (uint) (flags & AUTO_INCREMENT_FLAG)) &&
9099
          (new_field->pack_length == pack_length()));
unknown's avatar
unknown committed
9100 9101 9102
}


9103
bool Field_enum::can_optimize_keypart_ref(const Item_bool_func *cond,
9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117
                                          const Item *item) const
{
  DBUG_ASSERT(cmp_type() == INT_RESULT);
  DBUG_ASSERT(result_type() == STRING_RESULT);

  switch (item->cmp_type())
  {
  case TIME_RESULT:
    return false;
  case INT_RESULT:
  case DECIMAL_RESULT:
  case REAL_RESULT:
    return true;
  case STRING_RESULT:
9118
    return charset() == cond->compare_collation();
9119 9120 9121 9122 9123 9124 9125 9126
  case ROW_RESULT:
    DBUG_ASSERT(0);
    break;
  }
  return false;
}


unknown's avatar
unknown committed
9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155
/*
  Bit field.

  We store the first 0 - 6 uneven bits among the null bits 
  at the start of the record. The rest bytes are stored in 
  the record itself.

  For example:

  CREATE TABLE t1 (a int, b bit(17), c bit(21) not null, d bit(8));
  We would store data  as follows in the record:

  Byte        Bit
  1           7 - reserve for delete
              6 - null bit for 'a'
              5 - null bit for 'b'
              4 - first (high) bit of 'b'
              3 - first (high) bit of 'c'
              2 - second bit of 'c'
              1 - third bit of 'c'
              0 - forth bit of 'c'
  2           7 - firth bit of 'c'
              6 - null bit for 'd'
  3 - 6       four bytes for 'a'
  7 - 8       two bytes for 'b'
  9 - 10      two bytes for 'c'
  11          one byte for 'd'
*/

9156
Field_bit::Field_bit(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
unknown's avatar
unknown committed
9157
                     uchar null_bit_arg, uchar *bit_ptr_arg, uchar bit_ofs_arg,
unknown's avatar
unknown committed
9158
                     enum utype unireg_check_arg, const char *field_name_arg)
unknown's avatar
unknown committed
9159
  : Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
unknown's avatar
unknown committed
9160
          unireg_check_arg, field_name_arg),
unknown's avatar
unknown committed
9161 9162
    bit_ptr(bit_ptr_arg), bit_ofs(bit_ofs_arg), bit_len(len_arg & 7),
    bytes_in_rec(len_arg / 8)
unknown's avatar
unknown committed
9163
{
9164 9165 9166
  DBUG_ENTER("Field_bit::Field_bit");
  DBUG_PRINT("enter", ("ptr_arg: %p, null_ptr_arg: %p, len_arg: %u, bit_len: %u, bytes_in_rec: %u",
                       ptr_arg, null_ptr_arg, len_arg, bit_len, bytes_in_rec));
unknown's avatar
unknown committed
9167
  flags|= UNSIGNED_FLAG;
unknown's avatar
unknown committed
9168 9169 9170 9171 9172 9173
  /*
    Ensure that Field::eq() can distinguish between two different bit fields.
    (two bit fields that are not null, may have same ptr and null_ptr)
  */
  if (!null_ptr_arg)
    null_bit= bit_ofs_arg;
9174
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
9175 9176 9177
}


9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194
void Field_bit::hash(ulong *nr, ulong *nr2)
{
  if (is_null())
  {
    *nr^= (*nr << 1) | 1;
  }
  else
  {
    CHARSET_INFO *cs= &my_charset_bin;
    longlong value= Field_bit::val_int();
    uchar tmp[8];
    mi_int8store(tmp,value);
    cs->coll->hash_sort(cs, tmp, 8, nr, nr2);
  }
}


9195
size_t
9196 9197 9198 9199 9200 9201 9202 9203 9204 9205
Field_bit::do_last_null_byte() const
{
  /*
    Code elsewhere is assuming that bytes are 8 bits, so I'm using
    that value instead of the correct one: CHAR_BIT.

    REFACTOR SUGGESTION (Matz): Change to use the correct number of
    bits. On systems with CHAR_BIT > 8 (not very common), the storage
    will lose the extra bits.
  */
unknown's avatar
unknown committed
9206 9207
  DBUG_PRINT("test", ("bit_ofs: %d, bit_len: %d  bit_ptr: 0x%lx",
                      bit_ofs, bit_len, (long) bit_ptr));
9208 9209 9210 9211 9212 9213 9214 9215
  uchar *result;
  if (bit_len == 0)
    result= null_ptr;
  else if (bit_ofs + bit_len > 8)
    result= bit_ptr + 1;
  else
    result= bit_ptr;

9216
  if (result)
9217 9218
    return (size_t) (result - table->record[0]) + 1;
  return LAST_NULL_BYTE_UNDEF;
9219 9220
}

9221

9222 9223 9224
Field *Field_bit::new_key_field(MEM_ROOT *root, TABLE *new_table,
                                uchar *new_ptr, uint32 length, 
                                uchar *new_null_ptr, uint new_null_bit)
unknown's avatar
unknown committed
9225 9226
{
  Field_bit *res;
9227 9228
  if ((res= (Field_bit*) Field::new_key_field(root, new_table, new_ptr, length,
                                              new_null_ptr, new_null_bit)))
unknown's avatar
unknown committed
9229 9230
  {
    /* Move bits normally stored in null_pointer to new_ptr */
9231
    res->bit_ptr= new_ptr;
unknown's avatar
unknown committed
9232 9233 9234 9235 9236 9237 9238 9239
    res->bit_ofs= 0;
    if (bit_len)
      res->ptr++;                               // Store rest of data here
  }
  return res;
}


unknown's avatar
unknown committed
9240
uint Field_bit::is_equal(Create_field *new_field) 
9241 9242 9243 9244 9245 9246
{
  return (new_field->sql_type == real_type() &&
          new_field->length == max_display_length());
}

                       
unknown's avatar
unknown committed
9247 9248
int Field_bit::store(const char *from, uint length, CHARSET_INFO *cs)
{
9249
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
unknown's avatar
unknown committed
9250 9251
  int delta;

9252 9253
  for (; length && !*from; from++, length--)          // skip left 0's
    ;
unknown's avatar
unknown committed
9254
  delta= bytes_in_rec - length;
unknown's avatar
unknown committed
9255 9256 9257 9258 9259

  if (delta < -1 ||
      (delta == -1 && (uchar) *from > ((1 << bit_len) - 1)) ||
      (!bit_len && delta < 0))
  {
9260
    set_rec_bits((1 << bit_len) - 1, bit_ptr, bit_ofs, bit_len);
unknown's avatar
unknown committed
9261
    memset(ptr, 0xff, bytes_in_rec);
9262
    if (get_thd()->really_abort_on_warning())
9263
      set_warning(ER_DATA_TOO_LONG, 1);
9264
    else
9265
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288
    return 1;
  }
  /* delta is >= -1 here */
  if (delta > 0)
  {
    if (bit_len)
      clr_rec_bits(bit_ptr, bit_ofs, bit_len);
    bzero(ptr, delta);
    memcpy(ptr + delta, from, length);
  }
  else if (delta == 0)
  {
    if (bit_len)
      clr_rec_bits(bit_ptr, bit_ofs, bit_len);
    memcpy(ptr, from, length);
  }
  else
  {
    if (bit_len)
    {
      set_rec_bits((uchar) *from, bit_ptr, bit_ofs, bit_len);
      from++;
    }
unknown's avatar
unknown committed
9289
    memcpy(ptr, from, bytes_in_rec);
unknown's avatar
unknown committed
9290 9291 9292 9293 9294 9295 9296
  }
  return 0;
}


int Field_bit::store(double nr)
{
9297
  return Field_bit::store((longlong) nr, FALSE);
unknown's avatar
unknown committed
9298 9299 9300
}


9301
int Field_bit::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
9302 9303 9304 9305 9306 9307 9308 9309
{
  char buf[8];

  mi_int8store(buf, nr);
  return store(buf, 8, NULL);
}


unknown's avatar
unknown committed
9310 9311 9312 9313
int Field_bit::store_decimal(const my_decimal *val)
{
  int err= 0;
  longlong i= convert_decimal2longlong(val, 1, &err);
9314
  return MY_TEST(err | store(i, TRUE));
unknown's avatar
unknown committed
9315 9316 9317
}


unknown's avatar
unknown committed
9318 9319 9320 9321 9322 9323 9324 9325
double Field_bit::val_real(void)
{
  return (double) Field_bit::val_int();
}


longlong Field_bit::val_int(void)
{
9326
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
9327 9328
  ulonglong bits= 0;
  if (bit_len)
9329
  {
unknown's avatar
unknown committed
9330
    bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
unknown's avatar
unknown committed
9331
    bits<<= (bytes_in_rec * 8);
9332
  }
unknown's avatar
unknown committed
9333

unknown's avatar
unknown committed
9334
  switch (bytes_in_rec) {
unknown's avatar
unknown committed
9335
  case 0: return bits;
9336
  case 1: return bits | (ulonglong) ptr[0];
unknown's avatar
unknown committed
9337 9338 9339 9340 9341 9342
  case 2: return bits | mi_uint2korr(ptr);
  case 3: return bits | mi_uint3korr(ptr);
  case 4: return bits | mi_uint4korr(ptr);
  case 5: return bits | mi_uint5korr(ptr);
  case 6: return bits | mi_uint6korr(ptr);
  case 7: return bits | mi_uint7korr(ptr);
unknown's avatar
unknown committed
9343
  default: return mi_uint8korr(ptr + bytes_in_rec - sizeof(longlong));
unknown's avatar
unknown committed
9344 9345 9346 9347 9348 9349 9350
  }
}  


String *Field_bit::val_str(String *val_buffer,
                           String *val_ptr __attribute__((unused)))
{
9351
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
9352
  char buff[sizeof(longlong)];
9353
  uint length= MY_MIN(pack_length(), sizeof(longlong));
unknown's avatar
unknown committed
9354
  ulonglong bits= val_int();
unknown's avatar
unknown committed
9355
  mi_int8store(buff,bits);
unknown's avatar
unknown committed
9356 9357

  val_buffer->alloc(length);
9358
  memcpy((char *) val_buffer->ptr(), buff+8-length, length);
unknown's avatar
unknown committed
9359 9360 9361 9362 9363 9364
  val_buffer->length(length);
  val_buffer->set_charset(&my_charset_bin);
  return val_buffer;
}


unknown's avatar
unknown committed
9365 9366
my_decimal *Field_bit::val_decimal(my_decimal *deciaml_value)
{
9367
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
9368 9369 9370 9371 9372
  int2my_decimal(E_DEC_FATAL_ERROR, val_int(), 1, deciaml_value);
  return deciaml_value;
}


9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385
/*
  Compare two bit fields using pointers within the record.
  SYNOPSIS
    cmp_max()
    a                 Pointer to field->ptr in first record
    b                 Pointer to field->ptr in second record
    max_len           Maximum length used in index
  DESCRIPTION
    This method is used from key_rec_cmp used by merge sorts used
    by partitioned index read and later other similar places.
    The a and b pointer must be pointers to the field in a record
    (not the table->record[0] necessarily)
*/
9386
int Field_bit::cmp_max(const uchar *a, const uchar *b, uint max_len)
9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397
{
  my_ptrdiff_t a_diff= a - ptr;
  my_ptrdiff_t b_diff= b - ptr;
  if (bit_len)
  {
    int flag;
    uchar bits_a= get_rec_bits(bit_ptr+a_diff, bit_ofs, bit_len);
    uchar bits_b= get_rec_bits(bit_ptr+b_diff, bit_ofs, bit_len);
    if ((flag= (int) (bits_a - bits_b)))
      return flag;
  }
Igor Babaev's avatar
Igor Babaev committed
9398 9399 9400
  if (!bytes_in_rec)
    return 0;
  return memcmp(a, b, bytes_in_rec);
9401 9402 9403
}


9404
int Field_bit::key_cmp(const uchar *str, uint length)
unknown's avatar
unknown committed
9405 9406 9407 9408 9409
{
  if (bit_len)
  {
    int flag;
    uchar bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
9410
    if ((flag= (int) (bits - *str)))
unknown's avatar
unknown committed
9411 9412 9413 9414
      return flag;
    str++;
    length--;
  }
unknown's avatar
unknown committed
9415
  return memcmp(ptr, str, length);
unknown's avatar
unknown committed
9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428
}


int Field_bit::cmp_offset(uint row_offset)
{
  if (bit_len)
  {
    int flag;
    uchar bits_a= get_rec_bits(bit_ptr, bit_ofs, bit_len);
    uchar bits_b= get_rec_bits(bit_ptr + row_offset, bit_ofs, bit_len);
    if ((flag= (int) (bits_a - bits_b)))
      return flag;
  }
unknown's avatar
unknown committed
9429
  return memcmp(ptr, ptr + row_offset, bytes_in_rec);
unknown's avatar
unknown committed
9430 9431 9432
}


9433
uint Field_bit::get_key_image(uchar *buff, uint length, imagetype type_arg)
unknown's avatar
unknown committed
9434 9435 9436 9437 9438 9439 9440
{
  if (bit_len)
  {
    uchar bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
    *buff++= bits;
    length--;
  }
9441 9442 9443
  uint tmp_data_length = MY_MIN(length, bytes_in_rec);
  memcpy(buff, ptr, tmp_data_length);
  return tmp_data_length + 1;
unknown's avatar
unknown committed
9444 9445 9446
}


9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459
/**
   Save the field metadata for bit fields.

   Saves the bit length in the first byte and bytes in record in the
   second byte of the field metadata array at index of *metadata_ptr and
   *(metadata_ptr + 1).

   @param   metadata_ptr   First byte of field metadata

   @returns number of bytes written to metadata_ptr
*/
int Field_bit::do_save_field_metadata(uchar *metadata_ptr)
{
9460 9461 9462
  DBUG_ENTER("Field_bit::do_save_field_metadata");
  DBUG_PRINT("debug", ("bit_len: %d, bytes_in_rec: %d",
                       bit_len, bytes_in_rec));
9463 9464 9465 9466 9467 9468 9469
  /*
    Since this class and Field_bit_as_char have different ideas of
    what should be stored here, we compute the values of the metadata
    explicitly using the field_length.
   */
  metadata_ptr[0]= field_length % 8;
  metadata_ptr[1]= field_length / 8;
9470
  DBUG_RETURN(2);
9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494
}


/**
   Returns the number of bytes field uses in row-based replication 
   row packed size.

   This method is used in row-based replication to determine the number
   of bytes that the field consumes in the row record format. This is
   used to skip fields in the master that do not exist on the slave.

   @param   field_metadata   Encoded size in field metadata

   @returns The size of the field based on the field metadata.
*/
uint Field_bit::pack_length_from_metadata(uint field_metadata)
{
  uint const from_len= (field_metadata >> 8U) & 0x00ff;
  uint const from_bit_len= field_metadata & 0x00ff;
  uint const source_size= from_len + ((from_bit_len > 0) ? 1 : 0);
  return (source_size);
}


9495 9496 9497
bool
Field_bit::compatible_field_size(uint field_metadata,
                                 Relay_log_info * __attribute__((unused)),
9498
                                 uint16 mflags,
9499
                                 int *order_var)
9500
{
9501 9502
  DBUG_ENTER("Field_bit::compatible_field_size");
  DBUG_ASSERT((field_metadata >> 16) == 0);
9503
  uint from_bit_len=
9504
    8 * (field_metadata >> 8) + (field_metadata & 0xff);
9505
  uint to_bit_len= max_display_length();
9506 9507
  DBUG_PRINT("debug", ("from_bit_len: %u, to_bit_len: %u",
                       from_bit_len, to_bit_len));
9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520
  /*
    If the bit length exact flag is clear, we are dealing with an old
    master, so we allow some less strict behaviour if replicating by
    moving both bit lengths to an even multiple of 8.

    We do this by computing the number of bytes to store the field
    instead, and then compare the result.
   */
  if (!(mflags & Table_map_log_event::TM_BIT_LEN_EXACT_F)) {
    from_bit_len= (from_bit_len + 7) / 8;
    to_bit_len= (to_bit_len + 7) / 8;
  }

9521 9522
  *order_var= compare(from_bit_len, to_bit_len);
  DBUG_RETURN(TRUE);
9523 9524 9525 9526
}



unknown's avatar
unknown committed
9527 9528 9529 9530
void Field_bit::sql_type(String &res) const
{
  CHARSET_INFO *cs= res.charset();
  ulong length= cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
unknown's avatar
unknown committed
9531
                                   "bit(%d)", (int) field_length);
unknown's avatar
unknown committed
9532 9533 9534 9535
  res.length((uint) length);
}


9536
uchar *
Sergei Golubchik's avatar
Sergei Golubchik committed
9537
Field_bit::pack(uchar *to, const uchar *from, uint max_length)
unknown's avatar
unknown committed
9538
{
9539
  DBUG_ASSERT(max_length > 0);
unknown's avatar
unknown committed
9540
  uint length;
unknown's avatar
unknown committed
9541
  if (bit_len > 0)
unknown's avatar
unknown committed
9542
  {
unknown's avatar
unknown committed
9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562
    /*
      We have the following:

      ptr        Points into a field in record R1
      from       Points to a field in a record R2
      bit_ptr    Points to the byte (in the null bytes) that holds the
                 odd bits of R1
      from_bitp  Points to the byte that holds the odd bits of R2

      We have the following:

          ptr - bit_ptr = from - from_bitp

      We want to isolate 'from_bitp', so this gives:

          ptr - bit_ptr - from = - from_bitp
          - ptr + bit_ptr + from = from_bitp
          bit_ptr + from - ptr = from_bitp
     */
    uchar bits= get_rec_bits(bit_ptr + (from - ptr), bit_ofs, bit_len);
unknown's avatar
unknown committed
9563 9564
    *to++= bits;
  }
9565
  length= MY_MIN(bytes_in_rec, max_length - (bit_len > 0));
unknown's avatar
unknown committed
9566
  memcpy(to, from, length);
unknown's avatar
unknown committed
9567 9568 9569 9570
  return to + length;
}


9571 9572 9573
/**
   Unpack a bit field from row data.

9574
   This method is used to unpack a bit field from a master whose size
9575
   of the field is less than that of the slave.
9576

9577 9578 9579 9580 9581 9582
   @param   to         Destination of the data
   @param   from       Source of the data
   @param   param_data Bit length (upper) and length (lower) values

   @return  New pointer into memory based on from + length of the data
*/
9583
const uchar *
9584 9585
Field_bit::unpack(uchar *to, const uchar *from, const uchar *from_end,
                  uint param_data)
9586
{
9587 9588 9589 9590 9591
  DBUG_ENTER("Field_bit::unpack");
  DBUG_PRINT("enter", ("to: %p, from: %p, param_data: 0x%x",
                       to, from, param_data));
  DBUG_PRINT("debug", ("bit_ptr: %p, bit_len: %u, bit_ofs: %u",
                       bit_ptr, bit_len, bit_ofs));
9592 9593
  uint const from_len= (param_data >> 8U) & 0x00ff;
  uint const from_bit_len= param_data & 0x00ff;
9594 9595
  DBUG_PRINT("debug", ("from_len: %u, from_bit_len: %u",
                       from_len, from_bit_len));
9596
  /*
9597 9598
    If the parameter data is zero (i.e., undefined), or if the master
    and slave have the same sizes, then use the old unpack() method.
9599
  */
9600
  if (param_data == 0 ||
9601
      ((from_bit_len == bit_len) && (from_len == bytes_in_rec)))
9602
  {
9603
    if (from + bytes_in_rec + MY_TEST(bit_len) > from_end)
9604 9605
      return 0;                                 // Error in data

9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618
    if (bit_len > 0)
    {
      /*
        set_rec_bits is a macro, don't put the post-increment in the
        argument since that might cause strange side-effects.

        For the choice of the second argument, see the explanation for
        Field_bit::pack().
      */
      set_rec_bits(*from, bit_ptr + (to - ptr), bit_ofs, bit_len);
      from++;
    }
    memcpy(to, from, bytes_in_rec);
9619
    DBUG_RETURN(from + bytes_in_rec);
9620 9621
  }

9622 9623 9624 9625 9626 9627 9628 9629
  /*
    We are converting a smaller bit field to a larger one here.
    To do that, we first need to construct a raw value for the original
    bit value stored in the from buffer. Then that needs to be converted
    to the larger field then sent to store() for writing to the field.
    Lastly the odd bits need to be masked out if the bytes_in_rec > 0.
    Otherwise stray bits can cause spurious values.
  */
9630 9631

  uint len= from_len + ((from_bit_len > 0) ? 1 : 0);
9632
  uint new_len= (field_length + 7) / 8;
9633 9634 9635 9636

  if (from + len > from_end || new_len < len)
    return 0;                                 // Error in data

9637 9638
  char *value= (char *)my_alloca(new_len);
  bzero(value, new_len);
9639

9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650
  memcpy(value + (new_len - len), from, len);
  /*
    Mask out the unused bits in the partial byte. 
    TODO: Add code to the master to always mask these bits and remove
          the following.
  */
  if ((from_bit_len > 0) && (from_len > 0))
    value[new_len - len]= value[new_len - len] & ((1U << from_bit_len) - 1);
  bitmap_set_bit(table->write_set,field_index);
  store(value, new_len, system_charset_info);
  my_afree(value);
9651
  DBUG_RETURN(from + len);
9652 9653 9654
}


9655 9656
void Field_bit::set_default()
{
9657 9658
  if (bit_len > 0)
  {
9659 9660
    my_ptrdiff_t const col_offset= table->s->default_values - table->record[0];
    uchar bits= get_rec_bits(bit_ptr + col_offset, bit_ofs, bit_len);
9661 9662
    set_rec_bits(bits, bit_ptr, bit_ofs, bit_len);
  }
9663 9664 9665
  Field::set_default();
}

9666 9667 9668 9669
/*
  Bit field support for non-MyISAM tables.
*/

9670
Field_bit_as_char::Field_bit_as_char(uchar *ptr_arg, uint32 len_arg,
9671 9672
                                     uchar *null_ptr_arg, uchar null_bit_arg,
                                     enum utype unireg_check_arg,
unknown's avatar
unknown committed
9673
                                     const char *field_name_arg)
9674
  :Field_bit(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, 0, 0,
unknown's avatar
unknown committed
9675
             unireg_check_arg, field_name_arg)
9676
{
unknown's avatar
unknown committed
9677
  flags|= UNSIGNED_FLAG;
9678
  bit_len= 0;
unknown's avatar
unknown committed
9679
  bytes_in_rec= (len_arg + 7) / 8;
9680 9681 9682 9683 9684
}


int Field_bit_as_char::store(const char *from, uint length, CHARSET_INFO *cs)
{
9685
  ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
9686
  int delta;
9687
  uchar bits= (uchar) (field_length & 7);
9688

9689 9690
  for (; length && !*from; from++, length--)          // skip left 0's
    ;
unknown's avatar
unknown committed
9691
  delta= bytes_in_rec - length;
9692 9693 9694 9695

  if (delta < 0 ||
      (delta == 0 && bits && (uint) (uchar) *from >= (uint) (1 << bits)))
  {
unknown's avatar
unknown committed
9696
    memset(ptr, 0xff, bytes_in_rec);
9697
    if (bits)
9698
      *ptr&= ((1 << bits) - 1); /* set first uchar */
9699
    if (get_thd()->really_abort_on_warning())
9700
      set_warning(ER_DATA_TOO_LONG, 1);
9701
    else
9702
      set_warning(ER_WARN_DATA_OUT_OF_RANGE, 1);
9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714
    return 1;
  }
  bzero(ptr, delta);
  memcpy(ptr + delta, from, length);
  return 0;
}


void Field_bit_as_char::sql_type(String &res) const
{
  CHARSET_INFO *cs= res.charset();
  ulong length= cs->cset->snprintf(cs, (char*) res.ptr(), res.alloced_length(),
unknown's avatar
unknown committed
9715
                                   "bit(%d)", (int) field_length);
9716 9717 9718 9719
  res.length((uint) length);
}


unknown's avatar
unknown committed
9720
/*****************************************************************************
unknown's avatar
unknown committed
9721
  Handling of field and Create_field
unknown's avatar
unknown committed
9722 9723
*****************************************************************************/

9724 9725
/**
  Convert create_field::length from number of characters to number of bytes.
9726 9727
*/

Alexander Barkov's avatar
Alexander Barkov committed
9728
void Column_definition::create_length_to_internal_length(void)
9729
{
unknown's avatar
unknown committed
9730 9731 9732 9733 9734
  switch (sql_type) {
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_MEDIUM_BLOB:
  case MYSQL_TYPE_LONG_BLOB:
  case MYSQL_TYPE_BLOB:
9735
  case MYSQL_TYPE_GEOMETRY:
unknown's avatar
unknown committed
9736 9737
  case MYSQL_TYPE_VAR_STRING:
  case MYSQL_TYPE_STRING:
9738
  case MYSQL_TYPE_VARCHAR:
unknown's avatar
unknown committed
9739
    length*= charset->mbmaxlen;
9740
    key_length= length;
9741
    pack_length= calc_pack_length(sql_type, length);
unknown's avatar
unknown committed
9742 9743 9744
    break;
  case MYSQL_TYPE_ENUM:
  case MYSQL_TYPE_SET:
9745
    /* Pack_length already calculated in sql_parse.cc */
unknown's avatar
unknown committed
9746
    length*= charset->mbmaxlen;
9747
    key_length= pack_length;
unknown's avatar
unknown committed
9748
    break;
unknown's avatar
unknown committed
9749
  case MYSQL_TYPE_BIT:
9750 9751 9752 9753 9754 9755 9756 9757
    if (f_bit_as_char(pack_flag))
    {
      key_length= pack_length= ((length + 7) & ~7) / 8;
    }
    else
    {
      pack_length= length / 8;
      /* We need one extra byte to store the bits we save among the null bits */
9758
      key_length= pack_length + MY_TEST(length & 7);
9759
    }
unknown's avatar
unknown committed
9760
    break;
unknown's avatar
unknown committed
9761
  case MYSQL_TYPE_NEWDECIMAL:
unknown's avatar
unknown committed
9762 9763 9764 9765 9766 9767
    key_length= pack_length=
      my_decimal_get_binary_size(my_decimal_length_to_precision(length,
								decimals,
								flags &
								UNSIGNED_FLAG),
				 decimals);
unknown's avatar
unknown committed
9768
    break;
unknown's avatar
unknown committed
9769
  default:
9770
    key_length= pack_length= calc_pack_length(sql_type, length);
unknown's avatar
unknown committed
9771
    break;
9772 9773 9774
  }
}

9775

9776 9777 9778
bool check_expression(Virtual_column_info *vcol, const char *name,
                      enum_vcol_info_type type)

9779
{
9780 9781
  bool ret;
  Item::vcol_func_processor_result res;
9782 9783 9784

  if (!vcol->name.length)
    vcol->name.str= const_cast<char*>(name);
9785 9786 9787 9788 9789 9790

  /*
    Walk through the Item tree checking if all items are valid
    to be part of the virtual column
  */
  res.errors= 0;
9791
  ret= vcol->expr_item->walk(&Item::check_vcol_func_processor, 0, &res);
9792
  vcol->flags= res.errors;
9793

9794
  uint filter= VCOL_IMPOSSIBLE;
9795
  if (type != VCOL_GENERATED_VIRTUAL && type != VCOL_DEFAULT)
9796 9797 9798
    filter|= VCOL_NOT_STRICTLY_DETERMINISTIC;

  if (ret || (res.errors & filter))
9799 9800
  {
    my_error(ER_VIRTUAL_COLUMN_FUNCTION_IS_NOT_ALLOWED, MYF(0), res.name,
9801
             vcol_type_name(type), name);
9802 9803 9804 9805 9806 9807 9808 9809 9810
    return TRUE;
  }
  /*
    Safe to call before fix_fields as long as vcol's don't include sub
    queries (which is now checked in check_vcol_func_processor)
  */
  if (vcol->expr_item->check_cols(1))
    return TRUE;
  return FALSE;
9811
}
9812

9813

Alexander Barkov's avatar
Alexander Barkov committed
9814
bool Column_definition::check(THD *thd)
9815
{
9816
  const uint conditional_type_modifiers= AUTO_INCREMENT_FLAG;
9817 9818
  uint sign_len, allowed_type_modifier= 0;
  ulong max_field_charlength= MAX_FIELD_CHARLENGTH;
Michael Widenius's avatar
Michael Widenius committed
9819
  DBUG_ENTER("Column_definition::check");
9820

9821
  /* Initialize data for a computed field */
9822 9823
  if (vcol_info)
  {
Sergei Golubchik's avatar
Sergei Golubchik committed
9824
    DBUG_ASSERT(vcol_info->expr_item);
9825
    vcol_info->set_field_type(sql_type);
9826 9827
    if (check_expression(vcol_info, field_name, vcol_info->stored_in_db
                         ? VCOL_GENERATED_STORED : VCOL_GENERATED_VIRTUAL))
9828
      DBUG_RETURN(TRUE);
9829 9830
  }

9831
  if (check_constraint &&
9832 9833
      check_expression(check_constraint, field_name, VCOL_CHECK_FIELD))
      DBUG_RETURN(1);
9834 9835

  if (default_value)
9836
  {
9837
    Item *def_expr= default_value->expr_item;
9838
    if (check_expression(default_value, field_name, VCOL_DEFAULT))
9839
      DBUG_RETURN(TRUE);
9840 9841 9842

    /* Constant's are stored in the 'empty_record', except for blobs */
    if (def_expr->basic_const_item())
9843
    {
9844
      if (def_expr->type() == Item::NULL_ITEM)
9845
      {
9846 9847 9848 9849 9850 9851
        default_value= 0;
        if ((flags & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) == NOT_NULL_FLAG)
        {
          my_error(ER_INVALID_DEFAULT, MYF(0), field_name);
          DBUG_RETURN(1);
        }
9852 9853
      }
    }
9854
  }
9855

9856 9857 9858 9859
  if (default_value && (flags & AUTO_INCREMENT_FLAG))
  {
    my_error(ER_INVALID_DEFAULT, MYF(0), field_name);
    DBUG_RETURN(1);
9860
  }
9861

9862 9863 9864
  if (default_value && !default_value->expr_item->basic_const_item() &&
      mysql_type_to_time_type(sql_type) == MYSQL_TIMESTAMP_DATETIME &&
      default_value->expr_item->type() == Item::FUNC_ITEM)
9865
  {
9866
    /*
9867 9868
      Special case: NOW() for TIMESTAMP and DATETIME fields are handled
      as in MariaDB 10.1 by marking them in unireg_check.
9869
    */
9870 9871 9872
    Item_func *fn= static_cast<Item_func*>(default_value->expr_item);
    if (fn->functype() == Item_func::NOW_FUNC &&
        (fn->decimals == 0 || fn->decimals >= length))
9873 9874
    {
      default_value= 0;
9875
      unireg_check= Field::TIMESTAMP_DN_FIELD;
9876
    }
9877 9878
  }

9879
  if (on_update)
9880
  {
9881 9882 9883 9884 9885 9886 9887 9888
    if (mysql_type_to_time_type(sql_type) != MYSQL_TIMESTAMP_DATETIME ||
        on_update->decimals < length)
    {
      my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name);
      DBUG_RETURN(TRUE);
    }
    unireg_check= unireg_check == Field::NONE ? Field::TIMESTAMP_UN_FIELD
                                              : Field::TIMESTAMP_DNUN_FIELD;
9889
  }
9890 9891
  else if (flags & AUTO_INCREMENT_FLAG)
    unireg_check= Field::NEXT_NUMBER;
9892

9893
  sign_len= flags & UNSIGNED_FLAG ? 0 : 1;
9894

9895
  switch (sql_type) {
9896
  case MYSQL_TYPE_TINY:
9897
    if (!length)
9898 9899 9900
      length= MAX_TINYINT_WIDTH+sign_len;
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
    break;
9901
  case MYSQL_TYPE_SHORT:
9902
    if (!length)
9903 9904 9905
      length= MAX_SMALLINT_WIDTH+sign_len;
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
    break;
9906
  case MYSQL_TYPE_INT24:
9907
    if (!length)
9908 9909 9910
      length= MAX_MEDIUMINT_WIDTH+sign_len;
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
    break;
9911
  case MYSQL_TYPE_LONG:
9912
    if (!length)
9913 9914 9915
      length= MAX_INT_WIDTH+sign_len;
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
    break;
9916
  case MYSQL_TYPE_LONGLONG:
9917
    if (!length)
9918 9919 9920
      length= MAX_BIGINT_WIDTH;
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
    break;
9921
  case MYSQL_TYPE_NULL:
9922
    break;
9923
  case MYSQL_TYPE_NEWDECIMAL:
9924 9925 9926 9927 9928 9929
    if (decimals >= NOT_FIXED_DEC)
    {
      my_error(ER_TOO_BIG_SCALE, MYF(0), static_cast<ulonglong>(decimals),
               field_name, static_cast<ulong>(NOT_FIXED_DEC - 1));
      DBUG_RETURN(TRUE);
    }
9930
    my_decimal_trim(&length, &decimals);
9931 9932
    if (length > DECIMAL_MAX_PRECISION)
    {
9933 9934
      my_error(ER_TOO_BIG_PRECISION, MYF(0), length, field_name,
               DECIMAL_MAX_PRECISION);
9935 9936 9937 9938
      DBUG_RETURN(TRUE);
    }
    if (length < decimals)
    {
9939
      my_error(ER_M_BIGGER_THAN_D, MYF(0), field_name);
9940 9941 9942
      DBUG_RETURN(TRUE);
    }
    length=
9943
      my_decimal_precision_to_length(length, decimals, flags & UNSIGNED_FLAG);
9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955
    pack_length=
      my_decimal_get_binary_size(length, decimals);
    break;
  case MYSQL_TYPE_VARCHAR:
    /*
      Long VARCHAR's are automaticly converted to blobs in mysql_prepare_table
      if they don't have a default value
    */
    max_field_charlength= MAX_FIELD_VARCHARLENGTH;
    break;
  case MYSQL_TYPE_STRING:
    break;
9956 9957 9958 9959 9960
  case MYSQL_TYPE_BLOB:
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_LONG_BLOB:
  case MYSQL_TYPE_MEDIUM_BLOB:
  case MYSQL_TYPE_GEOMETRY:
9961 9962
    flags|= BLOB_FLAG;
    break;
9963
  case MYSQL_TYPE_YEAR:
9964
    if (!length || length != 2)
9965 9966 9967
      length= 4; /* Default length */
    flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
    break;
9968
  case MYSQL_TYPE_FLOAT:
9969 9970
    /* change FLOAT(precision) to FLOAT or DOUBLE */
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
9971
    if (!length && !decimals)
9972
    {
9973
      length=  MAX_FLOAT_STR_LENGTH;
9974 9975 9976 9977 9978
      decimals= NOT_FIXED_DEC;
    }
    if (length < decimals &&
        decimals != NOT_FIXED_DEC)
    {
9979
      my_error(ER_M_BIGGER_THAN_D, MYF(0), field_name);
9980 9981
      DBUG_RETURN(TRUE);
    }
9982 9983 9984 9985 9986 9987
    if (decimals != NOT_FIXED_DEC && decimals >= FLOATING_POINT_DECIMALS)
    {
      my_error(ER_TOO_BIG_SCALE, MYF(0), static_cast<ulonglong>(decimals),
               field_name, static_cast<ulong>(FLOATING_POINT_DECIMALS-1));
      DBUG_RETURN(TRUE);
    }
9988
    break;
9989
  case MYSQL_TYPE_DOUBLE:
9990
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
9991
    if (!length && !decimals)
9992 9993 9994 9995 9996 9997 9998
    {
      length= DBL_DIG+7;
      decimals= NOT_FIXED_DEC;
    }
    if (length < decimals &&
        decimals != NOT_FIXED_DEC)
    {
9999
      my_error(ER_M_BIGGER_THAN_D, MYF(0), field_name);
10000 10001
      DBUG_RETURN(TRUE);
    }
10002 10003 10004 10005 10006 10007
    if (decimals != NOT_FIXED_DEC && decimals >= FLOATING_POINT_DECIMALS)
    {
      my_error(ER_TOO_BIG_SCALE, MYF(0), static_cast<ulonglong>(decimals),
               field_name, static_cast<ulong>(FLOATING_POINT_DECIMALS-1));
      DBUG_RETURN(TRUE);
    }
10008
    break;
10009
  case MYSQL_TYPE_TIMESTAMP:
10010
  case MYSQL_TYPE_TIMESTAMP2:
10011
    if (length > MAX_DATETIME_PRECISION)
10012
    {
10013
      my_error(ER_TOO_BIG_PRECISION, MYF(0), length, field_name,
10014 10015
               MAX_DATETIME_PRECISION);
      DBUG_RETURN(TRUE);
10016
    }
10017 10018
    length+= MAX_DATETIME_WIDTH + (length ? 1 : 0);
    flags|= UNSIGNED_FLAG;
10019
    break;
10020
  case MYSQL_TYPE_DATE:
Michael Widenius's avatar
Michael Widenius committed
10021
    /* We don't support creation of MYSQL_TYPE_DATE anymore */
10022
    sql_type= MYSQL_TYPE_NEWDATE;
10023
    /* fall trough */
10024
  case MYSQL_TYPE_NEWDATE:
10025
    length= MAX_DATE_WIDTH;
10026
    break;
10027
  case MYSQL_TYPE_TIME:
10028
  case MYSQL_TYPE_TIME2:
10029 10030
    if (length > MAX_DATETIME_PRECISION)
    {
10031
      my_error(ER_TOO_BIG_PRECISION, MYF(0), length, field_name,
10032 10033 10034 10035
               MAX_DATETIME_PRECISION);
      DBUG_RETURN(TRUE);
    }
    length+= MIN_TIME_WIDTH + (length ? 1 : 0);
10036
    break;
10037
  case MYSQL_TYPE_DATETIME:
10038
  case MYSQL_TYPE_DATETIME2:
10039 10040
    if (length > MAX_DATETIME_PRECISION)
    {
10041
      my_error(ER_TOO_BIG_PRECISION, MYF(0), length, field_name,
10042 10043 10044 10045
               MAX_DATETIME_PRECISION);
      DBUG_RETURN(TRUE);
    }
    length+= MAX_DATETIME_WIDTH + (length ? 1 : 0);
10046
    break;
10047
  case MYSQL_TYPE_SET:
10048 10049
    pack_length= get_set_pack_length(interval_list.elements);
    break;
10050
  case MYSQL_TYPE_ENUM:
10051 10052 10053
    /* Should be safe. */
    pack_length= get_enum_pack_length(interval_list.elements);
    break;
10054 10055 10056 10057 10058
  case MYSQL_TYPE_VAR_STRING:
    DBUG_ASSERT(0);  /* Impossible. */
    break;
  case MYSQL_TYPE_BIT:
    {
10059
      if (!length)
10060 10061 10062
        length= 1;
      if (length > MAX_BIT_FIELD_LENGTH)
      {
10063
        my_error(ER_TOO_BIG_DISPLAYWIDTH, MYF(0), field_name,
10064
                 static_cast<ulong>(MAX_BIT_FIELD_LENGTH));
10065 10066 10067 10068 10069
        DBUG_RETURN(TRUE);
      }
      pack_length= (length + 7) / 8;
      break;
    }
10070
  case MYSQL_TYPE_DECIMAL:
10071
    DBUG_ASSERT(0); /* Was obsolete */
10072
  }
unknown's avatar
unknown committed
10073 10074
  /* Remember the value of length */
  char_length= length;
10075

10076 10077
  /*
    Set NO_DEFAULT_VALUE_FLAG if this field doesn't have a default value and
10078
    it is NOT NULL, not an AUTO_INCREMENT field.
10079 10080 10081
    We need to do this check here and in mysql_create_prepare_table() as
    sp_head::fill_field_definition() calls this function.
  */
10082
  if (!default_value && unireg_check == Field::NONE && (flags & NOT_NULL_FLAG))
10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093
  {
    /*
      TIMESTAMP columns get implicit DEFAULT value when
      explicit_defaults_for_timestamp is not set.
    */
    if (opt_explicit_defaults_for_timestamp ||
        !is_timestamp_type(sql_type))
    {
      flags|= NO_DEFAULT_VALUE_FLAG;
    }
  }
10094

10095
  if (!(flags & BLOB_FLAG) &&
10096
      ((length > max_field_charlength &&
10097
        sql_type != MYSQL_TYPE_VARCHAR) ||
10098 10099 10100 10101 10102 10103 10104 10105
       (length == 0 &&
        sql_type != MYSQL_TYPE_ENUM && sql_type != MYSQL_TYPE_SET &&
        sql_type != MYSQL_TYPE_STRING && sql_type != MYSQL_TYPE_VARCHAR &&
        sql_type != MYSQL_TYPE_GEOMETRY)))
  {
    my_error((sql_type == MYSQL_TYPE_VAR_STRING ||
              sql_type == MYSQL_TYPE_VARCHAR ||
              sql_type == MYSQL_TYPE_STRING) ?  ER_TOO_BIG_FIELDLENGTH :
10106 10107
                                                ER_TOO_BIG_DISPLAYWIDTH,
              MYF(0),
10108
              field_name, max_field_charlength); /* purecov: inspected */
10109 10110
    DBUG_RETURN(TRUE);
  }
10111 10112 10113 10114 10115 10116
  else if (length > MAX_FIELD_BLOBLENGTH)
  {
    my_error(ER_TOO_BIG_DISPLAYWIDTH, MYF(0), field_name, MAX_FIELD_BLOBLENGTH);
    DBUG_RETURN(1);
  }

10117
  if ((~allowed_type_modifier) & flags & conditional_type_modifiers)
10118
  {
10119
    my_error(ER_WRONG_FIELD_SPEC, MYF(0), field_name);
10120 10121 10122 10123 10124 10125
    DBUG_RETURN(TRUE);
  }

  DBUG_RETURN(FALSE); /* success */
}

10126 10127 10128 10129
enum_field_types get_blob_type_from_length(ulong length)
{
  enum_field_types type;
  if (length < 256)
10130
    type= MYSQL_TYPE_TINY_BLOB;
10131
  else if (length < 65536)
10132
    type= MYSQL_TYPE_BLOB;
10133
  else if (length < 256L*256L*256L)
10134
    type= MYSQL_TYPE_MEDIUM_BLOB;
10135
  else
10136
    type= MYSQL_TYPE_LONG_BLOB;
10137 10138 10139 10140
  return type;
}


unknown's avatar
unknown committed
10141
/*
unknown's avatar
unknown committed
10142
  Make a field from the .frm file info
unknown's avatar
unknown committed
10143 10144 10145 10146 10147
*/

uint32 calc_pack_length(enum_field_types type,uint32 length)
{
  switch (type) {
10148
  case MYSQL_TYPE_VAR_STRING:
10149
  case MYSQL_TYPE_STRING:
10150
  case MYSQL_TYPE_DECIMAL:     return (length);
10151
  case MYSQL_TYPE_VARCHAR:     return (length + (length < 256 ? 1: 2));
10152 10153 10154 10155
  case MYSQL_TYPE_YEAR:
  case MYSQL_TYPE_TINY	: return 1;
  case MYSQL_TYPE_SHORT : return 2;
  case MYSQL_TYPE_INT24:
10156 10157
  case MYSQL_TYPE_NEWDATE: return 3;
  case MYSQL_TYPE_TIME:   return length > MIN_TIME_WIDTH
10158
                            ? time_hires_bytes[length - 1 - MIN_TIME_WIDTH]
10159
                            : 3;
10160 10161 10162
  case MYSQL_TYPE_TIME2:
    return length > MIN_TIME_WIDTH ?
           my_time_binary_length(length - MIN_TIME_WIDTH - 1) : 3;
10163
  case MYSQL_TYPE_TIMESTAMP:
10164 10165 10166
                          return length > MAX_DATETIME_WIDTH
                            ? 4 + sec_part_bytes[length - 1 - MAX_DATETIME_WIDTH]
                            : 4;
10167 10168 10169
  case MYSQL_TYPE_TIMESTAMP2:
    return length > MAX_DATETIME_WIDTH ?
           my_timestamp_binary_length(length - MAX_DATETIME_WIDTH - 1) : 4;
10170 10171 10172 10173 10174
  case MYSQL_TYPE_DATE:
  case MYSQL_TYPE_LONG	: return 4;
  case MYSQL_TYPE_FLOAT : return sizeof(float);
  case MYSQL_TYPE_DOUBLE: return sizeof(double);
  case MYSQL_TYPE_DATETIME:
10175
                          return length > MAX_DATETIME_WIDTH
10176
                            ? datetime_hires_bytes[length - 1 - MAX_DATETIME_WIDTH]
10177
                            : 8;
10178 10179 10180
  case MYSQL_TYPE_DATETIME2:
    return length > MAX_DATETIME_WIDTH ?
           my_datetime_binary_length(length - MAX_DATETIME_WIDTH - 1) : 5;
10181 10182 10183 10184 10185 10186 10187 10188 10189 10190
  case MYSQL_TYPE_LONGLONG: return 8;	/* Don't crash if no longlong */
  case MYSQL_TYPE_NULL	: return 0;
  case MYSQL_TYPE_TINY_BLOB:	return 1+portable_sizeof_char_ptr;
  case MYSQL_TYPE_BLOB:		return 2+portable_sizeof_char_ptr;
  case MYSQL_TYPE_MEDIUM_BLOB:	return 3+portable_sizeof_char_ptr;
  case MYSQL_TYPE_LONG_BLOB:	return 4+portable_sizeof_char_ptr;
  case MYSQL_TYPE_GEOMETRY:	return 4+portable_sizeof_char_ptr;
  case MYSQL_TYPE_SET:
  case MYSQL_TYPE_ENUM:
  case MYSQL_TYPE_NEWDECIMAL:
10191
    abort(); return 0;                          // This shouldn't happen
10192
  case MYSQL_TYPE_BIT: return length / 8;
10193 10194
  default:
    return 0;
unknown's avatar
unknown committed
10195 10196 10197 10198 10199 10200 10201
  }
}


uint pack_length_to_packflag(uint type)
{
  switch (type) {
10202 10203 10204 10205 10206
    case 1: return f_settype((uint) MYSQL_TYPE_TINY);
    case 2: return f_settype((uint) MYSQL_TYPE_SHORT);
    case 3: return f_settype((uint) MYSQL_TYPE_INT24);
    case 4: return f_settype((uint) MYSQL_TYPE_LONG);
    case 8: return f_settype((uint) MYSQL_TYPE_LONGLONG);
unknown's avatar
unknown committed
10207 10208 10209 10210
  }
  return 0;					// This shouldn't happen
}

Sergei Golubchik's avatar
Sergei Golubchik committed
10211

10212 10213 10214
Field *make_field(TABLE_SHARE *share,
                  MEM_ROOT *mem_root,
                  uchar *ptr, uint32 field_length,
unknown's avatar
unknown committed
10215
		  uchar *null_pos, uchar null_bit,
unknown's avatar
unknown committed
10216
		  uint pack_flag,
10217
		  enum_field_types field_type,
10218
		  CHARSET_INFO *field_charset,
10219
		  Field::geometry_type geom_type, uint srid,
unknown's avatar
unknown committed
10220 10221
		  Field::utype unireg_check,
		  TYPELIB *interval,
unknown's avatar
unknown committed
10222
		  const char *field_name)
unknown's avatar
unknown committed
10223
{
10224 10225
  uchar *UNINIT_VAR(bit_ptr);
  uchar UNINIT_VAR(bit_offset);
10226

10227
  if (field_type == MYSQL_TYPE_BIT && !f_bit_as_char(pack_flag))
unknown's avatar
unknown committed
10228 10229 10230 10231 10232 10233 10234 10235 10236 10237
  {
    bit_ptr= null_pos;
    bit_offset= null_bit;
    if (f_maybe_null(pack_flag))         // if null field
    {
       bit_ptr+= (null_bit == 7);        // shift bit_ptr and bit_offset
       bit_offset= (bit_offset + 1) & 7;
    }
  }

unknown's avatar
unknown committed
10238 10239 10240 10241 10242
  if (!f_maybe_null(pack_flag))
  {
    null_pos=0;
    null_bit=0;
  }
unknown's avatar
unknown committed
10243 10244 10245 10246
  else
  {
    null_bit= ((uchar) 1) << null_bit;
  }
unknown's avatar
unknown committed
10247

10248 10249 10250 10251 10252 10253 10254 10255
  DBUG_PRINT("debug", ("field_type: %d, field_length: %u, interval: %p, pack_flag: %s%s%s%s%s",
                       field_type, field_length, interval,
                       FLAGSTR(pack_flag, FIELDFLAG_BINARY),
                       FLAGSTR(pack_flag, FIELDFLAG_INTERVAL),
                       FLAGSTR(pack_flag, FIELDFLAG_NUMBER),
                       FLAGSTR(pack_flag, FIELDFLAG_PACK),
                       FLAGSTR(pack_flag, FIELDFLAG_BLOB)));

unknown's avatar
unknown committed
10256 10257 10258
  if (f_is_alpha(pack_flag))
  {
    if (!f_is_packed(pack_flag))
unknown's avatar
unknown committed
10259
    {
10260
      if (field_type == MYSQL_TYPE_STRING ||
10261
          field_type == MYSQL_TYPE_DECIMAL ||   // 3.23 or 4.0 string
10262
          field_type == MYSQL_TYPE_VAR_STRING)
10263 10264 10265 10266
        return new (mem_root)
          Field_string(ptr,field_length,null_pos,null_bit,
                       unireg_check, field_name,
                       field_charset);
10267
      if (field_type == MYSQL_TYPE_VARCHAR)
10268 10269 10270 10271 10272 10273 10274
        return new (mem_root)
          Field_varstring(ptr,field_length,
                          HA_VARCHAR_PACKLENGTH(field_length),
                          null_pos,null_bit,
                          unireg_check, field_name,
                          share,
                          field_charset);
unknown's avatar
unknown committed
10275 10276
      return 0;                                 // Error
    }
unknown's avatar
unknown committed
10277 10278 10279 10280 10281

    uint pack_length=calc_pack_length((enum_field_types)
				      f_packtype(pack_flag),
				      field_length);

unknown's avatar
unknown committed
10282
#ifdef HAVE_SPATIAL
unknown's avatar
unknown committed
10283
    if (f_is_geom(pack_flag))
10284 10285
    {
      status_var_increment(current_thd->status_var.feature_gis);
10286 10287 10288 10289
      return new (mem_root)
        Field_geom(ptr,null_pos,null_bit,
                   unireg_check, field_name, share,
                   pack_length, geom_type, srid);
10290
    }
unknown's avatar
unknown committed
10291
#endif
unknown's avatar
unknown committed
10292
    if (f_is_blob(pack_flag))
10293 10294 10295 10296
      return new (mem_root)
        Field_blob(ptr,null_pos,null_bit,
                   unireg_check, field_name, share,
                   pack_length, field_charset);
unknown's avatar
unknown committed
10297 10298 10299
    if (interval)
    {
      if (f_is_enum(pack_flag))
10300 10301 10302 10303
	return new (mem_root)
          Field_enum(ptr,field_length,null_pos,null_bit,
                     unireg_check, field_name,
                     pack_length, interval, field_charset);
unknown's avatar
unknown committed
10304
      else
10305 10306 10307 10308
	return new (mem_root)
          Field_set(ptr,field_length,null_pos,null_bit,
                    unireg_check, field_name,
                    pack_length, interval, field_charset);
unknown's avatar
unknown committed
10309 10310 10311
    }
  }

10312
  switch (field_type) {
10313
  case MYSQL_TYPE_DECIMAL:
10314 10315 10316 10317 10318 10319
    return new (mem_root)
      Field_decimal(ptr,field_length,null_pos,null_bit,
                    unireg_check, field_name,
                    f_decimals(pack_flag),
                    f_is_zerofill(pack_flag) != 0,
                    f_is_dec(pack_flag) == 0);
10320
  case MYSQL_TYPE_NEWDECIMAL:
10321 10322 10323 10324 10325 10326
    return new (mem_root)
      Field_new_decimal(ptr,field_length,null_pos,null_bit,
                        unireg_check, field_name,
                        f_decimals(pack_flag),
                        f_is_zerofill(pack_flag) != 0,
                        f_is_dec(pack_flag) == 0);
10327
  case MYSQL_TYPE_FLOAT:
10328 10329 10330 10331
  {
    int decimals= f_decimals(pack_flag);
    if (decimals == FLOATING_POINT_DECIMALS)
      decimals= NOT_FIXED_DEC;
10332 10333 10334
    return new (mem_root)
      Field_float(ptr,field_length,null_pos,null_bit,
                  unireg_check, field_name,
10335
                  decimals,
10336 10337
                  f_is_zerofill(pack_flag) != 0,
                  f_is_dec(pack_flag)== 0);
10338
  }
10339
  case MYSQL_TYPE_DOUBLE:
10340 10341 10342 10343
  {
    int decimals= f_decimals(pack_flag);
    if (decimals == FLOATING_POINT_DECIMALS)
      decimals= NOT_FIXED_DEC;
10344 10345 10346
    return new (mem_root)
      Field_double(ptr,field_length,null_pos,null_bit,
                   unireg_check, field_name,
10347
                   decimals,
10348 10349
                   f_is_zerofill(pack_flag) != 0,
                   f_is_dec(pack_flag)== 0);
10350
  }
10351
  case MYSQL_TYPE_TINY:
10352 10353 10354 10355 10356
    return new (mem_root)
      Field_tiny(ptr,field_length,null_pos,null_bit,
                 unireg_check, field_name,
                 f_is_zerofill(pack_flag) != 0,
                 f_is_dec(pack_flag) == 0);
10357
  case MYSQL_TYPE_SHORT:
10358 10359 10360 10361 10362
    return new (mem_root)
      Field_short(ptr,field_length,null_pos,null_bit,
                  unireg_check, field_name,
                  f_is_zerofill(pack_flag) != 0,
                  f_is_dec(pack_flag) == 0);
10363
  case MYSQL_TYPE_INT24:
10364 10365 10366 10367 10368
    return new (mem_root)
      Field_medium(ptr,field_length,null_pos,null_bit,
                   unireg_check, field_name,
                   f_is_zerofill(pack_flag) != 0,
                   f_is_dec(pack_flag) == 0);
10369
  case MYSQL_TYPE_LONG:
10370 10371 10372 10373 10374
    return new (mem_root)
      Field_long(ptr,field_length,null_pos,null_bit,
                 unireg_check, field_name,
                 f_is_zerofill(pack_flag) != 0,
                 f_is_dec(pack_flag) == 0);
10375
  case MYSQL_TYPE_LONGLONG:
10376 10377 10378 10379 10380
    return new (mem_root)
      Field_longlong(ptr,field_length,null_pos,null_bit,
                     unireg_check, field_name,
                     f_is_zerofill(pack_flag) != 0,
                     f_is_dec(pack_flag) == 0);
10381
  case MYSQL_TYPE_TIMESTAMP:
10382 10383 10384
  {
    uint dec= field_length > MAX_DATETIME_WIDTH ?
                       field_length - MAX_DATETIME_WIDTH - 1: 0;
10385
    return new_Field_timestamp(mem_root, ptr, null_pos, null_bit, unireg_check,
10386 10387 10388 10389 10390 10391
                               field_name, share, dec);
  }
  case MYSQL_TYPE_TIMESTAMP2:
  {
    uint dec= field_length > MAX_DATETIME_WIDTH ?
                       field_length - MAX_DATETIME_WIDTH - 1: 0;
10392 10393 10394
    return new (mem_root)
      Field_timestampf(ptr, null_pos, null_bit, unireg_check,
                       field_name, share, dec);
10395
  }
10396
  case MYSQL_TYPE_YEAR:
10397 10398 10399
    return new (mem_root)
      Field_year(ptr,field_length,null_pos,null_bit,
                 unireg_check, field_name);
10400
  case MYSQL_TYPE_DATE:
10401 10402 10403
    return new (mem_root)
      Field_date(ptr,null_pos,null_bit,
                 unireg_check, field_name);
10404
  case MYSQL_TYPE_NEWDATE:
10405 10406 10407
    return new (mem_root)
      Field_newdate(ptr,null_pos,null_bit,
                    unireg_check, field_name);
10408
  case MYSQL_TYPE_TIME:
10409 10410 10411
  {
    uint dec= field_length > MIN_TIME_WIDTH ?
                       field_length - MIN_TIME_WIDTH - 1: 0;
10412
    return new_Field_time(mem_root, ptr, null_pos, null_bit, unireg_check,
10413 10414 10415 10416 10417 10418
                          field_name, dec);
  }
  case MYSQL_TYPE_TIME2:
  {
    uint dec= field_length > MIN_TIME_WIDTH ?
                       field_length - MIN_TIME_WIDTH - 1: 0;
10419 10420 10421
    return new (mem_root)
      Field_timef(ptr, null_pos, null_bit, unireg_check,
                  field_name, dec);
10422
  }
10423
  case MYSQL_TYPE_DATETIME:
10424 10425 10426
  {
    uint dec= field_length > MAX_DATETIME_WIDTH ?
                       field_length - MAX_DATETIME_WIDTH - 1: 0;
10427
    return new_Field_datetime(mem_root, ptr, null_pos, null_bit, unireg_check,
10428 10429 10430 10431 10432 10433
                              field_name, dec);
  }
  case MYSQL_TYPE_DATETIME2:
  {
    uint dec= field_length > MAX_DATETIME_WIDTH ?
                       field_length - MAX_DATETIME_WIDTH - 1: 0;
10434 10435 10436
    return new (mem_root)
      Field_datetimef(ptr, null_pos, null_bit, unireg_check,
                      field_name, dec);
10437
  }
10438
  case MYSQL_TYPE_NULL:
10439 10440 10441
    return new (mem_root)
      Field_null(ptr, field_length, unireg_check, field_name,
                 field_charset);
10442
  case MYSQL_TYPE_BIT:
10443 10444 10445 10446 10447 10448 10449
    return (f_bit_as_char(pack_flag) ?
            new (mem_root)
            Field_bit_as_char(ptr, field_length, null_pos, null_bit,
                              unireg_check, field_name) :
            new (mem_root)
            Field_bit(ptr, field_length, null_pos, null_bit, bit_ptr,
                      bit_offset, unireg_check, field_name));
unknown's avatar
unknown committed
10450

10451 10452
  default:					// Impossible (Wrong version)
    break;
unknown's avatar
unknown committed
10453
  }
unknown's avatar
unknown committed
10454
  return 0;
unknown's avatar
unknown committed
10455 10456 10457
}


10458
/** Create a field suitable for create of table. */
unknown's avatar
unknown committed
10459

Alexander Barkov's avatar
Alexander Barkov committed
10460 10461
Column_definition::Column_definition(THD *thd, Field *old_field,
                                               Field *orig_field)
unknown's avatar
unknown committed
10462
{
Alexander Barkov's avatar
Alexander Barkov committed
10463
  field_name= old_field->field_name;
unknown's avatar
unknown committed
10464 10465 10466 10467
  length=     old_field->field_length;
  flags=      old_field->flags;
  unireg_check=old_field->unireg_check;
  pack_length=old_field->pack_length();
10468
  key_length= old_field->key_length();
unknown's avatar
unknown committed
10469
  sql_type=   old_field->real_type();
unknown's avatar
unknown committed
10470 10471
  charset=    old_field->charset();		// May be NULL ptr
  comment=    old_field->comment;
10472
  decimals=   old_field->decimals();
10473
  vcol_info=  old_field->vcol_info;
10474 10475
  default_value= orig_field ? orig_field->default_value : 0;
  check_constraint= orig_field ? orig_field->check_constraint : 0;
10476
  option_list= old_field->option_list;
unknown's avatar
unknown committed
10477

10478
  switch (sql_type) {
10479
  case MYSQL_TYPE_BLOB:
10480
    switch (pack_length - portable_sizeof_char_ptr) {
10481 10482 10483 10484
    case  1: sql_type= MYSQL_TYPE_TINY_BLOB; break;
    case  2: sql_type= MYSQL_TYPE_BLOB; break;
    case  3: sql_type= MYSQL_TYPE_MEDIUM_BLOB; break;
    default: sql_type= MYSQL_TYPE_LONG_BLOB; break;
10485
    }
10486
    length/= charset->mbmaxlen;
10487 10488
    key_length/= charset->mbmaxlen;
    break;
10489
  case MYSQL_TYPE_STRING:
unknown's avatar
unknown committed
10490
    /* Change CHAR -> VARCHAR if dynamic record length */
10491 10492 10493 10494 10495 10496 10497 10498
    if (old_field->type() == MYSQL_TYPE_VAR_STRING)
      sql_type= MYSQL_TYPE_VARCHAR;
    /* fall through */

  case MYSQL_TYPE_ENUM:
  case MYSQL_TYPE_SET:
  case MYSQL_TYPE_VARCHAR:
  case MYSQL_TYPE_VAR_STRING:
10499
    /* This is corrected in create_length_to_internal_length */
10500 10501 10502
    length= (length+charset->mbmaxlen-1) / charset->mbmaxlen;
    break;
#ifdef HAVE_SPATIAL
10503
  case MYSQL_TYPE_GEOMETRY:
10504
    geom_type= ((Field_geom*)old_field)->geom_type;
10505
    srid= ((Field_geom*)old_field)->srid;
10506 10507
    break;
#endif
10508 10509 10510 10511
  case MYSQL_TYPE_YEAR:
    if (length != 4)
    {
      char buff[sizeof("YEAR()") + MY_INT64_NUM_DECIMAL_DIGITS + 1];
10512
      my_snprintf(buff, sizeof(buff), "YEAR(%lu)", length);
10513
      push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
10514
                          ER_WARN_DEPRECATED_SYNTAX,
10515
                          ER_THD(thd, ER_WARN_DEPRECATED_SYNTAX),
10516 10517 10518
                          buff, "YEAR(4)");
    }
    break;
10519 10520 10521 10522 10523 10524 10525 10526 10527
  case MYSQL_TYPE_FLOAT:
  case MYSQL_TYPE_DOUBLE:
    /*
      Floating points are stored with FLOATING_POINT_DECIMALS but internally
      in MariaDB used with NOT_FIXED_DEC, which is >= FLOATING_POINT_DECIMALS.
    */
    if (decimals >= FLOATING_POINT_DECIMALS)
      decimals= NOT_FIXED_DEC;
    break;
10528 10529
  default:
    break;
unknown's avatar
unknown committed
10530
  }
10531

unknown's avatar
unknown committed
10532 10533 10534 10535
  if (flags & (ENUM_FLAG | SET_FLAG))
    interval= ((Field_enum*) old_field)->typelib;
  else
    interval=0;
10536
  char_length= length;
10537

10538
  /*
10539 10540 10541 10542 10543
    Copy the default (constant/function) from the column object orig_field, if
    supplied. We do this if all these conditions are met:

    - The column allows a default.

10544 10545
    - The column type is not a BLOB type (as BLOB's doesn't have constant
      defaults)
10546 10547 10548

    - The original column (old_field) was properly initialized with a record
      buffer pointer.
10549 10550

    - The column didn't have a default expression
10551
  */
10552
  if (!(flags & (NO_DEFAULT_VALUE_FLAG | BLOB_FLAG)) &&
10553
      old_field->ptr != NULL && orig_field != NULL)
10554
  {
10555 10556
    if (orig_field->unireg_check != Field::NEXT_NUMBER)
      unireg_check= orig_field->unireg_check;
10557 10558 10559 10560

    /* Get the value from default_values */
    const uchar *dv= orig_field->table->s->default_values;
    if (!default_value && !orig_field->is_null_in_record(dv))
10561
    {
10562 10563 10564 10565 10566 10567 10568
      StringBuffer<MAX_FIELD_WIDTH> tmp(charset);
      String *res= orig_field->val_str(&tmp, orig_field->ptr_in_record(dv));
      char *pos= (char*) thd->strmake(res->ptr(), res->length());
      default_value= new (thd->mem_root) Virtual_column_info();
      default_value->expr_item=
        new (thd->mem_root) Item_string(thd, pos, res->length(), charset);
      default_value->utf8= 0;
10569
    }
unknown's avatar
unknown committed
10570 10571
  }
}
10572 10573


10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606
/**
  maximum possible character length for blob.
  
  This method is used in Item_field::set_field to calculate
  max_length for Item.
  
  For example:
    CREATE TABLE t2 SELECT CONCAT(tinyblob_utf8_column) FROM t1;
  must create a "VARCHAR(255) CHARACTER SET utf8" column.
  
  @return
    length
*/

uint32 Field_blob::char_length()
{
  switch (packlength)
  {
  case 1:
    return 255;
  case 2:
    return 65535;
  case 3:
    return 16777215;
  case 4:
    return (uint32) 4294967295U;
  default:
    DBUG_ASSERT(0); // we should never go here
    return 0;
  }
}


10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618
/**
  Makes a clone of this object for ALTER/CREATE TABLE

  @param mem_root        MEM_ROOT where to clone the field
*/

Create_field *Create_field::clone(MEM_ROOT *mem_root) const
{
  Create_field *res= new (mem_root) Create_field(*this);
  return res;
}

10619 10620 10621 10622 10623 10624 10625 10626 10627 10628
/**
   Return true if default is an expression that must be saved explicitely

   This is:
     - Not basic constants
     - If field is a BLOB (Which doesn't support normal DEFAULT)
*/

bool Column_definition::has_default_expression()
{
Sergei Golubchik's avatar
Sergei Golubchik committed
10629
  return (default_value &&
10630 10631 10632
          (!default_value->expr_item->basic_const_item() ||
           (flags & BLOB_FLAG)));
}
10633

10634 10635
/**
  maximum possible display length for blob.
10636

10637
  @return
10638 10639
    length
*/
10640 10641

uint32 Field_blob::max_display_length()
10642 10643 10644 10645
{
  switch (packlength)
  {
  case 1:
10646
    return 255 * field_charset->mbmaxlen;
10647
  case 2:
10648
    return 65535 * field_charset->mbmaxlen;
10649
  case 3:
10650
    return 16777215 * field_charset->mbmaxlen;
10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662
  case 4:
    return (uint32) 4294967295U;
  default:
    DBUG_ASSERT(0); // we should never go here
    return 0;
  }
}


/*****************************************************************************
 Warning handling
*****************************************************************************/
10663

10664
/**
10665
*  Produce warning or note about data saved into field.
10666

10667 10668
  @param level            - level of message (Note/Warning/Error)
  @param code             - error code of message to be produced
10669
  @param cut_increment    - whenever we should increase cut fields count
10670

10671
  @note
10672
    This function won't produce warning and increase cut fields counter
10673 10674 10675 10676
    if count_cuted_fields == CHECK_FIELD_IGNORE for current thread.

    if count_cuted_fields == CHECK_FIELD_IGNORE then we ignore notes.
    This allows us to avoid notes in optimisation, like convert_constant_item().
10677 10678 10679 10680 10681

  @retval
    1 if count_cuted_fields == CHECK_FIELD_IGNORE and error level is not NOTE
  @retval
    0 otherwise
10682
*/
10683

10684 10685 10686
bool 
Field::set_warning(Sql_condition::enum_warning_level level, uint code,
                   int cut_increment) const
10687
{
10688 10689 10690 10691
  /*
    If this field was created only for type conversion purposes it
    will have table == NULL.
  */
10692
  THD *thd= get_thd();
unknown's avatar
unknown committed
10693 10694
  if (thd->count_cuted_fields)
  {
10695
    thd->cuted_fields+= cut_increment;
10696
    push_warning_printf(thd, level, code, ER_THD(thd, code), field_name,
10697 10698
                        thd->get_stmt_da()->current_row_for_warning());
    return 0;
10699
  }
10700
  return level >= Sql_condition::WARN_LEVEL_WARN;
10701 10702 10703
}


10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715
/**
  Produce warning or note about datetime string data saved into field.

  @param level            level of message (Note/Warning/Error)
  @param code             error code of message to be produced
  @param str              string value which we tried to save
  @param ts_type          type of datetime value (datetime/date/time)
  @param cuted_increment  whenever we should increase cut fields count or not

  @note
    This function will always produce some warning but won't increase cut
    fields counter if count_cuted_fields ==FIELD_CHECK_IGNORE for current
10716 10717
    thread.

10718
    See also bug#2336
10719

10720
*/
10721

10722
void Field::set_datetime_warning(Sql_condition::enum_warning_level level,
Sergei Golubchik's avatar
Sergei Golubchik committed
10723
                                 uint code, const ErrConv *str,
10724
                                 timestamp_type ts_type, int cuted_increment)
10725
                                 const
10726
{
10727
  THD *thd= get_thd();
10728
  if (thd->really_abort_on_warning() && level >= Sql_condition::WARN_LEVEL_WARN)
10729
    make_truncated_value_warning(thd, level, str, ts_type, field_name);
10730 10731
  else
    set_warning(level, code, cuted_increment);
10732 10733 10734
}


10735
void Field::set_warning_truncated_wrong_value(const char *type_arg,
10736 10737 10738 10739 10740
                                              const char *value)
{
  THD *thd= get_thd();
  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                      ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
10741 10742
                      ER_THD(thd, ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
                      type_arg, value, field_name,
10743 10744 10745 10746 10747
                      static_cast<ulong>(thd->get_stmt_da()->
                      current_row_for_warning()));
}


10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761
/*
  @brief
  Return possible keys for a field

  @details
  Return bit map of keys over this field which can be used by the range
  optimizer. For a field of a generic table such keys are all keys that starts
  from this field. For a field of a materialized derived table/view such keys
  are all keys in which this field takes a part. This is less restrictive as
  keys for a materialized derived table/view are generated on the fly from
  present fields, thus the case when a field for the beginning of a key is
  absent is impossible.

  @return map of possible keys
10762
*/
10763

10764
key_map Field::get_possible_keys()
10765
{
10766 10767 10768
  DBUG_ASSERT(table->pos_in_table_list);
  return (table->pos_in_table_list->is_materialized_derived() ?
          part_of_key : key_start);
10769
}
10770 10771


10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788
/**
  Mark the field as having an explicit default value.

  @param value  if available, the value that the field is being set to

  @note
    Fields that have an explicit default value should not be updated
    automatically via the DEFAULT or ON UPDATE functions. The functions
    that deal with data change functionality (INSERT/UPDATE/LOAD),
    determine if there is an explicit value for each field before performing
    the data change, and call this method to mark the field.

    If the 'value' parameter is NULL, then the field is marked unconditionally
    as having an explicit value. If 'value' is not NULL, then it can be further
    analyzed to check if it really should count as a value.
*/

10789 10790
void Field::set_explicit_default(Item *value)
{
10791
  if (value->type() == Item::DEFAULT_VALUE_ITEM &&
10792 10793
      !((Item_default_value*)value)->arg)
    return;
10794
  set_has_explicit_value();
10795
}
10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808


bool Field::validate_value_in_record_with_warn(THD *thd, const uchar *record)
{
  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->read_set);
  bool rc;
  if ((rc= validate_value_in_record(thd, record)))
  {
    // Get and report val_str() for the DEFAULT value
    StringBuffer<MAX_FIELD_WIDTH> tmp;
    val_str(&tmp, ptr_in_record(record));
    push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                        ER_INVALID_DEFAULT_VALUE_FOR_FIELD,
10809
                        ER_THD(thd, ER_INVALID_DEFAULT_VALUE_FOR_FIELD),
10810 10811 10812 10813 10814
                        ErrConvString(&tmp).ptr(), field_name);
  }
  dbug_tmp_restore_column_map(table->read_set, old_map);
  return rc;
}
10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854


bool Field::save_in_field_default_value(bool view_error_processing)
{
  THD *thd= table->in_use;

  if (flags & NO_DEFAULT_VALUE_FLAG &&
      real_type() != MYSQL_TYPE_ENUM)
  {
    if (reset())
    {
      my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
                 ER_THD(thd, ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
      return -1;
    }

    if (view_error_processing)
    {
      TABLE_LIST *view= table->pos_in_table_list->top_table();
      push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                          ER_NO_DEFAULT_FOR_VIEW_FIELD,
                          ER_THD(thd, ER_NO_DEFAULT_FOR_VIEW_FIELD),
                          view->view_db.str,
                          view->view_name.str);
    }
    else
    {
      push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                          ER_NO_DEFAULT_FOR_FIELD,
                          ER_THD(thd, ER_NO_DEFAULT_FOR_FIELD),
                          field_name);
    }
    return 1;
  }
  set_default();
  return
    !is_null() &&
    validate_value_in_record_with_warn(thd, table->record[0]) &&
    thd->is_error() ? -1 : 0;
}
10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866


bool Field::save_in_field_ignore_value(bool view_error_processing)
{
  enum_sql_command com= table->in_use->lex->sql_command;
  // All insert-like commands
  if (com == SQLCOM_INSERT || com == SQLCOM_REPLACE ||
      com == SQLCOM_INSERT_SELECT || com == SQLCOM_REPLACE_SELECT ||
      com == SQLCOM_LOAD)
    return save_in_field_default_value(view_error_processing);
  return 0; // ignore
}