field.cc 283 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000-2006 MySQL AB
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4
   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
5
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
6

unknown's avatar
unknown committed
7 8 9 10
   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
11

unknown's avatar
unknown committed
12 13 14 15 16
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


17 18 19 20 21 22
/**
  @file

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

24
#ifdef USE_PRAGMA_IMPLEMENTATION
unknown's avatar
unknown committed
25 26 27 28 29 30 31 32 33 34 35
#pragma implementation				// gcc: Class implementation
#endif

#include "mysql_priv.h"
#include "sql_select.h"
#include <m_ctype.h>
#include <errno.h>
#ifdef HAVE_FCONVERT
#include <floatingpoint.h>
#endif

unknown's avatar
unknown committed
36 37 38
// Maximum allowed exponent value for converting string to decimal
#define MAX_EXPONENT 1024

unknown's avatar
unknown committed
39
/*****************************************************************************
40
  Instansiate templates and static variables
unknown's avatar
unknown committed
41 42
*****************************************************************************/

43
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
unknown's avatar
unknown committed
44 45
template class List<Create_field>;
template class List_iterator<Create_field>;
unknown's avatar
unknown committed
46 47 48 49 50
#endif

uchar Field_null::null[1]={1};
const char field_separator=',';

51
#define DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE 320
52 53
#define LONGLONG_TO_STRING_CONVERSION_BUFFER_SIZE 128
#define DECIMAL_TO_STRING_CONVERSION_BUFFER_SIZE 128
54 55
#define BLOB_PACK_LENGTH_TO_MAX_LENGH(arg) \
((ulong) ((LL(1) << min(arg, 4) * 8) - LL(1)))
56

unknown's avatar
unknown committed
57 58
#define ASSERT_COLUMN_MARKED_FOR_READ DBUG_ASSERT(!table || (!table->read_set || bitmap_is_set(table->read_set, field_index)))
#define ASSERT_COLUMN_MARKED_FOR_WRITE DBUG_ASSERT(!table || (!table->write_set || bitmap_is_set(table->write_set, field_index)))
59

60 61 62 63 64 65 66
/*
  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
  and index of field in thia array.
*/
unknown's avatar
unknown committed
67 68 69
#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))
70 71 72 73 74 75 76
inline int field_type2index (enum_field_types field_type)
{
  return (field_type < FIELDTYPE_TEAR_FROM ?
          field_type :
          ((int)FIELDTYPE_TEAR_FROM) + (field_type - FIELDTYPE_TEAR_TO) - 1);
}

unknown's avatar
unknown committed
77

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

919 920
/**
  Return type of which can carry value of both given types in UNION result.
921

922 923
  @param a  type for merging
  @param b  type for merging
924

925
  @return
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
    type of field
*/

enum_field_types Field::field_type_merge(enum_field_types a,
                                         enum_field_types b)
{
  DBUG_ASSERT(a < FIELDTYPE_TEAR_FROM || a > FIELDTYPE_TEAR_TO);
  DBUG_ASSERT(b < FIELDTYPE_TEAR_FROM || b > FIELDTYPE_TEAR_TO);
  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
942
  DECIMAL_RESULT,           INT_RESULT,
943 944 945 946 947 948 949 950 951 952 953 954
  //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
955 956 957
  //MYSQL_TYPE_NEWDATE      MYSQL_TYPE_VARCHAR
  STRING_RESULT,            STRING_RESULT,
  //MYSQL_TYPE_BIT          <16>-<245>
958
  STRING_RESULT,
unknown's avatar
unknown committed
959 960
  //MYSQL_TYPE_NEWDECIMAL   MYSQL_TYPE_ENUM
  DECIMAL_RESULT,           STRING_RESULT,
961 962 963 964 965 966 967 968 969 970 971
  //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
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
/*
  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);
}


997 998
/**
  Detect Item_result by given field type of UNION merge result.
999

1000
  @param field_type  given field type
1001

1002
  @return
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    Item_result (type of internal MySQL expression result)
*/

Item_result Field::result_merge_type(enum_field_types field_type)
{
  DBUG_ASSERT(field_type < FIELDTYPE_TEAR_FROM || field_type
              > FIELDTYPE_TEAR_TO);
  return field_types_result_type[field_type2index(field_type)];
}

unknown's avatar
unknown committed
1013
/*****************************************************************************
1014
  Static help functions
unknown's avatar
unknown committed
1015 1016
*****************************************************************************/

1017

1018 1019
/**
  Check whether a field type can be partially indexed by a key.
1020 1021 1022 1023

  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().

1024
  @param type  field type
1025

1026
  @retval
1027
    TRUE  Type can have a prefixed key
1028
  @retval
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    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
1042
  case MYSQL_TYPE_GEOMETRY:
1043 1044 1045 1046 1047 1048 1049
    return TRUE;
  default:
    return FALSE;
  }
}


1050 1051
/**
  Numeric fields base class constructor.
unknown's avatar
unknown committed
1052
*/
1053
Field_num::Field_num(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
unknown's avatar
unknown committed
1054 1055 1056 1057
                     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
1058
         unireg_check_arg, field_name_arg),
unknown's avatar
unknown committed
1059 1060 1061 1062 1063 1064 1065 1066 1067
  dec(dec_arg),zerofill(zero_arg),unsigned_flag(unsigned_arg)
{
  if (zerofill)
    flags|=ZEROFILL_FLAG;
  if (unsigned_flag)
    flags|=UNSIGNED_FLAG;
}


unknown's avatar
unknown committed
1068 1069 1070 1071 1072
void Field_num::prepend_zeros(String *value)
{
  int diff;
  if ((diff= (int) (field_length - value->length())) > 0)
  {
1073 1074
    bmove_upp((uchar*) value->ptr()+field_length,
              (uchar*) value->ptr()+value->length(),
unknown's avatar
unknown committed
1075
	      value->length());
1076
    bfill((uchar*) value->ptr(),diff,'0');
unknown's avatar
unknown committed
1077 1078 1079 1080 1081
    value->length(field_length);
    (void) value->c_ptr_quick();		// Avoid warnings in purify
  }
}

1082
/**
unknown's avatar
unknown committed
1083
  Test if given number is a int.
1084

1085 1086
  @todo
    Make this multi-byte-character safe
1087

1088 1089 1090 1091 1092 1093
  @param str		String to test
  @param length        Length of 'str'
  @param int_end	Pointer to char after last used digit
  @param cs		Character set

  @note
unknown's avatar
unknown committed
1094
    This is called after one has called strntoull10rnd() function.
1095

1096 1097 1098
  @retval
    0	OK
  @retval
unknown's avatar
unknown committed
1099
    1	error: empty string or wrong integer.
1100
  @retval
unknown's avatar
unknown committed
1101
    2   error: garbage at the end of string.
unknown's avatar
unknown committed
1102 1103
*/

unknown's avatar
unknown committed
1104 1105
int Field_num::check_int(CHARSET_INFO *cs, const char *str, int length, 
                         const char *int_end, int error)
unknown's avatar
unknown committed
1106
{
unknown's avatar
unknown committed
1107 1108
  /* Test if we get an empty string or wrong integer */
  if (str == int_end || error == MY_ERRNO_EDOM)
unknown's avatar
unknown committed
1109 1110
  {
    char buff[128];
unknown's avatar
unknown committed
1111
    String tmp(buff, (uint32) sizeof(buff), system_charset_info);
unknown's avatar
unknown committed
1112 1113 1114 1115 1116 1117
    tmp.copy(str, length, system_charset_info);
    push_warning_printf(table->in_use, MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_TRUNCATED_WRONG_VALUE_FOR_FIELD, 
                        ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
                        "integer", tmp.c_ptr(), field_name,
                        (ulong) table->in_use->row_count);
unknown's avatar
unknown committed
1118
    return 1;
unknown's avatar
unknown committed
1119
  }
unknown's avatar
unknown committed
1120 1121 1122 1123 1124 1125 1126 1127
  /* Test if we have garbage at the end of the given string. */
  if (test_if_important_data(cs, int_end, str + length))
  {
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
    return 2;
  }
  return 0;
}
unknown's avatar
unknown committed
1128

unknown's avatar
unknown committed
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159

/*
  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;
  
1160 1161
  *rnd= (longlong) cs->cset->strntoull10rnd(cs, from, len,
                                            unsigned_flag, &end,
unknown's avatar
unknown committed
1162 1163
                                            &error);
  if (unsigned_flag)
unknown's avatar
unknown committed
1164
  {
unknown's avatar
unknown committed
1165 1166 1167 1168 1169 1170

    if (((ulonglong) *rnd > unsigned_max) && (*rnd= (longlong) unsigned_max) ||
        error == MY_ERRNO_ERANGE)
    {
      goto out_of_range;
    }
1171
  }
unknown's avatar
unknown committed
1172
  else
1173
  {
unknown's avatar
unknown committed
1174
    if (*rnd < signed_min)
unknown's avatar
unknown committed
1175
    {
unknown's avatar
unknown committed
1176 1177 1178 1179 1180 1181 1182
      *rnd= signed_min;
      goto out_of_range;
    }
    else if (*rnd > signed_max)
    {
      *rnd= signed_max;
      goto out_of_range;
unknown's avatar
unknown committed
1183
    }
unknown's avatar
unknown committed
1184
  }
1185 1186
  if (table->in_use->count_cuted_fields &&
      check_int(cs, from, len, end, error))
unknown's avatar
unknown committed
1187
    return 1;
unknown's avatar
unknown committed
1188
  return 0;
unknown's avatar
unknown committed
1189

unknown's avatar
unknown committed
1190 1191 1192 1193
out_of_range:
  set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
  return 1;
}
unknown's avatar
unknown committed
1194

1195
/**
unknown's avatar
unknown committed
1196 1197 1198
  Process decimal library return codes and issue warnings for overflow and
  truncation.

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

1201
  @retval
unknown's avatar
unknown committed
1202
    1  there was overflow
1203
  @retval
unknown's avatar
unknown committed
1204 1205 1206
    0  no error or some other errors except overflow
*/

unknown's avatar
unknown committed
1207
int Field::warn_if_overflow(int op_result)
unknown's avatar
unknown committed
1208 1209 1210 1211 1212 1213
{
  if (op_result == E_DEC_OVERFLOW)
  {
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
    return 1;
  }
unknown's avatar
unknown committed
1214 1215
  if (op_result == E_DEC_TRUNCATED)
  {
unknown's avatar
unknown committed
1216
    set_warning(MYSQL_ERROR::WARN_LEVEL_NOTE, WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
1217 1218
    /* We return 0 here as this is not a critical issue */
  }
unknown's avatar
unknown committed
1219 1220 1221
  return 0;
}

unknown's avatar
unknown committed
1222

unknown's avatar
unknown committed
1223
#ifdef NOT_USED
1224
static bool test_if_real(const char *str,int length, CHARSET_INFO *cs)
unknown's avatar
unknown committed
1225
{
1226
  cs= system_charset_info; // QQ move test_if_real into CHARSET_INFO struct
1227 1228

  while (length && my_isspace(cs,*str))
unknown's avatar
unknown committed
1229 1230 1231 1232 1233 1234 1235 1236
  {						// Allow start space
    length--; str++;
  }
  if (!length)
    return 0;
  if (*str == '+' || *str == '-')
  {
    length--; str++;
1237
    if (!length || !(my_isdigit(cs,*str) || *str == '.'))
unknown's avatar
unknown committed
1238 1239
      return 0;
  }
1240
  while (length && my_isdigit(cs,*str))
unknown's avatar
unknown committed
1241 1242 1243 1244 1245 1246 1247 1248
  {
    length--; str++;
  }
  if (!length)
    return 1;
  if (*str == '.')
  {
    length--; str++;
1249
    while (length && my_isdigit(cs,*str))
unknown's avatar
unknown committed
1250 1251 1252 1253 1254 1255 1256 1257
    {
      length--; str++;
    }
  }
  if (!length)
    return 1;
  if (*str == 'E' || *str == 'e')
  {
1258
    if (length < 3 || (str[1] != '+' && str[1] != '-') || 
1259
        !my_isdigit(cs,str[2]))
unknown's avatar
unknown committed
1260 1261 1262
      return 0;
    length-=3;
    str+=3;
1263
    while (length && my_isdigit(cs,*str))
unknown's avatar
unknown committed
1264 1265 1266 1267
    {
      length--; str++;
    }
  }
1268
  for (; length ; length--, str++)
unknown's avatar
unknown committed
1269
  {						// Allow end space
1270
    if (!my_isspace(cs,*str))
unknown's avatar
unknown committed
1271 1272 1273 1274
      return 0;
  }
  return 1;
}
unknown's avatar
unknown committed
1275
#endif
unknown's avatar
unknown committed
1276

1277

1278
/**
unknown's avatar
unknown committed
1279 1280
  Interpret field value as an integer but return the result as a string.

1281
  This is used for printing bit_fields as numbers while debugging.
unknown's avatar
unknown committed
1282 1283
*/

1284
String *Field::val_int_as_str(String *val_buffer, my_bool unsigned_val)
unknown's avatar
unknown committed
1285
{
1286
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
1287
  CHARSET_INFO *cs= &my_charset_bin;
1288
  uint length;
unknown's avatar
unknown committed
1289
  longlong value= val_int();
1290

1291
  if (val_buffer->alloc(MY_INT64_NUM_DECIMAL_DIGITS))
unknown's avatar
unknown committed
1292
    return 0;
unknown's avatar
unknown committed
1293
  length= (uint) (*cs->cset->longlong10_to_str)(cs, (char*) val_buffer->ptr(),
1294
                                                MY_INT64_NUM_DECIMAL_DIGITS,
1295
                                                unsigned_val ? 10 : -10,
unknown's avatar
unknown committed
1296
                                                value);
unknown's avatar
unknown committed
1297 1298 1299 1300 1301
  val_buffer->length(length);
  return val_buffer;
}


1302
/// This is used as a table name when the table structure is not set up
1303
Field::Field(uchar *ptr_arg,uint32 length_arg,uchar *null_ptr_arg,
unknown's avatar
unknown committed
1304
	     uchar null_bit_arg,
unknown's avatar
unknown committed
1305
	     utype unireg_check_arg, const char *field_name_arg)
1306
  :ptr(ptr_arg), null_ptr(null_ptr_arg),
unknown's avatar
unknown committed
1307
   table(0), orig_table(0), table_name(0),
unknown's avatar
unknown committed
1308
   field_name(field_name_arg),
1309 1310
   key_start(0), part_of_key(0), part_of_key_not_clustered(0),
   part_of_sortkey(0), unireg_check(unireg_check_arg),
1311 1312
   field_length(length_arg), null_bit(null_bit_arg), 
   is_created_from_null_item(FALSE)
unknown's avatar
unknown committed
1313 1314
{
  flags=null_ptr ? 0: NOT_NULL_FLAG;
unknown's avatar
unknown committed
1315 1316
  comment.str= (char*) "";
  comment.length=0;
1317
  field_index= 0;
unknown's avatar
unknown committed
1318 1319
}

1320

1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
void Field::hash(ulong *nr, ulong *nr2)
{
  if (is_null())
  {
    *nr^= (*nr << 1) | 1;
  }
  else
  {
    uint len= pack_length();
    CHARSET_INFO *cs= charset();
1331
    cs->coll->hash_sort(cs, ptr, len, nr, nr2);
1332 1333 1334
  }
}

1335
size_t
1336 1337
Field::do_last_null_byte() const
{
1338
  DBUG_ASSERT(null_ptr == NULL || null_ptr >= table->record[0]);
1339
  if (null_ptr)
1340 1341
    return (size_t) (null_ptr - table->record[0]) + 1;
  return LAST_NULL_BYTE_UNDEF;
1342 1343 1344
}


unknown's avatar
unknown committed
1345 1346 1347 1348 1349
void Field::copy_from_tmp(int row_offset)
{
  memcpy(ptr,ptr+row_offset,pack_length());
  if (null_ptr)
  {
unknown's avatar
unknown committed
1350 1351
    *null_ptr= (uchar) ((null_ptr[0] & (uchar) ~(uint) null_bit) |
			null_ptr[row_offset] & (uchar) null_bit);
unknown's avatar
unknown committed
1352 1353 1354 1355
  }
}


1356
bool Field::send_binary(Protocol *protocol)
unknown's avatar
unknown committed
1357 1358
{
  char buff[MAX_FIELD_WIDTH];
1359
  String tmp(buff,sizeof(buff),charset());
1360
  val_str(&tmp);
1361
  return protocol->store(tmp.ptr(), tmp.length(), tmp.charset());
unknown's avatar
unknown committed
1362 1363 1364
}


1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
/**
   Check to see if field size is compatible with destination.

   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). 

   @param   field_metadata   Encoded size in field metadata

   @retval 0 if this field's size is < the source field's size
   @retval 1 if this field's size is >= the source field's size
*/
int Field::compatible_field_size(uint field_metadata)
{
  uint const source_size= pack_length_from_metadata(field_metadata);
  uint const destination_size= row_pack_length();
  return (source_size <= destination_size);
}


1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
int Field::store(const char *to, uint length, CHARSET_INFO *cs,
                 enum_check_fields check_level)
{
  int res;
  enum_check_fields old_check_level= table->in_use->count_cuted_fields;
  table->in_use->count_cuted_fields= check_level;
  res= store(to, length, cs);
  table->in_use->count_cuted_fields= old_check_level;
  return res;
}


1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 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
/**
   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.

   The value of <code>low_byte_first</code> is dependent on how the
   packed data is going to be used: for local use, e.g., temporary
   store on disk or in memory, use the native format since that is
   faster. For data that is going to be transfered to other machines
   (e.g., when writing data to the binary log), data should always be
   stored in little-endian format.

   @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.

   @param low_byte_first
   @c TRUE if integers should be stored little-endian, @c FALSE if
   native format should be used. Note that for little-endian machines,
   the value of this flag is a moot point since the native format is
   little-endian.
*/
uchar *
Field::pack(uchar *to, const uchar *from, uint max_length,
            bool low_byte_first __attribute__((unused)))
{
  uint32 length= pack_length();
  set_if_smaller(length, max_length);
  memcpy(to, from, length);
  return to+length;
}

1445 1446 1447
/**
   Unpack a field from row data.

1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
   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).

1463 1464
   @param   to         Destination of the data
   @param   from       Source of the data
1465 1466 1467 1468 1469 1470 1471
   @param   param_data Real type and original pack length of the field
                       data

   @param low_byte_first
   If this flag is @c true, all composite entities (e.g., lengths)
   should be unpacked in little-endian format; otherwise, the entities
   are unpacked in native order.
1472 1473 1474

   @return  New pointer into memory based on from + length of the data
*/
1475 1476 1477
const uchar *
Field::unpack(uchar* to, const uchar *from, uint param_data,
              bool low_byte_first __attribute__((unused)))
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
{
  uint length=pack_length();
  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.
  }
1490 1491 1492 1493 1494 1495 1496 1497 1498

  if ((param_data == 0) ||
      (length == param_data) ||
      (from_type != real_type()))
  {
    memcpy(to, from, length);
    return from+length;
  }

1499 1500
  uint len= (param_data && (param_data < length)) ?
            param_data : length;
1501

1502 1503 1504 1505 1506
  memcpy(to, from, param_data > length ? length : len);
  return from+len;
}


unknown's avatar
unknown committed
1507 1508 1509 1510 1511 1512 1513 1514
my_decimal *Field::val_decimal(my_decimal *decimal)
{
  /* This never have to be called */
  DBUG_ASSERT(0);
  return 0;
}


unknown's avatar
unknown committed
1515 1516
void Field_num::add_zerofill_and_unsigned(String &res) const
{
1517
  if (unsigned_flag)
1518
    res.append(STRING_WITH_LEN(" unsigned"));
1519
  if (zerofill)
1520
    res.append(STRING_WITH_LEN(" zerofill"));
unknown's avatar
unknown committed
1521 1522
}

unknown's avatar
unknown committed
1523

1524
void Field::make_field(Send_field *field)
unknown's avatar
unknown committed
1525
{
unknown's avatar
unknown committed
1526
  if (orig_table && orig_table->s->db.str && *orig_table->s->db.str)
unknown's avatar
unknown committed
1527
  {
unknown's avatar
unknown committed
1528 1529
    field->db_name= orig_table->s->db.str;
    field->org_table_name= orig_table->s->table_name.str;
1530 1531
  }
  else
unknown's avatar
unknown committed
1532
    field->org_table_name= field->db_name= "";
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
  if (orig_table)
  {
    field->table_name= orig_table->alias;
    field->org_col_name= field_name;
  }
  else
  {
    field->table_name= "";
    field->org_col_name= "";
  }
  field->col_name= field_name;
1544
  field->charsetnr= charset()->number;
unknown's avatar
unknown committed
1545 1546 1547
  field->length=field_length;
  field->type=type();
  field->flags=table->maybe_null ? (flags & ~NOT_NULL_FLAG) : flags;
1548
  field->decimals= 0;
unknown's avatar
unknown committed
1549 1550 1551
}


1552
/**
unknown's avatar
unknown committed
1553
  Conversion from decimal to longlong with checking overflow and
1554
  setting correct value (min/max) in case of overflow.
unknown's avatar
unknown committed
1555

1556 1557 1558
  @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
1559

1560
  @return
unknown's avatar
unknown committed
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
    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())
    {
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
      i= 0;
      *err= 1;
    }
unknown's avatar
unknown committed
1575
    else if (warn_if_overflow(my_decimal2int(E_DEC_ERROR &
unknown's avatar
unknown committed
1576 1577 1578 1579 1580 1581 1582
                                           ~E_DEC_OVERFLOW & ~E_DEC_TRUNCATED,
                                           val, TRUE, &i)))
    {
      i= ~(longlong) 0;
      *err= 1;
    }
  }
unknown's avatar
unknown committed
1583
  else if (warn_if_overflow(my_decimal2int(E_DEC_ERROR &
unknown's avatar
unknown committed
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
                                         ~E_DEC_OVERFLOW & ~E_DEC_TRUNCATED,
                                         val, FALSE, &i)))
  {
    i= (val->sign() ? LONGLONG_MIN : LONGLONG_MAX);
    *err= 1;
  }
  return i;
}


1594
/**
unknown's avatar
unknown committed
1595 1596
  Storing decimal in integer fields.

1597
  @param val       value for storing
unknown's avatar
unknown committed
1598

1599
  @note
unknown's avatar
unknown committed
1600 1601
    This method is used by all integer fields, real/decimal redefine it

1602
  @retval
unknown's avatar
unknown committed
1603
    0     OK
1604 1605
  @retval
    !=0  error
unknown's avatar
unknown committed
1606 1607 1608 1609
*/

int Field_num::store_decimal(const my_decimal *val)
{
1610
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
1611 1612
  int err= 0;
  longlong i= convert_decimal2longlong(val, unsigned_flag, &err);
1613
  return test(err | store(i, unsigned_flag));
unknown's avatar
unknown committed
1614 1615 1616
}


1617 1618
/**
  Return decimal value of integer field.
unknown's avatar
unknown committed
1619

1620
  @param decimal_value     buffer for storing decimal value
unknown's avatar
unknown committed
1621

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

1627
  @return
unknown's avatar
unknown committed
1628 1629 1630 1631 1632
    pointer to decimal buffer with value of field
*/

my_decimal* Field_num::val_decimal(my_decimal *decimal_value)
{
1633
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
1634 1635
  DBUG_ASSERT(result_type() == INT_RESULT);
  longlong nr= val_int();
1636
  int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
unknown's avatar
unknown committed
1637 1638 1639 1640
  return decimal_value;
}


1641
Field_str::Field_str(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
unknown's avatar
unknown committed
1642
                     uchar null_bit_arg, utype unireg_check_arg,
unknown's avatar
unknown committed
1643
                     const char *field_name_arg, CHARSET_INFO *charset_arg)
unknown's avatar
unknown committed
1644
  :Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
unknown's avatar
unknown committed
1645
         unireg_check_arg, field_name_arg)
unknown's avatar
unknown committed
1646
{
1647 1648
  field_charset= charset_arg;
  if (charset_arg->state & MY_CS_BINSORT)
unknown's avatar
unknown committed
1649
    flags|=BINARY_FLAG;
1650
  field_derivation= DERIVATION_IMPLICIT;
unknown's avatar
unknown committed
1651 1652 1653
}


1654
void Field_num::make_field(Send_field *field)
unknown's avatar
unknown committed
1655
{
1656 1657
  Field::make_field(field);
  field->decimals= dec;
unknown's avatar
unknown committed
1658 1659
}

1660 1661
/**
  Decimal representation of Field_str.
unknown's avatar
unknown committed
1662

1663
  @param d         value for storing
unknown's avatar
unknown committed
1664

1665 1666 1667 1668 1669
  @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
1670

1671 1672 1673 1674
  @todo
    use decimal2string?

  @retval
unknown's avatar
unknown committed
1675
    0     OK
1676 1677
  @retval
    !=0  error
unknown's avatar
unknown committed
1678 1679 1680 1681
*/

int Field_str::store_decimal(const my_decimal *d)
{
1682
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
1683 1684
  double val;
  /* TODO: use decimal2string? */
unknown's avatar
unknown committed
1685
  int err= warn_if_overflow(my_decimal2double(E_DEC_FATAL_ERROR &
unknown's avatar
unknown committed
1686 1687 1688 1689 1690 1691 1692
                                            ~E_DEC_OVERFLOW, d, &val));
  return err | store(val);
}


my_decimal *Field_str::val_decimal(my_decimal *decimal_value)
{
1693
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
1694
  longlong nr= val_int();
1695
  int2my_decimal(E_DEC_FATAL_ERROR, nr, 0, decimal_value);
unknown's avatar
unknown committed
1696 1697 1698
  return decimal_value;
}

1699

unknown's avatar
unknown committed
1700 1701
uint Field::fill_cache_field(CACHE_FIELD *copy)
{
unknown's avatar
unknown committed
1702
  uint store_length;
unknown's avatar
unknown committed
1703 1704 1705 1706 1707 1708 1709
  copy->str=ptr;
  copy->length=pack_length();
  copy->blob_field=0;
  if (flags & BLOB_FLAG)
  {
    copy->blob_field=(Field_blob*) this;
    copy->strip=0;
1710
    copy->length-= table->s->blob_ptr_size;
unknown's avatar
unknown committed
1711 1712
    return copy->length;
  }
1713 1714 1715
  else if (!zero_pack() &&
           (type() == MYSQL_TYPE_STRING && copy->length >= 4 &&
            copy->length < 256))
unknown's avatar
unknown committed
1716
  {
unknown's avatar
unknown committed
1717
    copy->strip=1;				/* Remove end space */
unknown's avatar
unknown committed
1718 1719
    store_length= 2;
  }
unknown's avatar
unknown committed
1720
  else
unknown's avatar
unknown committed
1721
  {
unknown's avatar
unknown committed
1722
    copy->strip=0;
unknown's avatar
unknown committed
1723 1724 1725
    store_length= 0;
  }
  return copy->length+ store_length;
unknown's avatar
unknown committed
1726 1727
}

1728

1729
bool Field::get_date(MYSQL_TIME *ltime,uint fuzzydate)
unknown's avatar
unknown committed
1730 1731
{
  char buff[40];
1732 1733
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
  if (!(res=val_str(&tmp)) ||
1734 1735
      str_to_datetime_with_warn(res->ptr(), res->length(),
                                ltime, fuzzydate) <= MYSQL_TIMESTAMP_ERROR)
unknown's avatar
unknown committed
1736 1737 1738 1739
    return 1;
  return 0;
}

1740
bool Field::get_time(MYSQL_TIME *ltime)
unknown's avatar
unknown committed
1741 1742
{
  char buff[40];
1743 1744
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
  if (!(res=val_str(&tmp)) ||
1745
      str_to_time_with_warn(res->ptr(), res->length(), ltime))
unknown's avatar
unknown committed
1746 1747 1748 1749
    return 1;
  return 0;
}

1750 1751
/**
  This is called when storing a date in a string.
1752

1753 1754
  @note
    Needs to be changed if/when we want to support different time formats.
1755
*/
unknown's avatar
unknown committed
1756

1757
int Field::store_time(MYSQL_TIME *ltime, timestamp_type type_arg)
unknown's avatar
unknown committed
1758
{
1759
  ASSERT_COLUMN_MARKED_FOR_WRITE;
1760 1761
  char buff[MAX_DATE_STRING_REP_LENGTH];
  uint length= (uint) my_TIME_to_str(ltime, buff);
1762
  return store(buff, length, &my_charset_bin);
unknown's avatar
unknown committed
1763 1764 1765
}


1766
bool Field::optimize_range(uint idx, uint part)
unknown's avatar
unknown committed
1767
{
1768
  return test(table->file->index_flags(idx, part, 1) & HA_READ_RANGE);
unknown's avatar
unknown committed
1769 1770
}

1771

1772 1773
Field *Field::new_field(MEM_ROOT *root, struct st_table *new_table,
                        bool keep_type __attribute__((unused)))
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
{
  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);
unknown's avatar
unknown committed
1785
  tmp->unireg_check= Field::NONE;
1786 1787 1788 1789 1790 1791
  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
1792 1793

Field *Field::new_key_field(MEM_ROOT *root, struct st_table *new_table,
1794
                            uchar *new_ptr, uchar *new_null_ptr,
unknown's avatar
unknown committed
1795 1796 1797
                            uint new_null_bit)
{
  Field *tmp;
1798
  if ((tmp= new_field(root, new_table, table == new_table)))
unknown's avatar
unknown committed
1799 1800 1801 1802 1803 1804 1805 1806
  {
    tmp->ptr=      new_ptr;
    tmp->null_ptr= new_null_ptr;
    tmp->null_bit= new_null_bit;
  }
  return tmp;
}

1807

unknown's avatar
unknown committed
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
/* This is used to generate a field in TABLE from TABLE_SHARE */

Field *Field::clone(MEM_ROOT *root, struct st_table *new_table)
{
  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;
}


1823
/****************************************************************************
1824
  Field_null, a field that always return NULL
1825 1826 1827 1828
****************************************************************************/

void Field_null::sql_type(String &res) const
{
1829
  res.set_ascii(STRING_WITH_LEN("null"));
1830 1831 1832
}


unknown's avatar
unknown committed
1833
/****************************************************************************
unknown's avatar
unknown committed
1834 1835
  Functions for the Field_decimal class
  This is an number stored as a pre-space (or pre-zero) string
unknown's avatar
unknown committed
1836 1837
****************************************************************************/

1838
int
unknown's avatar
unknown committed
1839 1840
Field_decimal::reset(void)
{
1841
  Field_decimal::store(STRING_WITH_LEN("0"),&my_charset_bin);
1842
  return 0;
unknown's avatar
unknown committed
1843 1844 1845 1846 1847
}

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

1850
  set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
1851
  if (negative)
unknown's avatar
unknown committed
1852
  {
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
    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
1876
  }
1877
  bfill(to, len, filler);
unknown's avatar
unknown committed
1878 1879 1880 1881 1882 1883
  if (dec)
    ptr[field_length-dec-1]='.';
  return;
}


1884
int Field_decimal::store(const char *from_arg, uint len, CHARSET_INFO *cs)
unknown's avatar
unknown committed
1885
{
1886
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
1887
  char buff[STRING_BUFFER_USUAL_SIZE];
unknown's avatar
unknown committed
1888
  String tmp(buff,sizeof(buff), &my_charset_bin);
1889
  const uchar *from= (uchar*) from_arg;
1890

1891
  /* Convert character set if the old one is multi uchar */
1892 1893
  if (cs->mbmaxlen > 1)
  { 
1894
    uint dummy_errors;
1895 1896
    tmp.copy((char*) from, len, cs, &my_charset_bin, &dummy_errors);
    from= (uchar*) tmp.ptr();
1897 1898
    len=  tmp.length();
  }
1899

1900
  const uchar *end= from+len;
1901
  /* The pointer where the field value starts (i.e., "where to write") */
1902
  uchar *to= ptr;
1903 1904 1905 1906 1907
  uint tmp_dec, tmp_uint;
  /*
    The sign of the number : will be 0 (means positive but sign not
    specified), '+' or '-'
  */
1908
  uchar sign_char=0;
unknown's avatar
unknown committed
1909
  /* The pointers where prezeros start and stop */
1910
  const uchar *pre_zeros_from, *pre_zeros_end;
unknown's avatar
unknown committed
1911
  /* The pointers where digits at the left of '.' start and stop */
1912
  const uchar *int_digits_from, *int_digits_end;
unknown's avatar
unknown committed
1913
  /* The pointers where digits at the right of '.' start and stop */
1914
  const uchar *frac_digits_from, *frac_digits_end;
unknown's avatar
unknown committed
1915
  /* The sign of the exponent : will be 0 (means no exponent), '+' or '-' */
1916
  char expo_sign_char=0;
unknown's avatar
unknown committed
1917
  uint exponent=0;                                // value of the exponent
1918 1919 1920 1921
  /*
    Pointers used when digits move from the left of the '.' to the
    right of the '.' (explained below)
  */
1922
  const uchar *int_digits_tail_from;
1923 1924
  /* Number of 0 that need to be added at the left of the '.' (1E3: 3 zeros) */
  uint int_digits_added_zeros;
unknown's avatar
unknown committed
1925 1926 1927 1928
  /*
    Pointer used when digits move from the right of the '.' to the left
    of the '.'
  */
1929
  const uchar *frac_digits_head_end;
unknown's avatar
unknown committed
1930
  /* Number of 0 that need to be added at the right of the '.' (for 1E-3) */
1931
  uint frac_digits_added_zeros;
1932
  uchar *pos,*tmp_left_pos,*tmp_right_pos;
1933
  /* Pointers that are used as limits (begin and end of the field buffer) */
1934 1935
  uchar *left_wall,*right_wall;
  uchar tmp_char;
unknown's avatar
unknown committed
1936
  /*
1937
    To remember if table->in_use->cuted_fields has already been incremented,
unknown's avatar
unknown committed
1938 1939
    to do that only once
  */
1940 1941 1942 1943 1944 1945 1946 1947 1948
  bool is_cuted_fields_incr=0;

  LINT_INIT(int_digits_tail_from);
  LINT_INIT(int_digits_added_zeros);
  LINT_INIT(frac_digits_head_end);
  LINT_INIT(frac_digits_added_zeros);

  /*
    There are three steps in this function :
unknown's avatar
unknown committed
1949 1950
    - parse the input string
    - modify the position of digits around the decimal dot '.' 
1951
      according to the exponent value (if specified)
unknown's avatar
unknown committed
1952
    - write the formatted number
1953 1954 1955 1956 1957
  */

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

unknown's avatar
unknown committed
1958
  /* skip pre-space */
unknown's avatar
unknown committed
1959
  while (from != end && my_isspace(&my_charset_bin,*from))
unknown's avatar
unknown committed
1960
    from++;
1961
  if (from == end)
unknown's avatar
unknown committed
1962
  {
1963
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
1964
    is_cuted_fields_incr=1;
unknown's avatar
unknown committed
1965
  }
1966
  else if (*from == '+' || *from == '-')	// Found some sign ?
unknown's avatar
unknown committed
1967
  {
1968
    sign_char= *from++;
unknown's avatar
unknown committed
1969
    /*
1970 1971 1972
      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
1973 1974 1975 1976
    */ 
    if (unsigned_flag)  
    { 
      if (sign_char=='-')
1977
      {
1978
        Field_decimal::overflow(1);
unknown's avatar
unknown committed
1979
        return 1;
1980
      }
1981
      /* 
unknown's avatar
unknown committed
1982 1983
	 Defining this will not store "+" for unsigned decimal type even if
	 it is passed in numeric string. This will make some tests to fail
1984 1985
      */	 
#ifdef DONT_ALLOW_UNSIGNED_PLUS      
1986 1987
      else 
        sign_char=0;
1988
#endif 	
unknown's avatar
unknown committed
1989
    }
1990
  }
unknown's avatar
unknown committed
1991

1992 1993 1994 1995
  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
1996
  for (; from != end && my_isdigit(&my_charset_bin, *from) ; from++) ;
1997 1998 1999 2000 2001
  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
2002
  for (;from!=end && my_isdigit(&my_charset_bin, *from); from++) ;
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
  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= '+';
    /*
2013 2014 2015 2016
      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).
2017
    */
unknown's avatar
unknown committed
2018
    for (;from!=end && my_isdigit(&my_charset_bin, *from); from++)
2019
    {
2020
      exponent=10*exponent+(*from-'0');
unknown's avatar
unknown committed
2021
      if (exponent>MAX_EXPONENT)
2022 2023
        break;
    }
unknown's avatar
unknown committed
2024
  }
2025
  
unknown's avatar
unknown committed
2026
  /*
2027 2028
    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
2029
    Even if this flag is not set, it's OK to increment warnings, if
2030
    it makes the code easer to read.
unknown's avatar
unknown committed
2031
  */
2032

2033
  if (table->in_use->count_cuted_fields)
unknown's avatar
unknown committed
2034
  {
2035
    // Skip end spaces
unknown's avatar
unknown committed
2036
    for (;from != end && my_isspace(&my_charset_bin, *from); from++) ;
2037
    if (from != end)                     // If still something left, warn
unknown's avatar
unknown committed
2038
    {
2039
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
2040
      is_cuted_fields_incr=1;
unknown's avatar
unknown committed
2041
    }
2042 2043 2044 2045 2046 2047
  }
  
  /*
    Now "move" digits around the decimal dot according to the exponent value,
    and add necessary zeros.
    Examples :
unknown's avatar
unknown committed
2048 2049 2050
    - 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'
2051
    - 1234.5E-3 : '234' moves at the right of '.'
unknown's avatar
unknown committed
2052 2053
    These moves are implemented with pointers which point at the begin
    and end of each moved segment. Examples :
2054
    - 1234.5E-3 : before the code below is executed, the int_digits part is
unknown's avatar
unknown committed
2055 2056 2057
    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'.
2058
    - 1234.5E3 : before the code below is executed, the int_digits part is
unknown's avatar
unknown committed
2059 2060 2061 2062
    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).
2063 2064
  */
  
2065
  /* 
unknown's avatar
unknown committed
2066
     Below tmp_uint cannot overflow with small enough MAX_EXPONENT setting,
2067
     as int_digits_added_zeros<=exponent<4G and 
2068 2069
     (int_digits_end-int_digits_from)<=max_allowed_packet<=2G and
     (frac_digits_from-int_digits_tail_from)<=max_allowed_packet<=2G
2070 2071
  */

2072 2073 2074 2075 2076 2077 2078 2079
  if (!expo_sign_char)
    tmp_uint=tmp_dec+(uint)(int_digits_end-int_digits_from);
  else if (expo_sign_char == '-') 
  {
    tmp_uint=min(exponent,(uint)(int_digits_end-int_digits_from));
    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
2080
    tmp_uint=tmp_dec+(uint)(int_digits_end-int_digits_from);     
2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
  }
  else // (expo_sign_char=='+') 
  {
    tmp_uint=min(exponent,(uint)(frac_digits_end-frac_digits_from));
    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
2106
    }
2107
    tmp_uint= (uint) (tmp_dec+(int_digits_end-int_digits_from)+
2108 2109
               (uint)(frac_digits_from-int_digits_tail_from)+
               int_digits_added_zeros);
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
  }
  
  /*
    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
  */

2120
  if (field_length < tmp_uint + (int) (sign_char == '-')) 
2121
  {
unknown's avatar
unknown committed
2122
    // too big number, change to max or min number
2123
    Field_decimal::overflow(sign_char == '-');
2124
    return 1;
unknown's avatar
unknown committed
2125
  }
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
 
  /*
    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
2143
  }
2144 2145 2146 2147 2148 2149
  /*
    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
2150 2151

  /*
2152 2153
    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
2154
  */
2155 2156 2157 2158
  pos=tmp_left_pos-1;
  if (zerofill)
  {
    left_wall=to-1;
2159
    while (pos > left_wall)			// Fill with zeros
2160 2161 2162 2163
      *pos--='0';
  }
  else
  {
unknown's avatar
unknown committed
2164
    left_wall=to+(sign_char != 0)-1;
2165 2166
    if (!expo_sign_char)	// If exponent was specified, ignore prezeros
    {
2167
      for (;pos > left_wall && pre_zeros_from !=pre_zeros_end;
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
	   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
  }
  
2183 2184
  /*
    Write digits of the frac_% parts ;
2185
    Depending on table->in_use->count_cutted_fields, we may also want
2186 2187 2188 2189 2190
    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)
  */
2191
      
2192 2193 2194
  pos=to+(uint)(field_length-tmp_dec);	// Calculate post to '.'
  right_wall=to+field_length;
  if (pos != right_wall) 
2195 2196
    *pos++='.';

2197 2198 2199
  if (expo_sign_char == '-')
  {
    while (frac_digits_added_zeros-- > 0)
unknown's avatar
unknown committed
2200
    {
2201
      if (pos == right_wall) 
2202
      {
2203
        if (table->in_use->count_cuted_fields && !is_cuted_fields_incr) 
2204
          break; // Go on below to see if we lose non zero digits
unknown's avatar
unknown committed
2205
        return 0;
2206
      }
2207 2208 2209 2210 2211 2212
      *pos++='0';
    }
    while (int_digits_end != frac_digits_head_end)
    {
      tmp_char= *int_digits_end++;
      if (pos == right_wall)
unknown's avatar
unknown committed
2213
      {
2214 2215 2216
        if (tmp_char != '0')			// Losing a non zero digit ?
        {
          if (!is_cuted_fields_incr)
2217
            set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, 
2218
                        WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
2219
          return 0;
2220 2221
        }
        continue;
unknown's avatar
unknown committed
2222
      }
2223
      *pos++= tmp_char;
unknown's avatar
unknown committed
2224
    }
2225
  }
2226

2227 2228 2229 2230
  for (;frac_digits_from!=frac_digits_end;) 
  {
    tmp_char= *frac_digits_from++;
    if (pos == right_wall)
2231
    {
2232
      if (tmp_char != '0')			// Losing a non zero digit ?
2233
      {
2234
        if (!is_cuted_fields_incr)
unknown's avatar
unknown committed
2235 2236 2237 2238 2239
        {
          /*
            This is a note, not a warning, as we don't want to abort
            when we cut decimals in strict mode
          */
2240
	  set_warning(MYSQL_ERROR::WARN_LEVEL_NOTE, WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
2241
        }
unknown's avatar
unknown committed
2242
        return 0;
2243
      }
2244
      continue;
2245
    }
2246
    *pos++= tmp_char;
unknown's avatar
unknown committed
2247
  }
2248 2249 2250
      
  while (pos != right_wall)
   *pos++='0';			// Fill with zeros at right of '.'
unknown's avatar
unknown committed
2251
  return 0;
unknown's avatar
unknown committed
2252 2253 2254
}


unknown's avatar
unknown committed
2255
int Field_decimal::store(double nr)
unknown's avatar
unknown committed
2256
{
2257
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
2258 2259 2260
  if (unsigned_flag && nr < 0)
  {
    overflow(1);
2261
    return 1;
unknown's avatar
unknown committed
2262
  }
2263
  
2264 2265
#ifdef HAVE_FINITE
  if (!finite(nr)) // Handle infinity as special case
2266 2267
  {
    overflow(nr < 0.0);
unknown's avatar
unknown committed
2268
    return 1;
2269
  }
2270
#endif
unknown's avatar
unknown committed
2271

2272 2273 2274
  reg4 uint i;
  size_t length;
  uchar fyllchar,*to;
2275
  char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
unknown's avatar
unknown committed
2276 2277

  fyllchar = zerofill ? (char) '0' : (char) ' ';
unknown's avatar
unknown committed
2278
#ifdef HAVE_SNPRINTF
unknown's avatar
unknown committed
2279 2280
  buff[sizeof(buff)-1]=0;			// Safety
  snprintf(buff,sizeof(buff)-1, "%.*f",(int) dec,nr);
2281
  length= strlen(buff);
unknown's avatar
unknown committed
2282
#else
2283
  length= my_sprintf(buff,(buff,"%.*f",dec,nr));
unknown's avatar
unknown committed
2284
#endif
unknown's avatar
unknown committed
2285 2286 2287 2288

  if (length > field_length)
  {
    overflow(nr < 0.0);
2289
    return 1;
unknown's avatar
unknown committed
2290 2291 2292 2293 2294 2295 2296
  }
  else
  {
    to=ptr;
    for (i=field_length-length ; i-- > 0 ;)
      *to++ = fyllchar;
    memcpy(to,buff,length);
2297
    return 0;
unknown's avatar
unknown committed
2298 2299 2300 2301
  }
}


2302
int Field_decimal::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
2303
{
2304
  ASSERT_COLUMN_MARKED_FOR_WRITE;
2305 2306
  char buff[22];
  uint length, int_part;
2307 2308
  char fyllchar;
  uchar *to;
2309 2310

  if (nr < 0 && unsigned_flag && !unsigned_val)
unknown's avatar
unknown committed
2311 2312
  {
    overflow(1);
2313
    return 1;
unknown's avatar
unknown committed
2314
  }
2315 2316
  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
2317 2318 2319

  if (length > int_part)
  {
2320
    overflow(!unsigned_val && nr < 0L);		/* purecov: inspected */
2321
    return 1;
unknown's avatar
unknown committed
2322
  }
2323 2324 2325 2326 2327 2328 2329

  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
2330
  {
2331 2332
    to[length]='.';
    bfill(to+length+1,dec,'0');
unknown's avatar
unknown committed
2333
  }
2334
  return 0;
unknown's avatar
unknown committed
2335 2336 2337 2338 2339
}


double Field_decimal::val_real(void)
{
2340
  ASSERT_COLUMN_MARKED_FOR_READ;
2341
  int not_used;
2342
  char *end_not_used;
2343
  return my_strntod(&my_charset_bin, (char*) ptr, field_length, &end_not_used,
2344
                    &not_used);
unknown's avatar
unknown committed
2345 2346 2347 2348
}

longlong Field_decimal::val_int(void)
{
2349
  ASSERT_COLUMN_MARKED_FOR_READ;
2350
  int not_used;
unknown's avatar
unknown committed
2351
  if (unsigned_flag)
2352
    return my_strntoull(&my_charset_bin, (char*) ptr, field_length, 10, NULL,
2353
			&not_used);
2354 2355
  return my_strntoll(&my_charset_bin, (char*) ptr, field_length, 10, NULL,
                     &not_used);
unknown's avatar
unknown committed
2356 2357
}

2358

unknown's avatar
unknown committed
2359 2360 2361
String *Field_decimal::val_str(String *val_buffer __attribute__((unused)),
			       String *val_ptr)
{
2362
  ASSERT_COLUMN_MARKED_FOR_READ;
2363 2364 2365
  uchar *str;
  size_t tmp_length;

unknown's avatar
unknown committed
2366
  for (str=ptr ; *str == ' ' ; str++) ;
unknown's avatar
unknown committed
2367
  val_ptr->set_charset(&my_charset_bin);
2368
  tmp_length= (size_t) (str-ptr);
unknown's avatar
unknown committed
2369 2370 2371
  if (field_length < tmp_length)		// Error in data
    val_ptr->length(0);
  else
2372
    val_ptr->set_ascii((const char*) str, field_length-tmp_length);
unknown's avatar
unknown committed
2373 2374 2375
  return val_ptr;
}

2376 2377 2378
/**
  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
2379 2380
*/

2381
int Field_decimal::cmp(const uchar *a_ptr,const uchar *b_ptr)
unknown's avatar
unknown committed
2382
{
2383
  const uchar *end;
2384
  int swap=0;
unknown's avatar
unknown committed
2385 2386 2387 2388
  /* First remove prefixes '0', ' ', and '-' */
  for (end=a_ptr+field_length;
       a_ptr != end &&
	 (*a_ptr == *b_ptr ||
unknown's avatar
unknown committed
2389
	  ((my_isspace(&my_charset_bin,*a_ptr)  || *a_ptr == '+' || 
2390
            *a_ptr == '0') &&
unknown's avatar
unknown committed
2391
	   (my_isspace(&my_charset_bin,*b_ptr) || *b_ptr == '+' || 
2392
            *b_ptr == '0')));
2393 2394 2395 2396 2397
       a_ptr++,b_ptr++)
  {
    if (*a_ptr == '-')				// If both numbers are negative
      swap= -1 ^ 1;				// Swap result      
  }
unknown's avatar
unknown committed
2398 2399 2400
  if (a_ptr == end)
    return 0;
  if (*a_ptr == '-')
2401
    return -1;
2402
  if (*b_ptr == '-')
unknown's avatar
unknown committed
2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413
    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;
}


2414
void Field_decimal::sort_string(uchar *to,uint length)
unknown's avatar
unknown committed
2415
{
2416
  uchar *str,*end;
unknown's avatar
unknown committed
2417 2418
  for (str=ptr,end=ptr+length;
       str != end &&
unknown's avatar
unknown committed
2419
	 ((my_isspace(&my_charset_bin,*str) || *str == '+' ||
unknown's avatar
unknown committed
2420
	   *str == '0')) ;
unknown's avatar
unknown committed
2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
       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
2431
      if (my_isdigit(&my_charset_bin,*str))
unknown's avatar
unknown committed
2432 2433 2434 2435 2436 2437 2438
	*to++= (char) ('9' - *str++);
      else
	*to++= *str++;
  }
  else memcpy(to,str,(uint) (end-str));
}

unknown's avatar
unknown committed
2439

unknown's avatar
unknown committed
2440 2441
void Field_decimal::sql_type(String &res) const
{
unknown's avatar
unknown committed
2442
  CHARSET_INFO *cs=res.charset();
unknown's avatar
unknown committed
2443 2444 2445 2446 2447
  uint tmp=field_length;
  if (!unsigned_flag)
    tmp--;
  if (dec)
    tmp--;
2448
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
2449
			  "decimal(%d,%d)",tmp,dec));
unknown's avatar
unknown committed
2450 2451 2452 2453
  add_zerofill_and_unsigned(res);
}


unknown's avatar
unknown committed
2454 2455 2456 2457
/****************************************************************************
** Field_new_decimal
****************************************************************************/

2458
Field_new_decimal::Field_new_decimal(uchar *ptr_arg,
unknown's avatar
unknown committed
2459 2460 2461 2462 2463 2464
                                     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
2465 2466
  :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
2467
{
unknown's avatar
unknown committed
2468
  precision= my_decimal_length_to_precision(len_arg, dec_arg, unsigned_arg);
unknown's avatar
unknown committed
2469
  set_if_smaller(precision, DECIMAL_MAX_PRECISION);
unknown's avatar
unknown committed
2470 2471 2472
  DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION) &&
              (dec <= DECIMAL_MAX_SCALE));
  bin_size= my_decimal_get_binary_size(precision, dec);
unknown's avatar
unknown committed
2473 2474 2475 2476
}


Field_new_decimal::Field_new_decimal(uint32 len_arg,
2477
                                     bool maybe_null_arg,
unknown's avatar
unknown committed
2478
                                     const char *name,
unknown's avatar
unknown committed
2479 2480
                                     uint8 dec_arg,
                                     bool unsigned_arg)
2481
  :Field_num((uchar*) 0, len_arg,
2482
             maybe_null_arg ? (uchar*) "": 0, 0,
unknown's avatar
unknown committed
2483
             NONE, name, dec_arg, 0, unsigned_arg)
unknown's avatar
unknown committed
2484
{
unknown's avatar
unknown committed
2485
  precision= my_decimal_length_to_precision(len_arg, dec_arg, unsigned_arg);
unknown's avatar
unknown committed
2486
  set_if_smaller(precision, DECIMAL_MAX_PRECISION);
unknown's avatar
unknown committed
2487 2488 2489
  DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION) &&
              (dec <= DECIMAL_MAX_SCALE));
  bin_size= my_decimal_get_binary_size(precision, dec);
unknown's avatar
unknown committed
2490 2491 2492
}


unknown's avatar
unknown committed
2493
int Field_new_decimal::reset(void)
unknown's avatar
unknown committed
2494 2495
{
  store_value(&decimal_zero);
unknown's avatar
unknown committed
2496
  return 0;
unknown's avatar
unknown committed
2497 2498 2499
}


2500
/**
unknown's avatar
unknown committed
2501 2502
  Generate max/min decimal value in case of overflow.

2503 2504
  @param decimal_value     buffer for value
  @param sign              sign of value which caused overflow
unknown's avatar
unknown committed
2505 2506 2507 2508 2509 2510
*/

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
2511
  max_my_decimal(decimal_value, precision, decimals());
unknown's avatar
unknown committed
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
  if (sign)
  {
    if (unsigned_flag)
      my_decimal_set_zero(decimal_value);
    else
      decimal_value->sign(TRUE);
  }
  DBUG_VOID_RETURN;
}


2523 2524
/**
  Store decimal value in the binary buffer.
unknown's avatar
unknown committed
2525

2526 2527 2528
  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
2529

2530
  @param decimal_value   my_decimal
unknown's avatar
unknown committed
2531

2532 2533 2534 2535
  @retval
    0 ok
  @retval
    1 error
unknown's avatar
unknown committed
2536 2537 2538 2539
*/

bool Field_new_decimal::store_value(const my_decimal *decimal_value)
{
2540
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
2541 2542
  int error= 0;
  DBUG_ENTER("Field_new_decimal::store_value");
unknown's avatar
unknown committed
2543 2544 2545 2546 2547 2548
#ifndef DBUG_OFF
  {
    char dbug_buff[DECIMAL_MAX_STR_LENGTH+1];
    DBUG_PRINT("enter", ("value: %s", dbug_decimal_as_string(dbug_buff, decimal_value)));
  }
#endif
unknown's avatar
unknown committed
2549 2550 2551 2552 2553 2554

  /* check that we do not try to write negative value in unsigned field */
  if (unsigned_flag && decimal_value->sign())
  {
    DBUG_PRINT("info", ("unsigned overflow"));
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
2555
    error= 1;
unknown's avatar
unknown committed
2556 2557 2558 2559 2560
    decimal_value= &decimal_zero;
  }
#ifndef DBUG_OFF
  {
    char dbug_buff[DECIMAL_MAX_STR_LENGTH+1];
2561
    DBUG_PRINT("info", ("saving with precision %d  scale: %d  value %s",
unknown's avatar
unknown committed
2562 2563
                        (int)precision, (int)dec,
                        dbug_decimal_as_string(dbug_buff, decimal_value)));
unknown's avatar
unknown committed
2564
  }
unknown's avatar
unknown committed
2565
#endif
unknown's avatar
unknown committed
2566

unknown's avatar
unknown committed
2567 2568
  if (warn_if_overflow(my_decimal2binary(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW,
                                         decimal_value, ptr, precision, dec)))
unknown's avatar
unknown committed
2569 2570 2571
  {
    my_decimal buff;
    DBUG_PRINT("info", ("overflow"));
unknown's avatar
unknown committed
2572 2573
    set_value_on_overflow(&buff, decimal_value->sign());
    my_decimal2binary(E_DEC_FATAL_ERROR, &buff, ptr, precision, dec);
2574
    error= 1;
unknown's avatar
unknown committed
2575
  }
2576
  DBUG_EXECUTE("info", print_decimal_buff(decimal_value, (uchar *) ptr,
2577
                                          bin_size););
unknown's avatar
unknown committed
2578
  DBUG_RETURN(error);
unknown's avatar
unknown committed
2579 2580 2581 2582
}


int Field_new_decimal::store(const char *from, uint length,
2583
                             CHARSET_INFO *charset_arg)
unknown's avatar
unknown committed
2584
{
2585
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
2586 2587
  int err;
  my_decimal decimal_value;
unknown's avatar
unknown committed
2588 2589
  DBUG_ENTER("Field_new_decimal::store(char*)");

2590
  if ((err= str2my_decimal(E_DEC_FATAL_ERROR &
2591 2592 2593
                           ~(E_DEC_OVERFLOW | E_DEC_BAD_NUM),
                           from, length, charset_arg,
                           &decimal_value)) &&
2594 2595
      table->in_use->abort_on_warning)
  {
2596 2597 2598 2599
    /* Because "from" is not NUL-terminated and we use %s in the ER() */
    String from_as_str;
    from_as_str.copy(from, length, &my_charset_bin);

2600 2601 2602
    push_warning_printf(table->in_use, MYSQL_ERROR::WARN_LEVEL_ERROR,
                        ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
                        ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
2603
                        "decimal", from_as_str.c_ptr(), field_name,
2604
                        (ulong) table->in_use->row_count);
2605

2606 2607 2608 2609
    DBUG_RETURN(err);
  }

  switch (err) {
unknown's avatar
unknown committed
2610 2611 2612 2613 2614 2615 2616 2617
  case E_DEC_TRUNCATED:
    set_warning(MYSQL_ERROR::WARN_LEVEL_NOTE, WARN_DATA_TRUNCATED, 1);
    break;
  case E_DEC_OVERFLOW:
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
    set_value_on_overflow(&decimal_value, decimal_value.sign());
    break;
  case E_DEC_BAD_NUM:
2618 2619 2620 2621 2622
    {
      /* Because "from" is not NUL-terminated and we use %s in the ER() */
      String from_as_str;
      from_as_str.copy(from, length, &my_charset_bin);

unknown's avatar
unknown committed
2623 2624 2625
    push_warning_printf(table->in_use, MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
                        ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
2626
                          "decimal", from_as_str.c_ptr(), field_name,
unknown's avatar
unknown committed
2627 2628
                        (ulong) table->in_use->row_count);
    my_decimal_set_zero(&decimal_value);
2629

unknown's avatar
unknown committed
2630
    break;
2631
    }
unknown's avatar
unknown committed
2632 2633
  }

unknown's avatar
unknown committed
2634 2635 2636 2637 2638
#ifndef DBUG_OFF
  char dbug_buff[DECIMAL_MAX_STR_LENGTH+1];
  DBUG_PRINT("enter", ("value: %s",
                       dbug_decimal_as_string(dbug_buff, &decimal_value)));
#endif
unknown's avatar
unknown committed
2639 2640 2641 2642 2643
  store_value(&decimal_value);
  DBUG_RETURN(err);
}


2644 2645 2646 2647 2648 2649
/**
  @todo
  Fix following when double2my_decimal when double2decimal
  will return E_DEC_TRUNCATED always correctly
*/

unknown's avatar
unknown committed
2650 2651
int Field_new_decimal::store(double nr)
{
2652
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
2653
  my_decimal decimal_value;
unknown's avatar
unknown committed
2654 2655 2656 2657 2658
  int err;
  DBUG_ENTER("Field_new_decimal::store(double)");

  err= double2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW, nr,
                         &decimal_value);
unknown's avatar
unknown committed
2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
  /*
    TODO: fix following when double2my_decimal when double2decimal
    will return E_DEC_TRUNCATED always correctly
  */
  if (!err)
  {
    double nr2;
    my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &nr2);
    if (nr2 != nr)
      err= E_DEC_TRUNCATED;
  }
unknown's avatar
unknown committed
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
  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 */
    table->in_use->got_warning= 0;
  }
  if (store_value(&decimal_value))
    err= 1;
  else if (err && !table->in_use->got_warning)
    err= warn_if_overflow(err);
  DBUG_RETURN(err);
unknown's avatar
unknown committed
2682 2683 2684
}


2685
int Field_new_decimal::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
2686
{
2687
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
2688 2689
  my_decimal decimal_value;
  int err;
unknown's avatar
unknown committed
2690 2691

  if ((err= int2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_OVERFLOW,
2692
                           nr, unsigned_val, &decimal_value)))
unknown's avatar
unknown committed
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702
  {
    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 */
    table->in_use->got_warning= 0;
  }
  if (store_value(&decimal_value))
    err= 1;
  else if (err && !table->in_use->got_warning)
    err= warn_if_overflow(err);
unknown's avatar
unknown committed
2703 2704 2705 2706 2707 2708
  return err;
}


int Field_new_decimal::store_decimal(const my_decimal *decimal_value)
{
2709
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
2710 2711 2712 2713
  return store_value(decimal_value);
}


2714
int Field_new_decimal::store_time(MYSQL_TIME *ltime, timestamp_type t_type)
2715 2716 2717
{
    my_decimal decimal_value;
    return store_value(date2my_decimal(ltime, &decimal_value));
unknown's avatar
unknown committed
2718 2719 2720 2721 2722
}


double Field_new_decimal::val_real(void)
{
2723
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
2724 2725 2726 2727 2728 2729 2730 2731 2732
  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)
{
2733
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743
  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)
{
2744
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
2745 2746
  DBUG_ENTER("Field_new_decimal::val_decimal");
  binary2my_decimal(E_DEC_FATAL_ERROR, ptr, decimal_value,
unknown's avatar
unknown committed
2747
                    precision, dec);
2748
  DBUG_EXECUTE("info", print_decimal_buff(decimal_value, (uchar *) ptr,
2749
                                          bin_size););
unknown's avatar
unknown committed
2750 2751 2752 2753 2754
  DBUG_RETURN(decimal_value);
}


String *Field_new_decimal::val_str(String *val_buffer,
unknown's avatar
unknown committed
2755
                                   String *val_ptr __attribute__((unused)))
unknown's avatar
unknown committed
2756
{
2757
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
2758
  my_decimal decimal_value;
unknown's avatar
unknown committed
2759
  uint fixed_precision= zerofill ? precision : 0;
unknown's avatar
unknown committed
2760
  my_decimal2string(E_DEC_FATAL_ERROR, val_decimal(&decimal_value),
unknown's avatar
unknown committed
2761
                    fixed_precision, dec, '0', val_buffer);
unknown's avatar
unknown committed
2762 2763 2764 2765
  return val_buffer;
}


2766
int Field_new_decimal::cmp(const uchar *a,const uchar*b)
unknown's avatar
unknown committed
2767 2768 2769 2770 2771
{
  return memcmp(a, b, bin_size);
}


2772
void Field_new_decimal::sort_string(uchar *buff,
unknown's avatar
unknown committed
2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
                                    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
2783
                                "decimal(%d,%d)", precision, (int)dec));
unknown's avatar
unknown committed
2784 2785 2786
  add_zerofill_and_unsigned(str);
}

unknown's avatar
unknown committed
2787

2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857
/**
   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);
}


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

   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). 

   @param   field_metadata   Encoded size in field metadata

   @retval 0 if this field's size is < the source field's size
   @retval 1 if this field's size is >= the source field's size
*/
int Field_new_decimal::compatible_field_size(uint field_metadata)
{
  int compatible= 0;
  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);
  uint const destination_size= row_pack_length();
  compatible= (source_size <= destination_size);
  if (compatible)
    compatible= (source_precision <= precision) &&
                (source_decimal <= decimals());
  return (compatible);
}


unknown's avatar
unknown committed
2858
uint Field_new_decimal::is_equal(Create_field *new_field)
2859 2860 2861 2862 2863 2864
{
  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
2865
          (new_field->length == max_display_length()) &&
2866 2867 2868 2869
          (new_field->decimals == dec));
}


2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881
/**
   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
*/
2882 2883 2884 2885 2886
const uchar *
Field_new_decimal::unpack(uchar* to,
                          const uchar *from,
                          uint param_data,
                          bool low_byte_first)
2887
{
2888 2889 2890
  if (param_data == 0)
    return Field::unpack(to, from, param_data, low_byte_first);

2891 2892 2893 2894 2895 2896
  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;
2897 2898 2899
  if ((from_pack_len && (from_pack_len < length)) ||
      (from_precision < precision) ||
      (from_decimal < decimals()))
2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922
  {
    /*
      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];
    decimal_t dec;
    dec.len= from_precision;
    dec.buf= dec_buf;
    /*
      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.
    */
    bin2decimal((uchar *)from, &dec, from_precision, from_decimal);
    decimal2bin(&dec, to, precision, decimals());
  }
  else
    memcpy(to, from, len); // Sizes are the same, just copy the data.
  return from+len;
}

unknown's avatar
unknown committed
2923 2924 2925 2926
/****************************************************************************
** tiny int
****************************************************************************/

unknown's avatar
unknown committed
2927
int Field_tiny::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
2928
{
2929
  ASSERT_COLUMN_MARKED_FOR_WRITE;
2930
  int error;
unknown's avatar
unknown committed
2931 2932 2933 2934
  longlong rnd;
  
  error= get_int(cs, from, len, &rnd, 255, -128, 127);
  ptr[0]= unsigned_flag ? (char) (ulonglong) rnd : (char) rnd;
2935
  return error;
unknown's avatar
unknown committed
2936 2937 2938
}


unknown's avatar
unknown committed
2939
int Field_tiny::store(double nr)
unknown's avatar
unknown committed
2940
{
2941
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
2942
  int error= 0;
unknown's avatar
unknown committed
2943 2944 2945 2946 2947 2948
  nr=rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0.0)
    {
      *ptr=0;
2949
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
2950
      error= 1;
unknown's avatar
unknown committed
2951 2952 2953 2954
    }
    else if (nr > 255.0)
    {
      *ptr=(char) 255;
2955
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
2956
      error= 1;
unknown's avatar
unknown committed
2957 2958 2959 2960 2961 2962 2963 2964 2965
    }
    else
      *ptr=(char) nr;
  }
  else
  {
    if (nr < -128.0)
    {
      *ptr= (char) -128;
2966
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
2967
      error= 1;
unknown's avatar
unknown committed
2968 2969 2970 2971
    }
    else if (nr > 127.0)
    {
      *ptr=127;
2972
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
2973
      error= 1;
unknown's avatar
unknown committed
2974 2975
    }
    else
unknown's avatar
unknown committed
2976
      *ptr=(char) (int) nr;
unknown's avatar
unknown committed
2977
  }
2978
  return error;
unknown's avatar
unknown committed
2979 2980
}

2981 2982

int Field_tiny::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
2983
{
2984
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
2985
  int error= 0;
2986

unknown's avatar
unknown committed
2987 2988
  if (unsigned_flag)
  {
2989
    if (nr < 0 && !unsigned_val)
unknown's avatar
unknown committed
2990
    {
2991
      *ptr= 0;
2992
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
2993
      error= 1;
unknown's avatar
unknown committed
2994
    }
2995
    else if ((ulonglong) nr > (ulonglong) 255)
unknown's avatar
unknown committed
2996 2997
    {
      *ptr= (char) 255;
2998
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
2999
      error= 1;
unknown's avatar
unknown committed
3000 3001 3002 3003 3004 3005
    }
    else
      *ptr=(char) nr;
  }
  else
  {
3006 3007 3008
    if (nr < 0 && unsigned_val)
      nr= 256;                                    // Generate overflow
    if (nr < -128)
unknown's avatar
unknown committed
3009 3010
    {
      *ptr= (char) -128;
3011
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3012
      error= 1;
unknown's avatar
unknown committed
3013
    }
3014
    else if (nr > 127)
unknown's avatar
unknown committed
3015 3016
    {
      *ptr=127;
3017
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3018
      error= 1;
unknown's avatar
unknown committed
3019 3020 3021 3022
    }
    else
      *ptr=(char) nr;
  }
3023
  return error;
unknown's avatar
unknown committed
3024 3025 3026 3027 3028
}


double Field_tiny::val_real(void)
{
3029
  ASSERT_COLUMN_MARKED_FOR_READ;
3030
  int tmp= unsigned_flag ? (int) ptr[0] :
unknown's avatar
unknown committed
3031 3032 3033 3034
    (int) ((signed char*) ptr)[0];
  return (double) tmp;
}

3035

unknown's avatar
unknown committed
3036 3037
longlong Field_tiny::val_int(void)
{
3038
  ASSERT_COLUMN_MARKED_FOR_READ;
3039
  int tmp= unsigned_flag ? (int) ptr[0] :
unknown's avatar
unknown committed
3040 3041 3042 3043
    (int) ((signed char*) ptr)[0];
  return (longlong) tmp;
}

3044

unknown's avatar
unknown committed
3045 3046 3047
String *Field_tiny::val_str(String *val_buffer,
			    String *val_ptr __attribute__((unused)))
{
3048
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3049
  CHARSET_INFO *cs= &my_charset_bin;
unknown's avatar
unknown committed
3050
  uint length;
3051 3052
  uint mlength=max(field_length+1,5*cs->mbmaxlen);
  val_buffer->alloc(mlength);
unknown's avatar
unknown committed
3053
  char *to=(char*) val_buffer->ptr();
3054

unknown's avatar
unknown committed
3055
  if (unsigned_flag)
3056
    length= (uint) cs->cset->long10_to_str(cs,to,mlength, 10,
3057
					   (long) *ptr);
unknown's avatar
unknown committed
3058
  else
3059 3060
    length= (uint) cs->cset->long10_to_str(cs,to,mlength,-10,
					   (long) *((signed char*) ptr));
3061
  
unknown's avatar
unknown committed
3062 3063 3064 3065 3066 3067
  val_buffer->length(length);
  if (zerofill)
    prepend_zeros(val_buffer);
  return val_buffer;
}

3068 3069 3070 3071
bool Field_tiny::send_binary(Protocol *protocol)
{
  return protocol->store_tiny((longlong) (int8) ptr[0]);
}
unknown's avatar
unknown committed
3072

3073
int Field_tiny::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
3074 3075 3076 3077 3078 3079 3080 3081
{
  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;
}

3082
void Field_tiny::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
3083 3084 3085 3086
{
  if (unsigned_flag)
    *to= *ptr;
  else
3087
    to[0] = (char) (ptr[0] ^ (uchar) 128);	/* Revers signbit */
unknown's avatar
unknown committed
3088 3089 3090 3091
}

void Field_tiny::sql_type(String &res) const
{
unknown's avatar
unknown committed
3092
  CHARSET_INFO *cs=res.charset();
3093
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
3094
			  "tinyint(%d)",(int) field_length));
unknown's avatar
unknown committed
3095 3096 3097 3098
  add_zerofill_and_unsigned(res);
}

/****************************************************************************
3099
 Field type short int (2 byte)
unknown's avatar
unknown committed
3100 3101
****************************************************************************/

unknown's avatar
unknown committed
3102
int Field_short::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
3103
{
3104
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
3105
  int store_tmp;
3106
  int error;
unknown's avatar
unknown committed
3107 3108 3109 3110
  longlong rnd;
  
  error= get_int(cs, from, len, &rnd, UINT_MAX16, INT_MIN16, INT_MAX16);
  store_tmp= unsigned_flag ? (int) (ulonglong) rnd : (int) rnd;
3111
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3112 3113 3114
  if (table->s->db_low_byte_first)
  {
    int2store(ptr, store_tmp);
unknown's avatar
unknown committed
3115 3116 3117
  }
  else
#endif
unknown's avatar
unknown committed
3118
    shortstore(ptr, (short) store_tmp);
3119
  return error;
unknown's avatar
unknown committed
3120 3121 3122
}


unknown's avatar
unknown committed
3123
int Field_short::store(double nr)
unknown's avatar
unknown committed
3124
{
3125
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
3126
  int error= 0;
unknown's avatar
unknown committed
3127 3128 3129 3130 3131 3132 3133
  int16 res;
  nr=rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0)
    {
      res=0;
3134
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3135
      error= 1;
unknown's avatar
unknown committed
3136
    }
unknown's avatar
unknown committed
3137
    else if (nr > (double) UINT_MAX16)
unknown's avatar
unknown committed
3138
    {
unknown's avatar
unknown committed
3139
      res=(int16) UINT_MAX16;
3140
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3141
      error= 1;
unknown's avatar
unknown committed
3142 3143 3144 3145 3146 3147 3148 3149 3150
    }
    else
      res=(int16) (uint16) nr;
  }
  else
  {
    if (nr < (double) INT_MIN16)
    {
      res=INT_MIN16;
3151
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3152
      error= 1;
unknown's avatar
unknown committed
3153 3154 3155 3156
    }
    else if (nr > (double) INT_MAX16)
    {
      res=INT_MAX16;
3157
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3158
      error= 1;
unknown's avatar
unknown committed
3159 3160
    }
    else
unknown's avatar
unknown committed
3161
      res=(int16) (int) nr;
unknown's avatar
unknown committed
3162 3163
  }
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3164
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3165 3166 3167 3168 3169 3170
  {
    int2store(ptr,res);
  }
  else
#endif
    shortstore(ptr,res);
3171
  return error;
unknown's avatar
unknown committed
3172 3173
}

3174 3175

int Field_short::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
3176
{
3177
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
3178
  int error= 0;
unknown's avatar
unknown committed
3179
  int16 res;
3180

unknown's avatar
unknown committed
3181 3182
  if (unsigned_flag)
  {
3183
    if (nr < 0L && !unsigned_val)
unknown's avatar
unknown committed
3184 3185
    {
      res=0;
3186
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3187
      error= 1;
unknown's avatar
unknown committed
3188
    }
3189
    else if ((ulonglong) nr > (ulonglong) UINT_MAX16)
unknown's avatar
unknown committed
3190
    {
unknown's avatar
unknown committed
3191
      res=(int16) UINT_MAX16;
3192
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3193
      error= 1;
unknown's avatar
unknown committed
3194 3195 3196 3197 3198 3199
    }
    else
      res=(int16) (uint16) nr;
  }
  else
  {
3200 3201 3202
    if (nr < 0 && unsigned_val)
      nr= UINT_MAX16+1;                         // Generate overflow

unknown's avatar
unknown committed
3203 3204 3205
    if (nr < INT_MIN16)
    {
      res=INT_MIN16;
3206
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3207
      error= 1;
unknown's avatar
unknown committed
3208
    }
3209
    else if (nr > (longlong) INT_MAX16)
unknown's avatar
unknown committed
3210 3211
    {
      res=INT_MAX16;
3212
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3213
      error= 1;
unknown's avatar
unknown committed
3214 3215 3216 3217 3218
    }
    else
      res=(int16) nr;
  }
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3219
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3220 3221 3222 3223 3224 3225
  {
    int2store(ptr,res);
  }
  else
#endif
    shortstore(ptr,res);
3226
  return error;
unknown's avatar
unknown committed
3227 3228 3229 3230 3231
}


double Field_short::val_real(void)
{
3232
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3233 3234
  short j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3235
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3236 3237 3238 3239 3240 3241 3242 3243 3244
    j=sint2korr(ptr);
  else
#endif
    shortget(j,ptr);
  return unsigned_flag ? (double) (unsigned short) j : (double) j;
}

longlong Field_short::val_int(void)
{
3245
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3246 3247
  short j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3248
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3249 3250 3251 3252 3253 3254 3255
    j=sint2korr(ptr);
  else
#endif
    shortget(j,ptr);
  return unsigned_flag ? (longlong) (unsigned short) j : (longlong) j;
}

3256

unknown's avatar
unknown committed
3257 3258 3259
String *Field_short::val_str(String *val_buffer,
			     String *val_ptr __attribute__((unused)))
{
3260
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3261
  CHARSET_INFO *cs= &my_charset_bin;
unknown's avatar
unknown committed
3262
  uint length;
3263 3264
  uint mlength=max(field_length+1,7*cs->mbmaxlen);
  val_buffer->alloc(mlength);
unknown's avatar
unknown committed
3265 3266 3267
  char *to=(char*) val_buffer->ptr();
  short j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3268
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3269 3270 3271 3272 3273 3274
    j=sint2korr(ptr);
  else
#endif
    shortget(j,ptr);

  if (unsigned_flag)
3275 3276
    length=(uint) cs->cset->long10_to_str(cs, to, mlength, 10, 
					  (long) (uint16) j);
unknown's avatar
unknown committed
3277
  else
3278
    length=(uint) cs->cset->long10_to_str(cs, to, mlength,-10, (long) j);
unknown's avatar
unknown committed
3279 3280 3281 3282 3283 3284 3285
  val_buffer->length(length);
  if (zerofill)
    prepend_zeros(val_buffer);
  return val_buffer;
}


3286 3287 3288 3289 3290 3291
bool Field_short::send_binary(Protocol *protocol)
{
  return protocol->store_short(Field_short::val_int());
}


3292
int Field_short::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
3293 3294 3295
{
  short a,b;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3296
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
  {
    a=sint2korr(a_ptr);
    b=sint2korr(b_ptr);
  }
  else
#endif
  {
    shortget(a,a_ptr);
    shortget(b,b_ptr);
  }

  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;
}

3314
void Field_short::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
3315 3316
{
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3317
  if (!table->s->db_low_byte_first)
unknown's avatar
unknown committed
3318 3319 3320 3321
  {
    if (unsigned_flag)
      to[0] = ptr[0];
    else
unknown's avatar
unknown committed
3322
      to[0] = (char) (ptr[0] ^ 128);		/* Revers signbit */
unknown's avatar
unknown committed
3323 3324 3325 3326 3327 3328 3329 3330
    to[1]   = ptr[1];
  }
  else
#endif
  {
    if (unsigned_flag)
      to[0] = ptr[1];
    else
unknown's avatar
unknown committed
3331
      to[0] = (char) (ptr[1] ^ 128);		/* Revers signbit */
unknown's avatar
unknown committed
3332 3333 3334 3335 3336 3337
    to[1]   = ptr[0];
  }
}

void Field_short::sql_type(String &res) const
{
unknown's avatar
unknown committed
3338
  CHARSET_INFO *cs=res.charset();
3339
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
3340
			  "smallint(%d)",(int) field_length));
unknown's avatar
unknown committed
3341 3342 3343 3344 3345
  add_zerofill_and_unsigned(res);
}


/****************************************************************************
3346
  Field type medium int (3 byte)
unknown's avatar
unknown committed
3347 3348
****************************************************************************/

unknown's avatar
unknown committed
3349
int Field_medium::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
3350
{
3351
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
3352
  int store_tmp;
3353
  int error;
unknown's avatar
unknown committed
3354 3355 3356 3357 3358
  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);
3359
  return error;
unknown's avatar
unknown committed
3360 3361 3362
}


unknown's avatar
unknown committed
3363
int Field_medium::store(double nr)
unknown's avatar
unknown committed
3364
{
3365
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
3366
  int error= 0;
unknown's avatar
unknown committed
3367 3368 3369 3370 3371 3372
  nr=rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0)
    {
      int3store(ptr,0);
3373
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3374
      error= 1;
unknown's avatar
unknown committed
3375 3376 3377
    }
    else if (nr >= (double) (long) (1L << 24))
    {
unknown's avatar
unknown committed
3378
      uint32 tmp=(uint32) (1L << 24)-1L;
unknown's avatar
unknown committed
3379
      int3store(ptr,tmp);
3380
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3381
      error= 1;
unknown's avatar
unknown committed
3382 3383
    }
    else
unknown's avatar
unknown committed
3384
      int3store(ptr,(uint32) nr);
unknown's avatar
unknown committed
3385 3386 3387 3388 3389 3390 3391
  }
  else
  {
    if (nr < (double) INT_MIN24)
    {
      long tmp=(long) INT_MIN24;
      int3store(ptr,tmp);
3392
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3393
      error= 1;
unknown's avatar
unknown committed
3394 3395 3396 3397 3398
    }
    else if (nr > (double) INT_MAX24)
    {
      long tmp=(long) INT_MAX24;
      int3store(ptr,tmp);
3399
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3400
      error= 1;
unknown's avatar
unknown committed
3401 3402 3403 3404
    }
    else
      int3store(ptr,(long) nr);
  }
3405
  return error;
unknown's avatar
unknown committed
3406 3407
}

3408 3409

int Field_medium::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
3410
{
3411
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
3412
  int error= 0;
3413

unknown's avatar
unknown committed
3414 3415
  if (unsigned_flag)
  {
3416
    if (nr < 0 && !unsigned_val)
unknown's avatar
unknown committed
3417 3418
    {
      int3store(ptr,0);
3419
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3420
      error= 1;
unknown's avatar
unknown committed
3421
    }
3422
    else if ((ulonglong) nr >= (ulonglong) (long) (1L << 24))
unknown's avatar
unknown committed
3423
    {
3424
      long tmp= (long) (1L << 24)-1L;
unknown's avatar
unknown committed
3425
      int3store(ptr,tmp);
3426
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3427
      error= 1;
unknown's avatar
unknown committed
3428 3429
    }
    else
unknown's avatar
unknown committed
3430
      int3store(ptr,(uint32) nr);
unknown's avatar
unknown committed
3431 3432 3433
  }
  else
  {
3434 3435 3436
    if (nr < 0 && unsigned_val)
      nr= (ulonglong) (long) (1L << 24);        // Generate overflow

unknown's avatar
unknown committed
3437 3438
    if (nr < (longlong) INT_MIN24)
    {
3439
      long tmp= (long) INT_MIN24;
unknown's avatar
unknown committed
3440
      int3store(ptr,tmp);
3441
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3442
      error= 1;
unknown's avatar
unknown committed
3443 3444 3445 3446 3447
    }
    else if (nr > (longlong) INT_MAX24)
    {
      long tmp=(long) INT_MAX24;
      int3store(ptr,tmp);
3448
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3449
      error= 1;
unknown's avatar
unknown committed
3450 3451 3452 3453
    }
    else
      int3store(ptr,(long) nr);
  }
3454
  return error;
unknown's avatar
unknown committed
3455 3456 3457 3458 3459
}


double Field_medium::val_real(void)
{
3460
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3461 3462 3463 3464
  long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
  return (double) j;
}

3465

unknown's avatar
unknown committed
3466 3467
longlong Field_medium::val_int(void)
{
3468
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3469 3470 3471 3472
  long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);
  return (longlong) j;
}

3473

unknown's avatar
unknown committed
3474 3475 3476
String *Field_medium::val_str(String *val_buffer,
			      String *val_ptr __attribute__((unused)))
{
3477
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3478
  CHARSET_INFO *cs= &my_charset_bin;
unknown's avatar
unknown committed
3479
  uint length;
3480 3481
  uint mlength=max(field_length+1,10*cs->mbmaxlen);
  val_buffer->alloc(mlength);
unknown's avatar
unknown committed
3482 3483 3484
  char *to=(char*) val_buffer->ptr();
  long j= unsigned_flag ? (long) uint3korr(ptr) : sint3korr(ptr);

3485
  length=(uint) cs->cset->long10_to_str(cs,to,mlength,-10,j);
unknown's avatar
unknown committed
3486 3487 3488 3489 3490 3491 3492
  val_buffer->length(length);
  if (zerofill)
    prepend_zeros(val_buffer); /* purecov: inspected */
  return val_buffer;
}


3493 3494
bool Field_medium::send_binary(Protocol *protocol)
{
3495
  ASSERT_COLUMN_MARKED_FOR_READ;
3496 3497 3498 3499
  return protocol->store_long(Field_medium::val_int());
}


3500
int Field_medium::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515
{
  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;
}

3516
void Field_medium::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528
{
  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
3529
  CHARSET_INFO *cs=res.charset();
3530
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(), 
3531
			  "mediumint(%d)",(int) field_length));
unknown's avatar
unknown committed
3532 3533 3534 3535 3536 3537 3538
  add_zerofill_and_unsigned(res);
}

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

unknown's avatar
unknown committed
3539
int Field_long::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
3540
{
3541
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
3542 3543
  long store_tmp;
  int error;
unknown's avatar
unknown committed
3544 3545 3546 3547
  longlong rnd;
  
  error= get_int(cs, from, len, &rnd, UINT_MAX32, INT_MIN32, INT_MAX32);
  store_tmp= unsigned_flag ? (long) (ulonglong) rnd : (long) rnd;
unknown's avatar
unknown committed
3548
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3549
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3550
  {
unknown's avatar
unknown committed
3551
    int4store(ptr, store_tmp);
unknown's avatar
unknown committed
3552 3553 3554
  }
  else
#endif
unknown's avatar
unknown committed
3555
    longstore(ptr, store_tmp);
3556
  return error;
unknown's avatar
unknown committed
3557 3558 3559
}


unknown's avatar
unknown committed
3560
int Field_long::store(double nr)
unknown's avatar
unknown committed
3561
{
3562
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
3563
  int error= 0;
unknown's avatar
unknown committed
3564 3565 3566 3567 3568 3569 3570
  int32 res;
  nr=rint(nr);
  if (unsigned_flag)
  {
    if (nr < 0)
    {
      res=0;
unknown's avatar
unknown committed
3571
      error= 1;
unknown's avatar
unknown committed
3572
    }
3573
    else if (nr > (double) UINT_MAX32)
unknown's avatar
unknown committed
3574
    {
3575
      res= UINT_MAX32;
3576
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
3577
      error= 1;
unknown's avatar
unknown committed
3578 3579 3580 3581 3582 3583 3584 3585 3586
    }
    else
      res=(int32) (ulong) nr;
  }
  else
  {
    if (nr < (double) INT_MIN32)
    {
      res=(int32) INT_MIN32;
unknown's avatar
unknown committed
3587
      error= 1;
unknown's avatar
unknown committed
3588 3589 3590 3591
    }
    else if (nr > (double) INT_MAX32)
    {
      res=(int32) INT_MAX32;
unknown's avatar
unknown committed
3592
      error= 1;
unknown's avatar
unknown committed
3593 3594
    }
    else
unknown's avatar
unknown committed
3595
      res=(int32) (longlong) nr;
unknown's avatar
unknown committed
3596
  }
unknown's avatar
unknown committed
3597 3598 3599
  if (error)
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);

unknown's avatar
unknown committed
3600
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3601
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3602 3603 3604 3605 3606 3607
  {
    int4store(ptr,res);
  }
  else
#endif
    longstore(ptr,res);
3608
  return error;
unknown's avatar
unknown committed
3609 3610 3611
}


3612
int Field_long::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
3613
{
3614
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
3615
  int error= 0;
unknown's avatar
unknown committed
3616
  int32 res;
unknown's avatar
unknown committed
3617

unknown's avatar
unknown committed
3618 3619
  if (unsigned_flag)
  {
3620
    if (nr < 0 && !unsigned_val)
unknown's avatar
unknown committed
3621 3622
    {
      res=0;
unknown's avatar
unknown committed
3623
      error= 1;
unknown's avatar
unknown committed
3624
    }
3625
    else if ((ulonglong) nr >= (LL(1) << 32))
unknown's avatar
unknown committed
3626 3627
    {
      res=(int32) (uint32) ~0L;
unknown's avatar
unknown committed
3628
      error= 1;
unknown's avatar
unknown committed
3629 3630 3631 3632 3633 3634
    }
    else
      res=(int32) (uint32) nr;
  }
  else
  {
3635
    if (nr < 0 && unsigned_val)
3636
      nr= ((longlong) INT_MAX32) + 1;           // Generate overflow
3637
    if (nr < (longlong) INT_MIN32) 
unknown's avatar
unknown committed
3638 3639
    {
      res=(int32) INT_MIN32;
unknown's avatar
unknown committed
3640
      error= 1;
unknown's avatar
unknown committed
3641 3642 3643 3644
    }
    else if (nr > (longlong) INT_MAX32)
    {
      res=(int32) INT_MAX32;
unknown's avatar
unknown committed
3645
      error= 1;
unknown's avatar
unknown committed
3646 3647 3648 3649
    }
    else
      res=(int32) nr;
  }
unknown's avatar
unknown committed
3650 3651 3652
  if (error)
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);

unknown's avatar
unknown committed
3653
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3654
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3655 3656 3657 3658 3659 3660
  {
    int4store(ptr,res);
  }
  else
#endif
    longstore(ptr,res);
3661
  return error;
unknown's avatar
unknown committed
3662 3663 3664 3665 3666
}


double Field_long::val_real(void)
{
3667
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3668 3669
  int32 j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3670
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3671 3672 3673 3674 3675 3676 3677 3678 3679
    j=sint4korr(ptr);
  else
#endif
    longget(j,ptr);
  return unsigned_flag ? (double) (uint32) j : (double) j;
}

longlong Field_long::val_int(void)
{
3680
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3681
  int32 j;
3682 3683
  /* See the comment in Field_long::store(long long) */
  DBUG_ASSERT(table->in_use == current_thd);
unknown's avatar
unknown committed
3684
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3685
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3686 3687 3688 3689 3690 3691 3692 3693 3694 3695
    j=sint4korr(ptr);
  else
#endif
    longget(j,ptr);
  return unsigned_flag ? (longlong) (uint32) j : (longlong) j;
}

String *Field_long::val_str(String *val_buffer,
			    String *val_ptr __attribute__((unused)))
{
3696
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3697
  CHARSET_INFO *cs= &my_charset_bin;
unknown's avatar
unknown committed
3698
  uint length;
3699 3700
  uint mlength=max(field_length+1,12*cs->mbmaxlen);
  val_buffer->alloc(mlength);
unknown's avatar
unknown committed
3701 3702 3703
  char *to=(char*) val_buffer->ptr();
  int32 j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3704
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3705 3706 3707 3708 3709
    j=sint4korr(ptr);
  else
#endif
    longget(j,ptr);

3710
  if (unsigned_flag)
3711
    length=cs->cset->long10_to_str(cs,to,mlength, 10,(long) (uint32)j);
3712
  else
3713
    length=cs->cset->long10_to_str(cs,to,mlength,-10,(long) j);
unknown's avatar
unknown committed
3714 3715 3716 3717 3718 3719 3720
  val_buffer->length(length);
  if (zerofill)
    prepend_zeros(val_buffer);
  return val_buffer;
}


3721 3722
bool Field_long::send_binary(Protocol *protocol)
{
3723
  ASSERT_COLUMN_MARKED_FOR_READ;
3724 3725 3726
  return protocol->store_long(Field_long::val_int());
}

3727
int Field_long::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
3728 3729 3730
{
  int32 a,b;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3731
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742
  {
    a=sint4korr(a_ptr);
    b=sint4korr(b_ptr);
  }
  else
#endif
  {
    longget(a,a_ptr);
    longget(b,b_ptr);
  }
  if (unsigned_flag)
unknown's avatar
unknown committed
3743
    return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
unknown's avatar
unknown committed
3744 3745 3746
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

3747
void Field_long::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
3748 3749
{
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3750
  if (!table->s->db_low_byte_first)
unknown's avatar
unknown committed
3751 3752 3753 3754
  {
    if (unsigned_flag)
      to[0] = ptr[0];
    else
unknown's avatar
unknown committed
3755
      to[0] = (char) (ptr[0] ^ 128);		/* Revers signbit */
unknown's avatar
unknown committed
3756 3757 3758 3759 3760 3761 3762 3763 3764 3765
    to[1]   = ptr[1];
    to[2]   = ptr[2];
    to[3]   = ptr[3];
  }
  else
#endif
  {
    if (unsigned_flag)
      to[0] = ptr[3];
    else
unknown's avatar
unknown committed
3766
      to[0] = (char) (ptr[3] ^ 128);		/* Revers signbit */
unknown's avatar
unknown committed
3767 3768 3769 3770 3771 3772 3773 3774 3775
    to[1]   = ptr[2];
    to[2]   = ptr[1];
    to[3]   = ptr[0];
  }
}


void Field_long::sql_type(String &res) const
{
unknown's avatar
unknown committed
3776
  CHARSET_INFO *cs=res.charset();
3777
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
3778
			  "int(%d)",(int) field_length));
unknown's avatar
unknown committed
3779 3780 3781 3782
  add_zerofill_and_unsigned(res);
}

/****************************************************************************
3783
 Field type longlong int (8 bytes)
unknown's avatar
unknown committed
3784 3785
****************************************************************************/

unknown's avatar
unknown committed
3786
int Field_longlong::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
3787
{
3788
  ASSERT_COLUMN_MARKED_FOR_WRITE;
3789
  int error= 0;
3790
  char *end;
3791
  ulonglong tmp;
3792

3793 3794
  tmp= cs->cset->strntoull10rnd(cs,from,len,unsigned_flag,&end,&error);
  if (error == MY_ERRNO_ERANGE)
3795
  {
unknown's avatar
unknown committed
3796
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
3797 3798
    error= 1;
  }
unknown's avatar
unknown committed
3799 3800
  else if (table->in_use->count_cuted_fields && 
           check_int(cs, from, len, end, error))
3801 3802 3803
    error= 1;
  else
    error= 0;
unknown's avatar
unknown committed
3804
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3805
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3806 3807 3808 3809 3810 3811
  {
    int8store(ptr,tmp);
  }
  else
#endif
    longlongstore(ptr,tmp);
3812
  return error;
unknown's avatar
unknown committed
3813 3814 3815
}


unknown's avatar
unknown committed
3816
int Field_longlong::store(double nr)
unknown's avatar
unknown committed
3817
{
3818
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
3819
  int error= 0;
unknown's avatar
unknown committed
3820
  longlong res;
unknown's avatar
unknown committed
3821 3822

  nr= rint(nr);
unknown's avatar
unknown committed
3823 3824 3825 3826 3827
  if (unsigned_flag)
  {
    if (nr < 0)
    {
      res=0;
unknown's avatar
unknown committed
3828
      error= 1;
unknown's avatar
unknown committed
3829
    }
unknown's avatar
unknown committed
3830
    else if (nr >= (double) ULONGLONG_MAX)
unknown's avatar
unknown committed
3831 3832
    {
      res= ~(longlong) 0;
unknown's avatar
unknown committed
3833
      error= 1;
unknown's avatar
unknown committed
3834 3835 3836 3837 3838 3839
    }
    else
      res=(longlong) (ulonglong) nr;
  }
  else
  {
unknown's avatar
unknown committed
3840
    if (nr <= (double) LONGLONG_MIN)
unknown's avatar
unknown committed
3841
    {
unknown's avatar
unknown committed
3842
      res= LONGLONG_MIN;
unknown's avatar
unknown committed
3843
      error= (nr < (double) LONGLONG_MIN);
unknown's avatar
unknown committed
3844
    }
3845
    else if (nr >= (double) (ulonglong) LONGLONG_MAX)
unknown's avatar
unknown committed
3846
    {
unknown's avatar
unknown committed
3847
      res= LONGLONG_MAX;
unknown's avatar
unknown committed
3848
      error= (nr > (double) LONGLONG_MAX);
unknown's avatar
unknown committed
3849 3850 3851 3852
    }
    else
      res=(longlong) nr;
  }
unknown's avatar
unknown committed
3853 3854 3855
  if (error)
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);

unknown's avatar
unknown committed
3856
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3857
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3858 3859 3860 3861 3862 3863
  {
    int8store(ptr,res);
  }
  else
#endif
    longlongstore(ptr,res);
3864
  return error;
unknown's avatar
unknown committed
3865 3866 3867
}


3868
int Field_longlong::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
3869
{
3870
  ASSERT_COLUMN_MARKED_FOR_WRITE;
3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886
  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;
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
      error= 1;
    }
  }

unknown's avatar
unknown committed
3887
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3888
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3889 3890 3891 3892 3893 3894
  {
    int8store(ptr,nr);
  }
  else
#endif
    longlongstore(ptr,nr);
3895
  return error;
unknown's avatar
unknown committed
3896 3897 3898 3899 3900
}


double Field_longlong::val_real(void)
{
3901
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3902 3903
  longlong j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3904
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3905 3906 3907 3908 3909 3910
  {
    j=sint8korr(ptr);
  }
  else
#endif
    longlongget(j,ptr);
3911 3912 3913 3914 3915 3916 3917
  /* 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
3918 3919
}

3920

unknown's avatar
unknown committed
3921 3922
longlong Field_longlong::val_int(void)
{
3923
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
3924 3925
  longlong j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3926
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937
    j=sint8korr(ptr);
  else
#endif
    longlongget(j,ptr);
  return j;
}


String *Field_longlong::val_str(String *val_buffer,
				String *val_ptr __attribute__((unused)))
{
unknown's avatar
unknown committed
3938
  CHARSET_INFO *cs= &my_charset_bin;
unknown's avatar
unknown committed
3939
  uint length;
3940 3941
  uint mlength=max(field_length+1,22*cs->mbmaxlen);
  val_buffer->alloc(mlength);
unknown's avatar
unknown committed
3942 3943 3944
  char *to=(char*) val_buffer->ptr();
  longlong j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3945
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3946 3947 3948 3949 3950
    j=sint8korr(ptr);
  else
#endif
    longlongget(j,ptr);

3951
  length=(uint) (cs->cset->longlong10_to_str)(cs,to,mlength,
unknown's avatar
unknown committed
3952
					unsigned_flag ? 10 : -10, j);
unknown's avatar
unknown committed
3953 3954 3955 3956 3957 3958 3959
  val_buffer->length(length);
  if (zerofill)
    prepend_zeros(val_buffer);
  return val_buffer;
}


3960 3961
bool Field_longlong::send_binary(Protocol *protocol)
{
3962
  ASSERT_COLUMN_MARKED_FOR_READ;
3963 3964 3965 3966
  return protocol->store_longlong(Field_longlong::val_int(), unsigned_flag);
}


3967
int Field_longlong::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
3968 3969 3970
{
  longlong a,b;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3971
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987
  {
    a=sint8korr(a_ptr);
    b=sint8korr(b_ptr);
  }
  else
#endif
  {
    longlongget(a,a_ptr);
    longlongget(b,b_ptr);
  }
  if (unsigned_flag)
    return ((ulonglong) a < (ulonglong) b) ? -1 :
    ((ulonglong) a > (ulonglong) b) ? 1 : 0;
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

3988
void Field_longlong::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
3989 3990
{
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
3991
  if (!table->s->db_low_byte_first)
unknown's avatar
unknown committed
3992 3993 3994 3995
  {
    if (unsigned_flag)
      to[0] = ptr[0];
    else
unknown's avatar
unknown committed
3996
      to[0] = (char) (ptr[0] ^ 128);		/* Revers signbit */
unknown's avatar
unknown committed
3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010
    to[1]   = ptr[1];
    to[2]   = ptr[2];
    to[3]   = ptr[3];
    to[4]   = ptr[4];
    to[5]   = ptr[5];
    to[6]   = ptr[6];
    to[7]   = ptr[7];
  }
  else
#endif
  {
    if (unsigned_flag)
      to[0] = ptr[7];
    else
unknown's avatar
unknown committed
4011
      to[0] = (char) (ptr[7] ^ 128);		/* Revers signbit */
unknown's avatar
unknown committed
4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024
    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];
  }
}


void Field_longlong::sql_type(String &res) const
{
unknown's avatar
unknown committed
4025
  CHARSET_INFO *cs=res.charset();
4026
  res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
4027
			  "bigint(%d)",(int) field_length));
unknown's avatar
unknown committed
4028 4029 4030
  add_zerofill_and_unsigned(res);
}

unknown's avatar
unknown committed
4031

4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074
/*
  Floating-point numbers
 */

uchar *
Field_real::pack(uchar *to, const uchar *from,
                 uint max_length, bool low_byte_first)
{
  DBUG_ENTER("Field_real::pack");
  DBUG_ASSERT(max_length >= pack_length());
  DBUG_PRINT("debug", ("pack_length(): %u", pack_length()));
#ifdef WORDS_BIGENDIAN
  if (low_byte_first != table->s->db_low_byte_first)
  {
    const uchar *dptr= from + pack_length();
    while (dptr-- > from)
      *to++ = *dptr;
    DBUG_RETURN(to);
  }
  else
#endif
    DBUG_RETURN(Field::pack(to, from, max_length, low_byte_first));
}

const uchar *
Field_real::unpack(uchar *to, const uchar *from,
                   uint param_data, bool low_byte_first)
{
  DBUG_ENTER("Field_real::unpack");
  DBUG_PRINT("debug", ("pack_length(): %u", pack_length()));
#ifdef WORDS_BIGENDIAN
  if (low_byte_first != table->s->db_low_byte_first)
  {
    const uchar *dptr= from + pack_length();
    while (dptr-- > from)
      *to++ = *dptr;
    DBUG_RETURN(from + pack_length());
  }
  else
#endif
    DBUG_RETURN(Field::unpack(to, from, param_data, low_byte_first));
}

unknown's avatar
unknown committed
4075
/****************************************************************************
unknown's avatar
unknown committed
4076
  single precision float
unknown's avatar
unknown committed
4077 4078
****************************************************************************/

unknown's avatar
unknown committed
4079
int Field_float::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
4080
{
unknown's avatar
unknown committed
4081
  int error;
4082
  char *end;
unknown's avatar
unknown committed
4083
  double nr= my_strntod(cs,(char*) from,len,&end,&error);
unknown's avatar
unknown committed
4084 4085
  if (error || (!len || (uint) (end-from) != len &&
                table->in_use->count_cuted_fields))
4086
  {
unknown's avatar
unknown committed
4087
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
4088
                (error ? ER_WARN_DATA_OUT_OF_RANGE : WARN_DATA_TRUNCATED), 1);
unknown's avatar
unknown committed
4089
    error= error ? 1 : 2;
4090
  }
unknown's avatar
unknown committed
4091 4092
  Field_float::store(nr);
  return error;
unknown's avatar
unknown committed
4093 4094 4095
}


unknown's avatar
unknown committed
4096
int Field_float::store(double nr)
unknown's avatar
unknown committed
4097
{
4098
  ASSERT_COLUMN_MARKED_FOR_WRITE;
4099
  int error= truncate(&nr, FLT_MAX);
4100
  float j= (float)nr;
4101

unknown's avatar
unknown committed
4102
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4103
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
4104 4105 4106 4107 4108
  {
    float4store(ptr,j);
  }
  else
#endif
4109
    memcpy_fixed(ptr,(uchar*) &j,sizeof(j));
4110
  return error;
unknown's avatar
unknown committed
4111 4112 4113
}


4114
int Field_float::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
4115
{
4116 4117
  return Field_float::store(unsigned_val ? ulonglong2double((ulonglong) nr) :
                            (double) nr);
unknown's avatar
unknown committed
4118 4119
}

4120

unknown's avatar
unknown committed
4121 4122
double Field_float::val_real(void)
{
4123
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4124 4125
  float j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4126
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
4127 4128 4129 4130 4131
  {
    float4get(j,ptr);
  }
  else
#endif
4132
    memcpy_fixed((uchar*) &j,ptr,sizeof(j));
unknown's avatar
unknown committed
4133 4134 4135 4136 4137 4138 4139
  return ((double) j);
}

longlong Field_float::val_int(void)
{
  float j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4140
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
4141 4142 4143 4144 4145
  {
    float4get(j,ptr);
  }
  else
#endif
4146
    memcpy_fixed((uchar*) &j,ptr,sizeof(j));
4147
  return (longlong) rint(j);
unknown's avatar
unknown committed
4148 4149 4150 4151 4152 4153
}


String *Field_float::val_str(String *val_buffer,
			     String *val_ptr __attribute__((unused)))
{
4154
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4155 4156
  float nr;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4157
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
4158 4159 4160 4161 4162
  {
    float4get(nr,ptr);
  }
  else
#endif
4163
    memcpy_fixed((uchar*) &nr,ptr,sizeof(nr));
unknown's avatar
unknown committed
4164

4165 4166
  uint to_length=max(field_length,70);
  val_buffer->alloc(to_length);
unknown's avatar
unknown committed
4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214
  char *to=(char*) val_buffer->ptr();

  if (dec >= NOT_FIXED_DEC)
  {
    sprintf(to,"%-*.*g",(int) field_length,FLT_DIG,nr);
    to=strcend(to,' ');
    *to=0;
  }
  else
  {
#ifdef HAVE_FCONVERT
    char buff[70],*pos=buff;
    int decpt,sign,tmp_dec=dec;

    VOID(sfconvert(&nr,tmp_dec,&decpt,&sign,buff));
    if (sign)
    {
      *to++='-';
    }
    if (decpt < 0)
    {					/* val_buffer is < 0 */
      *to++='0';
      if (!tmp_dec)
	goto end;
      *to++='.';
      if (-decpt > tmp_dec)
	decpt= - (int) tmp_dec;
      tmp_dec=(uint) ((int) tmp_dec+decpt);
      while (decpt++ < 0)
	*to++='0';
    }
    else if (decpt == 0)
    {
      *to++= '0';
      if (!tmp_dec)
	goto end;
      *to++='.';
    }
    else
    {
      while (decpt-- > 0)
	*to++= *pos++;
      if (!tmp_dec)
	goto end;
      *to++='.';
    }
    while (tmp_dec--)
      *to++= *pos++;
unknown's avatar
unknown committed
4215
#else
4216 4217 4218
#ifdef HAVE_SNPRINTF
    to[to_length-1]=0;			// Safety
    snprintf(to,to_length-1,"%.*f",dec,nr);
4219
    to=strend(to);
unknown's avatar
unknown committed
4220
#else
4221
    to+= my_sprintf(to,(to,"%.*f",dec,nr));
unknown's avatar
unknown committed
4222
#endif
unknown's avatar
unknown committed
4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234
#endif
  }
#ifdef HAVE_FCONVERT
 end:
#endif
  val_buffer->length((uint) (to-val_buffer->ptr()));
  if (zerofill)
    prepend_zeros(val_buffer);
  return val_buffer;
}


4235
int Field_float::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
4236 4237 4238
{
  float a,b;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4239
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254
  {
    float4get(a,a_ptr);
    float4get(b,b_ptr);
  }
  else
#endif
  {
    memcpy_fixed(&a,a_ptr,sizeof(float));
    memcpy_fixed(&b,b_ptr,sizeof(float));
  }
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

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

4255
void Field_float::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
4256 4257 4258
{
  float nr;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4259
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
4260 4261 4262 4263 4264 4265 4266
  {
    float4get(nr,ptr);
  }
  else
#endif
    memcpy_fixed(&nr,ptr,sizeof(float));

4267
  uchar *tmp= to;
unknown's avatar
unknown committed
4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283
  if (nr == (float) 0.0)
  {						/* Change to zero string */
    tmp[0]=(uchar) 128;
    bzero((char*) tmp+1,sizeof(nr)-1);
  }
  else
  {
#ifdef WORDS_BIGENDIAN
    memcpy_fixed(tmp,&nr,sizeof(nr));
#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
4284
	tmp[i]= (uchar) (tmp[i] ^ (uchar) 255);
unknown's avatar
unknown committed
4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297
    }
    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;
    }
  }
}


4298 4299
bool Field_float::send_binary(Protocol *protocol)
{
4300
  ASSERT_COLUMN_MARKED_FOR_READ;
4301 4302 4303 4304
  return protocol->store((float) Field_float::val_real(), dec, (String*) 0);
}


4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320
/**
   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
4321 4322 4323
void Field_float::sql_type(String &res) const
{
  if (dec == NOT_FIXED_DEC)
4324
  {
4325
    res.set_ascii(STRING_WITH_LEN("float"));
4326
  }
unknown's avatar
unknown committed
4327
  else
4328
  {
4329
    CHARSET_INFO *cs= res.charset();
4330
    res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
4331
			    "float(%d,%d)",(int) field_length,dec));
4332
  }
unknown's avatar
unknown committed
4333 4334 4335
  add_zerofill_and_unsigned(res);
}

unknown's avatar
unknown committed
4336

unknown's avatar
unknown committed
4337
/****************************************************************************
unknown's avatar
unknown committed
4338
  double precision floating point numbers
unknown's avatar
unknown committed
4339 4340
****************************************************************************/

unknown's avatar
unknown committed
4341
int Field_double::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
4342
{
unknown's avatar
unknown committed
4343
  int error;
4344
  char *end;
unknown's avatar
unknown committed
4345
  double nr= my_strntod(cs,(char*) from, len, &end, &error);
unknown's avatar
unknown committed
4346 4347
  if (error || (!len || (uint) (end-from) != len &&
                table->in_use->count_cuted_fields))
unknown's avatar
unknown committed
4348
  {
unknown's avatar
unknown committed
4349
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
4350
                (error ? ER_WARN_DATA_OUT_OF_RANGE : WARN_DATA_TRUNCATED), 1);
unknown's avatar
unknown committed
4351
    error= error ? 1 : 2;
unknown's avatar
unknown committed
4352
  }
unknown's avatar
unknown committed
4353 4354
  Field_double::store(nr);
  return error;
unknown's avatar
unknown committed
4355 4356 4357
}


unknown's avatar
unknown committed
4358
int Field_double::store(double nr)
unknown's avatar
unknown committed
4359
{
4360
  ASSERT_COLUMN_MARKED_FOR_WRITE;
4361
  int error= truncate(&nr, DBL_MAX);
4362

unknown's avatar
unknown committed
4363
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4364
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
4365 4366 4367 4368 4369 4370
  {
    float8store(ptr,nr);
  }
  else
#endif
    doublestore(ptr,nr);
4371
  return error;
unknown's avatar
unknown committed
4372 4373 4374
}


4375
int Field_double::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
4376
{
4377 4378
  return Field_double::store(unsigned_val ? ulonglong2double((ulonglong) nr) :
                             (double) nr);
unknown's avatar
unknown committed
4379 4380
}

4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437
/*
  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.
*/

int Field_real::truncate(double *nr, double max_value)
{
  int error= 1;
  double res= *nr;
  
  if (isnan(res))
  {
    res= 0;
    set_null();
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
    goto end;
  }
  else if (unsigned_flag && res < 0)
  {
    res= 0;
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
    goto end;
  }

  if (!not_fixed)
  {
    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];

    double tmp= rint((res - floor(res)) * log_10[dec]) / log_10[dec];
    res= floor(res) + tmp;
  }
  
  if (res < -max_value)
  {
   res= -max_value;
   set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
  }
  else if (res > max_value)
  {
    res= max_value;
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
  }
  else
    error= 0;

end:
  *nr= res;
  return error;
}

4438

unknown's avatar
unknown committed
4439 4440 4441 4442 4443 4444
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
4445 4446 4447

double Field_double::val_real(void)
{
4448
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4449 4450
  double j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4451
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462
  {
    float8get(j,ptr);
  }
  else
#endif
    doubleget(j,ptr);
  return j;
}

longlong Field_double::val_int(void)
{
4463
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4464
  double j;
unknown's avatar
unknown committed
4465
  longlong res;
unknown's avatar
unknown committed
4466
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4467
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
4468 4469 4470 4471 4472 4473
  {
    float8get(j,ptr);
  }
  else
#endif
    doubleget(j,ptr);
4474 4475
  /* Check whether we fit into longlong range */
  if (j <= (double) LONGLONG_MIN)
unknown's avatar
unknown committed
4476 4477 4478 4479
  {
    res= (longlong) LONGLONG_MIN;
    goto warn;
  }
4480
  if (j >= (double) (ulonglong) LONGLONG_MAX)
unknown's avatar
unknown committed
4481 4482 4483 4484
  {
    res= (longlong) LONGLONG_MAX;
    goto warn;
  }
4485
  return (longlong) rint(j);
unknown's avatar
unknown committed
4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497

warn:
  {
    char buf[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
    String tmp(buf, sizeof(buf), &my_charset_latin1), *str;
    str= val_str(&tmp, 0);
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_TRUNCATED_WRONG_VALUE,
                        ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
                        str->c_ptr());
  }
  return res;
unknown's avatar
unknown committed
4498 4499 4500
}


unknown's avatar
unknown committed
4501 4502
my_decimal *Field_real::val_decimal(my_decimal *decimal_value)
{
4503
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4504 4505 4506 4507 4508
  double2my_decimal(E_DEC_FATAL_ERROR, val_real(), decimal_value);
  return decimal_value;
}


unknown's avatar
unknown committed
4509 4510 4511
String *Field_double::val_str(String *val_buffer,
			      String *val_ptr __attribute__((unused)))
{
4512
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4513 4514
  double nr;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4515
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
4516 4517 4518 4519 4520 4521 4522
  {
    float8get(nr,ptr);
  }
  else
#endif
    doubleget(nr,ptr);

4523
  uint to_length=max(field_length, DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE);
unknown's avatar
unknown committed
4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534
  val_buffer->alloc(to_length);
  char *to=(char*) val_buffer->ptr();

  if (dec >= NOT_FIXED_DEC)
  {
    sprintf(to,"%-*.*g",(int) field_length,DBL_DIG,nr);
    to=strcend(to,' ');
  }
  else
  {
#ifdef HAVE_FCONVERT
unknown's avatar
unknown committed
4535
    char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
4536
    char *pos= buff;
unknown's avatar
unknown committed
4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574
    int decpt,sign,tmp_dec=dec;

    VOID(fconvert(nr,tmp_dec,&decpt,&sign,buff));
    if (sign)
    {
      *to++='-';
    }
    if (decpt < 0)
    {					/* val_buffer is < 0 */
      *to++='0';
      if (!tmp_dec)
	goto end;
      *to++='.';
      if (-decpt > tmp_dec)
	decpt= - (int) tmp_dec;
      tmp_dec=(uint) ((int) tmp_dec+decpt);
      while (decpt++ < 0)
	*to++='0';
    }
    else if (decpt == 0)
    {
      *to++= '0';
      if (!tmp_dec)
	goto end;
      *to++='.';
    }
    else
    {
      while (decpt-- > 0)
	*to++= *pos++;
      if (!tmp_dec)
	goto end;
      *to++='.';
    }
    while (tmp_dec--)
      *to++= *pos++;
#else
#ifdef HAVE_SNPRINTF
unknown's avatar
unknown committed
4575
    to[to_length-1]=0;			// Safety
unknown's avatar
unknown committed
4576
    snprintf(to,to_length-1,"%.*f",dec,nr);
4577
    to=strend(to);
unknown's avatar
unknown committed
4578
#else
4579
    to+= my_sprintf(to,(to,"%.*f",dec,nr));
unknown's avatar
unknown committed
4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592
#endif
#endif
  }
#ifdef HAVE_FCONVERT
 end:
#endif

  val_buffer->length((uint) (to-val_buffer->ptr()));
  if (zerofill)
    prepend_zeros(val_buffer);
  return val_buffer;
}

4593 4594
bool Field_double::send_binary(Protocol *protocol)
{
unknown's avatar
unknown committed
4595
  return protocol->store((double) Field_double::val_real(), dec, (String*) 0);
4596 4597
}

unknown's avatar
unknown committed
4598

4599
int Field_double::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
4600
{
4601
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4602 4603
  double a,b;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4604
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
4605 4606 4607 4608 4609 4610 4611
  {
    float8get(a,a_ptr);
    float8get(b,b_ptr);
  }
  else
#endif
  {
unknown's avatar
unknown committed
4612 4613
    doubleget(a, a_ptr);
    doubleget(b, b_ptr);
unknown's avatar
unknown committed
4614 4615 4616 4617 4618 4619 4620 4621 4622
  }
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}


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

/* The following should work for IEEE */

4623
void Field_double::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
4624 4625 4626
{
  double nr;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4627
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
4628 4629 4630 4631 4632
  {
    float8get(nr,ptr);
  }
  else
#endif
unknown's avatar
unknown committed
4633
    doubleget(nr,ptr);
4634
  change_double_for_sort(nr, to);
unknown's avatar
unknown committed
4635 4636 4637
}


4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654
/**
   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
4655 4656
void Field_double::sql_type(String &res) const
{
unknown's avatar
unknown committed
4657
  CHARSET_INFO *cs=res.charset();
unknown's avatar
unknown committed
4658
  if (dec == NOT_FIXED_DEC)
4659
  {
4660
    res.set_ascii(STRING_WITH_LEN("double"));
4661
  }
unknown's avatar
unknown committed
4662
  else
4663
  {
4664
    res.length(cs->cset->snprintf(cs,(char*) res.ptr(),res.alloced_length(),
4665
			    "double(%d,%d)",(int) field_length,dec));
4666
  }
unknown's avatar
unknown committed
4667 4668 4669 4670
  add_zerofill_and_unsigned(res);
}


4671 4672
/**
  TIMESTAMP type holds datetime values in range from 1970-01-01 00:00:01 UTC to 
4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693
  2038-01-01 00:00:00 UTC stored as number of seconds since Unix 
  Epoch in UTC.
  
  Up to one of timestamps columns in the table can be automatically 
  set on row update and/or have NOW() as default value.
  TABLE::timestamp_field points to Field object for such timestamp with 
  auto-set-on-update. TABLE::time_stamp holds offset in record + 1 for this
  field, and is used by handler code which performs updates required.
  
  Actually SQL-99 says that we should allow niladic functions (like NOW())
  as defaults for any field. Current limitations (only NOW() and only 
  for one TIMESTAMP field) are because of restricted binary .frm format 
  and should go away in the future.
  
  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
4694
    field which has 0 as default value and is not automatically updated.
4695 4696 4697 4698 4699 4700 4701 4702 4703 4704
  TIMESTAMP_DN_FIELD - field with NOW() as default but not set on update
    automatically (TIMESTAMP DEFAULT NOW())
  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 
    update. (TIMESTAMP DEFAULT NOW() ON UPDATE NOW())
  NONE - field which is not auto-set on update with some other than NOW() 
    default value (TIMESTAMP DEFAULT 0).

4705
  Note that TIMESTAMP_OLD_FIELDs are never created explicitly now, they are 
4706 4707 4708 4709 4710 4711 4712 4713
  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
4714

4715
Field_timestamp::Field_timestamp(uchar *ptr_arg, uint32 len_arg,
4716
                                 uchar *null_ptr_arg, uchar null_bit_arg,
unknown's avatar
unknown committed
4717 4718
				 enum utype unireg_check_arg,
				 const char *field_name_arg,
unknown's avatar
unknown committed
4719
				 TABLE_SHARE *share,
4720
				 CHARSET_INFO *cs)
4721
  :Field_str(ptr_arg, MAX_DATETIME_WIDTH, null_ptr_arg, null_bit_arg,
unknown's avatar
unknown committed
4722
	     unireg_check_arg, field_name_arg, cs)
unknown's avatar
unknown committed
4723
{
unknown's avatar
unknown committed
4724 4725
  /* For 4.0 MYD and 4.0 InnoDB compatibility */
  flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
unknown's avatar
unknown committed
4726
  if (!share->timestamp_field && unireg_check != NONE)
unknown's avatar
unknown committed
4727
  {
4728
    /* This timestamp has auto-update */
unknown's avatar
unknown committed
4729 4730
    share->timestamp_field= this;
    flags|= TIMESTAMP_FLAG;
4731 4732
    if (unireg_check != TIMESTAMP_DN_FIELD)
      flags|= ON_UPDATE_NOW_FLAG;
unknown's avatar
unknown committed
4733 4734 4735 4736
  }
}


4737 4738
Field_timestamp::Field_timestamp(bool maybe_null_arg,
                                 const char *field_name_arg,
unknown's avatar
unknown committed
4739
                                 CHARSET_INFO *cs)
4740 4741
  :Field_str((uchar*) 0, MAX_DATETIME_WIDTH,
             maybe_null_arg ? (uchar*) "": 0, 0,
unknown's avatar
unknown committed
4742
	     NONE, field_name_arg, cs)
4743 4744 4745
{
  /* For 4.0 MYD and 4.0 InnoDB compatibility */
  flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
4746 4747
    if (unireg_check != TIMESTAMP_DN_FIELD)
      flags|= ON_UPDATE_NOW_FLAG;
4748 4749 4750
}


4751
/**
4752 4753
  Get auto-set type for TIMESTAMP field.

4754 4755
  Returns value indicating during which operations this TIMESTAMP field
  should be auto-set to current timestamp.
4756
*/
4757
timestamp_auto_set_type Field_timestamp::get_auto_set_type() const
4758
{
4759 4760 4761 4762 4763 4764
  switch (unireg_check)
  {
  case TIMESTAMP_DN_FIELD:
    return TIMESTAMP_AUTO_SET_ON_INSERT;
  case TIMESTAMP_UN_FIELD:
    return TIMESTAMP_AUTO_SET_ON_UPDATE;
4765 4766
  case TIMESTAMP_OLD_FIELD:
    /*
unknown's avatar
unknown committed
4767
      Although we can have several such columns in legacy tables this
4768 4769 4770 4771 4772
      function should be called only for first of them (i.e. the one
      having auto-set property).
    */
    DBUG_ASSERT(table->timestamp_field == this);
    /* Fall-through */
4773 4774 4775 4776 4777 4778 4779 4780 4781 4782
  case TIMESTAMP_DNUN_FIELD:
    return TIMESTAMP_AUTO_SET_ON_BOTH;
  default:
    /*
      Normally this function should not be called for TIMESTAMPs without
      auto-set property.
    */
    DBUG_ASSERT(0);
    return TIMESTAMP_NO_AUTO_SET;
  }
4783 4784 4785
}


unknown's avatar
unknown committed
4786
int Field_timestamp::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
4787
{
4788
  ASSERT_COLUMN_MARKED_FOR_WRITE;
4789
  MYSQL_TIME l_time;
4790 4791 4792
  my_time_t tmp= 0;
  int error;
  bool have_smth_to_conv;
4793
  my_bool in_dst_time_gap;
unknown's avatar
unknown committed
4794
  THD *thd= table ? table->in_use : current_thd;
4795

4796
  /* We don't want to store invalid or fuzzy datetime values in TIMESTAMP */
unknown's avatar
unknown committed
4797
  have_smth_to_conv= (str_to_datetime(from, len, &l_time,
unknown's avatar
unknown committed
4798
                                      (thd->variables.sql_mode &
4799 4800
                                       MODE_NO_ZERO_DATE) |
                                      MODE_NO_ZERO_IN_DATE, &error) >
4801
                      MYSQL_TIMESTAMP_ERROR);
4802

unknown's avatar
unknown committed
4803 4804 4805
  if (error || !have_smth_to_conv)
  {
    error= 1;
4806
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED,
4807
                         from, len, MYSQL_TIMESTAMP_DATETIME, 1);
unknown's avatar
unknown committed
4808
  }
4809

unknown's avatar
unknown committed
4810 4811
  /* Only convert a correct date (not a zero date) */
  if (have_smth_to_conv && l_time.month)
4812 4813 4814
  {
    if (!(tmp= TIME_to_timestamp(thd, &l_time, &in_dst_time_gap)))
    {
4815
      set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
4816
                           ER_WARN_DATA_OUT_OF_RANGE,
4817
                           from, len, MYSQL_TIMESTAMP_DATETIME, !error);
4818 4819 4820 4821 4822
      error= 1;
    }
    else if (in_dst_time_gap)
    {
      set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
4823
                           ER_WARN_INVALID_TIMESTAMP,
4824
                           from, len, MYSQL_TIMESTAMP_DATETIME, !error);
4825 4826 4827
      error= 1;
    }
  }
4828
  store_timestamp(tmp);
4829
  return error;
unknown's avatar
unknown committed
4830 4831
}

unknown's avatar
unknown committed
4832

unknown's avatar
unknown committed
4833
int Field_timestamp::store(double nr)
unknown's avatar
unknown committed
4834
{
unknown's avatar
unknown committed
4835
  int error= 0;
unknown's avatar
unknown committed
4836 4837
  if (nr < 0 || nr > 99991231235959.0)
  {
4838 4839
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
                         ER_WARN_DATA_OUT_OF_RANGE,
4840
                         nr, MYSQL_TIMESTAMP_DATETIME);
unknown's avatar
unknown committed
4841 4842
    nr= 0;					// Avoid overflow on buff
    error= 1;
unknown's avatar
unknown committed
4843
  }
4844
  error|= Field_timestamp::store((longlong) rint(nr), FALSE);
4845
  return error;
unknown's avatar
unknown committed
4846 4847 4848
}


4849
int Field_timestamp::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
4850
{
4851
  ASSERT_COLUMN_MARKED_FOR_WRITE;
4852
  MYSQL_TIME l_time;
4853 4854
  my_time_t timestamp= 0;
  int error;
4855
  my_bool in_dst_time_gap;
unknown's avatar
unknown committed
4856
  THD *thd= table ? table->in_use : current_thd;
unknown's avatar
unknown committed
4857

4858
  /* We don't want to store invalid or fuzzy datetime values in TIMESTAMP */
4859 4860 4861
  longlong tmp= number_to_datetime(nr, &l_time, (thd->variables.sql_mode &
                                                 MODE_NO_ZERO_DATE) |
                                   MODE_NO_ZERO_IN_DATE, &error);
4862
  if (tmp == LL(-1))
4863 4864 4865 4866 4867
  {
    error= 2;
  }

  if (!error && tmp)
unknown's avatar
unknown committed
4868
  {
4869 4870
    if (!(timestamp= TIME_to_timestamp(thd, &l_time, &in_dst_time_gap)))
    {
4871 4872 4873
      set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
                           ER_WARN_DATA_OUT_OF_RANGE,
                           nr, MYSQL_TIMESTAMP_DATETIME, 1);
4874 4875 4876 4877 4878
      error= 1;
    }
    if (in_dst_time_gap)
    {
      set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
4879 4880
                           ER_WARN_INVALID_TIMESTAMP,
                           nr, MYSQL_TIMESTAMP_DATETIME, 1);
4881 4882
      error= 1;
    }
4883 4884
  } else if (error)
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
4885
                         WARN_DATA_TRUNCATED,
4886
                         nr, MYSQL_TIMESTAMP_DATETIME, 1);
4887

4888
  store_timestamp(timestamp);
unknown's avatar
unknown committed
4889
  return error;
unknown's avatar
unknown committed
4890 4891 4892 4893
}

double Field_timestamp::val_real(void)
{
4894
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4895 4896 4897 4898 4899
  return (double) Field_timestamp::val_int();
}

longlong Field_timestamp::val_int(void)
{
4900
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
4901
  uint32 temp;
4902
  MYSQL_TIME time_tmp;
unknown's avatar
unknown committed
4903
  THD  *thd= table ? table->in_use : current_thd;
unknown's avatar
unknown committed
4904

4905
  thd->time_zone_used= 1;
unknown's avatar
unknown committed
4906
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4907
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
4908 4909 4910 4911 4912 4913 4914
    temp=uint4korr(ptr);
  else
#endif
    longget(temp,ptr);

  if (temp == 0L)				// No time
    return(0);					/* purecov: inspected */
4915 4916 4917 4918 4919 4920
  
  thd->variables.time_zone->gmt_sec_to_TIME(&time_tmp, (my_time_t)temp);
  
  return time_tmp.year * LL(10000000000) + time_tmp.month * LL(100000000) +
         time_tmp.day * 1000000L + time_tmp.hour * 10000L +
         time_tmp.minute * 100 + time_tmp.second;
unknown's avatar
unknown committed
4921 4922 4923
}


unknown's avatar
unknown committed
4924
String *Field_timestamp::val_str(String *val_buffer, String *val_ptr)
unknown's avatar
unknown committed
4925
{
4926
  ASSERT_COLUMN_MARKED_FOR_READ;
4927
  uint32 temp, temp2;
4928
  MYSQL_TIME time_tmp;
unknown's avatar
unknown committed
4929
  THD *thd= table ? table->in_use : current_thd;
unknown's avatar
unknown committed
4930
  char *to;
unknown's avatar
unknown committed
4931 4932

  val_buffer->alloc(field_length+1);
unknown's avatar
unknown committed
4933
  to= (char*) val_buffer->ptr();
4934
  val_buffer->length(field_length);
unknown's avatar
unknown committed
4935

4936
  thd->time_zone_used= 1;
unknown's avatar
unknown committed
4937
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
4938
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
4939 4940 4941 4942 4943 4944 4945
    temp=uint4korr(ptr);
  else
#endif
    longget(temp,ptr);

  if (temp == 0L)
  {				      /* Zero time is "000000" */
4946
    val_ptr->set(STRING_WITH_LEN("0000-00-00 00:00:00"), &my_charset_bin);
4947
    return val_ptr;
unknown's avatar
unknown committed
4948
  }
unknown's avatar
unknown committed
4949
  val_buffer->set_charset(&my_charset_bin);	// Safety
4950 4951
  
  thd->variables.time_zone->gmt_sec_to_TIME(&time_tmp,(my_time_t)temp);
4952

4953
  temp= time_tmp.year % 100;
4954
  if (temp < YY_PART_YEAR - 1)
4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967
  {
    *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++= '-';
4968
  temp=time_tmp.month;
4969 4970 4971 4972
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= '-';
4973
  temp=time_tmp.day;
4974 4975 4976 4977
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= ' ';
4978
  temp=time_tmp.hour;
4979 4980 4981 4982
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= ':';
4983
  temp=time_tmp.minute;
4984 4985 4986 4987
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to++= ':';
4988
  temp=time_tmp.second;
4989 4990 4991 4992
  temp2=temp/10; temp=temp-temp2*10;
  *to++= (char) ('0'+(char) (temp2));
  *to++= (char) ('0'+(char) (temp));
  *to= 0;
unknown's avatar
unknown committed
4993 4994 4995
  return val_buffer;
}

4996

4997
bool Field_timestamp::get_date(MYSQL_TIME *ltime, uint fuzzydate)
unknown's avatar
unknown committed
4998 4999
{
  long temp;
unknown's avatar
unknown committed
5000
  THD *thd= table ? table->in_use : current_thd;
5001
  thd->time_zone_used= 1;
unknown's avatar
unknown committed
5002
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
5003
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
5004 5005 5006 5007 5008 5009
    temp=uint4korr(ptr);
  else
#endif
    longget(temp,ptr);
  if (temp == 0L)
  {				      /* Zero time is "000000" */
unknown's avatar
unknown committed
5010
    if (fuzzydate & TIME_NO_ZERO_DATE)
unknown's avatar
unknown committed
5011
      return 1;
unknown's avatar
unknown committed
5012 5013 5014 5015
    bzero((char*) ltime,sizeof(*ltime));
  }
  else
  {
5016
    thd->variables.time_zone->gmt_sec_to_TIME(ltime, (my_time_t)temp);
unknown's avatar
unknown committed
5017 5018 5019 5020
  }
  return 0;
}

5021
bool Field_timestamp::get_time(MYSQL_TIME *ltime)
unknown's avatar
unknown committed
5022
{
unknown's avatar
unknown committed
5023
  return Field_timestamp::get_date(ltime,0);
unknown's avatar
unknown committed
5024 5025
}

5026 5027 5028

bool Field_timestamp::send_binary(Protocol *protocol)
{
5029
  MYSQL_TIME tm;
unknown's avatar
unknown committed
5030
  Field_timestamp::get_date(&tm, 0);
5031 5032 5033 5034
  return protocol->store(&tm);
}


5035
int Field_timestamp::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
5036 5037 5038
{
  int32 a,b;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
5039
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052
  {
    a=sint4korr(a_ptr);
    b=sint4korr(b_ptr);
  }
  else
#endif
  {
  longget(a,a_ptr);
  longget(b,b_ptr);
  }
  return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
}

5053

5054
void Field_timestamp::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
5055 5056
{
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
5057
  if (!table || !table->s->db_low_byte_first)
unknown's avatar
unknown committed
5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076
  {
    to[0] = ptr[0];
    to[1] = ptr[1];
    to[2] = ptr[2];
    to[3] = ptr[3];
  }
  else
#endif
  {
    to[0] = ptr[3];
    to[1] = ptr[2];
    to[2] = ptr[1];
    to[3] = ptr[0];
  }
}


void Field_timestamp::sql_type(String &res) const
{
5077
  res.set_ascii(STRING_WITH_LEN("timestamp"));
unknown's avatar
unknown committed
5078 5079 5080 5081 5082
}


void Field_timestamp::set_time()
{
unknown's avatar
unknown committed
5083 5084
  THD *thd= table ? table->in_use : current_thd;
  long tmp= (long) thd->query_start();
5085
  set_notnull();
5086
  store_timestamp(tmp);
unknown's avatar
unknown committed
5087 5088 5089 5090 5091 5092 5093 5094 5095
}

/****************************************************************************
** time type
** In string context: HH:MM:SS
** In number context: HHMMSS
** Stored as a 3 byte unsigned int
****************************************************************************/

unknown's avatar
unknown committed
5096
int Field_time::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
5097
{
5098
  MYSQL_TIME ltime;
unknown's avatar
unknown committed
5099
  long tmp;
5100 5101
  int error= 0;
  int warning;
5102

5103
  if (str_to_time(from, len, &ltime, &warning))
5104
  {
unknown's avatar
unknown committed
5105
    tmp=0L;
unknown's avatar
unknown committed
5106
    error= 2;
5107
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED,
5108
                         from, len, MYSQL_TIMESTAMP_TIME, 1);
5109
  }
unknown's avatar
unknown committed
5110 5111
  else
  {
5112
    if (warning & MYSQL_TIME_WARN_TRUNCATED)
5113 5114
    {
      set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
5115
                           WARN_DATA_TRUNCATED,
5116
                           from, len, MYSQL_TIMESTAMP_TIME, 1);
5117 5118
      error= 1;
    }
5119
    if (warning & MYSQL_TIME_WARN_OUT_OF_RANGE)
unknown's avatar
unknown committed
5120
    {
5121 5122
      set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, 
                           ER_WARN_DATA_OUT_OF_RANGE,
5123
                           from, len, MYSQL_TIMESTAMP_TIME, !error);
unknown's avatar
unknown committed
5124
      error= 1;
unknown's avatar
unknown committed
5125
    }
5126 5127 5128
    if (ltime.month)
      ltime.day=0;
    tmp=(ltime.day*24L+ltime.hour)*10000L+(ltime.minute*100+ltime.second);
unknown's avatar
unknown committed
5129
  }
5130
  
unknown's avatar
unknown committed
5131 5132
  if (ltime.neg)
    tmp= -tmp;
5133
  int3store(ptr,tmp);
5134
  return error;
unknown's avatar
unknown committed
5135 5136 5137
}


5138
int Field_time::store_time(MYSQL_TIME *ltime, timestamp_type time_type)
5139 5140 5141 5142 5143
{
  long tmp= ((ltime->month ? 0 : ltime->day * 24L) + ltime->hour) * 10000L +
            (ltime->minute * 100 + ltime->second);
  if (ltime->neg)
    tmp= -tmp;
unknown's avatar
unknown committed
5144
  return Field_time::store((longlong) tmp, FALSE);
5145 5146 5147
}


unknown's avatar
unknown committed
5148
int Field_time::store(double nr)
unknown's avatar
unknown committed
5149
{
5150
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
5151
  long tmp;
unknown's avatar
unknown committed
5152
  int error= 0;
5153
  if (nr > (double)TIME_MAX_VALUE)
unknown's avatar
unknown committed
5154
  {
5155
    tmp= TIME_MAX_VALUE;
5156
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
5157
                         ER_WARN_DATA_OUT_OF_RANGE, nr, MYSQL_TIMESTAMP_TIME);
unknown's avatar
unknown committed
5158
    error= 1;
unknown's avatar
unknown committed
5159
  }
5160
  else if (nr < (double)-TIME_MAX_VALUE)
unknown's avatar
unknown committed
5161
  {
5162
    tmp= -TIME_MAX_VALUE;
5163
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, 
5164
                         ER_WARN_DATA_OUT_OF_RANGE, nr, MYSQL_TIMESTAMP_TIME);
unknown's avatar
unknown committed
5165
    error= 1;
unknown's avatar
unknown committed
5166 5167 5168 5169 5170 5171 5172 5173 5174
  }
  else
  {
    tmp=(long) floor(fabs(nr));			// Remove fractions
    if (nr < 0)
      tmp= -tmp;
    if (tmp % 100 > 59 || tmp/100 % 100 > 59)
    {
      tmp=0;
5175
      set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, 
5176 5177
                           ER_WARN_DATA_OUT_OF_RANGE, nr,
                           MYSQL_TIMESTAMP_TIME);
unknown's avatar
unknown committed
5178
      error= 1;
unknown's avatar
unknown committed
5179 5180 5181
    }
  }
  int3store(ptr,tmp);
5182
  return error;
unknown's avatar
unknown committed
5183 5184 5185
}


5186
int Field_time::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
5187
{
5188
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
5189
  long tmp;
unknown's avatar
unknown committed
5190
  int error= 0;
5191
  if (nr < (longlong) -TIME_MAX_VALUE && !unsigned_val)
unknown's avatar
unknown committed
5192
  {
5193
    tmp= -TIME_MAX_VALUE;
5194
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, 
5195 5196
                         ER_WARN_DATA_OUT_OF_RANGE, nr,
                         MYSQL_TIMESTAMP_TIME, 1);
unknown's avatar
unknown committed
5197
    error= 1;
unknown's avatar
unknown committed
5198
  }
5199
  else if (nr > (longlong) TIME_MAX_VALUE || nr < 0 && unsigned_val)
unknown's avatar
unknown committed
5200
  {
5201
    tmp= TIME_MAX_VALUE;
5202
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, 
5203 5204
                         ER_WARN_DATA_OUT_OF_RANGE, nr,
                         MYSQL_TIMESTAMP_TIME, 1);
unknown's avatar
unknown committed
5205
    error= 1;
unknown's avatar
unknown committed
5206 5207 5208 5209 5210 5211 5212
  }
  else
  {
    tmp=(long) nr;
    if (tmp % 100 > 59 || tmp/100 % 100 > 59)
    {
      tmp=0;
5213
      set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, 
5214 5215
                           ER_WARN_DATA_OUT_OF_RANGE, nr,
                           MYSQL_TIMESTAMP_TIME, 1);
unknown's avatar
unknown committed
5216
      error= 1;
unknown's avatar
unknown committed
5217 5218 5219
    }
  }
  int3store(ptr,tmp);
5220
  return error;
unknown's avatar
unknown committed
5221 5222 5223 5224 5225
}


double Field_time::val_real(void)
{
5226
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
5227
  uint32 j= (uint32) uint3korr(ptr);
unknown's avatar
unknown committed
5228 5229 5230 5231 5232
  return (double) j;
}

longlong Field_time::val_int(void)
{
5233
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
5234 5235 5236
  return (longlong) sint3korr(ptr);
}

5237

5238 5239
/**
  @note
5240 5241 5242 5243
  This function is multi-byte safe as the result string is always of type
  my_charset_bin
*/

unknown's avatar
unknown committed
5244 5245 5246
String *Field_time::val_str(String *val_buffer,
			    String *val_ptr __attribute__((unused)))
{
5247
  ASSERT_COLUMN_MARKED_FOR_READ;
5248
  MYSQL_TIME ltime;
5249
  val_buffer->alloc(MAX_DATE_STRING_REP_LENGTH);
unknown's avatar
unknown committed
5250
  long tmp=(long) sint3korr(ptr);
5251
  ltime.neg= 0;
unknown's avatar
unknown committed
5252 5253 5254
  if (tmp < 0)
  {
    tmp= -tmp;
5255 5256 5257 5258 5259 5260
    ltime.neg= 1;
  }
  ltime.day= (uint) 0;
  ltime.hour= (uint) (tmp/10000);
  ltime.minute= (uint) (tmp/100 % 100);
  ltime.second= (uint) (tmp % 100);
5261
  make_time((DATE_TIME_FORMAT*) 0, &ltime, val_buffer);
unknown's avatar
unknown committed
5262 5263 5264
  return val_buffer;
}

5265

5266 5267
/**
  @note
unknown's avatar
unknown committed
5268
  Normally we would not consider 'time' as a valid date, but we allow
unknown's avatar
unknown committed
5269 5270 5271 5272
  get_date() here to be able to do things like
  DATE_FORMAT(time, "%l.%i %p")
*/
 
5273
bool Field_time::get_date(MYSQL_TIME *ltime, uint fuzzydate)
5274
{
unknown's avatar
unknown committed
5275
  long tmp;
unknown's avatar
unknown committed
5276
  THD *thd= table ? table->in_use : current_thd;
unknown's avatar
unknown committed
5277
  if (!(fuzzydate & TIME_FUZZY_DATE))
unknown's avatar
unknown committed
5278
  {
unknown's avatar
unknown committed
5279
    push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
5280 5281
                        ER_WARN_DATA_OUT_OF_RANGE,
                        ER(ER_WARN_DATA_OUT_OF_RANGE), field_name,
unknown's avatar
unknown committed
5282
                        thd->row_count);
unknown's avatar
unknown committed
5283 5284 5285
    return 1;
  }
  tmp=(long) sint3korr(ptr);
5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299
  ltime->neg=0;
  if (tmp < 0)
  {
    ltime->neg= 1;
    tmp=-tmp;
  }
  ltime->hour=tmp/10000;
  tmp-=ltime->hour*10000;
  ltime->minute=   tmp/100;
  ltime->second= tmp % 100;
  ltime->year= ltime->month= ltime->day= ltime->second_part= 0;
  return 0;
}

unknown's avatar
unknown committed
5300

5301
bool Field_time::get_time(MYSQL_TIME *ltime)
unknown's avatar
unknown committed
5302 5303 5304 5305 5306 5307 5308 5309
{
  long tmp=(long) sint3korr(ptr);
  ltime->neg=0;
  if (tmp < 0)
  {
    ltime->neg= 1;
    tmp=-tmp;
  }
unknown's avatar
unknown committed
5310
  ltime->day= 0;
unknown's avatar
unknown committed
5311
  ltime->hour=   (int) (tmp/10000);
unknown's avatar
unknown committed
5312
  tmp-=ltime->hour*10000;
unknown's avatar
unknown committed
5313 5314
  ltime->minute= (int) tmp/100;
  ltime->second= (int) tmp % 100;
unknown's avatar
unknown committed
5315
  ltime->second_part=0;
5316
  ltime->time_type= MYSQL_TIMESTAMP_TIME;
unknown's avatar
unknown committed
5317 5318 5319
  return 0;
}

5320 5321 5322

bool Field_time::send_binary(Protocol *protocol)
{
5323
  MYSQL_TIME tm;
5324
  Field_time::get_time(&tm);
5325 5326
  tm.day= tm.hour/24;				// Move hours to days
  tm.hour-= tm.day*24;
unknown's avatar
unknown committed
5327
  return protocol->store_time(&tm);
5328 5329 5330
}


5331
int Field_time::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
5332
{
unknown's avatar
unknown committed
5333 5334 5335
  int32 a,b;
  a=(int32) sint3korr(a_ptr);
  b=(int32) sint3korr(b_ptr);
unknown's avatar
unknown committed
5336 5337 5338
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

5339
void Field_time::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
5340 5341 5342 5343 5344 5345 5346 5347
{
  to[0] = (uchar) (ptr[2] ^ 128);
  to[1] = ptr[1];
  to[2] = ptr[0];
}

void Field_time::sql_type(String &res) const
{
5348
  res.set_ascii(STRING_WITH_LEN("time"));
unknown's avatar
unknown committed
5349 5350 5351 5352 5353 5354 5355 5356
}

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

unknown's avatar
unknown committed
5357
int Field_year::store(const char *from, uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
5358
{
5359
  ASSERT_COLUMN_MARKED_FOR_WRITE;
5360
  char *end;
unknown's avatar
unknown committed
5361
  int error;
unknown's avatar
unknown committed
5362
  longlong nr= cs->cset->strntoull10rnd(cs, from, len, 0, &end, &error);
unknown's avatar
unknown committed
5363

unknown's avatar
unknown committed
5364 5365
  if (nr < 0 || nr >= 100 && nr <= 1900 || nr > 2155 || 
      error == MY_ERRNO_ERANGE)
unknown's avatar
unknown committed
5366 5367
  {
    *ptr=0;
5368
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
5369
    return 1;
unknown's avatar
unknown committed
5370
  }
unknown's avatar
unknown committed
5371 5372 5373 5374 5375 5376 5377 5378
  if (table->in_use->count_cuted_fields && 
      (error= check_int(cs, from, len, end, error)))
  {
    if (error == 1)  /* empty or incorrect string */
    {
      *ptr= 0;
      return 1;
    }
unknown's avatar
unknown committed
5379
    error= 1;
unknown's avatar
unknown committed
5380
  }
unknown's avatar
unknown committed
5381

unknown's avatar
unknown committed
5382 5383 5384 5385 5386 5387 5388
  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
5389
  *ptr= (char) (uchar) nr;
unknown's avatar
unknown committed
5390
  return error;
unknown's avatar
unknown committed
5391 5392
}

unknown's avatar
unknown committed
5393

unknown's avatar
unknown committed
5394
int Field_year::store(double nr)
unknown's avatar
unknown committed
5395 5396
{
  if (nr < 0.0 || nr >= 2155.0)
5397
  {
5398
    (void) Field_year::store((longlong) -1, FALSE);
5399 5400
    return 1;
  }
5401
  return Field_year::store((longlong) nr, FALSE);
unknown's avatar
unknown committed
5402 5403
}

5404 5405

int Field_year::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
5406
{
5407
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
5408 5409
  if (nr < 0 || nr >= 100 && nr <= 1900 || nr > 2155)
  {
5410
    *ptr= 0;
5411
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
5412
    return 1;
unknown's avatar
unknown committed
5413 5414 5415 5416 5417 5418 5419 5420
  }
  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
5421
  *ptr= (char) (uchar) nr;
5422
  return 0;
unknown's avatar
unknown committed
5423 5424
}

5425

unknown's avatar
unknown committed
5426 5427
bool Field_year::send_binary(Protocol *protocol)
{
5428
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
5429
  ulonglong tmp= Field_year::val_int();
5430
  return protocol->store_short(tmp);
unknown's avatar
unknown committed
5431
}
unknown's avatar
unknown committed
5432

5433

unknown's avatar
unknown committed
5434 5435 5436 5437 5438
double Field_year::val_real(void)
{
  return (double) Field_year::val_int();
}

5439

unknown's avatar
unknown committed
5440 5441
longlong Field_year::val_int(void)
{
5442
  ASSERT_COLUMN_MARKED_FOR_READ;
5443
  int tmp= (int) ptr[0];
unknown's avatar
unknown committed
5444 5445 5446 5447 5448 5449 5450
  if (field_length != 4)
    tmp%=100;					// Return last 2 char
  else if (tmp)
    tmp+=1900;
  return (longlong) tmp;
}

5451

unknown's avatar
unknown committed
5452 5453 5454 5455 5456 5457 5458 5459 5460 5461
String *Field_year::val_str(String *val_buffer,
			    String *val_ptr __attribute__((unused)))
{
  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());
  return val_buffer;
}

5462

unknown's avatar
unknown committed
5463 5464
void Field_year::sql_type(String &res) const
{
unknown's avatar
unknown committed
5465
  CHARSET_INFO *cs=res.charset();
5466
  res.length(cs->cset->snprintf(cs,(char*)res.ptr(),res.alloced_length(),
5467
			  "year(%d)",(int) field_length));
unknown's avatar
unknown committed
5468 5469 5470 5471 5472 5473 5474 5475 5476 5477
}


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

unknown's avatar
unknown committed
5478
int Field_date::store(const char *from, uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
5479
{
5480
  ASSERT_COLUMN_MARKED_FOR_WRITE;
5481
  MYSQL_TIME l_time;
unknown's avatar
unknown committed
5482
  uint32 tmp;
5483
  int error;
unknown's avatar
unknown committed
5484
  THD *thd= table ? table->in_use : current_thd;
5485

unknown's avatar
unknown committed
5486
  if (str_to_datetime(from, len, &l_time, TIME_FUZZY_DATE |
unknown's avatar
unknown committed
5487
                      (thd->variables.sql_mode &
unknown's avatar
unknown committed
5488 5489 5490
                       (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE |
                        MODE_INVALID_DATES)),
                      &error) <= MYSQL_TIMESTAMP_ERROR)
5491
  {
5492
    tmp= 0;
unknown's avatar
unknown committed
5493
    error= 2;
5494
  }
unknown's avatar
unknown committed
5495
  else
unknown's avatar
unknown committed
5496
    tmp=(uint32) l_time.year*10000L + (uint32) (l_time.month*100+l_time.day);
5497 5498

  if (error)
5499
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED,
5500
                         from, len, MYSQL_TIMESTAMP_DATE, 1);
5501

unknown's avatar
unknown committed
5502
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
5503
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
5504 5505 5506 5507 5508 5509
  {
    int4store(ptr,tmp);
  }
  else
#endif
    longstore(ptr,tmp);
5510
  return error;
unknown's avatar
unknown committed
5511 5512 5513
}


unknown's avatar
unknown committed
5514
int Field_date::store(double nr)
unknown's avatar
unknown committed
5515
{
5516
  longlong tmp;
unknown's avatar
unknown committed
5517
  int error= 0;
unknown's avatar
unknown committed
5518 5519 5520 5521
  if (nr >= 19000000000000.0 && nr <= 99991231235959.0)
    nr=floor(nr/1000000.0);			// Timestamp to date
  if (nr < 0.0 || nr > 99991231.0)
  {
5522
    tmp= LL(0);
5523 5524
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
                         ER_WARN_DATA_OUT_OF_RANGE,
5525
                         nr, MYSQL_TIMESTAMP_DATE);
unknown's avatar
unknown committed
5526
    error= 1;
unknown's avatar
unknown committed
5527 5528
  }
  else
5529
    tmp= (longlong) rint(nr);
5530

5531
  return Field_date::store(tmp, TRUE);
unknown's avatar
unknown committed
5532 5533 5534
}


5535
int Field_date::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
5536
{
5537
  ASSERT_COLUMN_MARKED_FOR_WRITE;
5538
  MYSQL_TIME not_used;
5539 5540
  int error;
  longlong initial_nr= nr;
unknown's avatar
unknown committed
5541
  THD *thd= table ? table->in_use : current_thd;
5542 5543

  nr= number_to_datetime(nr, &not_used, (TIME_FUZZY_DATE |
unknown's avatar
unknown committed
5544
                                         (thd->variables.sql_mode &
5545 5546 5547 5548
                                          (MODE_NO_ZERO_IN_DATE |
                                           MODE_NO_ZERO_DATE |
                                           MODE_INVALID_DATES))), &error);

5549
  if (nr == LL(-1))
unknown's avatar
unknown committed
5550
  {
5551 5552
    nr= 0;
    error= 2;
unknown's avatar
unknown committed
5553
  }
5554

5555
  if (nr >= 19000000000000.0 && nr <= 99991231235959.0)
5556
    nr= (longlong) floor(nr/1000000.0);         // Timestamp to date
5557

5558 5559 5560 5561 5562
  if (error)
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
                         error == 2 ? ER_WARN_DATA_OUT_OF_RANGE :
                         WARN_DATA_TRUNCATED, initial_nr,
                         MYSQL_TIMESTAMP_DATETIME, 1);
5563

unknown's avatar
unknown committed
5564
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
5565
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
5566
  {
5567
    int4store(ptr, nr);
unknown's avatar
unknown committed
5568 5569 5570
  }
  else
#endif
5571
    longstore(ptr, nr);
5572
  return error;
unknown's avatar
unknown committed
5573 5574 5575
}


unknown's avatar
unknown committed
5576 5577 5578
bool Field_date::send_binary(Protocol *protocol)
{
  longlong tmp= Field_date::val_int();
5579
  MYSQL_TIME tm;
unknown's avatar
unknown committed
5580 5581 5582 5583 5584 5585
  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
5586 5587 5588

double Field_date::val_real(void)
{
5589
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
5590 5591
  int32 j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
5592
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
5593 5594 5595 5596 5597 5598 5599
    j=sint4korr(ptr);
  else
#endif
    longget(j,ptr);
  return (double) (uint32) j;
}

5600

unknown's avatar
unknown committed
5601 5602
longlong Field_date::val_int(void)
{
5603
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
5604 5605
  int32 j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
5606
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
5607 5608 5609 5610 5611 5612 5613
    j=sint4korr(ptr);
  else
#endif
    longget(j,ptr);
  return (longlong) (uint32) j;
}

5614

unknown's avatar
unknown committed
5615 5616 5617
String *Field_date::val_str(String *val_buffer,
			    String *val_ptr __attribute__((unused)))
{
5618
  ASSERT_COLUMN_MARKED_FOR_READ;
5619
  MYSQL_TIME ltime;
unknown's avatar
unknown committed
5620 5621 5622
  val_buffer->alloc(field_length);
  int32 tmp;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
5623
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
5624 5625 5626 5627
    tmp=sint4korr(ptr);
  else
#endif
    longget(tmp,ptr);
5628 5629 5630 5631
  ltime.neg= 0;
  ltime.year= (int) ((uint32) tmp/10000L % 10000);
  ltime.month= (int) ((uint32) tmp/100 % 100);
  ltime.day= (int) ((uint32) tmp % 100);
5632
  make_date((DATE_TIME_FORMAT *) 0, &ltime, val_buffer);
unknown's avatar
unknown committed
5633 5634 5635
  return val_buffer;
}

5636

5637 5638 5639 5640 5641 5642 5643
bool Field_date::get_time(MYSQL_TIME *ltime)
{
  bzero((char *)ltime, sizeof(MYSQL_TIME));
  return 0;
}


5644
int Field_date::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
5645 5646 5647
{
  int32 a,b;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
5648
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662
  {
    a=sint4korr(a_ptr);
    b=sint4korr(b_ptr);
  }
  else
#endif
  {
    longget(a,a_ptr);
    longget(b,b_ptr);
  }
  return ((uint32) a < (uint32) b) ? -1 : ((uint32) a > (uint32) b) ? 1 : 0;
}


5663
void Field_date::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
5664 5665
{
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
5666
  if (!table || !table->s->db_low_byte_first)
unknown's avatar
unknown committed
5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684
  {
    to[0] = ptr[0];
    to[1] = ptr[1];
    to[2] = ptr[2];
    to[3] = ptr[3];
  }
  else
#endif
  {
    to[0] = ptr[3];
    to[1] = ptr[2];
    to[2] = ptr[1];
    to[3] = ptr[0];
  }
}

void Field_date::sql_type(String &res) const
{
5685
  res.set_ascii(STRING_WITH_LEN("date"));
unknown's avatar
unknown committed
5686 5687
}

5688

unknown's avatar
unknown committed
5689 5690 5691 5692 5693 5694
/****************************************************************************
** The new date type
** This is identical to the old date type, but stored on 3 bytes instead of 4
** In number context: YYYYMMDD
****************************************************************************/

5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708
/*
  Store string into a date field

  SYNOPSIS
    Field_newdate::store()
    from                Date string
    len                 Length of date field
    cs                  Character set (not used)

  RETURN
    0  ok
    1  Value was cut during conversion
    2  Wrong date string
    3  Datetime value that was cut (warning level NOTE)
5709 5710 5711
       This is used by opt_range.cc:get_mm_leaf(). Note that there is a
       nearly-identical class Field_date doesn't ever return 3 from its
       store function.
5712 5713
*/

unknown's avatar
unknown committed
5714
int Field_newdate::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
5715
{
5716
  ASSERT_COLUMN_MARKED_FOR_WRITE;
5717 5718
  long tmp;
  MYSQL_TIME l_time;
5719
  int error;
unknown's avatar
unknown committed
5720
  THD *thd= table ? table->in_use : current_thd;
5721 5722 5723 5724 5725 5726 5727 5728
  enum enum_mysql_timestamp_type ret;
  if ((ret= str_to_datetime(from, len, &l_time,
                            (TIME_FUZZY_DATE |
                             (thd->variables.sql_mode &
                              (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE |
                               MODE_INVALID_DATES))),
                            &error)) <= MYSQL_TIMESTAMP_ERROR)
  {
5729
    tmp= 0;
unknown's avatar
unknown committed
5730
    error= 2;
5731
  }
unknown's avatar
unknown committed
5732
  else
5733
  {
5734
    tmp= l_time.day + l_time.month*32 + l_time.year*16*32;
5735
    if (!error && (ret != MYSQL_TIMESTAMP_DATE) &&
5736
        (l_time.hour || l_time.minute || l_time.second || l_time.second_part))
5737
      error= 3;                                 // Datetime was cut (note)
5738
  }
5739 5740

  if (error)
5741 5742 5743
    set_datetime_warning(error == 3 ? MYSQL_ERROR::WARN_LEVEL_NOTE :
                         MYSQL_ERROR::WARN_LEVEL_WARN,
                         WARN_DATA_TRUNCATED,
5744
                         from, len, MYSQL_TIMESTAMP_DATE, 1);
5745

5746
  int3store(ptr, tmp);
5747
  return error;
unknown's avatar
unknown committed
5748 5749
}

5750

unknown's avatar
unknown committed
5751
int Field_newdate::store(double nr)
unknown's avatar
unknown committed
5752 5753
{
  if (nr < 0.0 || nr > 99991231235959.0)
5754
  {
5755
    int3store(ptr,(int32) 0);
5756
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
5757
                         WARN_DATA_TRUNCATED, nr, MYSQL_TIMESTAMP_DATE);
5758 5759
    return 1;
  }
5760
  return Field_newdate::store((longlong) rint(nr), FALSE);
unknown's avatar
unknown committed
5761 5762 5763
}


5764
int Field_newdate::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
5765
{
5766
  ASSERT_COLUMN_MARKED_FOR_WRITE;
5767
  MYSQL_TIME l_time;
5768
  longlong tmp;
5769
  int error;
unknown's avatar
unknown committed
5770
  THD *thd= table ? table->in_use : current_thd;
5771 5772
  if (number_to_datetime(nr, &l_time,
                         (TIME_FUZZY_DATE |
unknown's avatar
unknown committed
5773
                          (thd->variables.sql_mode &
5774 5775 5776
                           (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE |
                            MODE_INVALID_DATES))),
                         &error) == LL(-1))
5777 5778 5779
  {
    tmp= 0L;
    error= 2;
unknown's avatar
unknown committed
5780 5781
  }
  else
5782
    tmp= l_time.day + l_time.month*32 + l_time.year*16*32;
5783

5784 5785 5786 5787
  if (!error && l_time.time_type != MYSQL_TIMESTAMP_DATE &&
      (l_time.hour || l_time.minute || l_time.second || l_time.second_part))
    error= 3;

5788
  if (error)
5789 5790 5791 5792 5793
    set_datetime_warning(error == 3 ? MYSQL_ERROR::WARN_LEVEL_NOTE :
                         MYSQL_ERROR::WARN_LEVEL_WARN,
                         error == 2 ? 
                         ER_WARN_DATA_OUT_OF_RANGE : WARN_DATA_TRUNCATED,
                         nr,MYSQL_TIMESTAMP_DATE, 1);
5794 5795

  int3store(ptr,tmp);
5796
  return error;
unknown's avatar
unknown committed
5797 5798
}

5799

5800
int Field_newdate::store_time(MYSQL_TIME *ltime,timestamp_type time_type)
unknown's avatar
unknown committed
5801
{
5802
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
5803
  long tmp;
5804
  int error= 0;
5805 5806
  if (time_type == MYSQL_TIMESTAMP_DATE ||
      time_type == MYSQL_TIMESTAMP_DATETIME)
5807
  {
unknown's avatar
unknown committed
5808
    tmp=ltime->year*16*32+ltime->month*32+ltime->day;
5809 5810 5811 5812 5813
    if (check_date(ltime, tmp != 0,
                   (TIME_FUZZY_DATE |
                    (current_thd->variables.sql_mode &
                     (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE |
                      MODE_INVALID_DATES))), &error))
5814
    {
5815
      char buff[MAX_DATE_STRING_REP_LENGTH];
5816 5817 5818 5819 5820
      String str(buff, sizeof(buff), &my_charset_latin1);
      make_date((DATE_TIME_FORMAT *) 0, ltime, &str);
      set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED,
                           str.ptr(), str.length(), MYSQL_TIMESTAMP_DATE, 1);
    }
5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831
    if (!error && ltime->time_type != MYSQL_TIMESTAMP_DATE &&
        (ltime->hour || ltime->minute || ltime->second || ltime->second_part))
    {
      char buff[MAX_DATE_STRING_REP_LENGTH];
      String str(buff, sizeof(buff), &my_charset_latin1);
      make_datetime((DATE_TIME_FORMAT *) 0, ltime, &str);
      set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_NOTE,
                           WARN_DATA_TRUNCATED,
                           str.ptr(), str.length(), MYSQL_TIMESTAMP_DATE, 1);
      error= 3;
    }
5832
  }
unknown's avatar
unknown committed
5833 5834 5835
  else
  {
    tmp=0;
5836
    error= 1;
5837
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
5838 5839
  }
  int3store(ptr,tmp);
5840
  return error;
unknown's avatar
unknown committed
5841 5842
}

5843

unknown's avatar
unknown committed
5844 5845
bool Field_newdate::send_binary(Protocol *protocol)
{
5846
  MYSQL_TIME tm;
unknown's avatar
unknown committed
5847 5848 5849
  Field_newdate::get_date(&tm,0);
  return protocol->store_date(&tm);
}
unknown's avatar
unknown committed
5850

5851

unknown's avatar
unknown committed
5852 5853
double Field_newdate::val_real(void)
{
5854
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
5855 5856 5857
  return (double) Field_newdate::val_int();
}

5858

unknown's avatar
unknown committed
5859 5860
longlong Field_newdate::val_int(void)
{
5861
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
5862
  ulong j= uint3korr(ptr);
unknown's avatar
unknown committed
5863 5864 5865 5866
  j= (j % 32L)+(j / 32L % 16L)*100L + (j/(16L*32L))*10000L;
  return (longlong) j;
}

5867

unknown's avatar
unknown committed
5868 5869 5870
String *Field_newdate::val_str(String *val_buffer,
			       String *val_ptr __attribute__((unused)))
{
5871
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
5872 5873
  val_buffer->alloc(field_length);
  val_buffer->length(field_length);
unknown's avatar
unknown committed
5874
  uint32 tmp=(uint32) uint3korr(ptr);
unknown's avatar
unknown committed
5875 5876 5877 5878
  int part;
  char *pos=(char*) val_buffer->ptr()+10;

  /* Open coded to get more speed */
unknown's avatar
unknown committed
5879
  *pos--=0;					// End NULL
unknown's avatar
unknown committed
5880
  part=(int) (tmp & 31);
unknown's avatar
unknown committed
5881 5882 5883
  *pos--= (char) ('0'+part%10);
  *pos--= (char) ('0'+part/10);
  *pos--= '-';
unknown's avatar
unknown committed
5884
  part=(int) (tmp >> 5 & 15);
unknown's avatar
unknown committed
5885 5886 5887
  *pos--= (char) ('0'+part%10);
  *pos--= (char) ('0'+part/10);
  *pos--= '-';
unknown's avatar
unknown committed
5888
  part=(int) (tmp >> 9);
unknown's avatar
unknown committed
5889 5890 5891 5892
  *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);
unknown's avatar
unknown committed
5893 5894 5895
  return val_buffer;
}

5896

5897
bool Field_newdate::get_date(MYSQL_TIME *ltime,uint fuzzydate)
unknown's avatar
unknown committed
5898
{
unknown's avatar
unknown committed
5899
  uint32 tmp=(uint32) uint3korr(ptr);
unknown's avatar
unknown committed
5900 5901 5902
  ltime->day=   tmp & 31;
  ltime->month= (tmp >> 5) & 15;
  ltime->year=  (tmp >> 9);
5903
  ltime->time_type= MYSQL_TIMESTAMP_DATE;
5904
  ltime->hour= ltime->minute= ltime->second= ltime->second_part= ltime->neg= 0;
unknown's avatar
unknown committed
5905 5906
  return ((!(fuzzydate & TIME_FUZZY_DATE) && (!ltime->month || !ltime->day)) ?
          1 : 0);
unknown's avatar
unknown committed
5907 5908
}

5909

5910
bool Field_newdate::get_time(MYSQL_TIME *ltime)
unknown's avatar
unknown committed
5911
{
unknown's avatar
unknown committed
5912
  return Field_newdate::get_date(ltime,0);
unknown's avatar
unknown committed
5913 5914
}

5915

5916
int Field_newdate::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
5917
{
unknown's avatar
unknown committed
5918 5919 5920
  uint32 a,b;
  a=(uint32) uint3korr(a_ptr);
  b=(uint32) uint3korr(b_ptr);
unknown's avatar
unknown committed
5921 5922 5923
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

5924

5925
void Field_newdate::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
5926 5927 5928 5929 5930 5931
{
  to[0] = ptr[2];
  to[1] = ptr[1];
  to[2] = ptr[0];
}

5932

unknown's avatar
unknown committed
5933 5934
void Field_newdate::sql_type(String &res) const
{
5935
  res.set_ascii(STRING_WITH_LEN("date"));
unknown's avatar
unknown committed
5936 5937 5938 5939 5940 5941 5942 5943 5944 5945
}


/****************************************************************************
** 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.
****************************************************************************/

unknown's avatar
unknown committed
5946
int Field_datetime::store(const char *from,uint len,CHARSET_INFO *cs)
unknown's avatar
unknown committed
5947
{
5948
  ASSERT_COLUMN_MARKED_FOR_WRITE;
5949
  MYSQL_TIME time_tmp;
5950 5951
  int error;
  ulonglong tmp= 0;
5952
  enum enum_mysql_timestamp_type func_res;
unknown's avatar
unknown committed
5953
  THD *thd= table ? table->in_use : current_thd;
5954

5955 5956
  func_res= str_to_datetime(from, len, &time_tmp,
                            (TIME_FUZZY_DATE |
unknown's avatar
unknown committed
5957
                             (thd->variables.sql_mode &
5958 5959 5960 5961
                              (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE |
                               MODE_INVALID_DATES))),
                            &error);
  if ((int) func_res > (int) MYSQL_TIMESTAMP_ERROR)
5962
    tmp= TIME_to_ulonglong_datetime(&time_tmp);
5963 5964 5965
  else
    error= 1;                                 // Fix if invalid zero date

5966
  if (error)
5967
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
5968
                         ER_WARN_DATA_OUT_OF_RANGE,
5969
                         from, len, MYSQL_TIMESTAMP_DATETIME, 1);
5970

unknown's avatar
unknown committed
5971
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
5972
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
5973 5974 5975 5976 5977 5978
  {
    int8store(ptr,tmp);
  }
  else
#endif
    longlongstore(ptr,tmp);
5979
  return error;
unknown's avatar
unknown committed
5980 5981 5982
}


unknown's avatar
unknown committed
5983
int Field_datetime::store(double nr)
unknown's avatar
unknown committed
5984
{
unknown's avatar
unknown committed
5985
  int error= 0;
unknown's avatar
unknown committed
5986 5987
  if (nr < 0.0 || nr > 99991231235959.0)
  {
5988 5989
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, 
                         ER_WARN_DATA_OUT_OF_RANGE,
5990
                         nr, MYSQL_TIMESTAMP_DATETIME);
5991
    nr= 0.0;
unknown's avatar
unknown committed
5992
    error= 1;
unknown's avatar
unknown committed
5993
  }
5994
  error|= Field_datetime::store((longlong) rint(nr), FALSE);
5995
  return error;
unknown's avatar
unknown committed
5996 5997 5998
}


5999
int Field_datetime::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
6000
{
6001
  ASSERT_COLUMN_MARKED_FOR_WRITE;
6002
  MYSQL_TIME not_used;
6003 6004
  int error;
  longlong initial_nr= nr;
unknown's avatar
unknown committed
6005
  THD *thd= table ? table->in_use : current_thd;
6006

6007
  nr= number_to_datetime(nr, &not_used, (TIME_FUZZY_DATE |
unknown's avatar
unknown committed
6008
                                         (thd->variables.sql_mode &
6009 6010 6011 6012
                                          (MODE_NO_ZERO_IN_DATE |
                                           MODE_NO_ZERO_DATE |
                                           MODE_INVALID_DATES))), &error);

6013
  if (nr == LL(-1))
6014
  {
6015 6016
    nr= 0;
    error= 2;
6017
  }
6018

6019 6020 6021 6022 6023 6024
  if (error)
    set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN,
                         error == 2 ? ER_WARN_DATA_OUT_OF_RANGE :
                         WARN_DATA_TRUNCATED, initial_nr,
                         MYSQL_TIMESTAMP_DATETIME, 1);

unknown's avatar
unknown committed
6025
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
6026
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
6027 6028 6029 6030 6031 6032
  {
    int8store(ptr,nr);
  }
  else
#endif
    longlongstore(ptr,nr);
6033
  return error;
unknown's avatar
unknown committed
6034 6035
}

unknown's avatar
unknown committed
6036

6037
int Field_datetime::store_time(MYSQL_TIME *ltime,timestamp_type time_type)
unknown's avatar
unknown committed
6038
{
6039
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
6040
  longlong tmp;
6041
  int error= 0;
6042 6043 6044 6045
  /*
    We don't perform range checking here since values stored in TIME
    structure always fit into DATETIME range.
  */
6046 6047
  if (time_type == MYSQL_TIMESTAMP_DATE ||
      time_type == MYSQL_TIMESTAMP_DATETIME)
6048
  {
unknown's avatar
unknown committed
6049 6050
    tmp=((ltime->year*10000L+ltime->month*100+ltime->day)*LL(1000000)+
	 (ltime->hour*10000L+ltime->minute*100+ltime->second));
6051 6052 6053 6054 6055
    if (check_date(ltime, tmp != 0,
                   (TIME_FUZZY_DATE |
                    (current_thd->variables.sql_mode &
                     (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE |
                      MODE_INVALID_DATES))), &error))
6056
    {
6057
      char buff[MAX_DATE_STRING_REP_LENGTH];
6058 6059 6060 6061 6062 6063
      String str(buff, sizeof(buff), &my_charset_latin1);
      make_datetime((DATE_TIME_FORMAT *) 0, ltime, &str);
      set_datetime_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED,
                           str.ptr(), str.length(), MYSQL_TIMESTAMP_DATETIME,1);
    }
  }
unknown's avatar
unknown committed
6064 6065 6066
  else
  {
    tmp=0;
6067
    error= 1;
6068
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
6069 6070
  }
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
6071
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
6072 6073 6074 6075 6076 6077
  {
    int8store(ptr,tmp);
  }
  else
#endif
    longlongstore(ptr,tmp);
6078
  return error;
unknown's avatar
unknown committed
6079 6080
}

unknown's avatar
unknown committed
6081 6082
bool Field_datetime::send_binary(Protocol *protocol)
{
6083
  MYSQL_TIME tm;
6084
  Field_datetime::get_date(&tm, TIME_FUZZY_DATE);
unknown's avatar
unknown committed
6085 6086 6087
  return protocol->store(&tm);
}

unknown's avatar
unknown committed
6088 6089 6090 6091 6092 6093 6094 6095

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

longlong Field_datetime::val_int(void)
{
6096
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
6097 6098
  longlong j;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
6099
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110
    j=sint8korr(ptr);
  else
#endif
    longlongget(j,ptr);
  return j;
}


String *Field_datetime::val_str(String *val_buffer,
				String *val_ptr __attribute__((unused)))
{
6111
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
6112 6113 6114 6115 6116 6117 6118 6119
  val_buffer->alloc(field_length);
  val_buffer->length(field_length);
  ulonglong tmp;
  long part1,part2;
  char *pos;
  int part3;

#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
6120
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
6121 6122 6123 6124 6125 6126
    tmp=sint8korr(ptr);
  else
#endif
    longlongget(tmp,ptr);

  /*
unknown's avatar
unknown committed
6127
    Avoid problem with slow longlong arithmetic and sprintf
unknown's avatar
unknown committed
6128 6129 6130 6131 6132
  */

  part1=(long) (tmp/LL(1000000));
  part2=(long) (tmp - (ulonglong) part1*LL(1000000));

6133
  pos=(char*) val_buffer->ptr() + MAX_DATETIME_WIDTH;
unknown's avatar
unknown committed
6134
  *pos--=0;
unknown's avatar
unknown committed
6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153
  *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);
unknown's avatar
unknown committed
6154 6155 6156
  return val_buffer;
}

6157
bool Field_datetime::get_date(MYSQL_TIME *ltime, uint fuzzydate)
unknown's avatar
unknown committed
6158 6159
{
  longlong tmp=Field_datetime::val_int();
unknown's avatar
unknown committed
6160 6161 6162
  uint32 part1,part2;
  part1=(uint32) (tmp/LL(1000000));
  part2=(uint32) (tmp - (ulonglong) part1*LL(1000000));
unknown's avatar
unknown committed
6163

6164
  ltime->time_type=	MYSQL_TIMESTAMP_DATETIME;
unknown's avatar
unknown committed
6165 6166 6167 6168 6169 6170 6171 6172
  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);
unknown's avatar
unknown committed
6173
  return (!(fuzzydate & TIME_FUZZY_DATE) && (!ltime->month || !ltime->day)) ? 1 : 0;
unknown's avatar
unknown committed
6174 6175
}

6176
bool Field_datetime::get_time(MYSQL_TIME *ltime)
unknown's avatar
unknown committed
6177
{
unknown's avatar
unknown committed
6178
  return Field_datetime::get_date(ltime,0);
unknown's avatar
unknown committed
6179 6180
}

6181
int Field_datetime::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
6182 6183 6184
{
  longlong a,b;
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
6185
  if (table && table->s->db_low_byte_first)
unknown's avatar
unknown committed
6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199
  {
    a=sint8korr(a_ptr);
    b=sint8korr(b_ptr);
  }
  else
#endif
  {
    longlongget(a,a_ptr);
    longlongget(b,b_ptr);
  }
  return ((ulonglong) a < (ulonglong) b) ? -1 :
    ((ulonglong) a > (ulonglong) b) ? 1 : 0;
}

6200
void Field_datetime::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
6201 6202
{
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
6203
  if (!table || !table->s->db_low_byte_first)
unknown's avatar
unknown committed
6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230
  {
    to[0] = ptr[0];
    to[1] = ptr[1];
    to[2] = ptr[2];
    to[3] = ptr[3];
    to[4] = ptr[4];
    to[5] = ptr[5];
    to[6] = ptr[6];
    to[7] = ptr[7];
  }
  else
#endif
  {
    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];
  }
}


void Field_datetime::sql_type(String &res) const
{
6231
  res.set_ascii(STRING_WITH_LEN("datetime"));
unknown's avatar
unknown committed
6232 6233 6234 6235 6236 6237 6238
}

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

6239 6240 6241 6242 6243 6244 6245 6246 6247 6248
/*
  Report "not well formed" or "cannot convert" error
  after storing a character string info a field.

  SYNOPSIS
    check_string_copy_error()
    field                    - Field
    well_formed_error_pos    - where not well formed data was first met
    cannot_convert_error_pos - where a not-convertable character was first met
    end                      - end of the string
6249
    cs                       - character set of the string
6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268

  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
*/

static bool
check_string_copy_error(Field_str *field,
                        const char *well_formed_error_pos,
                        const char *cannot_convert_error_pos,
6269 6270
                        const char *end,
                        CHARSET_INFO *cs)
6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283
{
  const char *pos, *end_orig;
  char tmp[64], *t;
  
  if (!(pos= well_formed_error_pos) &&
      !(pos= cannot_convert_error_pos))
    return FALSE;

  end_orig= end;
  set_if_smaller(end, pos + 6);

  for (t= tmp; pos < end; pos++)
  {
6284 6285 6286 6287 6288 6289 6290 6291 6292
    /*
      If the source string is ASCII compatible (mbminlen==1)
      and the source character is in ASCII printable range (0x20..0x7F),
      then display the character as is.
      
      Otherwise, if the source string is not ASCII compatible (e.g. UCS2),
      or the source character is not in the printable range,
      then print the character using HEX notation.
    */
6293
    if (((unsigned char) *pos) >= 0x20 &&
6294 6295
        ((unsigned char) *pos) <= 0x7F &&
        cs->mbminlen == 1)
6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348
    {
      *t++= *pos;
    }
    else
    {
      *t++= '\\';
      *t++= 'x';
      *t++= _dig_vec_upper[((unsigned char) *pos) >> 4];
      *t++= _dig_vec_upper[((unsigned char) *pos) & 15];
    }
  }
  if (end_orig > end)
  {
    *t++= '.';
    *t++= '.';
    *t++= '.';
  }
  *t= '\0';
  push_warning_printf(field->table->in_use, 
                      field->table->in_use->abort_on_warning ?
                      MYSQL_ERROR::WARN_LEVEL_ERROR :
                      MYSQL_ERROR::WARN_LEVEL_WARN,
                      ER_TRUNCATED_WRONG_VALUE_FOR_FIELD, 
                      ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
                      "string", tmp, field->field_name,
                      (ulong) field->table->in_use->row_count);
  return TRUE;
}



/*
  Send a truncation warning or a truncation error
  after storing a too long character string info a field.

  SYNOPSIS
    report_data_too_long()
    field                    - Field

  RETURN
    N/A
*/

inline void
report_data_too_long(Field_str *field)
{
  if (field->table->in_use->abort_on_warning)
    field->set_warning(MYSQL_ERROR::WARN_LEVEL_ERROR, ER_DATA_TOO_LONG, 1);
  else
    field->set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
}


unknown's avatar
unknown committed
6349 6350
	/* Copy a string and fill with space */

unknown's avatar
unknown committed
6351
int Field_string::store(const char *from,uint length,CHARSET_INFO *cs)
unknown's avatar
unknown committed
6352
{
6353
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
6354
  uint copy_length;
6355 6356 6357
  const char *well_formed_error_pos;
  const char *cannot_convert_error_pos;
  const char *from_end_pos;
6358

6359 6360
  /* See the comment for Field_long::store(long long) */
  DBUG_ASSERT(table->in_use == current_thd);
6361

6362
  copy_length= well_formed_copy_nchars(field_charset,
6363
                                       (char*) ptr, field_length,
6364 6365 6366 6367 6368
                                       cs, from, length,
                                       field_length / field_charset->mbmaxlen,
                                       &well_formed_error_pos,
                                       &cannot_convert_error_pos,
                                       &from_end_pos);
6369 6370 6371

  /* Append spaces if the string was shorter than the field. */
  if (copy_length < field_length)
6372
    field_charset->cset->fill(field_charset,(char*) ptr+copy_length,
6373
                              field_length-copy_length,
6374
                              field_charset->pad_char);
6375

6376
  if (check_string_copy_error(this, well_formed_error_pos,
6377
                              cannot_convert_error_pos, from + length, cs))
6378 6379
    return 2;

6380 6381 6382 6383
  /*
    Check if we lost any important data (anything in a binary string,
    or any non-space in others).
  */
6384
  if ((from_end_pos < from + length) && table->in_use->count_cuted_fields)
6385
  {
6386
    if (test_if_important_data(field_charset, from_end_pos, from + length))
6387
    {
6388 6389
      report_data_too_long(this);
      return 2;
6390
    }
unknown's avatar
unknown committed
6391
  }
6392
  return 0;
unknown's avatar
unknown committed
6393 6394 6395
}


6396
/**
6397 6398
  Store double value in Field_string or Field_varstring.

6399
  Pretty prints double number into field_length characters buffer.
6400

6401
  @param nr            number
6402 6403
*/

unknown's avatar
unknown committed
6404
int Field_str::store(double nr)
unknown's avatar
unknown committed
6405
{
6406
  ASSERT_COLUMN_MARKED_FOR_WRITE;
6407
  char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
6408
  uint length;
6409
  uint local_char_length= field_length / charset()->mbmaxlen;
6410
  double anr= fabs(nr);
6411
  bool fractional= (anr != floor(anr));
6412
  int neg= (nr < 0.0) ? 1 : 0;
6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439
  uint max_length;
  int exp;
  uint digits;
  uint i;

  /* Calculate the exponent from the 'e'-format conversion */
  if (anr < 1.0 && anr > 0)
  {
    for (exp= 0; anr < 1e-100; exp-= 100, anr*= 1e100);
    for (; anr < 1e-10; exp-= 10, anr*= 1e10);
    for (i= 1; anr < 1 / log_10[i]; exp--, i++);
    exp--;
  }
  else
  {
    for (exp= 0; anr > 1e100; exp+= 100, anr/= 1e100);
    for (; anr > 1e10; exp+= 10, anr/= 1e10);
    for (i= 1; anr > log_10[i]; exp++, i++);
  }

  max_length= local_char_length - neg;

  /*
    Since in sprintf("%g") precision means the number of significant digits,
    calculate the maximum number of significant digits if the 'f'-format
    would be used (+1 for decimal point if the number has a fractional part).
  */
6440
  digits= max(0, (int) max_length - fractional);
6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454
  /*
    If the exponent is negative, decrease digits by the number of leading zeros
    after the decimal point that do not count as significant digits.
  */
  if (exp < 0)
    digits= max(0, (int) digits + exp);
  /*
    'e'-format is used only if the exponent is less than -4 or greater than or
    equal to the precision. In this case we need to adjust the number of
    significant digits to take "e+NN" + decimal point into account (hence -5).
    We also have to reserve one additional character if abs(exp) >= 100.
  */
  if (exp >= (int) digits || exp < -4)
    digits= max(0, (int) (max_length - 5 - (exp >= 100 || exp <= -100)));
6455 6456 6457

  /* Limit precision to DBL_DIG to avoid garbage past significant digits */
  set_if_smaller(digits, DBL_DIG);
6458
  
6459
  length= (uint) my_sprintf(buff, (buff, "%-.*g", digits, nr));
6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476

#ifdef __WIN__
  /*
    Windows always zero-pads the exponent to 3 digits, we want to remove the
    leading 0 to match the sprintf() output on other platforms.
  */
  if ((exp >= (int) digits || exp < -4) && exp > -100 && exp < 100)
  {
    DBUG_ASSERT(length >= 6); /* 1e+NNN */
    uint tmp= length - 3;
    buff[tmp]= buff[tmp + 1];
    tmp++;
    buff[tmp]= buff[tmp + 1];
    length--;
  }
#endif
  
6477 6478 6479 6480 6481
  /*
    +1 below is because "precision" in %g above means the
    max. number of significant digits, not the output width.
    Thus the width can be larger than number of significant digits by 1
    (for decimal point)
6482
    the test for local_char_length < 5 is for extreme cases,
6483
    like inserting 500.0 in char(1)
6484
  */
6485
  DBUG_ASSERT(local_char_length < 5 || length <= local_char_length+1);
6486
  return store(buff, length, charset());
6487 6488
}

unknown's avatar
unknown committed
6489

unknown's avatar
unknown committed
6490
uint Field::is_equal(Create_field *new_field)
unknown's avatar
unknown committed
6491
{
6492
  return (new_field->sql_type == real_type());
unknown's avatar
unknown committed
6493 6494 6495
}


6496 6497
/* If one of the fields is binary and the other one isn't return 1 else 0 */

6498
bool Field_str::compare_str_field_flags(Create_field *new_field, uint32 flag_arg)
6499 6500
{
  return (((new_field->flags & (BINCMP_FLAG | BINARY_FLAG)) &&
6501
          !(flag_arg & (BINCMP_FLAG | BINARY_FLAG))) ||
6502
         (!(new_field->flags & (BINCMP_FLAG | BINARY_FLAG)) &&
6503
          (flag_arg & (BINCMP_FLAG | BINARY_FLAG))));
6504 6505 6506
}


unknown's avatar
unknown committed
6507
uint Field_str::is_equal(Create_field *new_field)
unknown's avatar
unknown committed
6508
{
6509 6510
  if (compare_str_field_flags(new_field, flags))
    return 0;
unknown's avatar
unknown committed
6511

6512
  return ((new_field->sql_type == real_type()) &&
unknown's avatar
unknown committed
6513
	  new_field->charset == field_charset &&
unknown's avatar
unknown committed
6514
	  new_field->length == max_display_length());
unknown's avatar
unknown committed
6515 6516 6517
}


6518
int Field_string::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
6519
{
unknown's avatar
unknown committed
6520 6521 6522
  char buff[64];
  int  l;
  CHARSET_INFO *cs=charset();
6523 6524
  l= (cs->cset->longlong10_to_str)(cs,buff,sizeof(buff),
                                   unsigned_val ? 10 : -10, nr);
unknown's avatar
unknown committed
6525
  return Field_string::store(buff,(uint)l,cs);
unknown's avatar
unknown committed
6526 6527
}

6528

unknown's avatar
unknown committed
6529 6530
int Field_longstr::store_decimal(const my_decimal *d)
{
6531 6532
  char buff[DECIMAL_MAX_STR_LENGTH+1];
  String str(buff, sizeof(buff), &my_charset_bin);
unknown's avatar
unknown committed
6533
  my_decimal2string(E_DEC_FATAL_ERROR, d, 0, 0, 0, &str);
6534
  return store(str.ptr(), str.length(), str.charset());
unknown's avatar
unknown committed
6535
}
unknown's avatar
unknown committed
6536

6537 6538 6539 6540 6541
uint32 Field_longstr::max_data_length() const
{
  return field_length + (field_length > 255 ? 2 : 1);
}

6542

unknown's avatar
unknown committed
6543 6544
double Field_string::val_real(void)
{
6545
  ASSERT_COLUMN_MARKED_FOR_READ;
6546 6547
  int error;
  char *end;
6548
  CHARSET_INFO *cs= charset();
6549 6550
  double result;
  
6551
  result=  my_strntod(cs,(char*) ptr,field_length,&end,&error);
6552
  if (!table->in_use->no_errors &&
6553 6554 6555
      (error || (field_length != (uint32)(end - (char*) ptr) && 
                 !check_if_only_end_space(cs, end,
                                          (char*) ptr + field_length))))
6556 6557 6558
  {
    char buf[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
    String tmp(buf, sizeof(buf), cs);
6559
    tmp.copy((char*) ptr, field_length, cs);
6560 6561 6562 6563 6564 6565
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_TRUNCATED_WRONG_VALUE, 
                        ER(ER_TRUNCATED_WRONG_VALUE),
                        "DOUBLE", tmp.c_ptr());
  }
  return result;
unknown's avatar
unknown committed
6566 6567 6568 6569 6570
}


longlong Field_string::val_int(void)
{
6571
  ASSERT_COLUMN_MARKED_FOR_READ;
6572 6573 6574 6575 6576
  int error;
  char *end;
  CHARSET_INFO *cs= charset();
  longlong result;

6577
  result= my_strntoll(cs, (char*) ptr,field_length,10,&end,&error);
6578
  if (!table->in_use->no_errors &&
6579 6580 6581
      (error || (field_length != (uint32)(end - (char*) ptr) && 
                 !check_if_only_end_space(cs, end,
                                          (char*) ptr + field_length))))
6582 6583 6584
  {
    char buf[LONGLONG_TO_STRING_CONVERSION_BUFFER_SIZE];
    String tmp(buf, sizeof(buf), cs);
6585
    tmp.copy((char*) ptr, field_length, cs);
6586 6587 6588 6589 6590 6591
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_TRUNCATED_WRONG_VALUE, 
                        ER(ER_TRUNCATED_WRONG_VALUE),
                        "INTEGER", tmp.c_ptr());
  }
  return result;
unknown's avatar
unknown committed
6592 6593 6594 6595 6596 6597
}


String *Field_string::val_str(String *val_buffer __attribute__((unused)),
			      String *val_ptr)
{
6598
  ASSERT_COLUMN_MARKED_FOR_READ;
6599 6600
  /* See the comment for Field_long::store(long long) */
  DBUG_ASSERT(table->in_use == current_thd);
6601 6602 6603 6604 6605
  uint length;
  if (table->in_use->variables.sql_mode &
      MODE_PAD_CHAR_TO_FULL_LENGTH)
    length= my_charpos(field_charset, ptr, ptr + field_length, field_length);
  else
6606 6607
    length= field_charset->cset->lengthsp(field_charset, (const char*) ptr,
                                          field_length);
unknown's avatar
unknown committed
6608
  val_ptr->set((const char*) ptr, length, field_charset);
unknown's avatar
unknown committed
6609 6610 6611 6612
  return val_ptr;
}


unknown's avatar
unknown committed
6613 6614
my_decimal *Field_string::val_decimal(my_decimal *decimal_value)
{
6615
  ASSERT_COLUMN_MARKED_FOR_READ;
6616 6617
  int err= str2my_decimal(E_DEC_FATAL_ERROR, (char*) ptr, field_length,
                          charset(), decimal_value);
6618 6619 6620 6621 6622
  if (!table->in_use->no_errors && err)
  {
    char buf[DECIMAL_TO_STRING_CONVERSION_BUFFER_SIZE];
    CHARSET_INFO *cs= charset();
    String tmp(buf, sizeof(buf), cs);
6623
    tmp.copy((char*) ptr, field_length, cs);
6624 6625 6626 6627 6628 6629
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_TRUNCATED_WRONG_VALUE, 
                        ER(ER_TRUNCATED_WRONG_VALUE),
                        "DECIMAL", tmp.c_ptr());
  }

unknown's avatar
unknown committed
6630 6631 6632 6633
  return decimal_value;
}


6634
int Field_string::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
6635
{
unknown's avatar
unknown committed
6636 6637 6638 6639 6640 6641 6642 6643 6644 6645
  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
6646 6647 6648 6649 6650
  /*
    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,
6651 6652
                                          a_ptr, a_len,
                                          b_ptr, b_len,
6653
                                          0);
unknown's avatar
unknown committed
6654 6655
}

6656

6657
void Field_string::sort_string(uchar *to,uint length)
unknown's avatar
unknown committed
6658
{
unknown's avatar
unknown committed
6659
  IF_DBUG(uint tmp=) my_strnxfrm(field_charset,
6660 6661
                                 to, length,
                                 ptr, field_length);
6662
  DBUG_ASSERT(tmp == length);
unknown's avatar
unknown committed
6663 6664 6665 6666 6667
}


void Field_string::sql_type(String &res) const
{
6668
  THD *thd= table->in_use;
unknown's avatar
unknown committed
6669
  CHARSET_INFO *cs=res.charset();
6670 6671 6672 6673 6674 6675 6676
  ulong length;

  length= cs->cset->snprintf(cs,(char*) res.ptr(),
                             res.alloced_length(), "%s(%d)",
                             ((type() == MYSQL_TYPE_VAR_STRING &&
                               !thd->variables.new_mode) ?
                              (has_charset() ? "varchar" : "varbinary") :
6677
			      (has_charset() ? "char" : "binary")),
6678
                             (int) field_length / charset()->mbmaxlen);
6679
  res.length(length);
6680 6681
  if ((thd->variables.sql_mode & (MODE_MYSQL323 | MODE_MYSQL40)) &&
      has_charset() && (charset()->state & MY_CS_BINSORT))
6682
    res.append(STRING_WITH_LEN(" binary"));
unknown's avatar
unknown committed
6683 6684
}

6685

6686 6687 6688
uchar *Field_string::pack(uchar *to, const uchar *from,
                          uint max_length,
                          bool low_byte_first __attribute__((unused)))
6689
{
unknown's avatar
unknown committed
6690
  uint length=      min(field_length,max_length);
6691 6692 6693 6694 6695
  uint local_char_length= max_length/field_charset->mbmaxlen;
  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);
6696
  while (length && from[length-1] == field_charset->pad_char)
unknown's avatar
unknown committed
6697
    length--;
6698 6699

  // Length always stored little-endian
6700
  *to++= (uchar) length;
6701
  if (field_length > 255)
6702
    *to++= (uchar) (length >> 8);
6703 6704

  // Store the actual bytes of the string
6705 6706
  memcpy(to, from, length);
  return to+length;
6707 6708 6709
}


6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725
/**
   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.

   @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
*/
6726 6727 6728 6729 6730 6731 6732 6733
const uchar *
Field_string::unpack(uchar *to,
                     const uchar *from,
                     uint param_data,
                     bool low_byte_first __attribute__((unused)))
{
  uint from_length=
    param_data ? min(param_data & 0x00ff, field_length) : field_length;
6734
  uint length;
6735 6736

  if (from_length > 255)
6737 6738 6739 6740 6741
  {
    length= uint2korr(from);
    from+= 2;
  }
  else
6742
    length= (uint) *from++;
6743 6744 6745 6746

  memcpy(to, from, length);
  // Pad the string with the pad character of the fields charset
  bfill(to + length, field_length - length, field_charset->pad_char);
unknown's avatar
unknown committed
6747 6748 6749 6750
  return from+length;
}


6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769
/**
   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).

   @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)
{
  *metadata_ptr= real_type();
  *(metadata_ptr + 1)= field_length;
  return 2;
}


6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785
/*
  Compare two packed keys

  SYNOPSIS
    pack_cmp()
     a			New key
     b			Original key
     length		Key length
     insert_or_update	1 if this is an insert or update

  RETURN
    < 0	  a < b
    0	  a = b
    > 0   a > b
*/

6786
int Field_string::pack_cmp(const uchar *a, const uchar *b, uint length,
6787
                           my_bool insert_or_update)
unknown's avatar
unknown committed
6788
{
6789
  uint a_length, b_length;
6790
  if (length > 255)
6791 6792 6793 6794 6795 6796 6797 6798
  {
    a_length= uint2korr(a);
    b_length= uint2korr(b);
    a+= 2;
    b+= 2;
  }
  else
  {
6799 6800
    a_length= (uint) *a++;
    b_length= (uint) *b++;
6801
  }
6802
  return field_charset->coll->strnncollsp(field_charset,
6803 6804
                                          a, a_length,
                                          b, b_length,
6805
                                          insert_or_update);
unknown's avatar
unknown committed
6806 6807 6808
}


6809 6810
/**
  Compare a packed key against row.
6811

6812 6813 6814
  @param key		        Original key
  @param length		Key length. (May be less than field length)
  @param insert_or_update	1 if this is an insert or update
6815

6816
  @return
6817
    < 0	  row < key
6818
  @return
6819
    0	  row = key
6820
  @return
6821 6822 6823
    > 0   row > key
*/

6824
int Field_string::pack_cmp(const uchar *key, uint length,
6825
                           my_bool insert_or_update)
6826
{
6827
  uint row_length, local_key_length;
6828
  uchar *end;
6829
  if (length > 255)
6830
  {
6831
    local_key_length= uint2korr(key);
6832
    key+= 2;
6833 6834
  }
  else
6835
    local_key_length= (uint) *key++;
6836 6837 6838
  
  /* Only use 'length' of key, not field_length */
  end= ptr + length;
6839 6840
  while (end > ptr && end[-1] == ' ')
    end--;
6841 6842 6843
  row_length= (uint) (end - ptr);

  return field_charset->coll->strnncollsp(field_charset,
6844 6845
                                          ptr, row_length,
                                          key, local_key_length,
6846
                                          insert_or_update);
6847 6848 6849
}


6850
uint Field_string::packed_col_length(const uchar *data_ptr, uint length)
unknown's avatar
unknown committed
6851
{
6852
  if (length > 255)
6853
    return uint2korr(data_ptr)+2;
6854
  return (uint) *data_ptr + 1;
unknown's avatar
unknown committed
6855 6856
}

6857

unknown's avatar
unknown committed
6858 6859
uint Field_string::max_packed_col_length(uint max_length)
{
6860
  return (max_length > 255 ? 2 : 1)+max_length;
unknown's avatar
unknown committed
6861 6862
}

6863 6864

uint Field_string::get_key_image(uchar *buff, uint length, imagetype type_arg)
unknown's avatar
unknown committed
6865
{
6866 6867
  uint bytes = my_charpos(field_charset, (char*) ptr,
                          (char*) ptr + field_length,
unknown's avatar
unknown committed
6868 6869 6870
                          length / field_charset->mbmaxlen);
  memcpy(buff, ptr, bytes);
  if (bytes < length)
6871 6872
    field_charset->cset->fill(field_charset, (char*) buff + bytes,
                              length - bytes, field_charset->pad_char);
unknown's avatar
unknown committed
6873 6874
  return bytes;
}
unknown's avatar
unknown committed
6875

6876

6877 6878
Field *Field_string::new_field(MEM_ROOT *root, struct st_table *new_table,
                               bool keep_type)
6879
{
unknown's avatar
unknown committed
6880
  Field *field;
6881
  if (type() != MYSQL_TYPE_VAR_STRING || keep_type)
unknown's avatar
unknown committed
6882
    field= Field::new_field(root, new_table, keep_type);
6883 6884
  else if ((field= new Field_varstring(field_length, maybe_null(), field_name,
                                       new_table->s, charset())))
6885 6886 6887 6888 6889 6890
  {
    /*
      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
6891
    field->init(new_table);
6892 6893 6894 6895 6896 6897
    /*
      Normally orig_table is different from table only if field was created
      via ::new_field.  Here we alter the type of field, so ::new_field is
      not applicable. But we still need to preserve the original field
      metadata for the client-server protocol.
    */
unknown's avatar
unknown committed
6898
    field->orig_table= orig_table;
6899
  }
unknown's avatar
unknown committed
6900
  return field;
6901 6902
}

unknown's avatar
unknown committed
6903

unknown's avatar
unknown committed
6904
/****************************************************************************
6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917
  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
6918 6919
****************************************************************************/

unknown's avatar
unknown committed
6920
const uint Field_varstring::MAX_SIZE= UINT_MAX16;
unknown's avatar
unknown committed
6921

6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935
/**
   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)
{
  char *ptr= (char *)metadata_ptr;
6936
  DBUG_ASSERT(field_length <= 65535);
6937 6938 6939 6940
  int2store(ptr, field_length);
  return 2;
}

unknown's avatar
unknown committed
6941
int Field_varstring::store(const char *from,uint length,CHARSET_INFO *cs)
unknown's avatar
unknown committed
6942
{
6943
  ASSERT_COLUMN_MARKED_FOR_WRITE;
6944 6945 6946 6947 6948 6949
  uint copy_length;
  const char *well_formed_error_pos;
  const char *cannot_convert_error_pos;
  const char *from_end_pos;

  copy_length= well_formed_copy_nchars(field_charset,
6950 6951
                                       (char*) ptr + length_bytes,
                                       field_length,
6952 6953 6954 6955 6956
                                       cs, from, length,
                                       field_length / field_charset->mbmaxlen,
                                       &well_formed_error_pos,
                                       &cannot_convert_error_pos,
                                       &from_end_pos);
unknown's avatar
unknown committed
6957

6958 6959 6960 6961
  if (length_bytes == 1)
    *ptr= (uchar) copy_length;
  else
    int2store(ptr, copy_length);
6962

6963
  if (check_string_copy_error(this, well_formed_error_pos,
6964
                              cannot_convert_error_pos, from + length, cs))
6965 6966
    return 2;

6967
  // Check if we lost something other than just trailing spaces
6968
  if ((from_end_pos < from + length) && table->in_use->count_cuted_fields)
6969
  {
6970 6971 6972 6973
    if (test_if_important_data(field_charset, from_end_pos, from + length))
      report_data_too_long(this);
    else /* If we lost only spaces then produce a NOTE, not a WARNING */
      set_warning(MYSQL_ERROR::WARN_LEVEL_NOTE, WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
6974
    return 2;
6975
  }
unknown's avatar
unknown committed
6976
  return 0;
unknown's avatar
unknown committed
6977 6978 6979
}


6980
int Field_varstring::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
6981
{
unknown's avatar
unknown committed
6982
  char buff[64];
6983 6984 6985 6986
  uint  length;
  length= (uint) (field_charset->cset->longlong10_to_str)(field_charset,
                                                          buff,
                                                          sizeof(buff),
6987 6988 6989
                                                          (unsigned_val ? 10:
                                                           -10),
                                                           nr);
6990
  return Field_varstring::store(buff, length, field_charset);
unknown's avatar
unknown committed
6991 6992 6993 6994 6995
}


double Field_varstring::val_real(void)
{
6996
  ASSERT_COLUMN_MARKED_FOR_READ;
6997
  int not_used;
6998
  char *end_not_used;
6999 7000 7001
  uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
  return my_strntod(field_charset, (char*) ptr+length_bytes, length,
                    &end_not_used, &not_used);
unknown's avatar
unknown committed
7002 7003 7004 7005 7006
}


longlong Field_varstring::val_int(void)
{
7007
  ASSERT_COLUMN_MARKED_FOR_READ;
7008
  int not_used;
7009
  char *end_not_used;
7010 7011
  uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
  return my_strntoll(field_charset, (char*) ptr+length_bytes, length, 10,
7012
                     &end_not_used, &not_used);
unknown's avatar
unknown committed
7013 7014 7015 7016 7017
}

String *Field_varstring::val_str(String *val_buffer __attribute__((unused)),
				 String *val_ptr)
{
7018
  ASSERT_COLUMN_MARKED_FOR_READ;
7019
  uint length=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7020
  val_ptr->set((const char*) ptr+length_bytes, length, field_charset);
unknown's avatar
unknown committed
7021 7022 7023 7024
  return val_ptr;
}


unknown's avatar
unknown committed
7025 7026
my_decimal *Field_varstring::val_decimal(my_decimal *decimal_value)
{
7027
  ASSERT_COLUMN_MARKED_FOR_READ;
7028 7029 7030
  uint length= length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
  str2my_decimal(E_DEC_FATAL_ERROR, (char*) ptr+length_bytes, length,
                 charset(), decimal_value);
unknown's avatar
unknown committed
7031 7032 7033 7034
  return decimal_value;
}


7035
int Field_varstring::cmp_max(const uchar *a_ptr, const uchar *b_ptr,
7036
                             uint max_len)
unknown's avatar
unknown committed
7037
{
7038
  uint a_length, b_length;
unknown's avatar
unknown committed
7039
  int diff;
7040 7041 7042

  if (length_bytes == 1)
  {
7043 7044
    a_length= (uint) *a_ptr;
    b_length= (uint) *b_ptr;
7045 7046 7047 7048 7049 7050
  }
  else
  {
    a_length= uint2korr(a_ptr);
    b_length= uint2korr(b_ptr);
  }
7051 7052
  set_if_smaller(a_length, max_len);
  set_if_smaller(b_length, max_len);
7053
  diff= field_charset->coll->strnncollsp(field_charset,
7054
                                         a_ptr+
7055
                                         length_bytes,
7056
                                         a_length,
7057
                                         b_ptr+
7058
                                         length_bytes,
7059 7060
                                         b_length,0);
  return diff;
unknown's avatar
unknown committed
7061 7062
}

7063

7064 7065 7066
/**
  @note
    varstring and blob keys are ALWAYS stored with a 2 byte length prefix
7067 7068
*/

7069
int Field_varstring::key_cmp(const uchar *key_ptr, uint max_key_length)
7070
{
7071
  uint length=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7072
  uint local_char_length= max_key_length / field_charset->mbmaxlen;
7073

7074 7075 7076
  local_char_length= my_charpos(field_charset, ptr + length_bytes,
                          ptr + length_bytes + length, local_char_length);
  set_if_smaller(length, local_char_length);
7077
  return field_charset->coll->strnncollsp(field_charset, 
7078
                                          ptr + length_bytes,
7079
                                          length,
7080
                                          key_ptr+
7081 7082
                                          HA_KEY_BLOB_LENGTH,
                                          uint2korr(key_ptr), 0);
unknown's avatar
unknown committed
7083 7084
}

7085

7086 7087
/**
  Compare to key segments (always 2 byte length prefix).
7088

7089
  @note
7090 7091 7092 7093
    This is used only to compare key segments created for index_read().
    (keys are created and compared in key.cc)
*/

7094
int Field_varstring::key_cmp(const uchar *a,const uchar *b)
7095
{
7096
  return field_charset->coll->strnncollsp(field_charset,
7097
                                          a + HA_KEY_BLOB_LENGTH,
7098
                                          uint2korr(a),
7099
                                          b + HA_KEY_BLOB_LENGTH,
7100 7101
                                          uint2korr(b),
                                          0);
7102 7103 7104
}


7105
void Field_varstring::sort_string(uchar *to,uint length)
unknown's avatar
unknown committed
7106
{
7107
  uint tot_length=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118

  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;
  }
 
7119
  tot_length= my_strnxfrm(field_charset,
7120
			  to, length, ptr + length_bytes,
7121
			  tot_length);
unknown's avatar
unknown committed
7122
  DBUG_ASSERT(tot_length == length);
unknown's avatar
unknown committed
7123 7124 7125
}


7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137
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
7138 7139
void Field_varstring::sql_type(String &res) const
{
7140
  THD *thd= table->in_use;
unknown's avatar
unknown committed
7141
  CHARSET_INFO *cs=res.charset();
7142 7143 7144 7145 7146 7147
  ulong length;

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

7154

7155
uint32 Field_varstring::data_length()
7156
{
7157
  return length_bytes == 1 ? (uint32) *ptr : uint2korr(ptr);
7158 7159
}

7160 7161 7162 7163 7164
/*
  Functions to create a packed row.
  Here the number of length bytes are depending on the given max_length
*/

7165 7166 7167
uchar *Field_varstring::pack(uchar *to, const uchar *from,
                             uint max_length,
                             bool low_byte_first __attribute__((unused)))
unknown's avatar
unknown committed
7168
{
7169
  uint length= length_bytes == 1 ? (uint) *from : uint2korr(from);
7170
  set_if_smaller(max_length, field_length);
unknown's avatar
unknown committed
7171 7172
  if (length > max_length)
    length=max_length;
7173 7174 7175

  /* Length always stored little-endian */
  *to++= length & 0xFF;
unknown's avatar
unknown committed
7176
  if (max_length > 255)
7177 7178 7179 7180
    *to++= (length >> 8) & 0xFF;

  /* Store bytes of string */
  if (length > 0)
7181
    memcpy(to, from+length_bytes, length);
unknown's avatar
unknown committed
7182 7183 7184 7185
  return to+length;
}


7186 7187 7188
uchar *
Field_varstring::pack_key(uchar *to, const uchar *key, uint max_length,
                          bool low_byte_first __attribute__((unused)))
7189
{
7190
  uint length=  length_bytes == 1 ? (uint) *key : uint2korr(key);
7191
  uint local_char_length= ((field_charset->mbmaxlen > 1) ?
7192
                     max_length/field_charset->mbmaxlen : max_length);
7193
  key+= length_bytes;
7194
  if (length > local_char_length)
7195
  {
7196 7197 7198
    local_char_length= my_charpos(field_charset, key, key+length,
                                  local_char_length);
    set_if_smaller(length, local_char_length);
7199
  }
7200 7201 7202 7203
  *to++= (char) (length & 255);
  if (max_length > 255)
    *to++= (char) (length >> 8);
  if (length)
7204 7205 7206 7207 7208
    memcpy(to, key, length);
  return to+length;
}


7209
/**
7210 7211
  Unpack a key into a record buffer.

7212 7213 7214
  A VARCHAR key has a maximum size of 64K-1.
  In its packed form, the length field is one or two bytes long,
  depending on 'max_length'.
7215

7216 7217 7218
  @param to                          Pointer into the record buffer.
  @param key                         Pointer to the packed key.
  @param max_length                  Key length limit from key description.
7219

7220
  @return
7221 7222 7223
    Pointer to end of 'key' (To the next key part if multi-segment key)
*/

7224 7225 7226
const uchar *
Field_varstring::unpack_key(uchar *to, const uchar *key, uint max_length,
                            bool low_byte_first __attribute__((unused)))
7227 7228
{
  /* get length of the blob key */
7229
  uint32 length= *key++;
7230
  if (max_length > 255)
7231
    length+= (*key++) << 8;
7232 7233 7234 7235 7236 7237 7238 7239 7240 7241

  /* put the length into the record buffer */
  if (length_bytes == 1)
    *ptr= (uchar) length;
  else
    int2store(ptr, length);
  memcpy(ptr + length_bytes, key, length);
  return key + length;
}

7242 7243
/**
  Create a packed key that will be used for storage in the index tree.
7244

7245 7246 7247
  @param to		Store packed key segment here
  @param from		Key segment (as given to index_read())
  @param max_length  	Max length of key
7248

7249
  @return
7250 7251 7252
    end of key storage
*/

7253 7254 7255
uchar *
Field_varstring::pack_key_from_key_image(uchar *to, const uchar *from, uint max_length,
                                         bool low_byte_first __attribute__((unused)))
7256 7257 7258 7259 7260 7261 7262 7263 7264 7265
{
  /* Key length is always stored as 2 bytes */
  uint length= uint2korr(from);
  if (length > max_length)
    length= max_length;
  *to++= (char) (length & 255);
  if (max_length > 255)
    *to++= (char) (length >> 8);
  if (length)
    memcpy(to, from+HA_KEY_BLOB_LENGTH, length);
7266 7267 7268 7269
  return to+length;
}


7270 7271 7272 7273 7274
/**
   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.
7275 7276 7277

   @note
   The string length is always packed little-endian.
7278 7279 7280 7281 7282 7283 7284
  
   @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
*/
7285 7286 7287 7288
const uchar *
Field_varstring::unpack(uchar *to, const uchar *from,
                        uint param_data,
                        bool low_byte_first __attribute__((unused)))
7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299
{
  uint length;
  uint l_bytes= (param_data && (param_data < field_length)) ? 
                (param_data <= 255) ? 1 : 2 : length_bytes;
  if (l_bytes == 1)
  {
    to[0]= *from++;
    length= to[0];
    if (length_bytes == 2)
      to[1]= 0;
  }
7300
  else /* l_bytes == 2 */
unknown's avatar
unknown committed
7301
  {
7302 7303 7304
    length= uint2korr(from);
    to[0]= *from++;
    to[1]= *from++;
unknown's avatar
unknown committed
7305 7306
  }
  if (length)
7307
    memcpy(to+ length_bytes, from, length);
unknown's avatar
unknown committed
7308 7309 7310 7311
  return from+length;
}


7312
int Field_varstring::pack_cmp(const uchar *a, const uchar *b,
7313
                              uint key_length_arg,
7314
                              my_bool insert_or_update)
unknown's avatar
unknown committed
7315
{
7316
  uint a_length, b_length;
7317
  if (key_length_arg > 255)
unknown's avatar
unknown committed
7318
  {
7319 7320
    a_length=uint2korr(a); a+= 2;
    b_length=uint2korr(b); b+= 2;
unknown's avatar
unknown committed
7321 7322 7323
  }
  else
  {
7324 7325
    a_length= (uint) *a++;
    b_length= (uint) *b++;
unknown's avatar
unknown committed
7326
  }
7327
  return field_charset->coll->strnncollsp(field_charset,
7328 7329
                                          a, a_length,
                                          b, b_length,
7330
                                          insert_or_update);
unknown's avatar
unknown committed
7331 7332
}

7333

7334
int Field_varstring::pack_cmp(const uchar *b, uint key_length_arg,
7335
                              my_bool insert_or_update)
7336
{
7337 7338
  uchar *a= ptr+ length_bytes;
  uint a_length=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7339
  uint b_length;
7340 7341 7342
  uint local_char_length= ((field_charset->mbmaxlen > 1) ?
                           key_length_arg / field_charset->mbmaxlen :
                           key_length_arg);
7343

7344
  if (key_length_arg > 255)
7345
  {
7346
    b_length=uint2korr(b); b+= HA_KEY_BLOB_LENGTH;
7347 7348
  }
  else
7349
    b_length= (uint) *b++;
7350

7351
  if (a_length > local_char_length)
7352
  {
7353 7354 7355
    local_char_length= my_charpos(field_charset, a, a+a_length,
                                  local_char_length);
    set_if_smaller(a_length, local_char_length);
7356
  }
7357 7358

  return field_charset->coll->strnncollsp(field_charset,
7359 7360
                                          a, a_length,
                                          b, b_length,
7361
                                          insert_or_update);
7362 7363
}

7364

7365
uint Field_varstring::packed_col_length(const uchar *data_ptr, uint length)
unknown's avatar
unknown committed
7366
{
7367
  if (length > 255)
7368
    return uint2korr(data_ptr)+2;
7369
  return (uint) *data_ptr + 1;
unknown's avatar
unknown committed
7370 7371
}

7372

unknown's avatar
unknown committed
7373 7374
uint Field_varstring::max_packed_col_length(uint max_length)
{
7375
  return (max_length > 255 ? 2 : 1)+max_length;
unknown's avatar
unknown committed
7376 7377
}

7378
uint Field_varstring::get_key_image(uchar *buff, uint length, imagetype type)
7379
{
7380
  uint f_length=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7381
  uint local_char_length= length / field_charset->mbmaxlen;
7382
  uchar *pos= ptr+length_bytes;
7383 7384 7385
  local_char_length= my_charpos(field_charset, pos, pos + f_length,
                                local_char_length);
  set_if_smaller(f_length, local_char_length);
7386
  /* Key is always stored with 2 bytes */
7387
  int2store(buff,f_length);
7388
  memcpy(buff+HA_KEY_BLOB_LENGTH, pos, f_length);
7389
  if (f_length < length)
7390 7391 7392 7393 7394
  {
    /*
      Must clear this as we do a memcmp in opt_range.cc to detect
      identical keys
    */
7395
    bzero(buff+HA_KEY_BLOB_LENGTH+f_length, (length-f_length));
7396
  }
unknown's avatar
unknown committed
7397
  return HA_KEY_BLOB_LENGTH+f_length;
7398 7399
}

7400

7401
void Field_varstring::set_key_image(const uchar *buff,uint length)
7402
{
7403
  length= uint2korr(buff);			// Real length is here
7404
  (void) Field_varstring::store((const char*) buff+HA_KEY_BLOB_LENGTH, length,
7405
                                field_charset);
7406 7407 7408
}


7409
int Field_varstring::cmp_binary(const uchar *a_ptr, const uchar *b_ptr,
7410 7411 7412 7413
                                uint32 max_length)
{
  uint32 a_length,b_length;

7414 7415
  if (length_bytes == 1)
  {
7416 7417
    a_length= (uint) *a_ptr;
    b_length= (uint) *b_ptr;
7418 7419 7420 7421 7422 7423
  }
  else
  {
    a_length= uint2korr(a_ptr);
    b_length= uint2korr(b_ptr);
  }
7424 7425 7426 7427
  set_if_smaller(a_length, max_length);
  set_if_smaller(b_length, max_length);
  if (a_length != b_length)
    return 1;
7428 7429 7430 7431
  return memcmp(a_ptr+length_bytes, b_ptr+length_bytes, a_length);
}


7432 7433
Field *Field_varstring::new_field(MEM_ROOT *root, struct st_table *new_table,
                                  bool keep_type)
7434
{
7435 7436
  Field_varstring *res= (Field_varstring*) Field::new_field(root, new_table,
                                                            keep_type);
7437 7438 7439 7440 7441 7442 7443
  if (res)
    res->length_bytes= length_bytes;
  return res;
}


Field *Field_varstring::new_key_field(MEM_ROOT *root,
unknown's avatar
unknown committed
7444
                                      struct st_table *new_table,
7445
                                      uchar *new_ptr, uchar *new_null_ptr,
unknown's avatar
unknown committed
7446 7447 7448 7449 7450 7451 7452 7453 7454 7455
                                      uint new_null_bit)
{
  Field_varstring *res;
  if ((res= (Field_varstring*) Field::new_key_field(root,
                                                    new_table,
                                                    new_ptr,
                                                    new_null_ptr,
                                                    new_null_bit)))
  {
    /* Keys length prefixes are always packed with 2 bytes */
7456
    res->length_bytes= 2;
unknown's avatar
unknown committed
7457
  }
7458
  return res;
7459 7460
}

7461

unknown's avatar
unknown committed
7462
uint Field_varstring::is_equal(Create_field *new_field)
unknown's avatar
unknown committed
7463
{
7464
  if (new_field->sql_type == real_type() &&
unknown's avatar
unknown committed
7465 7466
      new_field->charset == field_charset)
  {
unknown's avatar
unknown committed
7467
    if (new_field->length == max_display_length())
unknown's avatar
unknown committed
7468
      return IS_EQUAL_YES;
unknown's avatar
unknown committed
7469 7470 7471
    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
7472 7473 7474 7475 7476 7477
      return IS_EQUAL_PACK_LENGTH; // VARCHAR, longer variable length
  }
  return IS_EQUAL_NO;
}


7478 7479 7480 7481 7482 7483 7484 7485
void Field_varstring::hash(ulong *nr, ulong *nr2)
{
  if (is_null())
  {
    *nr^= (*nr << 1) | 1;
  }
  else
  {
7486
    uint len=  length_bytes == 1 ? (uint) *ptr : uint2korr(ptr);
7487
    CHARSET_INFO *cs= charset();
7488
    cs->coll->hash_sort(cs, ptr + length_bytes, len, nr, nr2);
7489 7490 7491 7492
  }
}


unknown's avatar
unknown committed
7493 7494 7495 7496 7497 7498
/****************************************************************************
** 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.
****************************************************************************/

7499
Field_blob::Field_blob(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
unknown's avatar
unknown committed
7500
		       enum utype unireg_check_arg, const char *field_name_arg,
unknown's avatar
unknown committed
7501
                       TABLE_SHARE *share, uint blob_pack_length,
7502
		       CHARSET_INFO *cs)
7503
  :Field_longstr(ptr_arg, BLOB_PACK_LENGTH_TO_MAX_LENGH(blob_pack_length),
unknown's avatar
unknown committed
7504 7505
                 null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg,
                 cs),
unknown's avatar
unknown committed
7506
   packlength(blob_pack_length)
unknown's avatar
unknown committed
7507 7508
{
  flags|= BLOB_FLAG;
unknown's avatar
unknown committed
7509
  share->blob_fields++;
7510
  /* TODO: why do not fill table->s->blob_field array here? */
unknown's avatar
unknown committed
7511 7512 7513
}


7514 7515 7516 7517
void Field_blob::store_length(uchar *i_ptr, 
                              uint i_packlength, 
                              uint32 i_number, 
                              bool low_byte_first)
unknown's avatar
unknown committed
7518
{
unknown's avatar
unknown committed
7519
  switch (i_packlength) {
unknown's avatar
unknown committed
7520
  case 1:
unknown's avatar
unknown committed
7521
    i_ptr[0]= (uchar) i_number;
unknown's avatar
unknown committed
7522 7523 7524
    break;
  case 2:
#ifdef WORDS_BIGENDIAN
7525
    if (low_byte_first)
unknown's avatar
unknown committed
7526
    {
unknown's avatar
unknown committed
7527
      int2store(i_ptr,(unsigned short) i_number);
unknown's avatar
unknown committed
7528 7529 7530
    }
    else
#endif
unknown's avatar
unknown committed
7531
      shortstore(i_ptr,(unsigned short) i_number);
unknown's avatar
unknown committed
7532 7533
    break;
  case 3:
unknown's avatar
unknown committed
7534
    int3store(i_ptr,i_number);
unknown's avatar
unknown committed
7535 7536 7537
    break;
  case 4:
#ifdef WORDS_BIGENDIAN
7538
    if (low_byte_first)
unknown's avatar
unknown committed
7539
    {
unknown's avatar
unknown committed
7540
      int4store(i_ptr,i_number);
unknown's avatar
unknown committed
7541 7542 7543
    }
    else
#endif
unknown's avatar
unknown committed
7544
      longstore(i_ptr,i_number);
unknown's avatar
unknown committed
7545 7546 7547 7548
  }
}


7549
uint32 Field_blob::get_length(const uchar *pos, uint packlength_arg, bool low_byte_first)
unknown's avatar
unknown committed
7550
{
7551
  switch (packlength_arg) {
unknown's avatar
unknown committed
7552
  case 1:
7553
    return (uint32) pos[0];
unknown's avatar
unknown committed
7554 7555 7556 7557
  case 2:
    {
      uint16 tmp;
#ifdef WORDS_BIGENDIAN
7558
      if (low_byte_first)
unknown's avatar
unknown committed
7559 7560 7561 7562
	tmp=sint2korr(pos);
      else
#endif
	shortget(tmp,pos);
unknown's avatar
unknown committed
7563
      return (uint32) tmp;
unknown's avatar
unknown committed
7564 7565
    }
  case 3:
unknown's avatar
unknown committed
7566
    return (uint32) uint3korr(pos);
unknown's avatar
unknown committed
7567 7568 7569 7570
  case 4:
    {
      uint32 tmp;
#ifdef WORDS_BIGENDIAN
7571
      if (low_byte_first)
unknown's avatar
unknown committed
7572 7573 7574 7575
	tmp=uint4korr(pos);
      else
#endif
	longget(tmp,pos);
unknown's avatar
unknown committed
7576
      return (uint32) tmp;
unknown's avatar
unknown committed
7577 7578 7579 7580 7581 7582
    }
  }
  return 0;					// Impossible
}


7583
/**
7584 7585
  Put a blob length field into a record buffer.

7586 7587 7588
  Depending on the maximum length of a blob, its length field is
  put into 1 to 4 bytes. This is a property of the blob object,
  described by 'packlength'.
7589

7590 7591
  @param pos                 Pointer into the record buffer.
  @param length              The length value to put.
7592 7593
*/

7594
void Field_blob::put_length(uchar *pos, uint32 length)
7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612
{
  switch (packlength) {
  case 1:
    *pos= (char) length;
    break;
  case 2:
    int2store(pos, length);
    break;
  case 3:
    int3store(pos, length);
    break;
  case 4:
    int4store(pos, length);
    break;
  }
}


unknown's avatar
unknown committed
7613
int Field_blob::store(const char *from,uint length,CHARSET_INFO *cs)
unknown's avatar
unknown committed
7614
{
7615
  ASSERT_COLUMN_MARKED_FOR_WRITE;
7616 7617 7618 7619 7620 7621 7622
  uint copy_length, new_length;
  const char *well_formed_error_pos;
  const char *cannot_convert_error_pos;
  const char *from_end_pos, *tmp;
  char buff[STRING_BUFFER_USUAL_SIZE];
  String tmpstr(buff,sizeof(buff), &my_charset_bin);

unknown's avatar
unknown committed
7623
  if (!length)
unknown's avatar
unknown committed
7624 7625
  {
    bzero(ptr,Field_blob::pack_length());
7626
    return 0;
unknown's avatar
unknown committed
7627
  }
unknown's avatar
unknown committed
7628

7629 7630 7631 7632 7633 7634 7635 7636
  if (from == value.ptr())
  {
    uint32 dummy_offset;
    if (!String::needs_conversion(length, cs, field_charset, &dummy_offset))
    {
      Field_blob::store_length(length);
      bmove(ptr+packlength,(char*) &from,sizeof(char*));
      return 0;
unknown's avatar
unknown committed
7637
    }
7638 7639 7640
    if (tmpstr.copy(from, length, cs))
      goto oom_error;
    from= tmpstr.ptr();
unknown's avatar
unknown committed
7641
  }
7642 7643 7644 7645 7646

  new_length= min(max_data_length(), field_charset->mbmaxlen * length);
  if (value.alloc(new_length))
    goto oom_error;

7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657

  if (f_is_hex_escape(flags))
  {
    copy_length= my_copy_with_hex_escaping(field_charset,
                                           (char*) value.ptr(), new_length,
                                            from, length);
    Field_blob::store_length(copy_length);
    tmp= value.ptr();
    bmove(ptr + packlength, (uchar*) &tmp, sizeof(char*));
    return 0;
  }
7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672
  /*
    "length" is OK as "nchars" argument to well_formed_copy_nchars as this
    is never used to limit the length of the data. The cut of long data
    is done with the new_length value.
  */
  copy_length= well_formed_copy_nchars(field_charset,
                                       (char*) value.ptr(), new_length,
                                       cs, from, length,
                                       length,
                                       &well_formed_error_pos,
                                       &cannot_convert_error_pos,
                                       &from_end_pos);

  Field_blob::store_length(copy_length);
  tmp= value.ptr();
7673
  bmove(ptr+packlength,(uchar*) &tmp,sizeof(char*));
7674 7675

  if (check_string_copy_error(this, well_formed_error_pos,
7676
                              cannot_convert_error_pos, from + length, cs))
7677 7678
    return 2;

7679
  if (from_end_pos < from + length)
7680
  {
7681 7682
    report_data_too_long(this);
    return 2;
7683
  }
7684

7685
  return 0;
7686 7687 7688 7689 7690

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


unknown's avatar
unknown committed
7694
int Field_blob::store(double nr)
unknown's avatar
unknown committed
7695
{
7696
  CHARSET_INFO *cs=charset();
7697
  value.set_real(nr, 2, cs);
7698
  return Field_blob::store(value.ptr(),(uint) value.length(), cs);
unknown's avatar
unknown committed
7699 7700 7701
}


7702
int Field_blob::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
7703
{
7704
  CHARSET_INFO *cs=charset();
7705
  value.set_int(nr, unsigned_val, cs);
7706
  return Field_blob::store(value.ptr(), (uint) value.length(), cs);
unknown's avatar
unknown committed
7707 7708
}

7709

unknown's avatar
unknown committed
7710 7711
double Field_blob::val_real(void)
{
7712
  ASSERT_COLUMN_MARKED_FOR_READ;
7713
  int not_used;
7714 7715 7716 7717
  char *end_not_used, *blob;
  uint32 length;
  CHARSET_INFO *cs;

unknown's avatar
unknown committed
7718 7719 7720
  memcpy_fixed(&blob,ptr+packlength,sizeof(char*));
  if (!blob)
    return 0.0;
7721 7722
  length= get_length(ptr);
  cs= charset();
unknown's avatar
unknown committed
7723
  return my_strntod(cs, blob, length, &end_not_used, &not_used);
unknown's avatar
unknown committed
7724 7725 7726 7727 7728
}


longlong Field_blob::val_int(void)
{
7729
  ASSERT_COLUMN_MARKED_FOR_READ;
7730
  int not_used;
unknown's avatar
unknown committed
7731 7732 7733 7734
  char *blob;
  memcpy_fixed(&blob,ptr+packlength,sizeof(char*));
  if (!blob)
    return 0;
unknown's avatar
unknown committed
7735
  uint32 length=get_length(ptr);
7736
  return my_strntoll(charset(),blob,length,10,NULL,&not_used);
unknown's avatar
unknown committed
7737 7738 7739 7740 7741
}

String *Field_blob::val_str(String *val_buffer __attribute__((unused)),
			    String *val_ptr)
{
7742
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
7743 7744 7745
  char *blob;
  memcpy_fixed(&blob,ptr+packlength,sizeof(char*));
  if (!blob)
7746
    val_ptr->set("",0,charset());	// A bit safer than ->length(0)
unknown's avatar
unknown committed
7747
  else
7748
    val_ptr->set((const char*) blob,get_length(ptr),charset());
unknown's avatar
unknown committed
7749 7750 7751 7752
  return val_ptr;
}


unknown's avatar
unknown committed
7753 7754
my_decimal *Field_blob::val_decimal(my_decimal *decimal_value)
{
7755
  ASSERT_COLUMN_MARKED_FOR_READ;
7756
  const char *blob;
7757 7758
  size_t length;
  memcpy_fixed(&blob, ptr+packlength, sizeof(const uchar*));
unknown's avatar
unknown committed
7759
  if (!blob)
7760
  {
unknown's avatar
unknown committed
7761
    blob= "";
7762 7763 7764 7765 7766 7767
    length= 0;
  }
  else
    length= get_length(ptr);

  str2my_decimal(E_DEC_FATAL_ERROR, blob, length, charset(),
unknown's avatar
unknown committed
7768 7769 7770 7771 7772
                 decimal_value);
  return decimal_value;
}


7773
int Field_blob::cmp(const uchar *a,uint32 a_length, const uchar *b,
unknown's avatar
unknown committed
7774
		    uint32 b_length)
unknown's avatar
unknown committed
7775
{
7776
  return field_charset->coll->strnncollsp(field_charset, 
7777
                                          a, a_length, b, b_length,
7778
                                          0);
unknown's avatar
unknown committed
7779 7780 7781
}


7782
int Field_blob::cmp_max(const uchar *a_ptr, const uchar *b_ptr,
7783
                        uint max_length)
unknown's avatar
unknown committed
7784
{
7785
  uchar *blob1,*blob2;
unknown's avatar
unknown committed
7786 7787
  memcpy_fixed(&blob1,a_ptr+packlength,sizeof(char*));
  memcpy_fixed(&blob2,b_ptr+packlength,sizeof(char*));
7788 7789 7790 7791
  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
7792 7793 7794
}


7795
int Field_blob::cmp_binary(const uchar *a_ptr, const uchar *b_ptr,
unknown's avatar
unknown committed
7796
			   uint32 max_length)
unknown's avatar
unknown committed
7797 7798 7799
{
  char *a,*b;
  uint diff;
unknown's avatar
unknown committed
7800
  uint32 a_length,b_length;
unknown's avatar
unknown committed
7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815
  memcpy_fixed(&a,a_ptr+packlength,sizeof(char*));
  memcpy_fixed(&b,b_ptr+packlength,sizeof(char*));
  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;
  diff=memcmp(a,b,min(a_length,b_length));
  return diff ? diff : (int) (a_length - b_length);
}


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

7816
uint Field_blob::get_key_image(uchar *buff,uint length, imagetype type_arg)
unknown's avatar
unknown committed
7817
{
unknown's avatar
unknown committed
7818
  uint32 blob_length= get_length(ptr);
7819
  uchar *blob;
unknown's avatar
unknown committed
7820

unknown's avatar
unknown committed
7821
#ifdef HAVE_SPATIAL
7822
  if (type_arg == itMBR)
unknown's avatar
unknown committed
7823
  {
unknown's avatar
unknown committed
7824
    const char *dummy;
unknown's avatar
unknown committed
7825
    MBR mbr;
7826 7827
    Geometry_buffer buffer;
    Geometry *gobj;
unknown's avatar
unknown committed
7828
    const uint image_length= SIZEOF_STORED_DOUBLE*4;
unknown's avatar
unknown committed
7829 7830 7831

    if (blob_length < SRID_SIZE)
    {
unknown's avatar
unknown committed
7832 7833
      bzero(buff, image_length);
      return image_length;
unknown's avatar
unknown committed
7834 7835
    }
    get_ptr(&blob);
7836
    gobj= Geometry::construct(&buffer, (char*) blob, blob_length);
7837
    if (!gobj || gobj->get_mbr(&mbr, &dummy))
unknown's avatar
unknown committed
7838
      bzero(buff, image_length);
unknown's avatar
unknown committed
7839 7840 7841 7842 7843 7844 7845
    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
7846
    return image_length;
unknown's avatar
unknown committed
7847
  }
unknown's avatar
unknown committed
7848
#endif /*HAVE_SPATIAL*/
unknown's avatar
unknown committed
7849

7850
  get_ptr(&blob);
7851 7852 7853 7854
  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);
7855

unknown's avatar
unknown committed
7856
  if ((uint32) length > blob_length)
unknown's avatar
unknown committed
7857
  {
7858 7859 7860 7861
    /*
      Must clear this as we do a memcmp in opt_range.cc to detect
      identical keys
    */
7862
    bzero(buff+HA_KEY_BLOB_LENGTH+blob_length, (length-blob_length));
unknown's avatar
unknown committed
7863
    length=(uint) blob_length;
unknown's avatar
unknown committed
7864
  }
unknown's avatar
unknown committed
7865
  int2store(buff,length);
7866
  memcpy(buff+HA_KEY_BLOB_LENGTH, blob, length);
unknown's avatar
unknown committed
7867
  return HA_KEY_BLOB_LENGTH+length;
unknown's avatar
unknown committed
7868 7869
}

7870

7871
void Field_blob::set_key_image(const uchar *buff,uint length)
unknown's avatar
unknown committed
7872
{
7873
  length= uint2korr(buff);
7874 7875
  (void) Field_blob::store((const char*) buff+HA_KEY_BLOB_LENGTH, length,
                           field_charset);
unknown's avatar
unknown committed
7876 7877
}

unknown's avatar
unknown committed
7878

7879
int Field_blob::key_cmp(const uchar *key_ptr, uint max_key_length)
unknown's avatar
unknown committed
7880
{
7881
  uchar *blob1;
unknown's avatar
unknown committed
7882 7883
  uint blob_length=get_length(ptr);
  memcpy_fixed(&blob1,ptr+packlength,sizeof(char*));
7884
  CHARSET_INFO *cs= charset();
7885 7886 7887 7888
  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);
7889
  return Field_blob::cmp(blob1, blob_length,
7890
			 key_ptr+HA_KEY_BLOB_LENGTH,
7891
			 uint2korr(key_ptr));
unknown's avatar
unknown committed
7892 7893
}

7894
int Field_blob::key_cmp(const uchar *a,const uchar *b)
unknown's avatar
unknown committed
7895
{
7896 7897
  return Field_blob::cmp(a+HA_KEY_BLOB_LENGTH, uint2korr(a),
			 b+HA_KEY_BLOB_LENGTH, uint2korr(b));
unknown's avatar
unknown committed
7898 7899 7900
}


7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917
/**
   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)
{
  *metadata_ptr= pack_length_no_ptr();
  return 1;
}


7918 7919 7920 7921 7922 7923 7924
uint32 Field_blob::sort_length() const
{
  return (uint32) (current_thd->variables.max_sort_length + 
                   (field_charset == &my_charset_bin ? 0 : packlength));
}


7925
void Field_blob::sort_string(uchar *to,uint length)
unknown's avatar
unknown committed
7926
{
7927
  uchar *blob;
unknown's avatar
unknown committed
7928
  uint blob_length=get_length();
unknown's avatar
unknown committed
7929

unknown's avatar
unknown committed
7930 7931 7932 7933
  if (!blob_length)
    bzero(to,length);
  else
  {
7934 7935
    if (field_charset == &my_charset_bin)
    {
7936
      uchar *pos;
7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958

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

      switch (packlength) {
      case 1:
        *pos= (char) blob_length;
        break;
      case 2:
        mi_int2store(pos, blob_length);
        break;
      case 3:
        mi_int3store(pos, blob_length);
        break;
      case 4:
        mi_int4store(pos, blob_length);
        break;
      }
    }
unknown's avatar
unknown committed
7959
    memcpy_fixed(&blob,ptr+packlength,sizeof(char*));
unknown's avatar
unknown committed
7960 7961
    
    blob_length=my_strnxfrm(field_charset,
7962
                            to, length, blob, blob_length);
7963
    DBUG_ASSERT(blob_length == length);
unknown's avatar
unknown committed
7964 7965 7966 7967 7968 7969 7970
  }
}


void Field_blob::sql_type(String &res) const
{
  const char *str;
7971
  uint length;
unknown's avatar
unknown committed
7972
  switch (packlength) {
7973 7974 7975 7976 7977
  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;
  }
7978
  res.set_ascii(str,length);
7979
  if (charset() == &my_charset_bin)
7980
    res.append(STRING_WITH_LEN("blob"));
7981 7982
  else
  {
7983
    res.append(STRING_WITH_LEN("text"));
unknown's avatar
unknown committed
7984 7985 7986
  }
}

7987 7988
uchar *Field_blob::pack(uchar *to, const uchar *from,
                        uint max_length, bool low_byte_first)
7989
{
7990 7991 7992 7993 7994 7995
  DBUG_ENTER("Field_blob::pack");
  DBUG_PRINT("enter", ("to: 0x%lx; from: 0x%lx;"
                       " max_length: %u; low_byte_first: %d",
                       (ulong) to, (ulong) from,
                       max_length, low_byte_first));
  DBUG_DUMP("record", from, table->s->reclength);
7996 7997
  uchar *save= ptr;
  ptr= (uchar*) from;
unknown's avatar
unknown committed
7998
  uint32 length=get_length();			// Length of from string
7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010

  /*
    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.
  */
  store_length(to, packlength, min(length, max_length), low_byte_first);

  /*
    Store the actual blob data, which will occupy 'length' bytes.
   */
  if (length > 0)
8011
  {
8012
    get_ptr((uchar**) &from);
8013 8014 8015
    memcpy(to+packlength, from,length);
  }
  ptr=save;					// Restore org row pointer
8016 8017
  DBUG_DUMP("packed", to, packlength + length);
  DBUG_RETURN(to+packlength+length);
8018 8019 8020
}


8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031
/**
   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
8032 8033 8034
   @param   param_data @c TRUE if base types should be stored in little-
                       endian format, @c FALSE if native format should
                       be used.
8035 8036 8037 8038 8039

   @return  New pointer into memory based on from + length of the data
*/
const uchar *Field_blob::unpack(uchar *to, 
                                const uchar *from,
8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050
                                uint param_data,
                                bool low_byte_first)
{
  DBUG_ENTER("Field_blob::unpack");
  DBUG_PRINT("enter", ("to: 0x%lx; from: 0x%lx;"
                       " param_data: %u; low_byte_first: %d",
                       (ulong) to, (ulong) from, param_data, low_byte_first));
  uint const master_packlength=
    param_data > 0 ? param_data & 0xFF : packlength;
  uint32 const length= get_length(from, master_packlength, low_byte_first);
  DBUG_DUMP("packed", from, length + master_packlength);
8051
  bitmap_set_bit(table->write_set, field_index);
8052 8053 8054 8055
  store(reinterpret_cast<const char*>(from) + master_packlength,
        length, field_charset);
  DBUG_DUMP("record", to, table->s->reclength);
  DBUG_RETURN(from + master_packlength + length);
8056 8057
}

unknown's avatar
unknown committed
8058 8059
/* Keys for blobs are like keys on varchars */

8060
int Field_blob::pack_cmp(const uchar *a, const uchar *b, uint key_length_arg,
8061
                         my_bool insert_or_update)
unknown's avatar
unknown committed
8062
{
8063
  uint a_length, b_length;
8064
  if (key_length_arg > 255)
unknown's avatar
unknown committed
8065 8066 8067 8068 8069 8070
  {
    a_length=uint2korr(a); a+=2;
    b_length=uint2korr(b); b+=2;
  }
  else
  {
8071 8072
    a_length= (uint) *a++;
    b_length= (uint) *b++;
unknown's avatar
unknown committed
8073
  }
8074
  return field_charset->coll->strnncollsp(field_charset,
8075 8076
                                          a, a_length,
                                          b, b_length,
8077
                                          insert_or_update);
unknown's avatar
unknown committed
8078 8079
}

8080

8081
int Field_blob::pack_cmp(const uchar *b, uint key_length_arg,
8082
                         my_bool insert_or_update)
8083
{
8084
  uchar *a;
8085
  uint a_length, b_length;
8086 8087
  memcpy_fixed(&a,ptr+packlength,sizeof(char*));
  if (!a)
8088
    return key_length_arg > 0 ? -1 : 0;
8089

8090 8091
  a_length= get_length(ptr);
  if (key_length_arg > 255)
8092
  {
8093
    b_length= uint2korr(b); b+=2;
8094 8095
  }
  else
8096
    b_length= (uint) *b++;
8097
  return field_charset->coll->strnncollsp(field_charset,
8098 8099
                                          a, a_length,
                                          b, b_length,
8100
                                          insert_or_update);
8101 8102
}

8103
/** Create a packed key that will be used for storage from a MySQL row. */
8104

8105 8106 8107
uchar *
Field_blob::pack_key(uchar *to, const uchar *from, uint max_length,
                     bool low_byte_first __attribute__((unused)))
unknown's avatar
unknown committed
8108
{
8109 8110
  uchar *save= ptr;
  ptr= (uchar*) from;
8111
  uint32 length=get_length();        // Length of from string
8112
  uint local_char_length= ((field_charset->mbmaxlen > 1) ?
8113
                           max_length/field_charset->mbmaxlen : max_length);
8114
  if (length)
8115
    get_ptr((uchar**) &from);
8116 8117 8118 8119
  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);
8120 8121 8122
  *to++= (uchar) length;
  if (max_length > 255)				// 2 byte length
    *to++= (uchar) (length >> 8);
8123
  memcpy(to, from, length);
8124 8125 8126 8127
  ptr=save;					// Restore org row pointer
  return to+length;
}

8128

8129
/**
8130 8131
  Unpack a blob key into a record buffer.

8132 8133 8134 8135 8136 8137 8138 8139
  A blob key has a maximum size of 64K-1.
  In its packed form, the length field is one or two bytes long,
  depending on 'max_length'.
  Depending on the maximum length of a blob, its length field is
  put into 1 to 4 bytes. This is a property of the blob object,
  described by 'packlength'.
  Blobs are internally stored apart from the record buffer, which
  contains a pointer to the blob buffer.
8140 8141


8142 8143 8144 8145 8146
  @param to                          Pointer into the record buffer.
  @param from                        Pointer to the packed key.
  @param max_length                  Key length limit from key description.

  @return
8147 8148 8149
    Pointer into 'from' past the last byte copied from packed key.
*/

8150 8151 8152
const uchar *
Field_blob::unpack_key(uchar *to, const uchar *from, uint max_length,
                       bool low_byte_first __attribute__((unused)))
8153 8154
{
  /* get length of the blob key */
8155
  uint32 length= *from++;
8156
  if (max_length > 255)
8157
    length+= *from++ << 8;
8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171

  /* put the length into the record buffer */
  put_length(to, length);

  /* put the address of the blob buffer or NULL */
  if (length)
    memcpy_fixed(to + packlength, &from, sizeof(from));
  else
    bzero(to + packlength, sizeof(from));

  /* point to first byte of next field in 'from' */
  return from + length;
}

8172

8173
/** Create a packed key that will be used for storage from a MySQL key. */
8174

8175 8176 8177
uchar *
Field_blob::pack_key_from_key_image(uchar *to, const uchar *from, uint max_length,
                                    bool low_byte_first __attribute__((unused)))
8178 8179
{
  uint length=uint2korr(from);
unknown's avatar
unknown committed
8180 8181
  if (length > max_length)
    length=max_length;
unknown's avatar
unknown committed
8182
  *to++= (char) (length & 255);
unknown's avatar
unknown committed
8183
  if (max_length > 255)
unknown's avatar
unknown committed
8184
    *to++= (char) (length >> 8);
unknown's avatar
unknown committed
8185
  if (length)
8186
    memcpy(to, from+HA_KEY_BLOB_LENGTH, length);
unknown's avatar
unknown committed
8187 8188 8189
  return to+length;
}

8190

8191
uint Field_blob::packed_col_length(const uchar *data_ptr, uint length)
8192 8193
{
  if (length > 255)
8194
    return uint2korr(data_ptr)+2;
8195
  return (uint) *data_ptr + 1;
8196 8197
}

8198

8199 8200 8201 8202
uint Field_blob::max_packed_col_length(uint max_length)
{
  return (max_length > 255 ? 2 : 1)+max_length;
}
8203

unknown's avatar
unknown committed
8204

unknown's avatar
unknown committed
8205
uint Field_blob::is_equal(Create_field *new_field)
8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216
{
  if (compare_str_field_flags(new_field, flags))
    return 0;

  return ((new_field->sql_type == get_blob_type_from_length(max_data_length()))
          && new_field->charset == field_charset &&
          ((Field_blob *)new_field->field)->max_data_length() ==
          max_data_length());
}


unknown's avatar
unknown committed
8217
#ifdef HAVE_SPATIAL
unknown's avatar
unknown committed
8218 8219 8220

void Field_geom::sql_type(String &res) const
{
unknown's avatar
unknown committed
8221 8222 8223 8224
  CHARSET_INFO *cs= &my_charset_latin1;
  switch (geom_type)
  {
    case GEOM_POINT:
8225
     res.set(STRING_WITH_LEN("point"), cs);
unknown's avatar
unknown committed
8226 8227
     break;
    case GEOM_LINESTRING:
8228
     res.set(STRING_WITH_LEN("linestring"), cs);
unknown's avatar
unknown committed
8229 8230
     break;
    case GEOM_POLYGON:
8231
     res.set(STRING_WITH_LEN("polygon"), cs);
unknown's avatar
unknown committed
8232 8233
     break;
    case GEOM_MULTIPOINT:
8234
     res.set(STRING_WITH_LEN("multipoint"), cs);
unknown's avatar
unknown committed
8235 8236
     break;
    case GEOM_MULTILINESTRING:
8237
     res.set(STRING_WITH_LEN("multilinestring"), cs);
unknown's avatar
unknown committed
8238 8239
     break;
    case GEOM_MULTIPOLYGON:
8240
     res.set(STRING_WITH_LEN("multipolygon"), cs);
unknown's avatar
unknown committed
8241 8242
     break;
    case GEOM_GEOMETRYCOLLECTION:
8243
     res.set(STRING_WITH_LEN("geometrycollection"), cs);
unknown's avatar
unknown committed
8244 8245
     break;
    default:
8246
     res.set(STRING_WITH_LEN("geometry"), cs);
unknown's avatar
unknown committed
8247
  }
unknown's avatar
unknown committed
8248 8249 8250
}


8251 8252 8253 8254 8255 8256 8257 8258
int Field_geom::store(double nr)
{
  my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
             ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
  return -1;
}


8259
int Field_geom::store(longlong nr, bool unsigned_val)
8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274
{
  my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
             ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
  return -1;
}


int Field_geom::store_decimal(const my_decimal *)
{
  my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
             ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
  return -1;
}


unknown's avatar
unknown committed
8275 8276 8277 8278 8279 8280
int Field_geom::store(const char *from, uint length, CHARSET_INFO *cs)
{
  if (!length)
    bzero(ptr, Field_blob::pack_length());
  else
  {
8281 8282
    if (from == Geometry::bad_geometry_data.ptr())
      goto err;
unknown's avatar
unknown committed
8283 8284 8285 8286
    // Check given WKB
    uint32 wkb_type;
    if (length < SRID_SIZE + WKB_HEADER_SIZE + SIZEOF_STORED_DOUBLE*2)
      goto err;
8287
    wkb_type= uint4korr(from + SRID_SIZE + 1);
8288
    if (wkb_type < (uint32) Geometry::wkb_point ||
8289
	wkb_type > (uint32) Geometry::wkb_last)
8290
      goto err;
unknown's avatar
unknown committed
8291 8292 8293 8294 8295 8296 8297 8298 8299
    Field_blob::store_length(length);
    if (table->copy_blobs || length <= MAX_FIELD_WIDTH)
    {						// Must make a copy
      value.copy(from, length, cs);
      from= value.ptr();
    }
    bmove(ptr + packlength, (char*) &from, sizeof(char*));
  }
  return 0;
unknown's avatar
unknown committed
8300 8301 8302

err:
  bzero(ptr, Field_blob::pack_length());  
8303 8304
  my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
             ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
unknown's avatar
unknown committed
8305
  return -1;
unknown's avatar
unknown committed
8306 8307
}

unknown's avatar
unknown committed
8308
#endif /*HAVE_SPATIAL*/
unknown's avatar
unknown committed
8309

unknown's avatar
unknown committed
8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332
/****************************************************************************
** 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)
{
  switch (packlength) {
  case 1: ptr[0]= (uchar) value;  break;
  case 2:
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
8333
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
8334 8335 8336 8337 8338 8339 8340 8341 8342 8343
  {
    int2store(ptr,(unsigned short) value);
  }
  else
#endif
    shortstore(ptr,(unsigned short) value);
  break;
  case 3: int3store(ptr,(long) value); break;
  case 4:
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
8344
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
8345 8346 8347 8348 8349 8350 8351 8352 8353
  {
    int4store(ptr,value);
  }
  else
#endif
    longstore(ptr,(long) value);
  break;
  case 8:
#ifdef WORDS_BIGENDIAN
unknown's avatar
unknown committed
8354
  if (table->s->db_low_byte_first)
unknown's avatar
unknown committed
8355 8356 8357 8358 8359 8360 8361 8362 8363 8364
  {
    int8store(ptr,value);
  }
  else
#endif
    longlongstore(ptr,value); break;
  }
}


8365 8366 8367 8368
/**
  @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
8369 8370
*/

unknown's avatar
unknown committed
8371
int Field_enum::store(const char *from,uint length,CHARSET_INFO *cs)
unknown's avatar
unknown committed
8372
{
8373
  ASSERT_COLUMN_MARKED_FOR_WRITE;
8374
  int err= 0;
unknown's avatar
unknown committed
8375
  uint32 not_used;
unknown's avatar
unknown committed
8376
  char buff[STRING_BUFFER_USUAL_SIZE];
unknown's avatar
unknown committed
8377
  String tmpstr(buff,sizeof(buff), &my_charset_bin);
unknown's avatar
unknown committed
8378

unknown's avatar
unknown committed
8379
  /* Convert character set if necessary */
unknown's avatar
unknown committed
8380
  if (String::needs_conversion(length, cs, field_charset, &not_used))
unknown's avatar
unknown committed
8381
  { 
8382 8383
    uint dummy_errors;
    tmpstr.copy(from, length, cs, field_charset, &dummy_errors);
unknown's avatar
unknown committed
8384 8385 8386
    from= tmpstr.ptr();
    length=  tmpstr.length();
  }
8387 8388

  /* Remove end space */
8389
  length= field_charset->cset->lengthsp(field_charset, from, length);
8390
  uint tmp=find_type2(typelib, from, length, field_charset);
unknown's avatar
unknown committed
8391
  if (!tmp)
unknown's avatar
unknown committed
8392
  {
8393
    if (length < 6) // Can't be more than 99999 enums
unknown's avatar
unknown committed
8394
    {
unknown's avatar
unknown committed
8395
      /* This is for reading numbers with LOAD DATA INFILE */
8396
      char *end;
8397 8398
      tmp=(uint) my_strntoul(cs,from,length,10,&end,&err);
      if (err || end != from+length || tmp > typelib->count)
unknown's avatar
unknown committed
8399 8400
      {
	tmp=0;
8401
	set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
8402
      }
8403 8404
      if (!table->in_use->count_cuted_fields)
        err= 0;
unknown's avatar
unknown committed
8405 8406
    }
    else
8407
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
8408
  }
unknown's avatar
unknown committed
8409
  store_type((ulonglong) tmp);
8410
  return err;
unknown's avatar
unknown committed
8411 8412 8413
}


unknown's avatar
unknown committed
8414
int Field_enum::store(double nr)
unknown's avatar
unknown committed
8415
{
8416
  return Field_enum::store((longlong) nr, FALSE);
unknown's avatar
unknown committed
8417 8418 8419
}


8420
int Field_enum::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
8421
{
8422
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
8423
  int error= 0;
8424
  if ((ulonglong) nr > typelib->count || nr == 0)
unknown's avatar
unknown committed
8425
  {
8426
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
8427 8428 8429 8430 8431
    if (nr != 0 || table->in_use->count_cuted_fields)
    {
      nr= 0;
      error= 1;
    }
unknown's avatar
unknown committed
8432 8433
  }
  store_type((ulonglong) (uint) nr);
8434
  return error;
unknown's avatar
unknown committed
8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445
}


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


longlong Field_enum::val_int(void)
{
8446
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
8447 8448
  switch (packlength) {
  case 1:
8449
    return (longlong) ptr[0];
unknown's avatar
unknown committed
8450
  case 2:
8451 8452
  {
    uint16 tmp;
unknown's avatar
unknown committed
8453
#ifdef WORDS_BIGENDIAN
8454 8455 8456
    if (table->s->db_low_byte_first)
      tmp=sint2korr(ptr);
    else
unknown's avatar
unknown committed
8457
#endif
8458 8459 8460
      shortget(tmp,ptr);
    return (longlong) tmp;
  }
unknown's avatar
unknown committed
8461 8462 8463
  case 3:
    return (longlong) uint3korr(ptr);
  case 4:
8464 8465
  {
    uint32 tmp;
unknown's avatar
unknown committed
8466
#ifdef WORDS_BIGENDIAN
8467 8468 8469
    if (table->s->db_low_byte_first)
      tmp=uint4korr(ptr);
    else
unknown's avatar
unknown committed
8470
#endif
8471 8472 8473
      longget(tmp,ptr);
    return (longlong) tmp;
  }
unknown's avatar
unknown committed
8474
  case 8:
8475 8476
  {
    longlong tmp;
unknown's avatar
unknown committed
8477
#ifdef WORDS_BIGENDIAN
8478 8479 8480
    if (table->s->db_low_byte_first)
      tmp=sint8korr(ptr);
    else
unknown's avatar
unknown committed
8481
#endif
8482 8483 8484
      longlongget(tmp,ptr);
    return tmp;
  }
unknown's avatar
unknown committed
8485 8486 8487 8488 8489
  }
  return 0;					// impossible
}


8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508
/**
   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
8509 8510 8511 8512 8513
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
8514
    val_ptr->set("", 0, field_charset);
unknown's avatar
unknown committed
8515 8516
  else
    val_ptr->set((const char*) typelib->type_names[tmp-1],
8517
		 typelib->type_lengths[tmp-1],
8518
		 field_charset);
unknown's avatar
unknown committed
8519 8520 8521
  return val_ptr;
}

8522
int Field_enum::cmp(const uchar *a_ptr, const uchar *b_ptr)
unknown's avatar
unknown committed
8523
{
8524 8525
  uchar *old= ptr;
  ptr= (uchar*) a_ptr;
unknown's avatar
unknown committed
8526
  ulonglong a=Field_enum::val_int();
8527
  ptr= (uchar*) b_ptr;
unknown's avatar
unknown committed
8528
  ulonglong b=Field_enum::val_int();
8529
  ptr= old;
unknown's avatar
unknown committed
8530 8531 8532
  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

8533
void Field_enum::sort_string(uchar *to,uint length __attribute__((unused)))
unknown's avatar
unknown committed
8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546
{
  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
{
8547 8548 8549
  char buffer[255];
  String enum_item(buffer, sizeof(buffer), res.charset());

unknown's avatar
unknown committed
8550
  res.length(0);
8551
  res.append(STRING_WITH_LEN("enum("));
unknown's avatar
unknown committed
8552 8553

  bool flag=0;
8554 8555
  uint *len= typelib->type_lengths;
  for (const char **pos= typelib->type_names; *pos; pos++, len++)
unknown's avatar
unknown committed
8556
  {
8557
    uint dummy_errors;
unknown's avatar
unknown committed
8558 8559
    if (flag)
      res.append(',');
8560
    /* convert to res.charset() == utf8, then quote */
8561
    enum_item.copy(*pos, *len, charset(), res.charset(), &dummy_errors);
8562 8563
    append_unescaped(&res, enum_item.ptr(), enum_item.length());
    flag= 1;
unknown's avatar
unknown committed
8564 8565 8566 8567 8568
  }
  res.append(')');
}


8569 8570 8571 8572 8573 8574 8575 8576 8577 8578
Field *Field_enum::new_field(MEM_ROOT *root, struct st_table *new_table,
                             bool keep_type)
{
  Field_enum *res= (Field_enum*) Field::new_field(root, new_table, keep_type);
  if (res)
    res->typelib= copy_typelib(root, typelib);
  return res;
}


8579 8580 8581 8582 8583 8584 8585 8586
/*
   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
8587 8588


unknown's avatar
unknown committed
8589
int Field_set::store(const char *from,uint length,CHARSET_INFO *cs)
unknown's avatar
unknown committed
8590
{
8591
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
8592
  bool got_warning= 0;
8593
  int err= 0;
8594 8595
  char *not_used;
  uint not_used2;
unknown's avatar
unknown committed
8596
  uint32 not_used_offset;
unknown's avatar
unknown committed
8597
  char buff[STRING_BUFFER_USUAL_SIZE];
unknown's avatar
unknown committed
8598
  String tmpstr(buff,sizeof(buff), &my_charset_bin);
unknown's avatar
unknown committed
8599

unknown's avatar
unknown committed
8600
  /* Convert character set if necessary */
unknown's avatar
unknown committed
8601
  if (String::needs_conversion(length, cs, field_charset, &not_used_offset))
unknown's avatar
unknown committed
8602
  { 
8603 8604
    uint dummy_errors;
    tmpstr.copy(from, length, cs, field_charset, &dummy_errors);
unknown's avatar
unknown committed
8605 8606 8607
    from= tmpstr.ptr();
    length=  tmpstr.length();
  }
8608 8609
  ulonglong tmp= find_set(typelib, from, length, field_charset,
                          &not_used, &not_used2, &got_warning);
unknown's avatar
unknown committed
8610 8611 8612
  if (!tmp && length && length < 22)
  {
    /* This is for reading numbers with LOAD DATA INFILE */
8613
    char *end;
8614 8615
    tmp=my_strntoull(cs,from,length,10,&end,&err);
    if (err || end != from+length ||
unknown's avatar
unknown committed
8616
	tmp > (ulonglong) (((longlong) 1 << typelib->count) - (longlong) 1))
8617
    {
8618
      tmp=0;      
8619
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
8620
    }
unknown's avatar
unknown committed
8621
  }
unknown's avatar
unknown committed
8622
  else if (got_warning)
8623
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
unknown's avatar
unknown committed
8624
  store_type(tmp);
8625
  return err;
unknown's avatar
unknown committed
8626 8627 8628
}


8629
int Field_set::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
8630
{
8631
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
8632
  int error= 0;
unknown's avatar
unknown committed
8633 8634 8635
  if ((ulonglong) nr > (ulonglong) (((longlong) 1 << typelib->count) -
				    (longlong) 1))
  {
8636
    nr&= (longlong) (((longlong) 1 << typelib->count) - (longlong) 1);    
8637
    set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, WARN_DATA_TRUNCATED, 1);
8638
    error=1;
unknown's avatar
unknown committed
8639 8640
  }
  store_type((ulonglong) nr);
8641
  return error;
unknown's avatar
unknown committed
8642 8643 8644 8645 8646 8647 8648 8649 8650 8651
}


String *Field_set::val_str(String *val_buffer,
			   String *val_ptr __attribute__((unused)))
{
  ulonglong tmp=(ulonglong) Field_enum::val_int();
  uint bitnr=0;

  val_buffer->length(0);
8652
  val_buffer->set_charset(field_charset);
unknown's avatar
unknown committed
8653 8654 8655 8656 8657
  while (tmp && bitnr < (uint) typelib->count)
  {
    if (tmp & 1)
    {
      if (val_buffer->length())
8658
	val_buffer->append(&field_separator, 1, &my_charset_latin1);
unknown's avatar
unknown committed
8659
      String str(typelib->type_names[bitnr],
8660
		 typelib->type_lengths[bitnr],
8661
		 field_charset);
unknown's avatar
unknown committed
8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672
      val_buffer->append(str);
    }
    tmp>>=1;
    bitnr++;
  }
  return val_buffer;
}


void Field_set::sql_type(String &res) const
{
8673 8674 8675
  char buffer[255];
  String set_item(buffer, sizeof(buffer), res.charset());

unknown's avatar
unknown committed
8676
  res.length(0);
8677
  res.append(STRING_WITH_LEN("set("));
unknown's avatar
unknown committed
8678 8679

  bool flag=0;
8680 8681
  uint *len= typelib->type_lengths;
  for (const char **pos= typelib->type_names; *pos; pos++, len++)
unknown's avatar
unknown committed
8682
  {
8683
    uint dummy_errors;
unknown's avatar
unknown committed
8684 8685
    if (flag)
      res.append(',');
8686
    /* convert to res.charset() == utf8, then quote */
8687
    set_item.copy(*pos, *len, charset(), res.charset(), &dummy_errors);
8688 8689
    append_unescaped(&res, set_item.ptr(), set_item.length());
    flag= 1;
unknown's avatar
unknown committed
8690 8691 8692 8693
  }
  res.append(')');
}

8694 8695 8696 8697 8698 8699
/**
  @retval
    1  if the fields are equally defined
  @retval
    0  if the fields are unequally defined
*/
unknown's avatar
unknown committed
8700 8701 8702

bool Field::eq_def(Field *field)
{
8703
  if (real_type() != field->real_type() || charset() != field->charset() ||
unknown's avatar
unknown committed
8704 8705 8706 8707 8708
      pack_length() != field->pack_length())
    return 0;
  return 1;
}

8709 8710 8711 8712
/**
  @return
  returns 1 if the fields are equally defined
*/
unknown's avatar
unknown committed
8713 8714 8715 8716 8717
bool Field_enum::eq_def(Field *field)
{
  if (!Field::eq_def(field))
    return 0;
  TYPELIB *from_lib=((Field_enum*) field)->typelib;
unknown's avatar
unknown committed
8718

unknown's avatar
unknown committed
8719 8720 8721
  if (typelib->count < from_lib->count)
    return 0;
  for (uint i=0 ; i < from_lib->count ; i++)
8722 8723
    if (my_strnncoll(field_charset,
                     (const uchar*)typelib->type_names[i],
8724
                     strlen(typelib->type_names[i]),
8725
                     (const uchar*)from_lib->type_names[i],
8726
                     strlen(from_lib->type_names[i])))
unknown's avatar
unknown committed
8727 8728 8729 8730
      return 0;
  return 1;
}

8731 8732 8733 8734
/**
  @return
  returns 1 if the fields are equally defined
*/
unknown's avatar
unknown committed
8735
bool Field_num::eq_def(Field *field)
unknown's avatar
unknown committed
8736
{
unknown's avatar
unknown committed
8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748
  if (!Field::eq_def(field))
    return 0;
  Field_num *from_num= (Field_num*) field;

  if (unsigned_flag != from_num->unsigned_flag ||
      zerofill && !from_num->zerofill && !zero_pack() ||
      dec != from_num->dec)
    return 0;
  return 1;
}


unknown's avatar
unknown committed
8749
uint Field_num::is_equal(Create_field *new_field)
unknown's avatar
unknown committed
8750
{
8751
  return ((new_field->sql_type == real_type()) &&
unknown's avatar
unknown committed
8752 8753 8754 8755
	  ((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
8756
	  (new_field->length <= max_display_length()));
unknown's avatar
unknown committed
8757 8758 8759
}


unknown's avatar
unknown committed
8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788
/*
  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'
*/

8789
Field_bit::Field_bit(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg,
unknown's avatar
unknown committed
8790
                     uchar null_bit_arg, uchar *bit_ptr_arg, uchar bit_ofs_arg,
unknown's avatar
unknown committed
8791
                     enum utype unireg_check_arg, const char *field_name_arg)
unknown's avatar
unknown committed
8792
  : Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg,
unknown's avatar
unknown committed
8793
          unireg_check_arg, field_name_arg),
unknown's avatar
unknown committed
8794 8795
    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
8796
{
unknown's avatar
unknown committed
8797
  flags|= UNSIGNED_FLAG;
unknown's avatar
unknown committed
8798 8799 8800 8801 8802 8803 8804 8805 8806
  /*
    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;
}


8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823
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);
  }
}


8824
size_t
8825 8826 8827 8828 8829 8830 8831 8832 8833 8834
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
8835 8836
  DBUG_PRINT("test", ("bit_ofs: %d, bit_len: %d  bit_ptr: 0x%lx",
                      bit_ofs, bit_len, (long) bit_ptr));
8837 8838 8839 8840 8841 8842 8843 8844
  uchar *result;
  if (bit_len == 0)
    result= null_ptr;
  else if (bit_ofs + bit_len > 8)
    result= bit_ptr + 1;
  else
    result= bit_ptr;

8845
  if (result)
8846 8847
    return (size_t) (result - table->record[0]) + 1;
  return LAST_NULL_BYTE_UNDEF;
8848 8849
}

8850

unknown's avatar
unknown committed
8851 8852
Field *Field_bit::new_key_field(MEM_ROOT *root,
                                struct st_table *new_table,
8853
                                uchar *new_ptr, uchar *new_null_ptr,
unknown's avatar
unknown committed
8854 8855 8856 8857 8858 8859 8860 8861
                                uint new_null_bit)
{
  Field_bit *res;
  if ((res= (Field_bit*) Field::new_key_field(root, new_table,
                                              new_ptr, new_null_ptr,
                                              new_null_bit)))
  {
    /* Move bits normally stored in null_pointer to new_ptr */
8862
    res->bit_ptr= new_ptr;
unknown's avatar
unknown committed
8863 8864 8865 8866 8867 8868 8869 8870
    res->bit_ofs= 0;
    if (bit_len)
      res->ptr++;                               // Store rest of data here
  }
  return res;
}


unknown's avatar
unknown committed
8871
uint Field_bit::is_equal(Create_field *new_field) 
8872 8873 8874 8875 8876 8877
{
  return (new_field->sql_type == real_type() &&
          new_field->length == max_display_length());
}

                       
unknown's avatar
unknown committed
8878 8879
int Field_bit::store(const char *from, uint length, CHARSET_INFO *cs)
{
8880
  ASSERT_COLUMN_MARKED_FOR_WRITE;
unknown's avatar
unknown committed
8881 8882
  int delta;

8883
  for (; length && !*from; from++, length--);          // skip left 0's
unknown's avatar
unknown committed
8884
  delta= bytes_in_rec - length;
unknown's avatar
unknown committed
8885 8886 8887 8888 8889

  if (delta < -1 ||
      (delta == -1 && (uchar) *from > ((1 << bit_len) - 1)) ||
      (!bit_len && delta < 0))
  {
8890
    set_rec_bits((1 << bit_len) - 1, bit_ptr, bit_ofs, bit_len);
unknown's avatar
unknown committed
8891
    memset(ptr, 0xff, bytes_in_rec);
8892 8893 8894 8895
    if (table->in_use->really_abort_on_warning())
      set_warning(MYSQL_ERROR::WARN_LEVEL_ERROR, ER_DATA_TOO_LONG, 1);
    else
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
unknown's avatar
unknown committed
8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918
    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
8919
    memcpy(ptr, from, bytes_in_rec);
unknown's avatar
unknown committed
8920 8921 8922 8923 8924 8925 8926
  }
  return 0;
}


int Field_bit::store(double nr)
{
8927
  return Field_bit::store((longlong) nr, FALSE);
unknown's avatar
unknown committed
8928 8929 8930
}


8931
int Field_bit::store(longlong nr, bool unsigned_val)
unknown's avatar
unknown committed
8932 8933 8934 8935 8936 8937 8938 8939
{
  char buf[8];

  mi_int8store(buf, nr);
  return store(buf, 8, NULL);
}


unknown's avatar
unknown committed
8940 8941 8942 8943
int Field_bit::store_decimal(const my_decimal *val)
{
  int err= 0;
  longlong i= convert_decimal2longlong(val, 1, &err);
8944
  return test(err | store(i, TRUE));
unknown's avatar
unknown committed
8945 8946 8947
}


unknown's avatar
unknown committed
8948 8949 8950 8951 8952 8953 8954 8955
double Field_bit::val_real(void)
{
  return (double) Field_bit::val_int();
}


longlong Field_bit::val_int(void)
{
8956
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
8957 8958
  ulonglong bits= 0;
  if (bit_len)
8959
  {
unknown's avatar
unknown committed
8960
    bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
unknown's avatar
unknown committed
8961
    bits<<= (bytes_in_rec * 8);
8962
  }
unknown's avatar
unknown committed
8963

unknown's avatar
unknown committed
8964
  switch (bytes_in_rec) {
unknown's avatar
unknown committed
8965
  case 0: return bits;
8966
  case 1: return bits | (ulonglong) ptr[0];
unknown's avatar
unknown committed
8967 8968 8969 8970 8971 8972
  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
8973
  default: return mi_uint8korr(ptr + bytes_in_rec - sizeof(longlong));
unknown's avatar
unknown committed
8974 8975 8976 8977 8978 8979 8980
  }
}  


String *Field_bit::val_str(String *val_buffer,
                           String *val_ptr __attribute__((unused)))
{
8981
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
8982
  char buff[sizeof(longlong)];
unknown's avatar
unknown committed
8983 8984
  uint length= min(pack_length(), sizeof(longlong));
  ulonglong bits= val_int();
unknown's avatar
unknown committed
8985
  mi_int8store(buff,bits);
unknown's avatar
unknown committed
8986 8987

  val_buffer->alloc(length);
unknown's avatar
unknown committed
8988
  memcpy_fixed((char*) val_buffer->ptr(), buff+8-length, length);
unknown's avatar
unknown committed
8989 8990 8991 8992 8993 8994
  val_buffer->length(length);
  val_buffer->set_charset(&my_charset_bin);
  return val_buffer;
}


unknown's avatar
unknown committed
8995 8996
my_decimal *Field_bit::val_decimal(my_decimal *deciaml_value)
{
8997
  ASSERT_COLUMN_MARKED_FOR_READ;
unknown's avatar
unknown committed
8998 8999 9000 9001 9002
  int2my_decimal(E_DEC_FATAL_ERROR, val_int(), 1, deciaml_value);
  return deciaml_value;
}


9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015
/*
  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)
*/
9016
int Field_bit::cmp_max(const uchar *a, const uchar *b, uint max_len)
9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031
{
  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;
  }
  return memcmp(a, b, field_length);
}


9032
int Field_bit::key_cmp(const uchar *str, uint length)
unknown's avatar
unknown committed
9033 9034 9035 9036 9037
{
  if (bit_len)
  {
    int flag;
    uchar bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
9038
    if ((flag= (int) (bits - *str)))
unknown's avatar
unknown committed
9039 9040 9041 9042
      return flag;
    str++;
    length--;
  }
unknown's avatar
unknown committed
9043
  return memcmp(ptr, str, length);
unknown's avatar
unknown committed
9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056
}


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
9057
  return memcmp(ptr, ptr + row_offset, bytes_in_rec);
unknown's avatar
unknown committed
9058 9059 9060
}


9061
uint Field_bit::get_key_image(uchar *buff, uint length, imagetype type_arg)
unknown's avatar
unknown committed
9062 9063 9064 9065 9066 9067 9068
{
  if (bit_len)
  {
    uchar bits= get_rec_bits(bit_ptr, bit_ofs, bit_len);
    *buff++= bits;
    length--;
  }
9069 9070 9071
  uint data_length = min(length, bytes_in_rec);
  memcpy(buff, ptr, data_length);
  return data_length + 1;
unknown's avatar
unknown committed
9072 9073 9074
}


9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145
/**
   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)
{
  *metadata_ptr= bit_len;
  *(metadata_ptr + 1)= bytes_in_rec;
  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_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);
}


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

   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). 

   @param   field_metadata   Encoded size in field metadata

   @retval 0 if this field's size is < the source field's size
   @retval 1 if this field's size is >= the source field's size
*/
int Field_bit::compatible_field_size(uint field_metadata)
{
  int compatible= 0;
  uint const source_size= pack_length_from_metadata(field_metadata);
  uint const destination_size= row_pack_length();
  uint const from_bit_len= field_metadata & 0x00ff;
  uint const from_len= (field_metadata >> 8U) & 0x00ff;
  if ((bit_len == 0) || (from_bit_len == 0))
    compatible= (source_size <= destination_size);
  else if (from_bit_len > bit_len)
    compatible= (from_len < bytes_in_rec);
  else
    compatible= ((from_bit_len <= bit_len) && (from_len <= bytes_in_rec));
  return (compatible);
}



unknown's avatar
unknown committed
9146 9147 9148 9149
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
9150
                                   "bit(%d)", (int) field_length);
unknown's avatar
unknown committed
9151 9152 9153 9154
  res.length((uint) length);
}


9155 9156 9157
uchar *
Field_bit::pack(uchar *to, const uchar *from, uint max_length,
                bool low_byte_first __attribute__((unused)))
unknown's avatar
unknown committed
9158
{
9159
  DBUG_ASSERT(max_length > 0);
unknown's avatar
unknown committed
9160
  uint length;
unknown's avatar
unknown committed
9161
  if (bit_len > 0)
unknown's avatar
unknown committed
9162
  {
unknown's avatar
unknown committed
9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182
    /*
      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
9183 9184
    *to++= bits;
  }
unknown's avatar
unknown committed
9185 9186
  length= min(bytes_in_rec, max_length - (bit_len > 0));
  memcpy(to, from, length);
unknown's avatar
unknown committed
9187 9188 9189 9190
  return to + length;
}


9191 9192 9193
/**
   Unpack a bit field from row data.

9194
   This method is used to unpack a bit field from a master whose size
9195
   of the field is less than that of the slave.
9196

9197 9198 9199 9200 9201 9202
   @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
*/
9203 9204 9205
const uchar *
Field_bit::unpack(uchar *to, const uchar *from, uint param_data,
                  bool low_byte_first __attribute__((unused)))
9206 9207 9208 9209
{
  uint const from_len= (param_data >> 8U) & 0x00ff;
  uint const from_bit_len= param_data & 0x00ff;
  /*
9210 9211
    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.
9212
  */
9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231
  if (param_data == 0 ||
      (from_bit_len == bit_len) && (from_len == bytes_in_rec))
  {
    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);
    return from + bytes_in_rec;
  }

9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258
  /*
    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.
  */
  uint new_len= (field_length + 7) / 8;
  char *value= (char *)my_alloca(new_len);
  bzero(value, new_len);
  uint len= from_len + ((from_bit_len > 0) ? 1 : 0);
  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);
  return from + len;
}


9259 9260
void Field_bit::set_default()
{
9261 9262 9263 9264 9265 9266
  if (bit_len > 0)
  {
    my_ptrdiff_t const offset= table->s->default_values - table->record[0];
    uchar bits= get_rec_bits(bit_ptr + offset, bit_ofs, bit_len);
    set_rec_bits(bits, bit_ptr, bit_ofs, bit_len);
  }
9267 9268 9269
  Field::set_default();
}

9270 9271 9272 9273
/*
  Bit field support for non-MyISAM tables.
*/

9274
Field_bit_as_char::Field_bit_as_char(uchar *ptr_arg, uint32 len_arg,
9275 9276
                                     uchar *null_ptr_arg, uchar null_bit_arg,
                                     enum utype unireg_check_arg,
unknown's avatar
unknown committed
9277
                                     const char *field_name_arg)
9278
  :Field_bit(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, 0, 0,
unknown's avatar
unknown committed
9279
             unireg_check_arg, field_name_arg)
9280
{
unknown's avatar
unknown committed
9281
  flags|= UNSIGNED_FLAG;
9282
  bit_len= 0;
unknown's avatar
unknown committed
9283
  bytes_in_rec= (len_arg + 7) / 8;
9284 9285 9286 9287 9288
}


int Field_bit_as_char::store(const char *from, uint length, CHARSET_INFO *cs)
{
9289
  ASSERT_COLUMN_MARKED_FOR_WRITE;
9290
  int delta;
9291
  uchar bits= (uchar) (field_length & 7);
9292

9293
  for (; length && !*from; from++, length--);          // skip left 0's
unknown's avatar
unknown committed
9294
  delta= bytes_in_rec - length;
9295 9296 9297 9298

  if (delta < 0 ||
      (delta == 0 && bits && (uint) (uchar) *from >= (uint) (1 << bits)))
  {
unknown's avatar
unknown committed
9299
    memset(ptr, 0xff, bytes_in_rec);
9300
    if (bits)
9301
      *ptr&= ((1 << bits) - 1); /* set first uchar */
9302 9303 9304 9305
    if (table->in_use->really_abort_on_warning())
      set_warning(MYSQL_ERROR::WARN_LEVEL_ERROR, ER_DATA_TOO_LONG, 1);
    else
      set_warning(MYSQL_ERROR::WARN_LEVEL_WARN, ER_WARN_DATA_OUT_OF_RANGE, 1);
9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317
    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
9318
                                   "bit(%d)", (int) field_length);
9319 9320 9321 9322
  res.length((uint) length);
}


unknown's avatar
unknown committed
9323
/*****************************************************************************
unknown's avatar
unknown committed
9324
  Handling of field and Create_field
unknown's avatar
unknown committed
9325 9326
*****************************************************************************/

9327 9328
/**
  Convert create_field::length from number of characters to number of bytes.
9329 9330
*/

unknown's avatar
unknown committed
9331
void Create_field::create_length_to_internal_length(void)
9332
{
unknown's avatar
unknown committed
9333 9334 9335 9336 9337 9338 9339
  switch (sql_type) {
  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:
9340
  case MYSQL_TYPE_VARCHAR:
unknown's avatar
unknown committed
9341
    length*= charset->mbmaxlen;
9342
    key_length= length;
9343
    pack_length= calc_pack_length(sql_type, length);
unknown's avatar
unknown committed
9344 9345 9346
    break;
  case MYSQL_TYPE_ENUM:
  case MYSQL_TYPE_SET:
9347
    /* Pack_length already calculated in sql_parse.cc */
unknown's avatar
unknown committed
9348
    length*= charset->mbmaxlen;
9349
    key_length= pack_length;
unknown's avatar
unknown committed
9350
    break;
unknown's avatar
unknown committed
9351
  case MYSQL_TYPE_BIT:
9352 9353 9354 9355 9356 9357 9358 9359 9360 9361
    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 */
      key_length= pack_length + test(length & 7);
    }
unknown's avatar
unknown committed
9362
    break;
unknown's avatar
unknown committed
9363
  case MYSQL_TYPE_NEWDECIMAL:
unknown's avatar
unknown committed
9364 9365 9366 9367 9368 9369
    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
9370
    break;
unknown's avatar
unknown committed
9371
  default:
9372
    key_length= pack_length= calc_pack_length(sql_type, length);
unknown's avatar
unknown committed
9373
    break;
9374 9375 9376
  }
}

9377

9378 9379 9380
/**
  Init for a tmp table field. To be extended if need be.
*/
unknown's avatar
unknown committed
9381
void Create_field::init_for_tmp_table(enum_field_types sql_type_arg,
9382
                                      uint32 length_arg, uint32 decimals_arg,
9383 9384 9385 9386
                                      bool maybe_null, bool is_unsigned)
{
  field_name= "";
  sql_type= sql_type_arg;
unknown's avatar
unknown committed
9387
  char_length= length= length_arg;;
9388 9389 9390 9391 9392
  unireg_check= Field::NONE;
  interval= 0;
  charset= &my_charset_bin;
  geom_type= Field::GEOM_GEOMETRY;
  pack_flag= (FIELDFLAG_NUMBER |
9393
              ((decimals_arg & FIELDFLAG_MAX_DEC) << FIELDFLAG_DEC_SHIFT) |
9394 9395 9396 9397 9398
              (maybe_null ? FIELDFLAG_MAYBE_NULL : 0) |
              (is_unsigned ? 0 : FIELDFLAG_DECIMAL));
}


9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416
/**
  Initialize field definition for create.

  @param thd                   Thread handle
  @param fld_name              Field name
  @param fld_type              Field type
  @param fld_length            Field length
  @param fld_decimals          Decimal (if any)
  @param fld_type_modifier     Additional type information
  @param fld_default_value     Field default value (if any)
  @param fld_on_update_value   The value of ON UPDATE clause
  @param fld_comment           Field comment
  @param fld_change            Field change
  @param fld_interval_list     Interval list (if any)
  @param fld_charset           Field charset
  @param fld_geom_type         Field geometry type (if any)

  @retval
9417
    FALSE on success
9418
  @retval
9419 9420 9421
    TRUE  on error
*/

unknown's avatar
unknown committed
9422
bool Create_field::init(THD *thd, char *fld_name, enum_field_types fld_type,
9423 9424 9425 9426 9427 9428 9429 9430 9431
                        char *fld_length, char *fld_decimals,
                        uint fld_type_modifier, Item *fld_default_value,
                        Item *fld_on_update_value, LEX_STRING *fld_comment,
                        char *fld_change, List<String> *fld_interval_list,
                        CHARSET_INFO *fld_charset, uint fld_geom_type)
{
  uint sign_len, allowed_type_modifier= 0;
  ulong max_field_charlength= MAX_FIELD_CHARLENGTH;

unknown's avatar
unknown committed
9432
  DBUG_ENTER("Create_field::init()");
9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458
  
  field= 0;
  field_name= fld_name;
  def= fld_default_value;
  flags= fld_type_modifier;
  unireg_check= (fld_type_modifier & AUTO_INCREMENT_FLAG ?
                 Field::NEXT_NUMBER : Field::NONE);
  decimals= fld_decimals ? (uint)atoi(fld_decimals) : 0;
  if (decimals >= NOT_FIXED_DEC)
  {
    my_error(ER_TOO_BIG_SCALE, MYF(0), decimals, fld_name,
             NOT_FIXED_DEC-1);
    DBUG_RETURN(TRUE);
  }

  sql_type= fld_type;
  length= 0;
  change= fld_change;
  interval= 0;
  pack_length= key_length= 0;
  charset= fld_charset;
  geom_type= (Field::geometry_type) fld_geom_type;
  interval_list.empty();

  comment= *fld_comment;
  /*
9459 9460
    Set NO_DEFAULT_VALUE_FLAG if this field doesn't have a default value and
    it is NOT NULL, not an AUTO_INCREMENT field and not a TIMESTAMP.
9461 9462
  */
  if (!fld_default_value && !(fld_type_modifier & AUTO_INCREMENT_FLAG) &&
9463
      (fld_type_modifier & NOT_NULL_FLAG) && fld_type != MYSQL_TYPE_TIMESTAMP)
9464 9465 9466 9467 9468 9469 9470
    flags|= NO_DEFAULT_VALUE_FLAG;

  if (fld_length && !(length= (uint) atoi(fld_length)))
    fld_length= 0; /* purecov: inspected */
  sign_len= fld_type_modifier & UNSIGNED_FLAG ? 0 : 1;

  switch (fld_type) {
9471
  case MYSQL_TYPE_TINY:
9472 9473 9474 9475
    if (!fld_length)
      length= MAX_TINYINT_WIDTH+sign_len;
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
    break;
9476
  case MYSQL_TYPE_SHORT:
9477 9478 9479 9480
    if (!fld_length)
      length= MAX_SMALLINT_WIDTH+sign_len;
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
    break;
9481
  case MYSQL_TYPE_INT24:
9482 9483 9484 9485
    if (!fld_length)
      length= MAX_MEDIUMINT_WIDTH+sign_len;
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
    break;
9486
  case MYSQL_TYPE_LONG:
9487 9488 9489 9490
    if (!fld_length)
      length= MAX_INT_WIDTH+sign_len;
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
    break;
9491
  case MYSQL_TYPE_LONGLONG:
9492 9493 9494 9495
    if (!fld_length)
      length= MAX_BIGINT_WIDTH;
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
    break;
9496
  case MYSQL_TYPE_NULL:
9497
    break;
9498
  case MYSQL_TYPE_NEWDECIMAL:
9499
    my_decimal_trim(&length, &decimals);
9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525
    if (length > DECIMAL_MAX_PRECISION)
    {
      my_error(ER_TOO_BIG_PRECISION, MYF(0), length, fld_name,
               DECIMAL_MAX_PRECISION);
      DBUG_RETURN(TRUE);
    }
    if (length < decimals)
    {
      my_error(ER_M_BIGGER_THAN_D, MYF(0), fld_name);
      DBUG_RETURN(TRUE);
    }
    length=
      my_decimal_precision_to_length(length, decimals,
                                     fld_type_modifier & UNSIGNED_FLAG);
    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;
9526 9527 9528 9529 9530
  case MYSQL_TYPE_BLOB:
  case MYSQL_TYPE_TINY_BLOB:
  case MYSQL_TYPE_LONG_BLOB:
  case MYSQL_TYPE_MEDIUM_BLOB:
  case MYSQL_TYPE_GEOMETRY:
9531 9532 9533 9534 9535
    if (fld_default_value)
    {
      /* Allow empty as default value. */
      String str,*res;
      res= fld_default_value->val_str(&str);
9536 9537 9538 9539 9540 9541 9542
      /*
        A default other than '' is always an error, and any non-NULL
        specified default is an error in strict mode.
      */
      if (res->length() || (thd->variables.sql_mode &
                            (MODE_STRICT_TRANS_TABLES |
                             MODE_STRICT_ALL_TABLES)))
9543 9544 9545 9546 9547
      {
        my_error(ER_BLOB_CANT_HAVE_DEFAULT, MYF(0),
                 fld_name); /* purecov: inspected */
        DBUG_RETURN(TRUE);
      }
9548 9549 9550 9551 9552 9553 9554 9555 9556 9557
      else
      {
        /*
          Otherwise a default of '' is just a warning.
        */
        push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                            ER_BLOB_CANT_HAVE_DEFAULT,
                            ER(ER_BLOB_CANT_HAVE_DEFAULT),
                            fld_name);
      }
9558 9559 9560 9561
      def= 0;
    }
    flags|= BLOB_FLAG;
    break;
9562
  case MYSQL_TYPE_YEAR:
9563 9564 9565 9566
    if (!fld_length || length != 2)
      length= 4; /* Default length */
    flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
    break;
9567
  case MYSQL_TYPE_FLOAT:
9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579
    /* change FLOAT(precision) to FLOAT or DOUBLE */
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
    if (fld_length && !fld_decimals)
    {
      uint tmp_length= length;
      if (tmp_length > PRECISION_FOR_DOUBLE)
      {
        my_error(ER_WRONG_FIELD_SPEC, MYF(0), fld_name);
        DBUG_RETURN(TRUE);
      }
      else if (tmp_length > PRECISION_FOR_FLOAT)
      {
9580
        sql_type= MYSQL_TYPE_DOUBLE;
9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599
        length= DBL_DIG+7; /* -[digits].E+### */
      }
      else
        length= FLT_DIG+6; /* -[digits].E+## */
      decimals= NOT_FIXED_DEC;
      break;
    }
    if (!fld_length && !fld_decimals)
    {
      length=  FLT_DIG+6;
      decimals= NOT_FIXED_DEC;
    }
    if (length < decimals &&
        decimals != NOT_FIXED_DEC)
    {
      my_error(ER_M_BIGGER_THAN_D, MYF(0), fld_name);
      DBUG_RETURN(TRUE);
    }
    break;
9600
  case MYSQL_TYPE_DOUBLE:
9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613
    allowed_type_modifier= AUTO_INCREMENT_FLAG;
    if (!fld_length && !fld_decimals)
    {
      length= DBL_DIG+7;
      decimals= NOT_FIXED_DEC;
    }
    if (length < decimals &&
        decimals != NOT_FIXED_DEC)
    {
      my_error(ER_M_BIGGER_THAN_D, MYF(0), fld_name);
      DBUG_RETURN(TRUE);
    }
    break;
9614
  case MYSQL_TYPE_TIMESTAMP:
9615
    if (!fld_length)
9616 9617 9618 9619 9620
    {
      /* Compressed date YYYYMMDDHHMMSS */
      length= MAX_DATETIME_COMPRESSED_WIDTH;
    }
    else if (length != MAX_DATETIME_WIDTH)
9621 9622 9623 9624 9625 9626
    {
      /*
        We support only even TIMESTAMP lengths less or equal than 14
        and 19 as length of 4.1 compatible representation.
      */
      length= ((length+1)/2)*2; /* purecov: inspected */
9627
      length= min(length, MAX_DATETIME_COMPRESSED_WIDTH); /* purecov: inspected */
9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667
    }
    flags|= ZEROFILL_FLAG | UNSIGNED_FLAG;
    if (fld_default_value)
    {
      /* Grammar allows only NOW() value for ON UPDATE clause */
      if (fld_default_value->type() == Item::FUNC_ITEM && 
          ((Item_func*)fld_default_value)->functype() == Item_func::NOW_FUNC)
      {
        unireg_check= (fld_on_update_value ? Field::TIMESTAMP_DNUN_FIELD:
                                             Field::TIMESTAMP_DN_FIELD);
        /*
          We don't need default value any longer moreover it is dangerous.
          Everything handled by unireg_check further.
        */
        def= 0;
      }
      else
        unireg_check= (fld_on_update_value ? Field::TIMESTAMP_UN_FIELD:
                                             Field::NONE);
    }
    else
    {
      /*
        If we have default TIMESTAMP NOT NULL column without explicit DEFAULT
        or ON UPDATE values then for the sake of compatiblity we should treat
        this column as having DEFAULT NOW() ON UPDATE NOW() (when we don't
        have another TIMESTAMP column with auto-set option before this one)
        or DEFAULT 0 (in other cases).
        So here we are setting TIMESTAMP_OLD_FIELD only temporary, and will
        replace this value by TIMESTAMP_DNUN_FIELD or NONE later when
        information about all TIMESTAMP fields in table will be availiable.

        If we have TIMESTAMP NULL column without explicit DEFAULT value
        we treat it as having DEFAULT NULL attribute.
      */
      unireg_check= (fld_on_update_value ? Field::TIMESTAMP_UN_FIELD :
                     (flags & NOT_NULL_FLAG ? Field::TIMESTAMP_OLD_FIELD :
                                              Field::NONE));
    }
    break;
9668
  case MYSQL_TYPE_DATE:
9669 9670
    /* Old date type. */
    if (protocol_version != PROTOCOL_VERSION-1)
9671
      sql_type= MYSQL_TYPE_NEWDATE;
9672
    /* fall trough */
9673
  case MYSQL_TYPE_NEWDATE:
9674 9675
    length= 10;
    break;
9676
  case MYSQL_TYPE_TIME:
9677 9678
    length= 10;
    break;
9679
  case MYSQL_TYPE_DATETIME:
9680
    length= MAX_DATETIME_WIDTH;
9681
    break;
9682
  case MYSQL_TYPE_SET:
9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697
    {
      pack_length= get_set_pack_length(fld_interval_list->elements);

      List_iterator<String> it(*fld_interval_list);
      String *tmp;
      while ((tmp= it++))
        interval_list.push_back(tmp);
      /*
        Set fake length to 1 to pass the below conditions.
        Real length will be set in mysql_prepare_table()
        when we know the character set of the column
      */
      length= 1;
      break;
    }
9698
  case MYSQL_TYPE_ENUM:
9699 9700 9701 9702 9703 9704 9705 9706
    {
      /* Should be safe. */
      pack_length= get_enum_pack_length(fld_interval_list->elements);

      List_iterator<String> it(*fld_interval_list);
      String *tmp;
      while ((tmp= it++))
        interval_list.push_back(tmp);
9707
      length= 1; /* See comment for MYSQL_TYPE_SET above. */
9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725
      break;
   }
  case MYSQL_TYPE_VAR_STRING:
    DBUG_ASSERT(0);  /* Impossible. */
    break;
  case MYSQL_TYPE_BIT:
    {
      if (!fld_length)
        length= 1;
      if (length > MAX_BIT_FIELD_LENGTH)
      {
        my_error(ER_TOO_BIG_DISPLAYWIDTH, MYF(0), fld_name,
                 MAX_BIT_FIELD_LENGTH);
        DBUG_RETURN(TRUE);
      }
      pack_length= (length + 7) / 8;
      break;
    }
9726
  case MYSQL_TYPE_DECIMAL:
9727 9728
    DBUG_ASSERT(0); /* Was obsolete */
  }
unknown's avatar
unknown committed
9729 9730
  /* Remember the value of length */
  char_length= length;
9731 9732

  if (!(flags & BLOB_FLAG) &&
9733 9734
      ((length > max_field_charlength && fld_type != MYSQL_TYPE_SET &&
        fld_type != MYSQL_TYPE_ENUM &&
9735 9736 9737
        (fld_type != MYSQL_TYPE_VARCHAR || fld_default_value)) ||
       (!length &&
        fld_type != MYSQL_TYPE_STRING &&
9738
        fld_type != MYSQL_TYPE_VARCHAR && fld_type != MYSQL_TYPE_GEOMETRY)))
9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758
  {
    my_error((fld_type == MYSQL_TYPE_VAR_STRING ||
              fld_type == MYSQL_TYPE_VARCHAR ||
              fld_type == MYSQL_TYPE_STRING) ?  ER_TOO_BIG_FIELDLENGTH :
                                                ER_TOO_BIG_DISPLAYWIDTH,
              MYF(0),
              fld_name, max_field_charlength); /* purecov: inspected */
    DBUG_RETURN(TRUE);
  }
  fld_type_modifier&= AUTO_INCREMENT_FLAG;
  if ((~allowed_type_modifier) & fld_type_modifier)
  {
    my_error(ER_WRONG_FIELD_SPEC, MYF(0), fld_name);
    DBUG_RETURN(TRUE);
  }

  DBUG_RETURN(FALSE); /* success */
}


9759 9760 9761 9762
enum_field_types get_blob_type_from_length(ulong length)
{
  enum_field_types type;
  if (length < 256)
9763
    type= MYSQL_TYPE_TINY_BLOB;
9764
  else if (length < 65536)
9765
    type= MYSQL_TYPE_BLOB;
9766
  else if (length < 256L*256L*256L)
9767
    type= MYSQL_TYPE_MEDIUM_BLOB;
9768
  else
9769
    type= MYSQL_TYPE_LONG_BLOB;
9770 9771 9772 9773
  return type;
}


unknown's avatar
unknown committed
9774
/*
unknown's avatar
unknown committed
9775
  Make a field from the .frm file info
unknown's avatar
unknown committed
9776 9777 9778 9779 9780
*/

uint32 calc_pack_length(enum_field_types type,uint32 length)
{
  switch (type) {
9781
  case MYSQL_TYPE_VAR_STRING:
9782
  case MYSQL_TYPE_STRING:
9783
  case MYSQL_TYPE_DECIMAL:     return (length);
9784
  case MYSQL_TYPE_VARCHAR:     return (length + (length < 256 ? 1: 2));
9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806
  case MYSQL_TYPE_YEAR:
  case MYSQL_TYPE_TINY	: return 1;
  case MYSQL_TYPE_SHORT : return 2;
  case MYSQL_TYPE_INT24:
  case MYSQL_TYPE_NEWDATE:
  case MYSQL_TYPE_TIME:   return 3;
  case MYSQL_TYPE_TIMESTAMP:
  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:
  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:
9807
    abort(); return 0;                          // This shouldn't happen
9808
  case MYSQL_TYPE_BIT: return length / 8;
9809 9810
  default:
    return 0;
unknown's avatar
unknown committed
9811 9812 9813 9814 9815 9816 9817
  }
}


uint pack_length_to_packflag(uint type)
{
  switch (type) {
9818 9819 9820 9821 9822
    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
9823 9824 9825 9826 9827
  }
  return 0;					// This shouldn't happen
}


9828
Field *make_field(TABLE_SHARE *share, uchar *ptr, uint32 field_length,
unknown's avatar
unknown committed
9829
		  uchar *null_pos, uchar null_bit,
unknown's avatar
unknown committed
9830
		  uint pack_flag,
9831
		  enum_field_types field_type,
9832
		  CHARSET_INFO *field_charset,
unknown's avatar
unknown committed
9833
		  Field::geometry_type geom_type,
unknown's avatar
unknown committed
9834 9835
		  Field::utype unireg_check,
		  TYPELIB *interval,
unknown's avatar
unknown committed
9836
		  const char *field_name)
unknown's avatar
unknown committed
9837
{
unknown's avatar
unknown committed
9838 9839 9840 9841
  uchar *bit_ptr;
  uchar bit_offset;
  LINT_INIT(bit_ptr);
  LINT_INIT(bit_offset);
9842
  if (field_type == MYSQL_TYPE_BIT && !f_bit_as_char(pack_flag))
unknown's avatar
unknown committed
9843 9844 9845 9846 9847 9848 9849 9850 9851 9852
  {
    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
9853 9854 9855 9856 9857
  if (!f_maybe_null(pack_flag))
  {
    null_pos=0;
    null_bit=0;
  }
unknown's avatar
unknown committed
9858 9859 9860 9861
  else
  {
    null_bit= ((uchar) 1) << null_bit;
  }
unknown's avatar
unknown committed
9862

9863
  switch (field_type) {
9864 9865 9866 9867 9868
  case MYSQL_TYPE_DATE:
  case MYSQL_TYPE_NEWDATE:
  case MYSQL_TYPE_TIME:
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_TIMESTAMP:
9869 9870
    field_charset= &my_charset_bin;
  default: break;
unknown's avatar
unknown committed
9871 9872
  }

unknown's avatar
unknown committed
9873 9874 9875
  if (f_is_alpha(pack_flag))
  {
    if (!f_is_packed(pack_flag))
unknown's avatar
unknown committed
9876
    {
9877
      if (field_type == MYSQL_TYPE_STRING ||
9878
          field_type == MYSQL_TYPE_DECIMAL ||   // 3.23 or 4.0 string
9879
          field_type == MYSQL_TYPE_VAR_STRING)
unknown's avatar
unknown committed
9880
        return new Field_string(ptr,field_length,null_pos,null_bit,
unknown's avatar
unknown committed
9881
                                unireg_check, field_name,
unknown's avatar
unknown committed
9882
                                field_charset);
9883
      if (field_type == MYSQL_TYPE_VARCHAR)
9884 9885 9886
        return new Field_varstring(ptr,field_length,
                                   HA_VARCHAR_PACKLENGTH(field_length),
                                   null_pos,null_bit,
unknown's avatar
unknown committed
9887 9888
                                   unireg_check, field_name,
                                   share,
9889
                                   field_charset);
unknown's avatar
unknown committed
9890 9891
      return 0;                                 // Error
    }
unknown's avatar
unknown committed
9892 9893 9894 9895 9896

    uint pack_length=calc_pack_length((enum_field_types)
				      f_packtype(pack_flag),
				      field_length);

unknown's avatar
unknown committed
9897
#ifdef HAVE_SPATIAL
unknown's avatar
unknown committed
9898 9899
    if (f_is_geom(pack_flag))
      return new Field_geom(ptr,null_pos,null_bit,
unknown's avatar
unknown committed
9900
			    unireg_check, field_name, share,
unknown's avatar
unknown committed
9901
			    pack_length, geom_type);
unknown's avatar
unknown committed
9902
#endif
unknown's avatar
unknown committed
9903 9904
    if (f_is_blob(pack_flag))
      return new Field_blob(ptr,null_pos,null_bit,
unknown's avatar
unknown committed
9905
			    unireg_check, field_name, share,
unknown's avatar
unknown committed
9906
			    pack_length, field_charset);
unknown's avatar
unknown committed
9907 9908 9909 9910
    if (interval)
    {
      if (f_is_enum(pack_flag))
	return new Field_enum(ptr,field_length,null_pos,null_bit,
unknown's avatar
unknown committed
9911
				  unireg_check, field_name,
9912
				  pack_length, interval, field_charset);
unknown's avatar
unknown committed
9913 9914
      else
	return new Field_set(ptr,field_length,null_pos,null_bit,
unknown's avatar
unknown committed
9915
			     unireg_check, field_name,
9916
			     pack_length, interval, field_charset);
unknown's avatar
unknown committed
9917 9918 9919
    }
  }

9920
  switch (field_type) {
9921
  case MYSQL_TYPE_DECIMAL:
unknown's avatar
unknown committed
9922
    return new Field_decimal(ptr,field_length,null_pos,null_bit,
unknown's avatar
unknown committed
9923
			     unireg_check, field_name,
unknown's avatar
unknown committed
9924 9925 9926
			     f_decimals(pack_flag),
			     f_is_zerofill(pack_flag) != 0,
			     f_is_dec(pack_flag) == 0);
9927
  case MYSQL_TYPE_NEWDECIMAL:
unknown's avatar
unknown committed
9928
    return new Field_new_decimal(ptr,field_length,null_pos,null_bit,
unknown's avatar
unknown committed
9929
                                 unireg_check, field_name,
unknown's avatar
unknown committed
9930 9931 9932
                                 f_decimals(pack_flag),
                                 f_is_zerofill(pack_flag) != 0,
                                 f_is_dec(pack_flag) == 0);
9933
  case MYSQL_TYPE_FLOAT:
unknown's avatar
unknown committed
9934
    return new Field_float(ptr,field_length,null_pos,null_bit,
unknown's avatar
unknown committed
9935
			   unireg_check, field_name,
unknown's avatar
unknown committed
9936 9937 9938
			   f_decimals(pack_flag),
			   f_is_zerofill(pack_flag) != 0,
			   f_is_dec(pack_flag)== 0);
9939
  case MYSQL_TYPE_DOUBLE:
unknown's avatar
unknown committed
9940
    return new Field_double(ptr,field_length,null_pos,null_bit,
unknown's avatar
unknown committed
9941
			    unireg_check, field_name,
unknown's avatar
unknown committed
9942 9943 9944
			    f_decimals(pack_flag),
			    f_is_zerofill(pack_flag) != 0,
			    f_is_dec(pack_flag)== 0);
9945
  case MYSQL_TYPE_TINY:
unknown's avatar
unknown committed
9946
    return new Field_tiny(ptr,field_length,null_pos,null_bit,
unknown's avatar
unknown committed
9947
			  unireg_check, field_name,
unknown's avatar
unknown committed
9948 9949
			  f_is_zerofill(pack_flag) != 0,
			  f_is_dec(pack_flag) == 0);
9950
  case MYSQL_TYPE_SHORT:
unknown's avatar
unknown committed
9951
    return new Field_short(ptr,field_length,null_pos,null_bit,
unknown's avatar
unknown committed
9952
			   unireg_check, field_name,
unknown's avatar
unknown committed
9953 9954
			   f_is_zerofill(pack_flag) != 0,
			   f_is_dec(pack_flag) == 0);
9955
  case MYSQL_TYPE_INT24:
unknown's avatar
unknown committed
9956
    return new Field_medium(ptr,field_length,null_pos,null_bit,
unknown's avatar
unknown committed
9957
			    unireg_check, field_name,
unknown's avatar
unknown committed
9958 9959
			    f_is_zerofill(pack_flag) != 0,
			    f_is_dec(pack_flag) == 0);
9960
  case MYSQL_TYPE_LONG:
unknown's avatar
unknown committed
9961
    return new Field_long(ptr,field_length,null_pos,null_bit,
unknown's avatar
unknown committed
9962
			   unireg_check, field_name,
unknown's avatar
unknown committed
9963 9964
			   f_is_zerofill(pack_flag) != 0,
			   f_is_dec(pack_flag) == 0);
9965
  case MYSQL_TYPE_LONGLONG:
unknown's avatar
unknown committed
9966
    return new Field_longlong(ptr,field_length,null_pos,null_bit,
unknown's avatar
unknown committed
9967
			      unireg_check, field_name,
unknown's avatar
unknown committed
9968 9969
			      f_is_zerofill(pack_flag) != 0,
			      f_is_dec(pack_flag) == 0);
9970
  case MYSQL_TYPE_TIMESTAMP:
9971
    return new Field_timestamp(ptr,field_length, null_pos, null_bit,
unknown's avatar
unknown committed
9972
                               unireg_check, field_name, share,
9973
                               field_charset);
9974
  case MYSQL_TYPE_YEAR:
unknown's avatar
unknown committed
9975
    return new Field_year(ptr,field_length,null_pos,null_bit,
unknown's avatar
unknown committed
9976
			  unireg_check, field_name);
9977
  case MYSQL_TYPE_DATE:
unknown's avatar
unknown committed
9978
    return new Field_date(ptr,null_pos,null_bit,
unknown's avatar
unknown committed
9979
			  unireg_check, field_name, field_charset);
9980
  case MYSQL_TYPE_NEWDATE:
unknown's avatar
unknown committed
9981
    return new Field_newdate(ptr,null_pos,null_bit,
unknown's avatar
unknown committed
9982
			     unireg_check, field_name, field_charset);
9983
  case MYSQL_TYPE_TIME:
unknown's avatar
unknown committed
9984
    return new Field_time(ptr,null_pos,null_bit,
unknown's avatar
unknown committed
9985
			  unireg_check, field_name, field_charset);
9986
  case MYSQL_TYPE_DATETIME:
unknown's avatar
unknown committed
9987
    return new Field_datetime(ptr,null_pos,null_bit,
unknown's avatar
unknown committed
9988
			      unireg_check, field_name, field_charset);
9989
  case MYSQL_TYPE_NULL:
unknown's avatar
unknown committed
9990 9991
    return new Field_null(ptr, field_length, unireg_check, field_name,
                          field_charset);
9992
  case MYSQL_TYPE_BIT:
9993
    return f_bit_as_char(pack_flag) ?
9994
           new Field_bit_as_char(ptr, field_length, null_pos, null_bit,
9995
                                 unireg_check, field_name) :
9996
           new Field_bit(ptr, field_length, null_pos, null_bit, bit_ptr,
9997
                         bit_offset, unireg_check, field_name);
unknown's avatar
unknown committed
9998

9999 10000
  default:					// Impossible (Wrong version)
    break;
unknown's avatar
unknown committed
10001
  }
unknown's avatar
unknown committed
10002
  return 0;
unknown's avatar
unknown committed
10003 10004 10005
}


10006
/** Create a field suitable for create of table. */
unknown's avatar
unknown committed
10007

unknown's avatar
unknown committed
10008
Create_field::Create_field(Field *old_field,Field *orig_field)
unknown's avatar
unknown committed
10009 10010 10011 10012 10013 10014 10015
{
  field=      old_field;
  field_name=change=old_field->field_name;
  length=     old_field->field_length;
  flags=      old_field->flags;
  unireg_check=old_field->unireg_check;
  pack_length=old_field->pack_length();
10016
  key_length= old_field->key_length();
unknown's avatar
unknown committed
10017
  sql_type=   old_field->real_type();
unknown's avatar
unknown committed
10018 10019
  charset=    old_field->charset();		// May be NULL ptr
  comment=    old_field->comment;
10020
  decimals=   old_field->decimals();
unknown's avatar
unknown committed
10021 10022 10023

  /* Fix if the original table had 4 byte pointer blobs */
  if (flags & BLOB_FLAG)
10024
    pack_length= (pack_length- old_field->table->s->blob_ptr_size +
unknown's avatar
unknown committed
10025
		  portable_sizeof_char_ptr);
10026

10027
  switch (sql_type) {
10028
  case MYSQL_TYPE_BLOB:
10029
    switch (pack_length - portable_sizeof_char_ptr) {
10030 10031 10032 10033
    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;
10034
    }
10035
    length/= charset->mbmaxlen;
10036 10037
    key_length/= charset->mbmaxlen;
    break;
10038
  case MYSQL_TYPE_STRING:
unknown's avatar
unknown committed
10039
    /* Change CHAR -> VARCHAR if dynamic record length */
10040 10041 10042 10043 10044 10045 10046 10047
    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:
10048
    /* This is corrected in create_length_to_internal_length */
10049 10050 10051
    length= (length+charset->mbmaxlen-1) / charset->mbmaxlen;
    break;
#ifdef HAVE_SPATIAL
10052
  case MYSQL_TYPE_GEOMETRY:
10053 10054 10055 10056 10057
    geom_type= ((Field_geom*)old_field)->geom_type;
    break;
#endif
  default:
    break;
unknown's avatar
unknown committed
10058
  }
10059

unknown's avatar
unknown committed
10060 10061 10062 10063
  if (flags & (ENUM_FLAG | SET_FLAG))
    interval= ((Field_enum*) old_field)->typelib;
  else
    interval=0;
10064
  def=0;
10065
  char_length= length;
10066

10067
  if (!(flags & (NO_DEFAULT_VALUE_FLAG | BLOB_FLAG)) &&
10068
      old_field->ptr && orig_field &&
10069
      (sql_type != MYSQL_TYPE_TIMESTAMP ||                /* set def only if */
10070 10071
       old_field->table->timestamp_field != old_field ||  /* timestamp field */ 
       unireg_check == Field::TIMESTAMP_UN_FIELD))        /* has default val */
unknown's avatar
unknown committed
10072
  {
10073 10074
    char buff[MAX_FIELD_WIDTH];
    String tmp(buff,sizeof(buff), charset);
10075
    my_ptrdiff_t diff;
10076

unknown's avatar
unknown committed
10077
    /* Get the value from default_values */
10078 10079
    diff= (my_ptrdiff_t) (orig_field->table->s->default_values-
                          orig_field->table->record[0]);
unknown's avatar
unknown committed
10080
    orig_field->move_field_offset(diff);	// Points now at default_values
10081
    if (!orig_field->is_real_null())
10082
    {
10083 10084
      char buff[MAX_FIELD_WIDTH], *pos;
      String tmp(buff, sizeof(buff), charset), *res;
10085
      res= orig_field->val_str(&tmp);
10086 10087
      pos= (char*) sql_strmake(res->ptr(), res->length());
      def= new Item_string(pos, res->length(), charset);
10088
    }
10089
    orig_field->move_field_offset(-diff);	// Back to record[0]
unknown's avatar
unknown committed
10090 10091
  }
}
10092 10093


10094 10095
/**
  maximum possible display length for blob.
10096

10097
  @return
10098 10099
    length
*/
10100 10101

uint32 Field_blob::max_display_length()
10102 10103 10104 10105
{
  switch (packlength)
  {
  case 1:
10106
    return 255 * field_charset->mbmaxlen;
10107
  case 2:
10108
    return 65535 * field_charset->mbmaxlen;
10109
  case 3:
10110
    return 16777215 * field_charset->mbmaxlen;
10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122
  case 4:
    return (uint32) 4294967295U;
  default:
    DBUG_ASSERT(0); // we should never go here
    return 0;
  }
}


/*****************************************************************************
 Warning handling
*****************************************************************************/
10123

10124 10125
/**
  Produce warning or note about data saved into field.
10126

10127 10128 10129
  @param level            - level of message (Note/Warning/Error)
  @param code             - error code of message to be produced
  @param cuted_increment  - whenever we should increase cut fields count or not
10130

10131
  @note
10132
    This function won't produce warning and increase cut fields counter
10133 10134 10135 10136
    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().
10137

10138
  @retval
10139
    1 if count_cuted_fields == CHECK_FIELD_IGNORE and error level is not NOTE
10140
  @retval
10141
    0 otherwise
10142
*/
10143

10144
bool 
10145 10146
Field::set_warning(MYSQL_ERROR::enum_warning_level level, uint code,
                   int cuted_increment)
10147
{
10148 10149 10150 10151 10152
  /*
    If this field was created only for type conversion purposes it
    will have table == NULL.
  */
  THD *thd= table ? table->in_use : current_thd;
unknown's avatar
unknown committed
10153 10154
  if (thd->count_cuted_fields)
  {
10155
    thd->cuted_fields+= cuted_increment;
10156 10157
    push_warning_printf(thd, level, code, ER(code), field_name,
                        thd->row_count);
10158 10159
    return 0;
  }
10160
  return level >= MYSQL_ERROR::WARN_LEVEL_WARN;
10161 10162 10163
}


10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176
/**
  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 str_length       length of string 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
10177 10178
    thread.
*/
10179

10180
void 
10181
Field::set_datetime_warning(MYSQL_ERROR::enum_warning_level level, uint code, 
10182 10183 10184
                            const char *str, uint str_length, 
                            timestamp_type ts_type, int cuted_increment)
{
unknown's avatar
unknown committed
10185
  THD *thd= table ? table->in_use : current_thd;
10186 10187
  if ((thd->really_abort_on_warning() &&
       level >= MYSQL_ERROR::WARN_LEVEL_WARN) ||
unknown's avatar
unknown committed
10188
      set_warning(level, code, cuted_increment))
10189
    make_truncated_value_warning(thd, level, str, str_length, ts_type,
unknown's avatar
unknown committed
10190
                                 field_name);
10191 10192 10193
}


10194 10195
/**
  Produce warning or note about integer datetime value saved into field.
10196

10197 10198 10199 10200 10201 10202 10203 10204 10205
  @param level            level of message (Note/Warning/Error)
  @param code             error code of message to be produced
  @param nr               numeric 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
10206 10207
    thread.
*/
10208

10209
void 
10210
Field::set_datetime_warning(MYSQL_ERROR::enum_warning_level level, uint code, 
10211 10212 10213
                            longlong nr, timestamp_type ts_type,
                            int cuted_increment)
{
unknown's avatar
unknown committed
10214 10215
  THD *thd= table ? table->in_use : current_thd;
  if (thd->really_abort_on_warning() ||
unknown's avatar
unknown committed
10216
      set_warning(level, code, cuted_increment))
10217 10218 10219
  {
    char str_nr[22];
    char *str_end= longlong10_to_str(nr, str_nr, -10);
10220
    make_truncated_value_warning(thd, level, str_nr, (uint) (str_end - str_nr), 
unknown's avatar
unknown committed
10221
                                 ts_type, field_name);
10222 10223 10224 10225
  }
}


10226 10227
/**
  Produce warning or note about double datetime data saved into field.
10228

10229 10230 10231 10232 10233 10234 10235 10236
  @param level            level of message (Note/Warning/Error)
  @param code             error code of message to be produced
  @param nr               double value which we tried to save
  @param ts_type          type of datetime value (datetime/date/time)

  @note
    This function will always produce some warning but won't increase cut
    fields counter if count_cuted_fields == FIELD_CHECK_IGNORE for current
10237 10238
    thread.
*/
10239

10240
void 
10241
Field::set_datetime_warning(MYSQL_ERROR::enum_warning_level level, uint code, 
10242 10243
                            double nr, timestamp_type ts_type)
{
unknown's avatar
unknown committed
10244 10245
  THD *thd= table ? table->in_use : current_thd;
  if (thd->really_abort_on_warning() ||
unknown's avatar
unknown committed
10246
      set_warning(level, code, 1))
10247 10248 10249 10250
  {
    /* DBL_DIG is enough to print '-[digits].E+###' */
    char str_nr[DBL_DIG + 8];
    uint str_len= my_sprintf(str_nr, (str_nr, "%g", nr));
10251
    make_truncated_value_warning(thd, level, str_nr, str_len, ts_type,
unknown's avatar
unknown committed
10252
                                 field_name);
unknown's avatar
unknown committed
10253
  }
10254
}