item_timefunc.cc 90 KB
Newer Older
Kent Boortz's avatar
Kent Boortz committed
1
/*
Sergei Golubchik's avatar
Sergei Golubchik committed
2
   Copyright (c) 2000, 2012, Oracle and/or its affiliates.
3
   Copyright (c) 2009, 2016, MariaDB
unknown's avatar
unknown committed
4

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

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

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


unknown's avatar
unknown committed
19 20 21 22 23 24 25 26 27
/**
  @file

  @brief
  This file defines all time functions

  @todo
    Move month and days to language files
*/
unknown's avatar
unknown committed
28

29
#ifdef USE_PRAGMA_IMPLEMENTATION
unknown's avatar
unknown committed
30 31 32
#pragma implementation				// gcc: Class implementation
#endif

33
#include <my_global.h>
34 35 36 37 38 39 40 41 42 43 44
#include "sql_priv.h"
/*
  It is necessary to include set_var.h instead of item.h because there
  are dependencies on include order for set_var.h and item.h. This
  will be resolved later.
*/
#include "sql_class.h"                          // set_var.h: THD
#include "set_var.h"
#include "sql_locale.h"          // MY_LOCALE my_locale_en_US
#include "strfunc.h"             // check_word
#include "sql_time.h"            // make_truncated_value_warning,
Sergei Golubchik's avatar
Sergei Golubchik committed
45
                                 // get_date_from_daynr,
46 47 48
                                 // calc_weekday, calc_week,
                                 // convert_month_to_period,
                                 // convert_period_to_month,
Sergei Golubchik's avatar
Sergei Golubchik committed
49
                                 // TIME_to_timestamp,
50 51 52 53 54
                                 // calc_time_diff,
                                 // calc_time_from_sec,
                                 // get_date_time_format_str
#include "tztime.h"              // struct Time_zone
#include "sql_class.h"           // THD
unknown's avatar
unknown committed
55 56 57
#include <m_ctype.h>
#include <time.h>

unknown's avatar
unknown committed
58
/** Day number for Dec 31st, 9999. */
unknown's avatar
unknown committed
59 60
#define MAX_DAY_NUMBER 3652424L

unknown's avatar
unknown committed
61 62 63 64 65 66 67
/*
  Date formats corresponding to compound %r and %T conversion specifiers

  Note: We should init at least first element of "positions" array
        (first member) or hpux11 compiler will die horribly.
*/
static DATE_TIME_FORMAT time_ampm_format= {{0}, '\0', 0,
68
                                           {(char *)"%I:%i:%S %p", 11}};
unknown's avatar
unknown committed
69
static DATE_TIME_FORMAT time_24hrs_format= {{0}, '\0', 0,
70 71
                                            {(char *)"%H:%i:%S", 8}};

unknown's avatar
unknown committed
72
/**
73
  Extract datetime value to MYSQL_TIME struct from string value
unknown's avatar
unknown committed
74
  according to format string.
75

unknown's avatar
unknown committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
  @param format		date/time format specification
  @param val			String to decode
  @param length		Length of string
  @param l_time		Store result here
  @param cached_timestamp_type  It uses to get an appropriate warning
                                in the case when the value is truncated.
  @param sub_pattern_end    if non-zero then we are parsing string which
                            should correspond compound specifier (like %T or
                            %r) and this parameter is pointer to place where
                            pointer to end of string matching this specifier
                            should be stored.

  @note
    Possibility to parse strings matching to patterns equivalent to compound
    specifiers is mainly intended for use from inside of this function in
    order to understand %T and %r conversion specifiers, so number of
    conversion specifiers that can be used in such sub-patterns is limited.
    Also most of checks are skipped in this case.

  @note
    If one adds new format specifiers to this function he should also
    consider adding them to get_date_time_result_type() function.

  @retval
    0	ok
  @retval
    1	error
unknown's avatar
unknown committed
103
*/
104 105

static bool extract_date_time(DATE_TIME_FORMAT *format,
106
			      const char *val, uint length, MYSQL_TIME *l_time,
107
                              timestamp_type cached_timestamp_type,
108
                              const char **sub_pattern_end,
109
                              const char *date_time_type,
110
                              ulonglong fuzzy_date)
unknown's avatar
unknown committed
111
{
unknown's avatar
unknown committed
112
  int weekday= 0, yearday= 0, daypart= 0;
113
  int week_number= -1;
114
  int error= 0;
115
  int  strict_week_number_year= -1;
116
  int frac_part;
117
  bool usa_time= 0;
118 119 120
  bool UNINIT_VAR(sunday_first_n_first_week_non_iso);
  bool UNINIT_VAR(strict_week_number);
  bool UNINIT_VAR(strict_week_number_year_type);
121
  const char *val_begin= val;
122 123
  const char *val_end= val + length;
  const char *ptr= format->format.str;
124
  const char *end= ptr + format->format.length;
125
  CHARSET_INFO *cs= &my_charset_bin;
126
  DBUG_ENTER("extract_date_time");
127

128 129
  if (!sub_pattern_end)
    bzero((char*) l_time, sizeof(*l_time));
130

131 132
  l_time->time_type= cached_timestamp_type;

133
  for (; ptr != end && val != val_end; ptr++)
134
  {
135
    /* Skip pre-space between each argument */
136 137
    if ((val+= cs->cset->scan(cs, val, val_end, MY_SEQ_SPACES)) >= val_end)
      break;
138

139 140
    if (*ptr == '%' && ptr+1 != end)
    {
141 142 143
      int val_len;
      char *tmp;

144
      error= 0;
145 146

      val_len= (uint) (val_end - val);
147
      switch (*++ptr) {
148
	/* Year */
149
      case 'Y':
150
	tmp= (char*) val + MY_MIN(4, val_len);
151
	l_time->year= (int) my_strtoll10(val, &tmp, &error);
152 153
        if ((int) (tmp-val) <= 2)
          l_time->year= year_2000_handling(l_time->year);
154
	val= tmp;
155 156
	break;
      case 'y':
157
	tmp= (char*) val + MY_MIN(2, val_len);
158 159
	l_time->year= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
160
        l_time->year= year_2000_handling(l_time->year);
161
	break;
162 163

	/* Month */
164
      case 'm':
165
      case 'c':
166
	tmp= (char*) val + MY_MIN(2, val_len);
167 168 169 170
	l_time->month= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
	break;
      case 'M':
unknown's avatar
unknown committed
171 172 173 174
	if ((l_time->month= check_word(my_locale_en_US.month_names,
				       val, val_end, &val)) <= 0)
	  goto err;
	break;
175
      case 'b':
unknown's avatar
unknown committed
176
	if ((l_time->month= check_word(my_locale_en_US.ab_month_names,
177 178
				       val, val_end, &val)) <= 0)
	  goto err;
179
	break;
180
	/* Day */
181
      case 'd':
182
      case 'e':
183
	tmp= (char*) val + MY_MIN(2, val_len);
184 185
	l_time->day= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
186 187
	break;
      case 'D':
188
	tmp= (char*) val + MY_MIN(2, val_len);
189 190
	l_time->day= (int) my_strtoll10(val, &tmp, &error);
	/* Skip 'st, 'nd, 'th .. */
191
	val= tmp + MY_MIN((int) (val_end-tmp), 2);
192 193 194 195 196 197 198 199 200 201
	break;

	/* Hour */
      case 'h':
      case 'I':
      case 'l':
	usa_time= 1;
	/* fall through */
      case 'k':
      case 'H':
202
	tmp= (char*) val + MY_MIN(2, val_len);
203 204
	l_time->hour= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
205
	break;
206 207

	/* Minute */
208
      case 'i':
209
	tmp= (char*) val + MY_MIN(2, val_len);
210 211
	l_time->minute= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
212
	break;
213 214

	/* Second */
215 216
      case 's':
      case 'S':
217
	tmp= (char*) val + MY_MIN(2, val_len);
218 219
	l_time->second= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
220
	break;
221 222 223 224

	/* Second part */
      case 'f':
	tmp= (char*) val_end;
225 226
	if (tmp - val > 6)
	  tmp= (char*) val + 6;
unknown's avatar
unknown committed
227
	l_time->second_part= (int) my_strtoll10(val, &tmp, &error);
228
	frac_part= 6 - (int) (tmp - val);
229 230
	if (frac_part > 0)
	  l_time->second_part*= (ulong) log_10_int[frac_part];
231
	val= tmp;
232
	break;
233 234 235 236 237 238 239 240 241 242 243 244 245

	/* AM / PM */
      case 'p':
	if (val_len < 2 || ! usa_time)
	  goto err;
	if (!my_strnncoll(&my_charset_latin1,
			  (const uchar *) val, 2, 
			  (const uchar *) "PM", 2))
	  daypart= 12;
	else if (my_strnncoll(&my_charset_latin1,
			      (const uchar *) val, 2, 
			      (const uchar *) "AM", 2))
	  goto err;
246
	val+= 2;
247
	break;
248 249

	/* Exotic things */
250
      case 'W':
unknown's avatar
unknown committed
251 252 253
	if ((weekday= check_word(my_locale_en_US.day_names, val, val_end, &val)) <= 0)
	  goto err;
	break;
254
      case 'a':
unknown's avatar
unknown committed
255
	if ((weekday= check_word(my_locale_en_US.ab_day_names, val, val_end, &val)) <= 0)
256
	  goto err;
257 258
	break;
      case 'w':
259
	tmp= (char*) val + 1;
260
	if ((weekday= (int) my_strtoll10(val, &tmp, &error)) < 0 ||
261 262
	    weekday >= 7)
	  goto err;
263 264 265
        /* We should use the same 1 - 7 scale for %w as for %W */
        if (!weekday)
          weekday= 7;
266
	val= tmp;
267 268
	break;
      case 'j':
269
	tmp= (char*) val + MY_MIN(val_len, 3);
270 271
	yearday= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
272
	break;
273

274 275
        /* Week numbers */
      case 'V':
276
      case 'U':
277
      case 'v':
278
      case 'u':
279 280
        sunday_first_n_first_week_non_iso= (*ptr=='U' || *ptr== 'V');
        strict_week_number= (*ptr=='V' || *ptr=='v');
281
	tmp= (char*) val + MY_MIN(val_len, 2);
282
	if ((week_number= (int) my_strtoll10(val, &tmp, &error)) < 0 ||
283
            (strict_week_number && !week_number) ||
284 285
            week_number > 53)
          goto err;
286
	val= tmp;
287
	break;
288

289 290 291 292
        /* Year used with 'strict' %V and %v week numbers */
      case 'X':
      case 'x':
        strict_week_number_year_type= (*ptr=='X');
293
        tmp= (char*) val + MY_MIN(4, val_len);
294 295 296 297 298 299
        strict_week_number_year= (int) my_strtoll10(val, &tmp, &error);
        val= tmp;
        break;

        /* Time in AM/PM notation */
      case 'r':
300 301 302 303 304 305
        /*
          We can't just set error here, as we don't want to generate two
          warnings in case of errors
        */
        if (extract_date_time(&time_ampm_format, val,
                              (uint)(val_end - val), l_time,
306
                              cached_timestamp_type, &val, "time", fuzzy_date))
307
          DBUG_RETURN(1);
308 309 310 311
        break;

        /* Time in 24-hour notation */
      case 'T':
312 313
        if (extract_date_time(&time_24hrs_format, val,
                              (uint)(val_end - val), l_time,
314
                              cached_timestamp_type, &val, "time", fuzzy_date))
315
          DBUG_RETURN(1);
316 317 318
        break;

        /* Conversion specifiers that match classes of characters */
319 320 321 322 323 324 325 326 327 328 329 330
      case '.':
	while (my_ispunct(cs, *val) && val != val_end)
	  val++;
	break;
      case '@':
	while (my_isalpha(cs, *val) && val != val_end)
	  val++;
	break;
      case '#':
	while (my_isdigit(cs, *val) && val != val_end)
	  val++;
	break;
331
      default:
332
	goto err;
333
      }
334 335
      if (error)				// Error from my_strtoll10
	goto err;
336
    }
337
    else if (!my_isspace(cs, *ptr))
338
    {
339 340 341
      if (*val != *ptr)
	goto err;
      val++;
342 343 344 345 346
    }
  }
  if (usa_time)
  {
    if (l_time->hour > 12 || l_time->hour < 1)
347
      goto err;
348 349
    l_time->hour= l_time->hour%12+daypart;
  }
unknown's avatar
unknown committed
350

351 352 353 354 355 356 357 358 359 360
  /*
    If we are recursively called for parsing string matching compound
    specifiers we are already done.
  */
  if (sub_pattern_end)
  {
    *sub_pattern_end= val;
    DBUG_RETURN(0);
  }

361 362
  if (yearday > 0)
  {
363 364
    uint days;
    days= calc_daynr(l_time->year,1,1) +  yearday - 1;
365
    if (get_date_from_daynr(days,&l_time->year,&l_time->month,&l_time->day))
366
      goto err;
367
  }
unknown's avatar
unknown committed
368

369 370
  if (week_number >= 0 && weekday)
  {
371
    int days;
372 373
    uint weekday_b;

374 375 376 377
    /*
      %V,%v require %X,%x resprectively,
      %U,%u should be used with %Y and not %X or %x
    */
378
    if ((strict_week_number &&
379 380 381
         (strict_week_number_year < 0 ||
          strict_week_number_year_type !=
          sunday_first_n_first_week_non_iso)) ||
382
        (!strict_week_number && strict_week_number_year >= 0))
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
      goto err;

    /* Number of days since year 0 till 1st Jan of this year */
    days= calc_daynr((strict_week_number ? strict_week_number_year :
                                           l_time->year),
                     1, 1);
    /* Which day of week is 1st Jan of this year */
    weekday_b= calc_weekday(days, sunday_first_n_first_week_non_iso);

    /*
      Below we are going to sum:
      1) number of days since year 0 till 1st day of 1st week of this year
      2) number of days between 1st week and our week
      3) and position of our day in the week
    */
    if (sunday_first_n_first_week_non_iso)
399
    {
400 401 402
      days+= ((weekday_b == 0) ? 0 : 7) - weekday_b +
             (week_number - 1) * 7 +
             weekday % 7;
403 404 405
    }
    else
    {
406 407 408
      days+= ((weekday_b <= 3) ? 0 : 7) - weekday_b +
             (week_number - 1) * 7 +
             (weekday - 1);
409
    }
410

411
    if (get_date_from_daynr(days,&l_time->year,&l_time->month,&l_time->day))
412
      goto err;
unknown's avatar
unknown committed
413 414
  }

415 416
  if (l_time->month > 12 || l_time->day > 31 || l_time->hour > 23 || 
      l_time->minute > 59 || l_time->second > 59)
417
    goto err;
418

419 420
  int was_cut;
  if (check_date(l_time, fuzzy_date | TIME_INVALID_DATES, &was_cut))
421 422
    goto err;

423 424 425 426 427 428
  if (val != val_end)
  {
    do
    {
      if (!my_isspace(&my_charset_latin1,*val))
      {
429
        make_truncated_value_warning(current_thd,
430
                                     Sql_condition::WARN_LEVEL_WARN,
431
                                     val_begin, length,
unknown's avatar
unknown committed
432
				     cached_timestamp_type, NullS);
433 434 435 436
	break;
      }
    } while (++val != val_end);
  }
437 438
  DBUG_RETURN(0);

439
err:
440
  {
441
    THD *thd= current_thd;
442
    char buff[128];
443
    strmake(buff, val_begin, MY_MIN(length, sizeof(buff)-1));
444 445 446
    push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                        ER_WRONG_VALUE_FOR_TYPE,
                        ER_THD(thd, ER_WRONG_VALUE_FOR_TYPE),
447
                        date_time_type, buff, "str_to_date");
448
  }
449 450
  DBUG_RETURN(1);
}
451 452


unknown's avatar
unknown committed
453 454
/**
  Create a formated date/time value in a string.
455 456
*/

457 458
static bool make_date_time(DATE_TIME_FORMAT *format, MYSQL_TIME *l_time,
                           timestamp_type type, MY_LOCALE *locale, String *str)
459 460 461 462 463
{
  char intbuff[15];
  uint hours_i;
  uint weekday;
  ulong length;
464 465 466 467
  const char *ptr, *end;

  str->length(0);

468
  if (l_time->neg)
469
    str->append('-');
470 471
  
  end= (ptr= format->format.str) + format->format.length;
472 473 474 475 476 477 478 479
  for (; ptr != end ; ptr++)
  {
    if (*ptr != '%' || ptr+1 == end)
      str->append(*ptr);
    else
    {
      switch (*++ptr) {
      case 'M':
480 481 482
        if (!l_time->month)
          return 1;
        str->append(locale->month_names->type_names[l_time->month-1],
483
                    (uint) strlen(locale->month_names->type_names[l_time->month-1]),
484 485
                    system_charset_info);
        break;
486
      case 'b':
487 488 489
        if (!l_time->month)
          return 1;
        str->append(locale->ab_month_names->type_names[l_time->month-1],
490
                    (uint) strlen(locale->ab_month_names->type_names[l_time->month-1]),
491 492
                    system_charset_info);
        break;
493
      case 'W':
494
        if (type == MYSQL_TIMESTAMP_TIME || !(l_time->month || l_time->year))
495 496 497 498
          return 1;
        weekday= calc_weekday(calc_daynr(l_time->year,l_time->month,
                              l_time->day),0);
        str->append(locale->day_names->type_names[weekday],
499
                    (uint) strlen(locale->day_names->type_names[weekday]),
500 501
                    system_charset_info);
        break;
502
      case 'a':
503
        if (type == MYSQL_TIMESTAMP_TIME || !(l_time->month || l_time->year))
504 505 506 507
          return 1;
        weekday=calc_weekday(calc_daynr(l_time->year,l_time->month,
                             l_time->day),0);
        str->append(locale->ab_day_names->type_names[weekday],
508
                    (uint) strlen(locale->ab_day_names->type_names[weekday]),
509 510
                    system_charset_info);
        break;
511
      case 'D':
512
	if (type == MYSQL_TIMESTAMP_TIME)
513
	  return 1;
514
	length= (uint) (int10_to_str(l_time->day, intbuff, 10) - intbuff);
515 516
	str->append_with_prefill(intbuff, length, 1, '0');
	if (l_time->day >= 10 &&  l_time->day <= 19)
517
	  str->append(STRING_WITH_LEN("th"));
518 519 520 521
	else
	{
	  switch (l_time->day %10) {
	  case 1:
522
	    str->append(STRING_WITH_LEN("st"));
523 524
	    break;
	  case 2:
525
	    str->append(STRING_WITH_LEN("nd"));
526 527
	    break;
	  case 3:
528
	    str->append(STRING_WITH_LEN("rd"));
529 530
	    break;
	  default:
531
	    str->append(STRING_WITH_LEN("th"));
532 533 534 535 536
	    break;
	  }
	}
	break;
      case 'Y':
537
	length= (uint) (int10_to_str(l_time->year, intbuff, 10) - intbuff);
538 539 540
	str->append_with_prefill(intbuff, length, 4, '0');
	break;
      case 'y':
541
	length= (uint) (int10_to_str(l_time->year%100, intbuff, 10) - intbuff);
542 543 544
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'm':
545
	length= (uint) (int10_to_str(l_time->month, intbuff, 10) - intbuff);
546 547 548
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'c':
549
	length= (uint) (int10_to_str(l_time->month, intbuff, 10) - intbuff);
550 551 552
	str->append_with_prefill(intbuff, length, 1, '0');
	break;
      case 'd':
553
	length= (uint) (int10_to_str(l_time->day, intbuff, 10) - intbuff);
554 555 556
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'e':
557
	length= (uint) (int10_to_str(l_time->day, intbuff, 10) - intbuff);
558 559 560
	str->append_with_prefill(intbuff, length, 1, '0');
	break;
      case 'f':
561
	length= (uint) (int10_to_str(l_time->second_part, intbuff, 10) - intbuff);
562 563 564
	str->append_with_prefill(intbuff, length, 6, '0');
	break;
      case 'H':
565
	length= (uint) (int10_to_str(l_time->hour, intbuff, 10) - intbuff);
566 567 568 569
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'h':
      case 'I':
570
	hours_i= (l_time->hour%24 + 11)%12+1;
571
	length= (uint) (int10_to_str(hours_i, intbuff, 10) - intbuff);
572 573 574
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'i':					/* minutes */
575
	length= (uint) (int10_to_str(l_time->minute, intbuff, 10) - intbuff);
576 577 578
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'j':
579
	if (type == MYSQL_TIMESTAMP_TIME)
580
	  return 1;
581
	length= (uint) (int10_to_str(calc_daynr(l_time->year,l_time->month,
582
					l_time->day) - 
583
		     calc_daynr(l_time->year,1,1) + 1, intbuff, 10) - intbuff);
584 585 586
	str->append_with_prefill(intbuff, length, 3, '0');
	break;
      case 'k':
587
	length= (uint) (int10_to_str(l_time->hour, intbuff, 10) - intbuff);
588 589 590
	str->append_with_prefill(intbuff, length, 1, '0');
	break;
      case 'l':
591
	hours_i= (l_time->hour%24 + 11)%12+1;
592
	length= (uint) (int10_to_str(hours_i, intbuff, 10) - intbuff);
593 594 595 596 597 598 599
	str->append_with_prefill(intbuff, length, 1, '0');
	break;
      case 'p':
	hours_i= l_time->hour%24;
	str->append(hours_i < 12 ? "AM" : "PM",2);
	break;
      case 'r':
Sergei Golubchik's avatar
Sergei Golubchik committed
600
	length= sprintf(intbuff, ((l_time->hour % 24) < 12) ?
unknown's avatar
unknown committed
601
                    "%02d:%02d:%02d AM" : "%02d:%02d:%02d PM",
602 603
		    (l_time->hour+11)%12+1,
		    l_time->minute,
Sergei Golubchik's avatar
Sergei Golubchik committed
604
		    l_time->second);
605 606 607 608
	str->append(intbuff, length);
	break;
      case 'S':
      case 's':
609
	length= (uint) (int10_to_str(l_time->second, intbuff, 10) - intbuff);
610 611 612
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'T':
Sergei Golubchik's avatar
Sergei Golubchik committed
613 614
	length= sprintf(intbuff, "%02d:%02d:%02d",
		    l_time->hour, l_time->minute, l_time->second);
615 616 617 618 619 620
	str->append(intbuff, length);
	break;
      case 'U':
      case 'u':
      {
	uint year;
621
	if (type == MYSQL_TIMESTAMP_TIME)
622
	  return 1;
623
	length= (uint) (int10_to_str(calc_week(l_time,
unknown's avatar
unknown committed
624 625 626
				       (*ptr) == 'U' ?
				       WEEK_FIRST_WEEKDAY : WEEK_MONDAY_FIRST,
				       &year),
627
			     intbuff, 10) - intbuff);
628 629 630 631 632 633 634
	str->append_with_prefill(intbuff, length, 2, '0');
      }
      break;
      case 'v':
      case 'V':
      {
	uint year;
635
	if (type == MYSQL_TIMESTAMP_TIME)
636
	  return 1;
637
	length= (uint) (int10_to_str(calc_week(l_time,
unknown's avatar
unknown committed
638 639 640 641
				       ((*ptr) == 'V' ?
					(WEEK_YEAR | WEEK_FIRST_WEEKDAY) :
					(WEEK_YEAR | WEEK_MONDAY_FIRST)),
				       &year),
642
			     intbuff, 10) - intbuff);
643 644 645 646 647 648 649
	str->append_with_prefill(intbuff, length, 2, '0');
      }
      break;
      case 'x':
      case 'X':
      {
	uint year;
650
	if (type == MYSQL_TIMESTAMP_TIME)
651
	  return 1;
unknown's avatar
unknown committed
652 653 654 655 656
	(void) calc_week(l_time,
			 ((*ptr) == 'X' ?
			  WEEK_YEAR | WEEK_FIRST_WEEKDAY :
			  WEEK_YEAR | WEEK_MONDAY_FIRST),
			 &year);
657
	length= (uint) (int10_to_str(year, intbuff, 10) - intbuff);
658 659 660 661
	str->append_with_prefill(intbuff, length, 4, '0');
      }
      break;
      case 'w':
662
	if (type == MYSQL_TIMESTAMP_TIME || !(l_time->month || l_time->year))
663 664 665
	  return 1;
	weekday=calc_weekday(calc_daynr(l_time->year,l_time->month,
					l_time->day),1);
666
	length= (uint) (int10_to_str(weekday, intbuff, 10) - intbuff);
667 668
	str->append_with_prefill(intbuff, length, 1, '0');
	break;
669

670 671 672 673 674 675
      default:
	str->append(*ptr);
	break;
      }
    }
  }
676
  return 0;
unknown's avatar
unknown committed
677 678
}

679

unknown's avatar
unknown committed
680 681
/**
  @details
682 683 684 685 686 687 688
  Get a array of positive numbers from a string object.
  Each number is separated by 1 non digit character
  Return error if there is too many numbers.
  If there is too few numbers, assume that the numbers are left out
  from the high end. This allows one to give:
  DAY_TO_SECOND as "D MM:HH:SS", "MM:HH:SS" "HH:SS" or as seconds.

unknown's avatar
unknown committed
689 690 691 692 693 694 695 696
  @param length:         length of str
  @param cs:             charset of str
  @param values:         array of results
  @param count:          count of elements in result array
  @param transform_msec: if value is true we suppose
                         that the last part of string value is microseconds
                         and we should transform value to six digit value.
                         For example, '1.1' -> '1.100000'
unknown's avatar
unknown committed
697 698
*/

unknown's avatar
unknown committed
699
static bool get_interval_info(const char *str,uint length,CHARSET_INFO *cs,
unknown's avatar
unknown committed
700 701
                              uint count, ulonglong *values,
                              bool transform_msec)
unknown's avatar
unknown committed
702 703 704
{
  const char *end=str+length;
  uint i;
705 706
  long msec_length= 0;

707
  while (str != end && !my_isdigit(cs,*str))
unknown's avatar
unknown committed
708 709 710 711
    str++;

  for (i=0 ; i < count ; i++)
  {
712
    longlong value;
713
    const char *start= str;
714
    for (value= 0; str != end && my_isdigit(cs, *str); str++)
715
      value= value*10 + *str - '0';
Evgeny Potemkin's avatar
Evgeny Potemkin committed
716
    msec_length= 6 - (str - start);
unknown's avatar
unknown committed
717
    values[i]= value;
718
    while (str != end && !my_isdigit(cs,*str))
unknown's avatar
unknown committed
719 720 721 722 723
      str++;
    if (str == end && i != count-1)
    {
      i++;
      /* Change values[0...i-1] -> values[0...count-1] */
724
      bmove_upp((uchar*) (values+count), (uchar*) (values+i),
725
		sizeof(*values)*i);
726
      bzero((uchar*) values, sizeof(*values)*(count-i));
unknown's avatar
unknown committed
727 728 729
      break;
    }
  }
730 731 732 733

  if (transform_msec && msec_length > 0)
    values[count - 1] *= (long) log_10_int[msec_length];

unknown's avatar
unknown committed
734 735 736
  return (str != end);
}

unknown's avatar
unknown committed
737

unknown's avatar
unknown committed
738 739
longlong Item_func_period_add::val_int()
{
740
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
741 742 743 744 745 746 747 748 749 750 751 752 753 754
  ulong period=(ulong) args[0]->val_int();
  int months=(int) args[1]->val_int();

  if ((null_value=args[0]->null_value || args[1]->null_value) ||
      period == 0L)
    return 0; /* purecov: inspected */
  return (longlong)
    convert_month_to_period((uint) ((int) convert_period_to_month(period)+
				    months));
}


longlong Item_func_period_diff::val_int()
{
755
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
756 757 758 759 760 761 762 763 764 765 766 767 768
  ulong period1=(ulong) args[0]->val_int();
  ulong period2=(ulong) args[1]->val_int();

  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0; /* purecov: inspected */
  return (longlong) ((long) convert_period_to_month(period1)-
		     (long) convert_period_to_month(period2));
}



longlong Item_func_to_days::val_int()
{
769
  DBUG_ASSERT(fixed == 1);
770
  MYSQL_TIME ltime;
771
  if (get_arg0_date(&ltime, TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE))
unknown's avatar
unknown committed
772 773 774 775
    return 0;
  return (longlong) calc_daynr(ltime.year,ltime.month,ltime.day);
}

776

777 778 779
longlong Item_func_to_seconds::val_int_endpoint(bool left_endp,
                                                bool *incl_endp)
{
780 781 782 783 784
  DBUG_ASSERT(fixed == 1);
  MYSQL_TIME ltime;
  longlong seconds;
  longlong days;
  int dummy;                                /* unused */
Alexander Barkov's avatar
Alexander Barkov committed
785
  if (get_arg0_date(&ltime, TIME_FUZZY_DATES))
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
  {
    /* got NULL, leave the incl_endp intact */
    return LONGLONG_MIN;
  }
  seconds= ltime.hour * 3600L + ltime.minute * 60 + ltime.second;
  seconds= ltime.neg ? -seconds : seconds;
  days= (longlong) calc_daynr(ltime.year, ltime.month, ltime.day);
  seconds+= days * 24L * 3600L;
  /* Set to NULL if invalid date, but keep the value */
  null_value= check_date(&ltime,
                         (ltime.year || ltime.month || ltime.day),
                         (TIME_NO_ZERO_IN_DATE | TIME_NO_ZERO_DATE),
                         &dummy);
  /*
    Even if the evaluation return NULL, seconds is useful for pruning
  */
  return seconds;
803 804 805 806 807 808 809 810
}

longlong Item_func_to_seconds::val_int()
{
  DBUG_ASSERT(fixed == 1);
  MYSQL_TIME ltime;
  longlong seconds;
  longlong days;
Sergei Golubchik's avatar
Sergei Golubchik committed
811
  if (get_arg0_date(&ltime, TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE))
812
    return 0;
813
  seconds= ltime.hour * 3600L + ltime.minute * 60 + ltime.second;
814
  seconds=ltime.neg ? -seconds : seconds;
815 816
  days= (longlong) calc_daynr(ltime.year, ltime.month, ltime.day);
  return seconds + days * 24L * 3600L;
817 818
}

819 820 821 822 823 824 825 826 827 828 829 830 831 832
/*
  Get information about this Item tree monotonicity

  SYNOPSIS
    Item_func_to_days::get_monotonicity_info()

  DESCRIPTION
  Get information about monotonicity of the function represented by this item
  tree.

  RETURN
    See enum_monotonicity_info.
*/

unknown's avatar
unknown committed
833 834 835 836 837
enum_monotonicity_info Item_func_to_days::get_monotonicity_info() const
{
  if (args[0]->type() == Item::FIELD_ITEM)
  {
    if (args[0]->field_type() == MYSQL_TYPE_DATE)
838
      return MONOTONIC_STRICT_INCREASING_NOT_NULL;
unknown's avatar
unknown committed
839
    if (args[0]->field_type() == MYSQL_TYPE_DATETIME)
840
      return MONOTONIC_INCREASING_NOT_NULL;
unknown's avatar
unknown committed
841 842 843 844
  }
  return NON_MONOTONIC;
}

845 846 847 848
enum_monotonicity_info Item_func_to_seconds::get_monotonicity_info() const
{
  if (args[0]->type() == Item::FIELD_ITEM)
  {
849 850 851
    if (args[0]->field_type() == MYSQL_TYPE_DATE ||
        args[0]->field_type() == MYSQL_TYPE_DATETIME)
      return MONOTONIC_STRICT_INCREASING_NOT_NULL;
852 853 854 855
  }
  return NON_MONOTONIC;
}

unknown's avatar
unknown committed
856

857 858 859 860 861
longlong Item_func_to_days::val_int_endpoint(bool left_endp, bool *incl_endp)
{
  DBUG_ASSERT(fixed == 1);
  MYSQL_TIME ltime;
  longlong res;
862
  int dummy;                                /* unused */
863
  if (get_arg0_date(&ltime, 0))
864 865 866 867 868
  {
    /* got NULL, leave the incl_endp intact */
    return LONGLONG_MIN;
  }
  res=(longlong) calc_daynr(ltime.year,ltime.month,ltime.day);
869 870 871 872 873 874 875 876 877 878 879 880 881
  /* Set to NULL if invalid date, but keep the value */
  null_value= check_date(&ltime,
                         (TIME_NO_ZERO_IN_DATE | TIME_NO_ZERO_DATE),
                         &dummy);
  if (null_value)
  {
    /*
      Even if the evaluation return NULL, the calc_daynr is useful for pruning
    */
    if (args[0]->field_type() != MYSQL_TYPE_DATE)
      *incl_endp= TRUE;
    return res;
  }
882 883 884 885 886 887 888 889 890 891 892 893
  
  if (args[0]->field_type() == MYSQL_TYPE_DATE)
  {
    // TO_DAYS() is strictly monotonic for dates, leave incl_endp intact
    return res;
  }
 
  /*
    Handle the special but practically useful case of datetime values that
    point to day bound ("strictly less" comparison stays intact):

      col < '2007-09-15 00:00:00'  -> TO_DAYS(col) <  TO_DAYS('2007-09-15')
894
      col > '2007-09-15 23:59:59'  -> TO_DAYS(col) >  TO_DAYS('2007-09-15')
895 896 897 898 899 900

    which is different from the general case ("strictly less" changes to
    "less or equal"):

      col < '2007-09-15 12:34:56'  -> TO_DAYS(col) <= TO_DAYS('2007-09-15')
  */
901 902 903 904 905 906
  if ((!left_endp && !(ltime.hour || ltime.minute || ltime.second ||
                       ltime.second_part)) ||
       (left_endp && ltime.hour == 23 && ltime.minute == 59 &&
        ltime.second == 59))
    /* do nothing */
    ;
907 908 909 910 911 912
  else
    *incl_endp= TRUE;
  return res;
}


unknown's avatar
unknown committed
913 914
longlong Item_func_dayofyear::val_int()
{
915
  DBUG_ASSERT(fixed == 1);
916
  MYSQL_TIME ltime;
Sergei Golubchik's avatar
Sergei Golubchik committed
917
  if (get_arg0_date(&ltime, TIME_NO_ZERO_IN_DATE | TIME_NO_ZERO_DATE))
unknown's avatar
unknown committed
918 919 920 921 922 923 924
    return 0;
  return (longlong) calc_daynr(ltime.year,ltime.month,ltime.day) -
    calc_daynr(ltime.year,1,1) + 1;
}

longlong Item_func_dayofmonth::val_int()
{
925
  DBUG_ASSERT(fixed == 1);
926
  MYSQL_TIME ltime;
927
  return get_arg0_date(&ltime, 0) ? 0 : (longlong) ltime.day;
unknown's avatar
unknown committed
928 929 930 931
}

longlong Item_func_month::val_int()
{
932
  DBUG_ASSERT(fixed == 1);
933
  MYSQL_TIME ltime;
934
  return get_arg0_date(&ltime, 0) ? 0 : (longlong) ltime.month;
unknown's avatar
unknown committed
935 936
}

937

938 939 940 941 942
void Item_func_monthname::fix_length_and_dec()
{
  THD* thd= current_thd;
  CHARSET_INFO *cs= thd->variables.collation_connection;
  locale= thd->variables.lc_time_names;  
943
  collation.set(cs, DERIVATION_COERCIBLE, locale->repertoire());
944 945
  decimals=0;
  max_length= locale->max_month_name_length * collation.collation->mbmaxlen;
946
  maybe_null=1; 
947 948 949
}


unknown's avatar
unknown committed
950 951
String* Item_func_monthname::val_str(String* str)
{
952
  DBUG_ASSERT(fixed == 1);
953
  const char *month_name;
954
  uint err;
955
  MYSQL_TIME ltime;
956

Alexander Barkov's avatar
Alexander Barkov committed
957
  if ((null_value= (get_arg0_date(&ltime, 0) || !ltime.month)))
958 959 960
    return (String *) 0;

  month_name= locale->month_names->type_names[ltime.month - 1];
961
  str->copy(month_name, (uint) strlen(month_name), &my_charset_utf8_bin,
962
	    collation.collation, &err);
963
  return str;
unknown's avatar
unknown committed
964 965
}

966

unknown's avatar
unknown committed
967 968 969
/**
  Returns the quarter of the year.
*/
unknown's avatar
unknown committed
970 971 972

longlong Item_func_quarter::val_int()
{
973
  DBUG_ASSERT(fixed == 1);
974
  MYSQL_TIME ltime;
975
  if (get_arg0_date(&ltime, 0))
976
    return 0;
unknown's avatar
unknown committed
977 978 979 980 981
  return (longlong) ((ltime.month+2)/3);
}

longlong Item_func_hour::val_int()
{
982
  DBUG_ASSERT(fixed == 1);
983
  MYSQL_TIME ltime;
984
  return get_arg0_time(&ltime) ? 0 : ltime.hour;
unknown's avatar
unknown committed
985 986 987 988
}

longlong Item_func_minute::val_int()
{
989
  DBUG_ASSERT(fixed == 1);
990
  MYSQL_TIME ltime;
991
  return get_arg0_time(&ltime) ? 0 : ltime.minute;
unknown's avatar
unknown committed
992 993
}

unknown's avatar
unknown committed
994 995 996
/**
  Returns the second in time_exp in the range of 0 - 59.
*/
unknown's avatar
unknown committed
997 998
longlong Item_func_second::val_int()
{
999
  DBUG_ASSERT(fixed == 1);
1000
  MYSQL_TIME ltime;
1001
  return get_arg0_time(&ltime) ? 0 : ltime.second;
unknown's avatar
unknown committed
1002 1003 1004
}


1005 1006 1007 1008 1009 1010 1011
uint week_mode(uint mode)
{
  uint week_format= (mode & 7);
  if (!(week_format & WEEK_MONDAY_FIRST))
    week_format^= WEEK_FIRST_WEEKDAY;
  return week_format;
}
1012

unknown's avatar
unknown committed
1013 1014
/**
 @verbatim
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
  The bits in week_format(for calc_week() function) has the following meaning:
   WEEK_MONDAY_FIRST (0)  If not set	Sunday is first day of week
      		   	  If set	Monday is first day of week
   WEEK_YEAR (1)	  If not set	Week is in range 0-53

   	Week 0 is returned for the the last week of the previous year (for
	a date at start of january) In this case one can get 53 for the
	first week of next year.  This flag ensures that the week is
	relevant for the given year. Note that this flag is only
	releveant if WEEK_JANUARY is not set.

			  If set	 Week is in range 1-53.

	In this case one may get week 53 for a date in January (when
	the week is that last week of previous year) and week 1 for a
	date in December.

  WEEK_FIRST_WEEKDAY (2)  If not set	Weeks are numbered according
			   		to ISO 8601:1988
			  If set	The week that contains the first
					'first-day-of-week' is week 1.
	
	ISO 8601:1988 means that if the week containing January 1 has
	four or more days in the new year, then it is week 1;
	Otherwise it is the last week of the previous year, and the
	next week is week 1.
unknown's avatar
unknown committed
1041
 @endverbatim
1042
*/
unknown's avatar
unknown committed
1043 1044 1045

longlong Item_func_week::val_int()
{
1046
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1047
  uint year;
1048
  MYSQL_TIME ltime;
1049
  if (get_arg0_date(&ltime, TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE))
unknown's avatar
unknown committed
1050
    return 0;
1051 1052
  return (longlong) calc_week(&ltime,
			      week_mode((uint) args[1]->val_int()),
1053
			      &year);
unknown's avatar
unknown committed
1054 1055 1056 1057 1058
}


longlong Item_func_yearweek::val_int()
{
1059
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1060
  uint year,week;
1061
  MYSQL_TIME ltime;
1062
  if (get_arg0_date(&ltime, TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE))
unknown's avatar
unknown committed
1063
    return 0;
1064 1065 1066
  week= calc_week(&ltime, 
		  (week_mode((uint) args[1]->val_int()) | WEEK_YEAR),
		  &year);
unknown's avatar
unknown committed
1067 1068 1069 1070 1071 1072
  return week+year*100;
}


longlong Item_func_weekday::val_int()
{
1073
  DBUG_ASSERT(fixed == 1);
1074
  MYSQL_TIME ltime;
1075
  
1076
  if (get_arg0_date(&ltime, TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE))
1077
    return 0;
unknown's avatar
unknown committed
1078

1079 1080
  return (longlong) calc_weekday(calc_daynr(ltime.year, ltime.month,
                                            ltime.day),
1081
                                 odbc_type) + MY_TEST(odbc_type);
unknown's avatar
unknown committed
1082 1083
}

1084 1085 1086 1087 1088
void Item_func_dayname::fix_length_and_dec()
{
  THD* thd= current_thd;
  CHARSET_INFO *cs= thd->variables.collation_connection;
  locale= thd->variables.lc_time_names;  
1089
  collation.set(cs, DERIVATION_COERCIBLE, locale->repertoire());
1090 1091
  decimals=0;
  max_length= locale->max_day_name_length * collation.collation->mbmaxlen;
1092
  maybe_null=1; 
1093 1094
}

1095

unknown's avatar
unknown committed
1096 1097
String* Item_func_dayname::val_str(String* str)
{
1098
  DBUG_ASSERT(fixed == 1);
1099
  uint weekday=(uint) val_int();		// Always Item_func_weekday()
1100
  const char *day_name;
1101
  uint err;
1102

unknown's avatar
unknown committed
1103 1104
  if (null_value)
    return (String*) 0;
1105
  
1106
  day_name= locale->day_names->type_names[weekday];
1107
  str->copy(day_name, (uint) strlen(day_name), &my_charset_utf8_bin,
1108
	    collation.collation, &err);
1109
  return str;
unknown's avatar
unknown committed
1110 1111 1112 1113 1114
}


longlong Item_func_year::val_int()
{
1115
  DBUG_ASSERT(fixed == 1);
1116
  MYSQL_TIME ltime;
1117
  return get_arg0_date(&ltime, 0) ? 0 : (longlong) ltime.year;
unknown's avatar
unknown committed
1118 1119
}

1120 1121 1122 1123 1124

/*
  Get information about this Item tree monotonicity

  SYNOPSIS
1125
    Item_func_year::get_monotonicity_info()
1126 1127 1128 1129 1130 1131 1132 1133 1134

  DESCRIPTION
  Get information about monotonicity of the function represented by this item
  tree.

  RETURN
    See enum_monotonicity_info.
*/

unknown's avatar
unknown committed
1135 1136 1137 1138 1139 1140 1141 1142
enum_monotonicity_info Item_func_year::get_monotonicity_info() const
{
  if (args[0]->type() == Item::FIELD_ITEM &&
      (args[0]->field_type() == MYSQL_TYPE_DATE ||
       args[0]->field_type() == MYSQL_TYPE_DATETIME))
    return MONOTONIC_INCREASING;
  return NON_MONOTONIC;
}
unknown's avatar
unknown committed
1143

1144 1145 1146 1147 1148

longlong Item_func_year::val_int_endpoint(bool left_endp, bool *incl_endp)
{
  DBUG_ASSERT(fixed == 1);
  MYSQL_TIME ltime;
1149
  if (get_arg0_date(&ltime, 0))
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
  {
    /* got NULL, leave the incl_endp intact */
    return LONGLONG_MIN;
  }

  /*
    Handle the special but practically useful case of datetime values that
    point to year bound ("strictly less" comparison stays intact) :

      col < '2007-01-01 00:00:00'  -> YEAR(col) <  2007

    which is different from the general case ("strictly less" changes to
    "less or equal"):

      col < '2007-09-15 23:00:00'  -> YEAR(col) <= 2007
  */
  if (!left_endp && ltime.day == 1 && ltime.month == 1 && 
      !(ltime.hour || ltime.minute || ltime.second || ltime.second_part))
    ; /* do nothing */
  else
    *incl_endp= TRUE;
  return ltime.year;
}


1175 1176
bool Item_func_unix_timestamp::get_timestamp_value(my_time_t *seconds,
                                                   ulong *second_part)
unknown's avatar
unknown committed
1177
{
1178
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1179 1180 1181
  if (args[0]->type() == FIELD_ITEM)
  {						// Optimize timestamp field
    Field *field=((Item_field*) args[0])->field;
1182
    if (field->type() == MYSQL_TYPE_TIMESTAMP)
1183 1184
    {
      if ((null_value= field->is_null()))
1185 1186 1187
        return 1;
      *seconds= ((Field_timestamp*)field)->get_timestamp(second_part);
      return 0;
1188
    }
unknown's avatar
unknown committed
1189
  }
1190 1191

  MYSQL_TIME ltime;
1192
  if (get_arg0_date(&ltime, TIME_NO_ZERO_IN_DATE))
1193 1194
    return 1;

Michael Widenius's avatar
Michael Widenius committed
1195 1196
  uint error_code;
  *seconds= TIME_to_timestamp(current_thd, &ltime, &error_code);
1197
  *second_part= ltime.second_part;
Michael Widenius's avatar
Michael Widenius committed
1198
  return (null_value= (error_code == ER_WARN_DATA_OUT_OF_RANGE));
1199 1200 1201 1202 1203 1204 1205
}


longlong Item_func_unix_timestamp::int_op()
{
  if (arg_count == 0)
    return (longlong) current_thd->query_start();
1206
  
1207 1208 1209 1210 1211 1212
  ulong second_part;
  my_time_t seconds;
  if (get_timestamp_value(&seconds, &second_part))
    return 0;

  return seconds;
unknown's avatar
unknown committed
1213 1214 1215
}


1216
my_decimal *Item_func_unix_timestamp::decimal_op(my_decimal* buf)
1217 1218 1219 1220 1221 1222
{
  ulong second_part;
  my_time_t seconds;
  if (get_timestamp_value(&seconds, &second_part))
    return 0;

1223 1224
  return seconds2my_decimal(seconds < 0, seconds < 0 ? -seconds : seconds,
                            second_part, buf);
unknown's avatar
unknown committed
1225 1226
}

1227

Mattias Jonsson's avatar
Mattias Jonsson committed
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
enum_monotonicity_info Item_func_unix_timestamp::get_monotonicity_info() const
{
  if (args[0]->type() == Item::FIELD_ITEM &&
      (args[0]->field_type() == MYSQL_TYPE_TIMESTAMP))
    return MONOTONIC_INCREASING;
  return NON_MONOTONIC;
}


longlong Item_func_unix_timestamp::val_int_endpoint(bool left_endp, bool *incl_endp)
{
  DBUG_ASSERT(fixed == 1);
  DBUG_ASSERT(arg_count == 1 &&
              args[0]->type() == Item::FIELD_ITEM &&
              args[0]->field_type() == MYSQL_TYPE_TIMESTAMP);
Sergei Golubchik's avatar
Sergei Golubchik committed
1243
  Field_timestamp *field=(Field_timestamp *)(((Item_field*)args[0])->field);
Mattias Jonsson's avatar
Mattias Jonsson committed
1244
  /* Leave the incl_endp intact */
Sergei Golubchik's avatar
Sergei Golubchik committed
1245 1246 1247 1248
  ulong unused;
  my_time_t ts= field->get_timestamp(&unused);
  null_value= field->is_null();
  return ts;
Mattias Jonsson's avatar
Mattias Jonsson committed
1249 1250
}

unknown's avatar
unknown committed
1251

1252
longlong Item_func_time_to_sec::int_op()
unknown's avatar
unknown committed
1253
{
1254
  DBUG_ASSERT(fixed == 1);
1255
  MYSQL_TIME ltime;
1256 1257 1258 1259
  if (get_arg0_time(&ltime))
    return 0;

  longlong seconds=ltime.hour*3600L+ltime.minute*60+ltime.second;
1260
  return ltime.neg ? -seconds : seconds;
unknown's avatar
unknown committed
1261 1262 1263
}


1264
my_decimal *Item_func_time_to_sec::decimal_op(my_decimal* buf)
unknown's avatar
unknown committed
1265
{
1266
  DBUG_ASSERT(fixed == 1);
1267
  MYSQL_TIME ltime;
1268 1269 1270 1271 1272
  if (get_arg0_time(&ltime))
    return 0;

  longlong seconds= ltime.hour*3600L+ltime.minute*60+ltime.second;
  return seconds2my_decimal(ltime.neg, seconds, ltime.second_part, buf);
unknown's avatar
unknown committed
1273 1274 1275
}


unknown's avatar
unknown committed
1276 1277 1278
/**
  Convert a string to a interval value.

1279
  To make code easy, allow interval objects without separators.
unknown's avatar
unknown committed
1280 1281
*/

Sergei Golubchik's avatar
Sergei Golubchik committed
1282
bool get_interval_value(Item *args,interval_type int_type, INTERVAL *interval)
unknown's avatar
unknown committed
1283
{
unknown's avatar
unknown committed
1284
  ulonglong array[5];
1285 1286 1287
  longlong UNINIT_VAR(value);
  const char *UNINIT_VAR(str);
  size_t UNINIT_VAR(length);
Sergei Golubchik's avatar
Sergei Golubchik committed
1288 1289 1290
  CHARSET_INFO *UNINIT_VAR(cs);
  char buf[100];
  String str_value(buf, sizeof(buf), &my_charset_bin);
unknown's avatar
unknown committed
1291

1292
  bzero((char*) interval,sizeof(*interval));
1293 1294 1295 1296 1297 1298 1299 1300
  if (int_type == INTERVAL_SECOND && args->decimals)
  {
    my_decimal decimal_value, *val;
    ulonglong second;
    ulong second_part;
    if (!(val= args->val_decimal(&decimal_value)))
      return true;
    interval->neg= my_decimal2seconds(val, &second, &second_part);
1301 1302
    if (second == LONGLONG_MAX)
    {
1303
      THD *thd= current_thd;
1304
      ErrConvDecimal err(val);
1305
      push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
1306
                          ER_TRUNCATED_WRONG_VALUE,
1307
                          ER_THD(thd, ER_TRUNCATED_WRONG_VALUE), "DECIMAL",
1308
                          err.ptr());
1309 1310 1311
      return true;
    }

1312 1313 1314 1315 1316
    interval->second= second;
    interval->second_part= second_part;
    return false;
  }
  else if ((int) int_type <= INTERVAL_MICROSECOND)
unknown's avatar
unknown committed
1317
  {
1318
    value= args->val_int();
unknown's avatar
unknown committed
1319 1320 1321 1322
    if (args->null_value)
      return 1;
    if (value < 0)
    {
1323
      interval->neg=1;
unknown's avatar
unknown committed
1324 1325 1326 1327 1328 1329
      value= -value;
    }
  }
  else
  {
    String *res;
Sergei Golubchik's avatar
Sergei Golubchik committed
1330
    if (!(res= args->val_str_ascii(&str_value)))
unknown's avatar
unknown committed
1331 1332
      return (1);

1333
    /* record negative intervalls in interval->neg */
unknown's avatar
unknown committed
1334
    str=res->ptr();
Sergei Golubchik's avatar
Sergei Golubchik committed
1335
    cs= res->charset();
unknown's avatar
unknown committed
1336
    const char *end=str+res->length();
1337
    while (str != end && my_isspace(cs,*str))
unknown's avatar
unknown committed
1338 1339 1340
      str++;
    if (str != end && *str == '-')
    {
1341
      interval->neg=1;
unknown's avatar
unknown committed
1342 1343
      str++;
    }
1344
    length= (size_t) (end-str);		// Set up pointers to new str
unknown's avatar
unknown committed
1345 1346 1347 1348
  }

  switch (int_type) {
  case INTERVAL_YEAR:
unknown's avatar
unknown committed
1349
    interval->year= (ulong) value;
unknown's avatar
unknown committed
1350
    break;
1351
  case INTERVAL_QUARTER:
1352
    interval->month= (ulong)(value*3);
1353
    break;
unknown's avatar
unknown committed
1354
  case INTERVAL_MONTH:
unknown's avatar
unknown committed
1355
    interval->month= (ulong) value;
unknown's avatar
unknown committed
1356
    break;
1357
  case INTERVAL_WEEK:
1358
    interval->day= (ulong)(value*7);
1359
    break;
unknown's avatar
unknown committed
1360
  case INTERVAL_DAY:
unknown's avatar
unknown committed
1361
    interval->day= (ulong) value;
unknown's avatar
unknown committed
1362 1363
    break;
  case INTERVAL_HOUR:
unknown's avatar
unknown committed
1364
    interval->hour= (ulong) value;
unknown's avatar
unknown committed
1365
    break;
unknown's avatar
unknown committed
1366
  case INTERVAL_MICROSECOND:
1367
    interval->second_part=value;
unknown's avatar
unknown committed
1368
    break;
unknown's avatar
unknown committed
1369
  case INTERVAL_MINUTE:
1370
    interval->minute=value;
unknown's avatar
unknown committed
1371 1372
    break;
  case INTERVAL_SECOND:
1373
    interval->second=value;
unknown's avatar
unknown committed
1374 1375
    break;
  case INTERVAL_YEAR_MONTH:			// Allow YEAR-MONTH YYYYYMM
1376
    if (get_interval_info(str,length,cs,2,array,0))
unknown's avatar
unknown committed
1377
      return (1);
unknown's avatar
unknown committed
1378 1379
    interval->year=  (ulong) array[0];
    interval->month= (ulong) array[1];
unknown's avatar
unknown committed
1380 1381
    break;
  case INTERVAL_DAY_HOUR:
1382
    if (get_interval_info(str,length,cs,2,array,0))
unknown's avatar
unknown committed
1383
      return (1);
unknown's avatar
unknown committed
1384 1385
    interval->day=  (ulong) array[0];
    interval->hour= (ulong) array[1];
unknown's avatar
unknown committed
1386
    break;
unknown's avatar
unknown committed
1387
  case INTERVAL_DAY_MICROSECOND:
1388
    if (get_interval_info(str,length,cs,5,array,1))
unknown's avatar
unknown committed
1389
      return (1);
unknown's avatar
unknown committed
1390 1391 1392 1393 1394
    interval->day=    (ulong) array[0];
    interval->hour=   (ulong) array[1];
    interval->minute= array[2];
    interval->second= array[3];
    interval->second_part= array[4];
unknown's avatar
unknown committed
1395
    break;
unknown's avatar
unknown committed
1396
  case INTERVAL_DAY_MINUTE:
1397
    if (get_interval_info(str,length,cs,3,array,0))
unknown's avatar
unknown committed
1398
      return (1);
unknown's avatar
unknown committed
1399 1400 1401
    interval->day=    (ulong) array[0];
    interval->hour=   (ulong) array[1];
    interval->minute= array[2];
unknown's avatar
unknown committed
1402 1403
    break;
  case INTERVAL_DAY_SECOND:
1404
    if (get_interval_info(str,length,cs,4,array,0))
unknown's avatar
unknown committed
1405
      return (1);
unknown's avatar
unknown committed
1406 1407 1408 1409
    interval->day=    (ulong) array[0];
    interval->hour=   (ulong) array[1];
    interval->minute= array[2];
    interval->second= array[3];
unknown's avatar
unknown committed
1410
    break;
unknown's avatar
unknown committed
1411
  case INTERVAL_HOUR_MICROSECOND:
1412
    if (get_interval_info(str,length,cs,4,array,1))
unknown's avatar
unknown committed
1413
      return (1);
unknown's avatar
unknown committed
1414 1415 1416 1417
    interval->hour=   (ulong) array[0];
    interval->minute= array[1];
    interval->second= array[2];
    interval->second_part= array[3];
unknown's avatar
unknown committed
1418
    break;
unknown's avatar
unknown committed
1419
  case INTERVAL_HOUR_MINUTE:
1420
    if (get_interval_info(str,length,cs,2,array,0))
unknown's avatar
unknown committed
1421
      return (1);
unknown's avatar
unknown committed
1422 1423
    interval->hour=   (ulong) array[0];
    interval->minute= array[1];
unknown's avatar
unknown committed
1424 1425
    break;
  case INTERVAL_HOUR_SECOND:
1426
    if (get_interval_info(str,length,cs,3,array,0))
unknown's avatar
unknown committed
1427
      return (1);
unknown's avatar
unknown committed
1428 1429 1430
    interval->hour=   (ulong) array[0];
    interval->minute= array[1];
    interval->second= array[2];
unknown's avatar
unknown committed
1431
    break;
unknown's avatar
unknown committed
1432
  case INTERVAL_MINUTE_MICROSECOND:
1433
    if (get_interval_info(str,length,cs,3,array,1))
unknown's avatar
unknown committed
1434
      return (1);
unknown's avatar
unknown committed
1435 1436 1437
    interval->minute= array[0];
    interval->second= array[1];
    interval->second_part= array[2];
unknown's avatar
unknown committed
1438
    break;
unknown's avatar
unknown committed
1439
  case INTERVAL_MINUTE_SECOND:
1440
    if (get_interval_info(str,length,cs,2,array,0))
unknown's avatar
unknown committed
1441
      return (1);
unknown's avatar
unknown committed
1442 1443
    interval->minute= array[0];
    interval->second= array[1];
unknown's avatar
unknown committed
1444
    break;
unknown's avatar
unknown committed
1445
  case INTERVAL_SECOND_MICROSECOND:
1446
    if (get_interval_info(str,length,cs,2,array,1))
unknown's avatar
unknown committed
1447
      return (1);
unknown's avatar
unknown committed
1448 1449
    interval->second= array[0];
    interval->second_part= array[1];
unknown's avatar
unknown committed
1450
    break;
1451 1452 1453
  case INTERVAL_LAST: /* purecov: begin deadcode */
    DBUG_ASSERT(0); 
    break;            /* purecov: end */
unknown's avatar
unknown committed
1454 1455 1456 1457 1458
  }
  return 0;
}


Sergei Golubchik's avatar
Sergei Golubchik committed
1459 1460
void Item_temporal_func::fix_length_and_dec()
{ 
Sergei Golubchik's avatar
Sergei Golubchik committed
1461
  uint char_length= mysql_temporal_int_part_length(field_type());
Alexander Barkov's avatar
Alexander Barkov committed
1462 1463 1464 1465
  /*
    We set maybe_null to 1 as default as any bad argument with date or
    time can get us to return NULL.
  */ 
unknown's avatar
unknown committed
1466
  maybe_null= 1;
1467

Sergei Golubchik's avatar
Sergei Golubchik committed
1468 1469 1470
  if (decimals)
  {
    if (decimals == NOT_FIXED_DEC)
1471
      char_length+= TIME_SECOND_PART_DIGITS + 1;
Sergei Golubchik's avatar
Sergei Golubchik committed
1472 1473 1474
    else
    {
      set_if_smaller(decimals, TIME_SECOND_PART_DIGITS);
1475
      char_length+= decimals + 1;
Sergei Golubchik's avatar
Sergei Golubchik committed
1476 1477 1478 1479
    }
  }
  sql_mode= current_thd->variables.sql_mode &
                 (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE);
1480 1481
  collation.set(field_type() == MYSQL_TYPE_STRING ?
                default_charset() : &my_charset_numeric,
1482 1483 1484
                field_type() == MYSQL_TYPE_STRING ?
                DERIVATION_COERCIBLE : DERIVATION_NUMERIC,
                MY_REPERTOIRE_ASCII);
1485
  fix_char_length(char_length);
Sergei Golubchik's avatar
Sergei Golubchik committed
1486 1487
}

1488
String *Item_temporal_func::val_str(String *str)
unknown's avatar
unknown committed
1489
{
1490
  DBUG_ASSERT(fixed == 1);
Sergei Golubchik's avatar
Sergei Golubchik committed
1491
  return val_string_from_date(str);
unknown's avatar
unknown committed
1492 1493 1494
}


1495 1496 1497 1498
bool Item_temporal_hybrid_func::fix_temporal_type(MYSQL_TIME *ltime)
{
  if (ltime->time_type < 0) /* MYSQL_TIMESTAMP_NONE, MYSQL_TIMESTAMP_ERROR */
    return false;
1499 1500 1501 1502 1503

  if (ltime->time_type != MYSQL_TIMESTAMP_TIME)
    goto date_or_datetime_value;

  /* Convert TIME to DATE or DATETIME */
1504 1505
  switch (field_type())
  {
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
  case MYSQL_TYPE_DATE:
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_TIMESTAMP:
    {
      MYSQL_TIME tmp;
      if (time_to_datetime_with_warn(current_thd, ltime, &tmp, 0))
        return (null_value= true);
      *ltime= tmp;
      if (field_type() == MYSQL_TYPE_DATE)
        datetime_to_date(ltime);
      return false;
    }
1518
  case MYSQL_TYPE_TIME:
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
  case MYSQL_TYPE_STRING: /* DATE_ADD, ADDTIME can return VARCHAR */
    return false;
  default:
    DBUG_ASSERT(0);
    return (null_value= true);
  }

date_or_datetime_value:
  /* Convert DATE or DATETIME to TIME, DATE, or DATETIME */
  switch (field_type())
  {
  case MYSQL_TYPE_TIME:
    datetime_to_time(ltime);
1532 1533 1534
    return false;
  case MYSQL_TYPE_DATETIME:
  case MYSQL_TYPE_TIMESTAMP:
1535
    date_to_datetime(ltime);
1536 1537
    return false;
  case MYSQL_TYPE_DATE:
1538
    datetime_to_date(ltime);
1539 1540 1541 1542 1543
    return false;
  case MYSQL_TYPE_STRING: /* DATE_ADD, ADDTIME can return VARCHAR */
    return false;
  default:
    DBUG_ASSERT(0);
1544
    return (null_value= true);
1545 1546 1547 1548 1549
  }
  return false;
}


1550 1551 1552 1553 1554
String *Item_temporal_hybrid_func::val_str_ascii(String *str)
{
  DBUG_ASSERT(fixed == 1);
  MYSQL_TIME ltime;

1555
  if (get_date(&ltime, 0) || fix_temporal_type(&ltime) ||
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
      (null_value= my_TIME_to_str(&ltime, str, decimals)))
    return (String *) 0;

  /* Check that the returned timestamp type matches to the function type */
  DBUG_ASSERT(cached_field_type == MYSQL_TYPE_STRING ||
              ltime.time_type == MYSQL_TIMESTAMP_NONE ||
              mysql_type_to_time_type(cached_field_type) == ltime.time_type);
  return str;
}


1567
bool Item_func_from_days::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
unknown's avatar
unknown committed
1568 1569
{
  longlong value=args[0]->val_int();
1570 1571 1572
  if ((null_value= (args[0]->null_value ||
                    ((fuzzy_date & TIME_NO_ZERO_DATE) && value == 0))))
    return true;
1573
  bzero(ltime, sizeof(MYSQL_TIME));
1574 1575
  if (get_date_from_daynr((long) value, &ltime->year, &ltime->month,
                          &ltime->day))
1576
    return 0;
1577

1578
  ltime->time_type= MYSQL_TIMESTAMP_DATE;
1579
  return 0;
unknown's avatar
unknown committed
1580 1581 1582 1583 1584
}


void Item_func_curdate::fix_length_and_dec()
{
1585
  store_now_in_TIME(&ltime);
1586
  
1587 1588
  /* We don't need to set second_part and neg because they already 0 */
  ltime.hour= ltime.minute= ltime.second= 0;
1589
  ltime.time_type= MYSQL_TIMESTAMP_DATE;
Sergei Golubchik's avatar
Sergei Golubchik committed
1590
  Item_datefunc::fix_length_and_dec();
1591
  maybe_null= false;
1592
}
1593

unknown's avatar
unknown committed
1594
/**
1595
    Converts current time in my_time_t to MYSQL_TIME represenatation for local
1596 1597
    time zone. Defines time zone (local) used for whole CURDATE function.
*/
1598
void Item_func_curdate_local::store_now_in_TIME(MYSQL_TIME *now_time)
unknown's avatar
unknown committed
1599
{
1600
  THD *thd= current_thd;
1601
  thd->variables.time_zone->gmt_sec_to_TIME(now_time, thd->query_start());
1602
  thd->time_zone_used= 1;
unknown's avatar
unknown committed
1603 1604
}

1605

unknown's avatar
unknown committed
1606
/**
1607
    Converts current time in my_time_t to MYSQL_TIME represenatation for UTC
1608
    time zone. Defines time zone (UTC) used for whole UTC_DATE function.
1609
*/
1610
void Item_func_curdate_utc::store_now_in_TIME(MYSQL_TIME *now_time)
1611
{
1612 1613
  THD *thd= current_thd;
  my_tz_UTC->gmt_sec_to_TIME(now_time, thd->query_start());
1614 1615 1616 1617
  /* 
    We are not flagging this query as using time zone, since it uses fixed
    UTC-SYSTEM time-zone.
  */
1618 1619 1620
}


1621
bool Item_func_curdate::get_date(MYSQL_TIME *res,
1622
				 ulonglong fuzzy_date __attribute__((unused)))
1623
{
1624 1625
  *res=ltime;
  return 0;
1626 1627 1628
}


1629
bool Item_func_curtime::fix_fields(THD *thd, Item **items)
1630
{
Sergei Golubchik's avatar
Sergei Golubchik committed
1631
  if (decimals > TIME_SECOND_PART_DIGITS)
1632
  {
1633 1634
    my_error(ER_TOO_BIG_PRECISION, MYF(0), static_cast<ulonglong>(decimals),
             func_name(), TIME_SECOND_PART_DIGITS);
1635 1636 1637
    return 1;
  }
  return Item_timefunc::fix_fields(thd, items);
1638 1639
}

1640
bool Item_func_curtime::get_date(MYSQL_TIME *res,
1641
                                 ulonglong fuzzy_date __attribute__((unused)))
unknown's avatar
unknown committed
1642
{
1643 1644
  *res= ltime;
  return 0;
1645 1646
}

1647 1648 1649
static void set_sec_part(ulong sec_part, MYSQL_TIME *ltime, Item *item)
{
  DBUG_ASSERT(item->decimals == AUTO_SEC_PART_DIGITS ||
Sergei Golubchik's avatar
Sergei Golubchik committed
1650
              item->decimals <= TIME_SECOND_PART_DIGITS);
1651 1652 1653
  if (item->decimals)
  {
    ltime->second_part= sec_part;
Sergei Golubchik's avatar
Sergei Golubchik committed
1654
    if (item->decimals < TIME_SECOND_PART_DIGITS)
1655
      my_time_trunc(ltime, item->decimals);
1656 1657
  }
}
1658

unknown's avatar
unknown committed
1659
/**
1660
    Converts current time in my_time_t to MYSQL_TIME represenatation for local
1661
    time zone. Defines time zone (local) used for whole CURTIME function.
1662
*/
1663
void Item_func_curtime_local::store_now_in_TIME(MYSQL_TIME *now_time)
1664
{
1665
  THD *thd= current_thd;
1666 1667 1668 1669
  thd->variables.time_zone->gmt_sec_to_TIME(now_time, thd->query_start());
  now_time->year= now_time->month= now_time->day= 0;
  now_time->time_type= MYSQL_TIMESTAMP_TIME;
  set_sec_part(thd->query_start_sec_part(), now_time, this);
1670
  thd->time_zone_used= 1;
1671 1672 1673
}


unknown's avatar
unknown committed
1674
/**
1675
    Converts current time in my_time_t to MYSQL_TIME represenatation for UTC
1676
    time zone. Defines time zone (UTC) used for whole UTC_TIME function.
1677
*/
1678
void Item_func_curtime_utc::store_now_in_TIME(MYSQL_TIME *now_time)
1679
{
1680 1681 1682 1683 1684
  THD *thd= current_thd;
  my_tz_UTC->gmt_sec_to_TIME(now_time, thd->query_start());
  now_time->year= now_time->month= now_time->day= 0;
  now_time->time_type= MYSQL_TIMESTAMP_TIME;
  set_sec_part(thd->query_start_sec_part(), now_time, this);
1685 1686 1687 1688
  /* 
    We are not flagging this query as using time zone, since it uses fixed
    UTC-SYSTEM time-zone.
  */
1689 1690
}

1691
bool Item_func_now::fix_fields(THD *thd, Item **items)
unknown's avatar
unknown committed
1692
{
Sergei Golubchik's avatar
Sergei Golubchik committed
1693
  if (decimals > TIME_SECOND_PART_DIGITS)
1694
  {
1695 1696
    my_error(ER_TOO_BIG_PRECISION, MYF(0), static_cast<ulonglong>(decimals),
             func_name(), TIME_SECOND_PART_DIGITS);
1697 1698 1699
    return 1;
  }
  return Item_temporal_func::fix_fields(thd, items);
unknown's avatar
unknown committed
1700 1701
}

unknown's avatar
unknown committed
1702
/**
1703
    Converts current time in my_time_t to MYSQL_TIME represenatation for local
1704 1705
    time zone. Defines time zone (local) used for whole NOW function.
*/
1706
void Item_func_now_local::store_now_in_TIME(MYSQL_TIME *now_time)
unknown's avatar
unknown committed
1707
{
1708
  THD *thd= current_thd;
1709 1710
  thd->variables.time_zone->gmt_sec_to_TIME(now_time, thd->query_start());
  set_sec_part(thd->query_start_sec_part(), now_time, this);
1711
  thd->time_zone_used= 1;
unknown's avatar
unknown committed
1712 1713 1714
}


unknown's avatar
unknown committed
1715
/**
1716
    Converts current time in my_time_t to MYSQL_TIME represenatation for UTC
1717 1718
    time zone. Defines time zone (UTC) used for whole UTC_TIMESTAMP function.
*/
1719
void Item_func_now_utc::store_now_in_TIME(MYSQL_TIME *now_time)
unknown's avatar
unknown committed
1720
{
1721 1722 1723
  THD *thd= current_thd;
  my_tz_UTC->gmt_sec_to_TIME(now_time, thd->query_start());
  set_sec_part(thd->query_start_sec_part(), now_time, this);
1724 1725 1726 1727
  /* 
    We are not flagging this query as using time zone, since it uses fixed
    UTC-SYSTEM time-zone.
  */
unknown's avatar
unknown committed
1728 1729 1730
}


1731
bool Item_func_now::get_date(MYSQL_TIME *res,
1732
                             ulonglong fuzzy_date __attribute__((unused)))
1733
{
1734
  *res= ltime;
1735
  return 0;
1736 1737 1738
}


unknown's avatar
unknown committed
1739
/**
1740
    Converts current time in my_time_t to MYSQL_TIME represenatation for local
1741 1742
    time zone. Defines time zone (local) used for whole SYSDATE function.
*/
1743
void Item_func_sysdate_local::store_now_in_TIME(MYSQL_TIME *now_time)
1744 1745
{
  THD *thd= current_thd;
1746
  my_hrtime_t now= my_hrtime();
1747
  thd->variables.time_zone->gmt_sec_to_TIME(now_time, hrtime_to_my_time(now));
1748
  set_sec_part(hrtime_sec_part(now), now_time, this);
1749 1750 1751 1752
  thd->time_zone_used= 1;
}


1753
bool Item_func_sysdate_local::get_date(MYSQL_TIME *res,
1754
                                       ulonglong fuzzy_date __attribute__((unused)))
1755
{
Sergei Golubchik's avatar
Sergei Golubchik committed
1756
  store_now_in_TIME(res);
1757 1758 1759
  return 0;
}

1760
bool Item_func_sec_to_time::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
unknown's avatar
unknown committed
1761
{
1762
  DBUG_ASSERT(fixed == 1);
1763 1764 1765
  bool sign;
  ulonglong sec;
  ulong sec_part;
1766

1767 1768
  bzero((char *)ltime, sizeof(*ltime));
  ltime->time_type= MYSQL_TIMESTAMP_TIME;
1769

1770
  sign= args[0]->get_seconds(&sec, &sec_part);
unknown's avatar
unknown committed
1771

1772 1773
  if ((null_value= args[0]->null_value))
    return 1;
unknown's avatar
unknown committed
1774

1775 1776 1777 1778 1779
  ltime->neg= sign;
  if (sec > TIME_MAX_VALUE_SECONDS)
    goto overflow;

  DBUG_ASSERT(sec_part <= TIME_MAX_SECOND_PART);
1780
  
1781 1782 1783 1784
  ltime->hour=   (uint) (sec/3600);
  ltime->minute= (uint) (sec % 3600) /60;
  ltime->second= (uint) sec % 60;
  ltime->second_part= sec_part;
1785

1786
  return 0;
1787

1788 1789 1790 1791 1792
overflow:
  /* use check_time_range() to set ltime to the max value depending on dec */
  int unused;
  char buf[100];
  String tmp(buf, sizeof(buf), &my_charset_bin), *err= args[0]->val_str(&tmp);
unknown's avatar
unknown committed
1793

1794 1795
  ltime->hour= TIME_MAX_HOUR+1;
  check_time_range(ltime, decimals, &unused);
1796
  make_truncated_value_warning(current_thd, Sql_condition::WARN_LEVEL_WARN,
1797 1798
                               err->ptr(), err->length(),
                               MYSQL_TIMESTAMP_TIME, NullS);
1799
  return 0;
unknown's avatar
unknown committed
1800 1801 1802 1803
}

void Item_func_date_format::fix_length_and_dec()
{
1804
  THD* thd= current_thd;
1805 1806
  locale= thd->variables.lc_time_names;

1807 1808 1809 1810 1811 1812
  /*
    Must use this_item() in case it's a local SP variable
    (for ->max_length and ->str_value)
  */
  Item *arg1= args[1]->this_item();

unknown's avatar
unknown committed
1813
  decimals=0;
1814 1815 1816 1817 1818
  CHARSET_INFO *cs= thd->variables.collation_connection;
  uint32 repertoire= arg1->collation.repertoire;
  if (!thd->variables.lc_time_names->is_ascii)
    repertoire|= MY_REPERTOIRE_EXTENDED;
  collation.set(cs, arg1->collation.derivation, repertoire);
1819
  if (arg1->type() == STRING_ITEM)
unknown's avatar
unknown committed
1820 1821
  {						// Optimize the normal case
    fixed_length=1;
1822
    max_length= format_length(arg1->val_str(NULL)) *
1823
                collation.collation->mbmaxlen;
unknown's avatar
unknown committed
1824 1825 1826 1827
  }
  else
  {
    fixed_length=0;
1828
    max_length=MY_MIN(arg1->max_length, MAX_BLOB_WIDTH) * 10 *
1829
                   collation.collation->mbmaxlen;
unknown's avatar
unknown committed
1830 1831
    set_if_smaller(max_length,MAX_BLOB_WIDTH);
  }
1832
  maybe_null=1;					// If wrong date
unknown's avatar
unknown committed
1833 1834 1835
}


unknown's avatar
unknown committed
1836 1837 1838
bool Item_func_date_format::eq(const Item *item, bool binary_cmp) const
{
  Item_func_date_format *item_func;
1839

unknown's avatar
unknown committed
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
  if (item->type() != FUNC_ITEM)
    return 0;
  if (func_name() != ((Item_func*) item)->func_name())
    return 0;
  if (this == item)
    return 1;
  item_func= (Item_func_date_format*) item;
  if (!args[0]->eq(item_func->args[0], binary_cmp))
    return 0;
  /*
    We must compare format string case sensitive.
    This needed because format modifiers with different case,
    for example %m and %M, have different meaning.
  */
  if (!args[1]->eq(item_func->args[1], 1))
    return 0;
  return 1;
}



unknown's avatar
unknown committed
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
uint Item_func_date_format::format_length(const String *format)
{
  uint size=0;
  const char *ptr=format->ptr();
  const char *end=ptr+format->length();

  for (; ptr != end ; ptr++)
  {
    if (*ptr != '%' || ptr == end-1)
      size++;
    else
    {
      switch(*++ptr) {
      case 'M': /* month, textual */
      case 'W': /* day (of the week), textual */
unknown's avatar
unknown committed
1876
	size += 64; /* large for UTF8 locale data */
unknown's avatar
unknown committed
1877 1878 1879 1880 1881 1882 1883 1884 1885
	break;
      case 'D': /* day (of the month), numeric plus english suffix */
      case 'Y': /* year, numeric, 4 digits */
      case 'x': /* Year, used with 'v' */
      case 'X': /* Year, used with 'v, where week starts with Monday' */
	size += 4;
	break;
      case 'a': /* locale's abbreviated weekday name (Sun..Sat) */
      case 'b': /* locale's abbreviated month name (Jan.Dec) */
unknown's avatar
unknown committed
1886 1887
	size += 32; /* large for UTF8 locale data */
	break;
unknown's avatar
unknown committed
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
      case 'j': /* day of year (001..366) */
	size += 3;
	break;
      case 'U': /* week (00..52) */
      case 'u': /* week (00..52), where week starts with Monday */
      case 'V': /* week 1..53 used with 'x' */
      case 'v': /* week 1..53 used with 'x', where week starts with Monday */
      case 'y': /* year, numeric, 2 digits */
      case 'm': /* month, numeric */
      case 'd': /* day (of the month), numeric */
      case 'h': /* hour (01..12) */
      case 'I': /* --||-- */
      case 'i': /* minutes, numeric */
      case 'l': /* hour ( 1..12) */
      case 'p': /* locale's AM or PM */
      case 'S': /* second (00..61) */
      case 's': /* seconds, numeric */
      case 'c': /* month (0..12) */
      case 'e': /* day (0..31) */
	size += 2;
	break;
1909 1910 1911 1912
      case 'k': /* hour ( 0..23) */
      case 'H': /* hour (00..23; value > 23 OK, padding always 2-digit) */
	size += 7; /* docs allow > 23, range depends on sizeof(unsigned int) */
	break;
unknown's avatar
unknown committed
1913 1914 1915 1916 1917 1918
      case 'r': /* time, 12-hour (hh:mm:ss [AP]M) */
	size += 11;
	break;
      case 'T': /* time, 24-hour (hh:mm:ss) */
	size += 8;
	break;
unknown's avatar
unknown committed
1919 1920 1921
      case 'f': /* microseconds */
	size += 6;
	break;
unknown's avatar
unknown committed
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
      case 'w': /* day (of the week), numeric */
      case '%':
      default:
	size++;
	break;
      }
    }
  }
  return size;
}


String *Item_func_date_format::val_str(String *str)
{
  String *format;
1937
  MYSQL_TIME l_time;
1938
  uint size;
1939
  int is_time_flag = is_time_format ? TIME_TIME_ONLY : 0;
1940
  DBUG_ASSERT(fixed == 1);
Michael Widenius's avatar
Michael Widenius committed
1941
  
1942
  if (get_arg0_date(&l_time, is_time_flag))
1943
    return 0;
Michael Widenius's avatar
Michael Widenius committed
1944
  
unknown's avatar
unknown committed
1945
  if (!(format = args[1]->val_str(str)) || !format->length())
1946
    goto null_date;
unknown's avatar
unknown committed
1947 1948 1949 1950 1951

  if (fixed_length)
    size=max_length;
  else
    size=format_length(format);
1952 1953 1954 1955

  if (size < MAX_DATE_STRING_REP_LENGTH)
    size= MAX_DATE_STRING_REP_LENGTH;

unknown's avatar
unknown committed
1956
  if (format == str)
unknown's avatar
merge  
unknown committed
1957
    str= &value;				// Save result here
unknown's avatar
unknown committed
1958
  if (str->alloc(size))
1959 1960
    goto null_date;

1961 1962 1963
  DATE_TIME_FORMAT date_time_format;
  date_time_format.format.str=    (char*) format->ptr();
  date_time_format.format.length= format->length(); 
unknown's avatar
unknown committed
1964 1965

  /* Create the result string */
1966
  str->set_charset(collation.collation);
1967
  if (!make_date_time(&date_time_format, &l_time,
1968 1969
                      is_time_format ? MYSQL_TIMESTAMP_TIME :
                                       MYSQL_TIMESTAMP_DATE,
1970
                      locale, str))
1971
    return str;
unknown's avatar
unknown committed
1972

1973 1974 1975
null_date:
  null_value=1;
  return 0;
unknown's avatar
unknown committed
1976 1977 1978
}


1979 1980
void Item_func_from_unixtime::fix_length_and_dec()
{ 
1981
  THD *thd= current_thd;
1982
  thd->time_zone_used= 1;
1983
  tz= thd->variables.time_zone;
1984
  decimals= args[0]->decimals;
Sergei Golubchik's avatar
Sergei Golubchik committed
1985
  Item_temporal_func::fix_length_and_dec();
1986 1987 1988
}


1989
bool Item_func_from_unixtime::get_date(MYSQL_TIME *ltime,
1990
				       ulonglong fuzzy_date __attribute__((unused)))
unknown's avatar
unknown committed
1991
{
1992 1993 1994
  bool sign;
  ulonglong sec;
  ulong sec_part;
1995

1996 1997
  bzero((char *)ltime, sizeof(*ltime));
  ltime->time_type= MYSQL_TIMESTAMP_TIME;
1998

1999
  sign= args[0]->get_seconds(&sec, &sec_part);
2000

2001
  if (args[0]->null_value || sign || sec > TIMESTAMP_MAX_VALUE)
2002
    return (null_value= 1);
2003

2004
  tz->gmt_sec_to_TIME(ltime, (my_time_t)sec);
2005

2006
  ltime->second_part= sec_part;
2007

2008
  return (null_value= 0);
2009 2010 2011 2012 2013
}


void Item_func_convert_tz::fix_length_and_dec()
{
2014
  decimals= args[0]->temporal_precision(MYSQL_TYPE_DATETIME);
Sergei Golubchik's avatar
Sergei Golubchik committed
2015
  Item_temporal_func::fix_length_and_dec();
2016 2017 2018
}


2019
bool Item_func_convert_tz::get_date(MYSQL_TIME *ltime,
2020
                                    ulonglong fuzzy_date __attribute__((unused)))
2021 2022 2023
{
  my_time_t my_time_tmp;
  String str;
2024
  THD *thd= current_thd;
2025 2026 2027

  if (!from_tz_cached)
  {
2028
    from_tz= my_tz_find(thd, args[1]->val_str_ascii(&str));
2029 2030 2031 2032 2033
    from_tz_cached= args[1]->const_item();
  }

  if (!to_tz_cached)
  {
2034
    to_tz= my_tz_find(thd, args[2]->val_str_ascii(&str));
2035 2036 2037
    to_tz_cached= args[2]->const_item();
  }

2038 2039
  if (from_tz==0 || to_tz==0 ||
      get_arg0_date(ltime, TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE))
Sergei Golubchik's avatar
Sergei Golubchik committed
2040
    return (null_value= 1);
2041 2042

  {
2043
    uint not_used;
2044
    my_time_tmp= from_tz->TIME_to_gmt_sec(ltime, &not_used);
2045
    ulong sec_part= ltime->second_part;
2046 2047
    /* my_time_tmp is guranteed to be in the allowed range */
    if (my_time_tmp)
2048
      to_tz->gmt_sec_to_TIME(ltime, my_time_tmp);
2049 2050
    /* we rely on the fact that no timezone conversion can change sec_part */
    ltime->second_part= sec_part;
2051
  }
2052

Sergei Golubchik's avatar
Sergei Golubchik committed
2053
  return (null_value= 0);
unknown's avatar
unknown committed
2054 2055
}

2056

2057 2058 2059
void Item_func_convert_tz::cleanup()
{
  from_tz_cached= to_tz_cached= 0;
2060
  Item_temporal_func::cleanup();
2061 2062 2063
}


2064 2065 2066
void Item_date_add_interval::fix_length_and_dec()
{
  enum_field_types arg0_field_type;
2067

2068
  /*
2069
    The field type for the result of an Item_datefunc is defined as
2070 2071 2072 2073
    follows:

    - If first arg is a MYSQL_TYPE_DATETIME result is MYSQL_TYPE_DATETIME
    - If first arg is a MYSQL_TYPE_DATE and the interval type uses hours,
2074 2075 2076 2077 2078
      minutes or seconds then type is MYSQL_TYPE_DATETIME
      otherwise it's MYSQL_TYPE_DATE
    - if first arg is a MYSQL_TYPE_TIME and the interval type isn't using
      anything larger than days, then the result is MYSQL_TYPE_TIME,
      otherwise - MYSQL_TYPE_DATETIME.
2079
    - Otherwise the result is MYSQL_TYPE_STRING
Michael Widenius's avatar
Michael Widenius committed
2080 2081
      (This is because you can't know if the string contains a DATE,
      MYSQL_TIME or DATETIME argument)
2082 2083 2084
  */
  cached_field_type= MYSQL_TYPE_STRING;
  arg0_field_type= args[0]->field_type();
2085 2086 2087 2088 2089 2090
  uint interval_dec= 0;
  if (int_type == INTERVAL_MICROSECOND ||
      (int_type >= INTERVAL_DAY_MICROSECOND &&
       int_type <= INTERVAL_SECOND_MICROSECOND))
    interval_dec= TIME_SECOND_PART_DIGITS;
  else if (int_type == INTERVAL_SECOND && args[1]->decimals > 0)
Sergei Golubchik's avatar
Sergei Golubchik committed
2091
    interval_dec= MY_MIN(args[1]->decimals, TIME_SECOND_PART_DIGITS);
2092

2093 2094
  if (arg0_field_type == MYSQL_TYPE_DATETIME ||
      arg0_field_type == MYSQL_TYPE_TIMESTAMP)
2095
  {
Sergei Golubchik's avatar
Sergei Golubchik committed
2096
    decimals= MY_MAX(args[0]->temporal_precision(MYSQL_TYPE_DATETIME), interval_dec);
2097
    cached_field_type= MYSQL_TYPE_DATETIME;
2098
  }
2099 2100
  else if (arg0_field_type == MYSQL_TYPE_DATE)
  {
unknown's avatar
unknown committed
2101
    if (int_type <= INTERVAL_DAY || int_type == INTERVAL_YEAR_MONTH)
2102 2103
      cached_field_type= arg0_field_type;
    else
2104 2105
    {
      decimals= interval_dec;
2106
      cached_field_type= MYSQL_TYPE_DATETIME;
2107
    }
2108
  }
2109
  else if (arg0_field_type == MYSQL_TYPE_TIME)
2110
  {
Sergei Golubchik's avatar
Sergei Golubchik committed
2111
    decimals= MY_MAX(args[0]->temporal_precision(MYSQL_TYPE_TIME), interval_dec);
2112 2113 2114 2115
    if (int_type >= INTERVAL_DAY && int_type != INTERVAL_YEAR_MONTH)
      cached_field_type= arg0_field_type;
    else
      cached_field_type= MYSQL_TYPE_DATETIME;
2116 2117
  }
  else
Sergei Golubchik's avatar
Sergei Golubchik committed
2118
    decimals= MY_MAX(args[0]->temporal_precision(MYSQL_TYPE_DATETIME), interval_dec);
Sergei Golubchik's avatar
Sergei Golubchik committed
2119
  Item_temporal_func::fix_length_and_dec();
2120 2121 2122
}


2123
bool Item_date_add_interval::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
unknown's avatar
unknown committed
2124 2125
{
  INTERVAL interval;
2126

2127 2128 2129
  if (args[0]->get_date(ltime,
                        cached_field_type == MYSQL_TYPE_TIME ?
                        TIME_TIME_ONLY : 0) ||
Sergei Golubchik's avatar
Sergei Golubchik committed
2130
      get_interval_value(args[1], int_type, &interval))
2131
    return (null_value=1);
2132

2133 2134 2135 2136 2137
  if (ltime->time_type != MYSQL_TIMESTAMP_TIME &&
      check_date_with_warn(ltime, TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE,
                           MYSQL_TIMESTAMP_ERROR))
    return (null_value=1);

unknown's avatar
unknown committed
2138
  if (date_sub_interval)
2139
    interval.neg = !interval.neg;
2140

Sergei Golubchik's avatar
Sergei Golubchik committed
2141 2142 2143
  if (date_add_interval(ltime, int_type, interval))
    return (null_value=1);
  return (null_value= 0);
unknown's avatar
unknown committed
2144 2145
}

2146 2147 2148 2149

bool Item_date_add_interval::eq(const Item *item, bool binary_cmp) const
{
  Item_date_add_interval *other= (Item_date_add_interval*) item;
2150 2151 2152 2153
  if (!Item_func::eq(item, binary_cmp))
    return 0;
  return ((int_type == other->int_type) &&
          (date_sub_interval == other->date_sub_interval));
2154 2155
}

2156 2157 2158 2159
/*
   'interval_names' reflects the order of the enumeration interval_type.
   See item_timefunc.h
 */
2160

2161 2162
static const char *interval_names[]=
{
2163 2164
  "year", "quarter", "month", "week", "day",  
  "hour", "minute", "second", "microsecond",
unknown's avatar
unknown committed
2165 2166 2167 2168 2169
  "year_month", "day_hour", "day_minute", 
  "day_second", "hour_minute", "hour_second",
  "minute_second", "day_microsecond",
  "hour_microsecond", "minute_microsecond",
  "second_microsecond"
2170 2171
};

2172
void Item_date_add_interval::print(String *str, enum_query_type query_type)
2173 2174
{
  str->append('(');
2175
  args[0]->print(str, query_type);
2176
  str->append(date_sub_interval?" - interval ":" + interval ");
2177
  args[1]->print(str, query_type);
2178
  str->append(' ');
2179 2180 2181 2182
  str->append(interval_names[int_type]);
  str->append(')');
}

2183
void Item_extract::print(String *str, enum_query_type query_type)
2184
{
2185
  str->append(STRING_WITH_LEN("extract("));
2186
  str->append(interval_names[int_type]);
2187
  str->append(STRING_WITH_LEN(" from "));
2188
  args[0]->print(str, query_type);
2189 2190 2191
  str->append(')');
}

unknown's avatar
unknown committed
2192 2193
void Item_extract::fix_length_and_dec()
{
2194
  maybe_null=1;					// If wrong date
unknown's avatar
unknown committed
2195
  switch (int_type) {
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
  case INTERVAL_YEAR:             set_date_length(4); break; // YYYY
  case INTERVAL_YEAR_MONTH:       set_date_length(6); break; // YYYYMM
  case INTERVAL_QUARTER:          set_date_length(2); break; // 1..4
  case INTERVAL_MONTH:            set_date_length(2); break; // MM
  case INTERVAL_WEEK:             set_date_length(2); break; // 0..52
  case INTERVAL_DAY:              set_date_length(2); break; // DD
  case INTERVAL_DAY_HOUR:         set_time_length(4); break; // DDhh
  case INTERVAL_DAY_MINUTE:       set_time_length(6); break; // DDhhmm
  case INTERVAL_DAY_SECOND:       set_time_length(8); break; // DDhhmmss
  case INTERVAL_HOUR:             set_time_length(2); break; // hh
  case INTERVAL_HOUR_MINUTE:      set_time_length(4); break; // hhmm
  case INTERVAL_HOUR_SECOND:      set_time_length(6); break; // hhmmss
  case INTERVAL_MINUTE:           set_time_length(2); break; // mm
  case INTERVAL_MINUTE_SECOND:    set_time_length(4); break; // mmss
  case INTERVAL_SECOND:           set_time_length(2); break; // ss
  case INTERVAL_MICROSECOND:      set_time_length(6); break; // ffffff
  case INTERVAL_DAY_MICROSECOND:  set_time_length(14); break; // DDhhmmssffffff
  case INTERVAL_HOUR_MICROSECOND: set_time_length(12); break; // hhmmssffffff
  case INTERVAL_MINUTE_MICROSECOND: set_time_length(10); break; // mmssffffff
  case INTERVAL_SECOND_MICROSECOND: set_time_length(8); break; // ssffffff
2216
  case INTERVAL_LAST: DBUG_ASSERT(0); break; /* purecov: deadcode */
unknown's avatar
unknown committed
2217 2218 2219 2220 2221 2222
  }
}


longlong Item_extract::val_int()
{
2223
  DBUG_ASSERT(fixed == 1);
2224
  MYSQL_TIME ltime;
2225 2226
  uint year;
  ulong week_format;
unknown's avatar
unknown committed
2227
  long neg;
2228 2229
  int is_time_flag = date_value ? 0 : TIME_TIME_ONLY;

2230 2231
  // Not using get_arg0_date to avoid automatic TIME to DATETIME conversion
  if ((null_value= args[0]->get_date(&ltime, is_time_flag)))
2232
    return 0;
2233

2234 2235
  neg= ltime.neg ? -1 : 1;

2236 2237 2238 2239
  DBUG_ASSERT(ltime.time_type != MYSQL_TIMESTAMP_TIME ||  ltime.day == 0);
  if (ltime.time_type == MYSQL_TIMESTAMP_TIME)
    time_to_daytime_interval(&ltime);

unknown's avatar
unknown committed
2240 2241 2242
  switch (int_type) {
  case INTERVAL_YEAR:		return ltime.year;
  case INTERVAL_YEAR_MONTH:	return ltime.year*100L+ltime.month;
2243
  case INTERVAL_QUARTER:	return (ltime.month+2)/3;
unknown's avatar
unknown committed
2244
  case INTERVAL_MONTH:		return ltime.month;
2245 2246 2247
  case INTERVAL_WEEK:
  {
    week_format= current_thd->variables.default_week_format;
unknown's avatar
unknown committed
2248
    return calc_week(&ltime, week_mode(week_format), &year);
2249
  }
unknown's avatar
unknown committed
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
  case INTERVAL_DAY:		return ltime.day;
  case INTERVAL_DAY_HOUR:	return (long) (ltime.day*100L+ltime.hour)*neg;
  case INTERVAL_DAY_MINUTE:	return (long) (ltime.day*10000L+
					       ltime.hour*100L+
					       ltime.minute)*neg;
  case INTERVAL_DAY_SECOND:	 return ((longlong) ltime.day*1000000L+
					 (longlong) (ltime.hour*10000L+
						     ltime.minute*100+
						     ltime.second))*neg;
  case INTERVAL_HOUR:		return (long) ltime.hour*neg;
  case INTERVAL_HOUR_MINUTE:	return (long) (ltime.hour*100+ltime.minute)*neg;
  case INTERVAL_HOUR_SECOND:	return (long) (ltime.hour*10000+ltime.minute*100+
					       ltime.second)*neg;
  case INTERVAL_MINUTE:		return (long) ltime.minute*neg;
  case INTERVAL_MINUTE_SECOND:	return (long) (ltime.minute*100+ltime.second)*neg;
  case INTERVAL_SECOND:		return (long) ltime.second*neg;
unknown's avatar
unknown committed
2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
  case INTERVAL_MICROSECOND:	return (long) ltime.second_part*neg;
  case INTERVAL_DAY_MICROSECOND: return (((longlong)ltime.day*1000000L +
					  (longlong)ltime.hour*10000L +
					  ltime.minute*100 +
					  ltime.second)*1000000L +
					 ltime.second_part)*neg;
  case INTERVAL_HOUR_MICROSECOND: return (((longlong)ltime.hour*10000L +
					   ltime.minute*100 +
					   ltime.second)*1000000L +
					  ltime.second_part)*neg;
  case INTERVAL_MINUTE_MICROSECOND: return (((longlong)(ltime.minute*100+
							ltime.second))*1000000L+
					    ltime.second_part)*neg;
  case INTERVAL_SECOND_MICROSECOND: return ((longlong)ltime.second*1000000L+
					    ltime.second_part)*neg;
2281
  case INTERVAL_LAST: DBUG_ASSERT(0); break;  /* purecov: deadcode */
unknown's avatar
unknown committed
2282 2283 2284
  }
  return 0;					// Impossible
}
unknown's avatar
unknown committed
2285

unknown's avatar
unknown committed
2286 2287 2288 2289 2290
bool Item_extract::eq(const Item *item, bool binary_cmp) const
{
  if (this == item)
    return 1;
  if (item->type() != FUNC_ITEM ||
2291
      functype() != ((Item_func*)item)->functype())
unknown's avatar
unknown committed
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
    return 0;

  Item_extract* ie= (Item_extract*)item;
  if (ie->int_type != int_type)
    return 0;

  if (!args[0]->eq(ie->args[0], binary_cmp))
      return 0;
  return 1;
}
unknown's avatar
unknown committed
2302

unknown's avatar
unknown committed
2303

2304 2305 2306 2307 2308
bool Item_char_typecast::eq(const Item *item, bool binary_cmp) const
{
  if (this == item)
    return 1;
  if (item->type() != FUNC_ITEM ||
2309
      functype() != ((Item_func*)item)->functype())
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
    return 0;

  Item_char_typecast *cast= (Item_char_typecast*)item;
  if (cast_length != cast->cast_length ||
      cast_cs     != cast->cast_cs)
    return 0;

  if (!args[0]->eq(cast->args[0], binary_cmp))
      return 0;
  return 1;
}
unknown's avatar
unknown committed
2321

2322
void Item_temporal_typecast::print(String *str, enum_query_type query_type)
unknown's avatar
unknown committed
2323
{
2324
  char buf[32];
2325
  str->append(STRING_WITH_LEN("cast("));
2326
  args[0]->print(str, query_type);
2327
  str->append(STRING_WITH_LEN(" as "));
2328
  str->append(cast_type());
2329 2330 2331 2332 2333 2334
  if (decimals)
  {
    str->append('(');
    str->append(llstr(decimals, buf));
    str->append(')');
  }
2335 2336 2337
  str->append(')');
}

unknown's avatar
unknown committed
2338

2339
void Item_char_typecast::print(String *str, enum_query_type query_type)
2340
{
2341
  str->append(STRING_WITH_LEN("cast("));
2342
  args[0]->print(str, query_type);
2343
  str->append(STRING_WITH_LEN(" as char"));
Sergei Golubchik's avatar
Sergei Golubchik committed
2344
  if (cast_length != ~0U)
2345 2346
  {
    str->append('(');
2347
    char buffer[20];
unknown's avatar
unknown committed
2348 2349
    // my_charset_bin is good enough for numbers
    String st(buffer, sizeof(buffer), &my_charset_bin);
Sergei Golubchik's avatar
Sergei Golubchik committed
2350
    st.set(static_cast<ulonglong>(cast_length), &my_charset_bin);
2351
    str->append(st);
2352 2353 2354 2355
    str->append(')');
  }
  if (cast_cs)
  {
2356
    str->append(STRING_WITH_LEN(" charset "));
2357
    str->append(cast_cs->csname);
2358
  }
unknown's avatar
unknown committed
2359 2360
  str->append(')');
}
unknown's avatar
unknown committed
2361

2362 2363 2364 2365 2366

void Item_char_typecast::check_truncation_with_warn(String *src, uint dstlen)
{
  if (dstlen < src->length())
  {
2367
    THD *thd= current_thd;
2368
    char char_type[40];
2369
    ErrConvString err(src);
2370 2371 2372
    my_snprintf(char_type, sizeof(char_type), "%s(%lu)",
                cast_cs == &my_charset_bin ? "BINARY" : "CHAR",
                (ulong) cast_length);
2373
    push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
2374
                        ER_TRUNCATED_WRONG_VALUE,
2375
                        ER_THD(thd, ER_TRUNCATED_WRONG_VALUE), char_type,
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
                        err.ptr());
  }
}


String *Item_char_typecast::reuse(String *src, uint32 length)
{
  DBUG_ASSERT(length <= src->length());
  check_truncation_with_warn(src, length);
  tmp_value.set(src->ptr(), length, cast_cs);
  return &tmp_value;
}


/*
  Make a copy, to handle conversion or fix bad bytes.
*/
String *Item_char_typecast::copy(String *str, CHARSET_INFO *strcs)
{
  String_copier_for_item copier(current_thd);
  if (copier.copy_with_warn(cast_cs, &tmp_value, strcs,
                            str->ptr(), str->length(), cast_length))
  {
2399
    null_value= 1; // EOM
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410
    return 0;
  }
  check_truncation_with_warn(str, copier.source_end_pos() - str->ptr());
  return &tmp_value;
}


uint Item_char_typecast::adjusted_length_with_warn(uint length)
{
  if (length <= current_thd->variables.max_allowed_packet)
    return length;
2411 2412 2413

  THD *thd= current_thd;
  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
2414
                      ER_WARN_ALLOWED_PACKET_OVERFLOWED,
2415
                      ER_THD(thd, ER_WARN_ALLOWED_PACKET_OVERFLOWED),
2416 2417
                      cast_cs == &my_charset_bin ?
                      "cast_as_binary" : func_name(),
2418 2419
                      thd->variables.max_allowed_packet);
  return thd->variables.max_allowed_packet;
2420 2421 2422
}


2423 2424
String *Item_char_typecast::val_str(String *str)
{
2425
  DBUG_ASSERT(fixed == 1);
2426
  String *res;
2427

2428 2429 2430 2431
  if (has_explicit_length())
    cast_length= adjusted_length_with_warn(cast_length);

  if (!(res= args[0]->val_str(str)))
2432
  {
2433 2434
    null_value= 1;
    return 0;
2435 2436
  }

2437 2438 2439
  if (cast_cs == &my_charset_bin &&
      has_explicit_length() &&
      cast_length > res->length())
2440
  {
2441 2442 2443
    // Special case: pad binary value with trailing 0x00
    DBUG_ASSERT(cast_length <= current_thd->variables.max_allowed_packet);
    if (res->alloced_length() < cast_length)
2444
    {
2445 2446 2447
      str_value.alloc(cast_length);
      str_value.copy(*res);
      res= &str_value;
2448
    }
2449 2450 2451
    bzero((char*) res->ptr() + res->length(), cast_length - res->length());
    res->length(cast_length);
    res->set_charset(&my_charset_bin);
2452 2453 2454
  }
  else
  {
2455 2456 2457 2458
    /*
      from_cs is 0 in the case where the result set may vary between calls,
      for example with dynamic columns.
    */
2459 2460
    CHARSET_INFO *cs= from_cs ? from_cs : res->charset();
    if (!charset_conversion)
2461
    {
2462 2463 2464 2465 2466
      // Try to reuse the original string (if well formed).
      MY_STRCOPY_STATUS status;
      cs->cset->well_formed_char_length(cs, res->ptr(), res->end(),
                                        cast_length, &status);
      if (!status.m_well_formed_error_pos)
2467
      {
2468
        res= reuse(res, status.m_source_end_pos - res->ptr());
2469
      }
2470
      goto end;
2471
    }
2472 2473 2474
    // Character set conversion, or bad bytes were found.
    if (!(res= copy(res, cs)))
      return 0;
2475
  }
Michael Widenius's avatar
Michael Widenius committed
2476

2477 2478 2479
end:
  return ((null_value= (res->length() >
                        adjusted_length_with_warn(res->length())))) ? 0 : res;
2480 2481
}

2482

2483 2484 2485
void Item_char_typecast::fix_length_and_dec()
{
  uint32 char_length;
unknown's avatar
unknown committed
2486 2487 2488 2489 2490 2491 2492
  /* 
     We always force character set conversion if cast_cs
     is a multi-byte character set. It garantees that the
     result of CAST is a well-formed string.
     For single-byte character sets we allow just to copy
     from the argument. A single-byte character sets string
     is always well-formed. 
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
     
     There is a special trick to convert form a number to ucs2.
     As numbers have my_charset_bin as their character set,
     it wouldn't do conversion to ucs2 without an additional action.
     To force conversion, we should pretend to be non-binary.
     Let's choose from_cs this way:
     - If the argument in a number and cast_cs is ucs2 (i.e. mbminlen > 1),
       then from_cs is set to latin1, to perform latin1 -> ucs2 conversion.
     - If the argument is a number and cast_cs is ASCII-compatible
       (i.e. mbminlen == 1), then from_cs is set to cast_cs,
       which allows just to take over the args[0]->val_str() result
       and thus avoid unnecessary character set conversion.
     - If the argument is not a number, then from_cs is set to
       the argument's charset.
2507 2508 2509
     - If argument has a dynamic collation (can change from call to call)
       we set from_cs to 0 as a marker that we have to take the collation
       from the result string.
2510 2511

       Note (TODO): we could use repertoire technique here.
unknown's avatar
unknown committed
2512
  */
2513 2514 2515 2516 2517 2518 2519
  from_cs= ((args[0]->result_type() == INT_RESULT || 
             args[0]->result_type() == DECIMAL_RESULT ||
             args[0]->result_type() == REAL_RESULT) ?
            (cast_cs->mbminlen == 1 ? cast_cs : &my_charset_latin1) :
            args[0]->dynamic_result() ? 0 :
            args[0]->collation.collation);
  charset_conversion= !from_cs || (cast_cs->mbmaxlen > 1) ||
2520 2521 2522
                      (!my_charset_same(from_cs, cast_cs) &&
                       from_cs != &my_charset_bin &&
                       cast_cs != &my_charset_bin);
2523
  collation.set(cast_cs, DERIVATION_IMPLICIT);
Michael Widenius's avatar
Michael Widenius committed
2524
  char_length= ((cast_length != ~0U) ? cast_length :
2525
                args[0]->max_length /
Michael Widenius's avatar
Michael Widenius committed
2526 2527
                (cast_cs == &my_charset_bin ? 1 :
                 args[0]->collation.collation->mbmaxlen));
2528 2529 2530
  max_length= char_length * cast_cs->mbmaxlen;
}

2531

2532
bool Item_time_typecast::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
unknown's avatar
unknown committed
2533
{
2534 2535
  if (get_arg0_time(ltime))
    return 1;
2536
  if (decimals < TIME_SECOND_PART_DIGITS)
2537
    my_time_trunc(ltime, decimals);
2538
  /*
2539
    MYSQL_TIMESTAMP_TIME value can have non-zero day part,
2540 2541
    which we should not lose.
  */
2542
  if (ltime->time_type != MYSQL_TIMESTAMP_TIME)
2543
    ltime->year= ltime->month= ltime->day= 0;
2544
  ltime->time_type= MYSQL_TIMESTAMP_TIME;
2545 2546 2547
  return (fuzzy_date & TIME_TIME_ONLY) ? 0 :
         (null_value= check_date_with_warn(ltime, fuzzy_date,
                                           MYSQL_TIMESTAMP_ERROR)); 
unknown's avatar
unknown committed
2548 2549 2550
}


2551
bool Item_date_typecast::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
unknown's avatar
unknown committed
2552
{
Sergei Golubchik's avatar
cleanup  
Sergei Golubchik committed
2553
  fuzzy_date |= sql_mode_for_dates(current_thd);
2554
  if (get_arg0_date(ltime, fuzzy_date & ~TIME_TIME_ONLY))
2555
    return 1;
Sergei Golubchik's avatar
Sergei Golubchik committed
2556

2557 2558 2559 2560
  if (make_date_with_warn(ltime, fuzzy_date, MYSQL_TIMESTAMP_DATE))
    return (null_value= 1);

  return 0;
2561
}
2562

unknown's avatar
unknown committed
2563

2564
bool Item_datetime_typecast::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
unknown's avatar
unknown committed
2565
{
Sergei Golubchik's avatar
cleanup  
Sergei Golubchik committed
2566
  fuzzy_date |= sql_mode_for_dates(current_thd);
2567
  if (get_arg0_date(ltime, fuzzy_date & ~TIME_TIME_ONLY))
2568
    return 1;
unknown's avatar
unknown committed
2569

2570
  if (decimals < TIME_SECOND_PART_DIGITS)
2571
    my_time_trunc(ltime, decimals);
2572

2573
  DBUG_ASSERT(ltime->time_type != MYSQL_TIMESTAMP_TIME);
2574
  ltime->time_type= MYSQL_TIMESTAMP_DATETIME;
unknown's avatar
unknown committed
2575 2576 2577 2578
  return 0;
}


unknown's avatar
unknown committed
2579
/**
2580 2581 2582 2583
  MAKEDATE(a,b) is a date function that creates a date value 
  from a year and day value.

  NOTES:
Michael Widenius's avatar
Michael Widenius committed
2584 2585 2586 2587
    As arguments are integers, we can't know if the year is a 2 digit
    or 4 digit year.  In this case we treat all years < 100 as 2 digit
    years. Ie, this is not safe for dates between 0000-01-01 and
    0099-12-31
2588 2589
*/

2590
bool Item_func_makedate::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
2591 2592 2593
{
  DBUG_ASSERT(fixed == 1);
  long daynr=  (long) args[1]->val_int();
2594
  long year= (long) args[0]->val_int();
2595 2596 2597
  long days;

  if (args[0]->null_value || args[1]->null_value ||
2598
      year < 0 || year > 9999 || daynr <= 0)
2599 2600
    goto err;

2601 2602 2603 2604
  if (year < 100)
    year= year_2000_handling(year);

  days= calc_daynr(year,1,1) + daynr - 1;
2605 2606 2607 2608 2609 2610
  if (get_date_from_daynr(days, &ltime->year, &ltime->month, &ltime->day))
    goto err;
  ltime->time_type= MYSQL_TIMESTAMP_DATE;
  ltime->neg= 0;
  ltime->hour= ltime->minute= ltime->second= ltime->second_part= 0;
  return (null_value= 0);
2611 2612

err:
2613
  return (null_value= 1);
2614 2615 2616
}


unknown's avatar
unknown committed
2617 2618 2619
void Item_func_add_time::fix_length_and_dec()
{
  enum_field_types arg0_field_type;
2620
  decimals= MY_MAX(args[0]->decimals, args[1]->decimals);
unknown's avatar
unknown committed
2621 2622

  /*
2623 2624
    The field type for the result of an Item_func_add_time function is defined
    as follows:
unknown's avatar
unknown committed
2625 2626 2627 2628 2629 2630 2631 2632 2633

    - If first arg is a MYSQL_TYPE_DATETIME or MYSQL_TYPE_TIMESTAMP 
      result is MYSQL_TYPE_DATETIME
    - If first arg is a MYSQL_TYPE_TIME result is MYSQL_TYPE_TIME
    - Otherwise the result is MYSQL_TYPE_STRING
  */

  cached_field_type= MYSQL_TYPE_STRING;
  arg0_field_type= args[0]->field_type();
unknown's avatar
unknown committed
2634 2635
  if (arg0_field_type == MYSQL_TYPE_DATE ||
      arg0_field_type == MYSQL_TYPE_DATETIME ||
2636 2637
      arg0_field_type == MYSQL_TYPE_TIMESTAMP ||
      is_date)
2638
  {
unknown's avatar
unknown committed
2639
    cached_field_type= MYSQL_TYPE_DATETIME;
Sergei Golubchik's avatar
Sergei Golubchik committed
2640 2641
    decimals= MY_MAX(args[0]->temporal_precision(MYSQL_TYPE_DATETIME),
                     args[1]->temporal_precision(MYSQL_TYPE_TIME));
2642
  }
unknown's avatar
unknown committed
2643
  else if (arg0_field_type == MYSQL_TYPE_TIME)
2644
  {
unknown's avatar
unknown committed
2645
    cached_field_type= MYSQL_TYPE_TIME;
Sergei Golubchik's avatar
Sergei Golubchik committed
2646 2647
    decimals= MY_MAX(args[0]->temporal_precision(MYSQL_TYPE_TIME),
                     args[1]->temporal_precision(MYSQL_TYPE_TIME));
2648
  }
Sergei Golubchik's avatar
Sergei Golubchik committed
2649
  Item_temporal_func::fix_length_and_dec();
unknown's avatar
unknown committed
2650 2651
}

unknown's avatar
unknown committed
2652
/**
2653 2654
  ADDTIME(t,a) and SUBTIME(t,a) are time functions that calculate a
  time/datetime value 
unknown's avatar
unknown committed
2655 2656 2657 2658 2659 2660 2661

  t: time_or_datetime_expression
  a: time_expression
  
  Result: Time value or datetime value
*/

2662
bool Item_func_add_time::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
unknown's avatar
unknown committed
2663
{
2664
  DBUG_ASSERT(fixed == 1);
2665
  MYSQL_TIME l_time1, l_time2;
unknown's avatar
unknown committed
2666
  bool is_time= 0;
2667 2668
  long days, microseconds;
  longlong seconds;
2669
  int l_sign= sign;
unknown's avatar
unknown committed
2670

2671
  if (cached_field_type == MYSQL_TYPE_DATETIME)
unknown's avatar
unknown committed
2672
  {
2673
    // TIMESTAMP function OR the first argument is DATE/DATETIME/TIMESTAMP
2674
    if (get_arg0_date(&l_time1, 0) || 
unknown's avatar
unknown committed
2675
        args[1]->get_time(&l_time2) ||
2676 2677
        l_time1.time_type == MYSQL_TIMESTAMP_TIME || 
        l_time2.time_type != MYSQL_TIMESTAMP_TIME)
2678
      return (null_value= 1);
unknown's avatar
unknown committed
2679
  }
2680
  else
unknown's avatar
unknown committed
2681
  {
2682
    // ADDTIME function AND the first argument is TIME
unknown's avatar
unknown committed
2683 2684
    if (args[0]->get_time(&l_time1) || 
        args[1]->get_time(&l_time2) ||
2685
        l_time2.time_type == MYSQL_TIMESTAMP_DATETIME)
2686
      return (null_value= 1);
2687
    is_time= (l_time1.time_type == MYSQL_TIMESTAMP_TIME);
unknown's avatar
unknown committed
2688 2689 2690
  }
  if (l_time1.neg != l_time2.neg)
    l_sign= -l_sign;
2691
  
2692
  bzero(ltime, sizeof(*ltime));
2693
  
2694
  ltime->neg= calc_time_diff(&l_time1, &l_time2, -l_sign,
2695
			      &seconds, &microseconds);
unknown's avatar
unknown committed
2696

2697 2698 2699 2700 2701
  /*
    If first argument was negative and diff between arguments
    is non-zero we need to swap sign to get proper result.
  */
  if (l_time1.neg && (seconds || microseconds))
2702
    ltime->neg= 1-ltime->neg;         // Swap sign of result
unknown's avatar
unknown committed
2703

2704 2705
  if (!is_time && ltime->neg)
    return (null_value= 1);
2706

2707
  days= (long) (seconds / SECONDS_IN_24H);
unknown's avatar
unknown committed
2708

2709
  calc_time_from_sec(ltime, (long)(seconds % SECONDS_IN_24H), microseconds);
2710 2711 2712

  ltime->time_type= is_time ? MYSQL_TIMESTAMP_TIME : MYSQL_TIMESTAMP_DATETIME;

unknown's avatar
unknown committed
2713 2714
  if (!is_time)
  {
2715 2716
    if (get_date_from_daynr(days,&ltime->year,&ltime->month,&ltime->day) ||
        !ltime->day)
2717 2718
      return (null_value= 1);
    return (null_value= 0);
unknown's avatar
unknown committed
2719
  }
2720
  
2721
  ltime->hour+= days*24;
2722
  return (null_value= adjust_time_range_with_warn(ltime, decimals));
2723 2724 2725
}


2726
void Item_func_add_time::print(String *str, enum_query_type query_type)
2727 2728 2729 2730
{
  if (is_date)
  {
    DBUG_ASSERT(sign > 0);
2731
    str->append(STRING_WITH_LEN("timestamp("));
2732 2733 2734 2735
  }
  else
  {
    if (sign > 0)
2736
      str->append(STRING_WITH_LEN("addtime("));
2737
    else
2738
      str->append(STRING_WITH_LEN("subtime("));
2739
  }
2740
  args[0]->print(str, query_type);
2741
  str->append(',');
2742
  args[1]->print(str, query_type);
2743 2744 2745 2746
  str->append(')');
}


unknown's avatar
unknown committed
2747
/**
unknown's avatar
unknown committed
2748 2749 2750 2751 2752 2753 2754
  TIMEDIFF(t,s) is a time function that calculates the 
  time value between a start and end time.

  t and s: time_or_datetime_expression
  Result: Time value
*/

2755
bool Item_func_timediff::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
unknown's avatar
unknown committed
2756
{
2757
  DBUG_ASSERT(fixed == 1);
2758
  int l_sign= 1;
2759
  MYSQL_TIME l_time1,l_time2,l_time3;
Sergei Golubchik's avatar
Sergei Golubchik committed
2760
  ErrConvTime str(&l_time3);
unknown's avatar
unknown committed
2761

Sergei Golubchik's avatar
Sergei Golubchik committed
2762 2763
  /* the following may be true in, for example, date_add(timediff(...), ... */
  if (fuzzy_date & TIME_NO_ZERO_IN_DATE)
Sergei Golubchik's avatar
Sergei Golubchik committed
2764
    return (null_value= 1);
unknown's avatar
unknown committed
2765 2766 2767 2768

  if (args[0]->get_time(&l_time1) ||
      args[1]->get_time(&l_time2) ||
      l_time1.time_type != l_time2.time_type)
Sergei Golubchik's avatar
Sergei Golubchik committed
2769
    return (null_value= 1);
unknown's avatar
unknown committed
2770 2771 2772 2773

  if (l_time1.neg != l_time2.neg)
    l_sign= -l_sign;

2774
  if (calc_time_diff(&l_time1, &l_time2, l_sign, &l_time3, fuzzy_date))
Sergei Golubchik's avatar
Sergei Golubchik committed
2775
    return (null_value= 1);
unknown's avatar
unknown committed
2776

2777
  *ltime= l_time3;
2778
  return (null_value= adjust_time_range_with_warn(ltime, decimals));
unknown's avatar
unknown committed
2779 2780
}

unknown's avatar
unknown committed
2781
/**
unknown's avatar
unknown committed
2782 2783 2784 2785 2786
  MAKETIME(h,m,s) is a time function that calculates a time value 
  from the total number of hours, minutes, and seconds.
  Result: Time value
*/

2787
bool Item_func_maketime::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
unknown's avatar
unknown committed
2788
{
2789
  DBUG_ASSERT(fixed == 1);
2790 2791 2792
  bool overflow= 0;
  longlong hour=   args[0]->val_int();
  longlong minute= args[1]->val_int();
2793 2794 2795
  ulonglong second;
  ulong microsecond;
  bool neg= args[2]->get_seconds(&second, &microsecond);
unknown's avatar
unknown committed
2796

Sergei Golubchik's avatar
Sergei Golubchik committed
2797
  if (args[0]->null_value || args[1]->null_value || args[2]->null_value ||
Alexander Barkov's avatar
Alexander Barkov committed
2798
       minute < 0 || minute > 59 || neg || second > 59)
Sergei Golubchik's avatar
Sergei Golubchik committed
2799
    return (null_value= 1);
unknown's avatar
unknown committed
2800

2801 2802
  bzero(ltime, sizeof(*ltime));
  ltime->time_type= MYSQL_TIMESTAMP_TIME;
2803 2804

  /* Check for integer overflows */
unknown's avatar
unknown committed
2805 2806
  if (hour < 0)
  {
2807 2808 2809
    if (args[0]->unsigned_flag)
      overflow= 1;
    else
2810
      ltime->neg= 1;
2811
  }
2812
  if (-hour > TIME_MAX_HOUR || hour > TIME_MAX_HOUR)
2813 2814 2815 2816
    overflow= 1;

  if (!overflow)
  {
2817 2818 2819
    ltime->hour=   (uint) ((hour < 0 ? -hour : hour));
    ltime->minute= (uint) minute;
    ltime->second= (uint) second;
2820
    ltime->second_part= microsecond;
2821 2822 2823
  }
  else
  {
2824 2825 2826
    ltime->hour= TIME_MAX_HOUR;
    ltime->minute= TIME_MAX_MINUTE;
    ltime->second= TIME_MAX_SECOND;
2827 2828
    char buf[28];
    char *ptr= longlong10_to_str(hour, buf, args[0]->unsigned_flag ? 10 : -10);
Sergei Golubchik's avatar
Sergei Golubchik committed
2829
    int len = (int)(ptr - buf) + sprintf(ptr, ":%02u:%02u", (uint)minute, (uint)second);
2830
    make_truncated_value_warning(current_thd, Sql_condition::WARN_LEVEL_WARN,
2831
                                 buf, len, MYSQL_TIMESTAMP_TIME,
2832
                                 NullS);
2833
  }
2834

Sergei Golubchik's avatar
Sergei Golubchik committed
2835
  return (null_value= 0);
unknown's avatar
unknown committed
2836 2837
}

2838

unknown's avatar
unknown committed
2839
/**
2840 2841
  MICROSECOND(a) is a function ( extraction) that extracts the microseconds
  from a.
unknown's avatar
unknown committed
2842 2843 2844 2845

  a: Datetime or time value
  Result: int value
*/
2846

unknown's avatar
unknown committed
2847 2848
longlong Item_func_microsecond::val_int()
{
2849
  DBUG_ASSERT(fixed == 1);
2850
  MYSQL_TIME ltime;
Sergei Golubchik's avatar
Sergei Golubchik committed
2851
  if (!get_arg0_date(&ltime, TIME_TIME_ONLY))
unknown's avatar
unknown committed
2852 2853 2854
    return ltime.second_part;
  return 0;
}
2855 2856


2857 2858
longlong Item_func_timestamp_diff::val_int()
{
2859
  MYSQL_TIME ltime1, ltime2;
2860 2861 2862 2863 2864 2865
  longlong seconds;
  long microseconds;
  long months= 0;
  int neg= 1;

  null_value= 0;  
2866 2867 2868 2869 2870 2871
  if (args[0]->get_date_with_conversion(&ltime1,
                                        TIME_NO_ZERO_DATE |
                                        TIME_NO_ZERO_IN_DATE) ||
      args[1]->get_date_with_conversion(&ltime2,
                                        TIME_NO_ZERO_DATE |
                                        TIME_NO_ZERO_IN_DATE))
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881
    goto null_date;

  if (calc_time_diff(&ltime2,&ltime1, 1,
		     &seconds, &microseconds))
    neg= -1;

  if (int_type == INTERVAL_YEAR ||
      int_type == INTERVAL_QUARTER ||
      int_type == INTERVAL_MONTH)
  {
2882 2883
    uint year_beg, year_end, month_beg, month_end, day_beg, day_end;
    uint years= 0;
2884 2885
    uint second_beg, second_end, microsecond_beg, microsecond_end;

2886 2887 2888 2889 2890 2891
    if (neg == -1)
    {
      year_beg= ltime2.year;
      year_end= ltime1.year;
      month_beg= ltime2.month;
      month_end= ltime1.month;
2892 2893
      day_beg= ltime2.day;
      day_end= ltime1.day;
2894 2895 2896 2897
      second_beg= ltime2.hour * 3600 + ltime2.minute * 60 + ltime2.second;
      second_end= ltime1.hour * 3600 + ltime1.minute * 60 + ltime1.second;
      microsecond_beg= ltime2.second_part;
      microsecond_end= ltime1.second_part;
2898 2899 2900 2901 2902 2903 2904
    }
    else
    {
      year_beg= ltime1.year;
      year_end= ltime2.year;
      month_beg= ltime1.month;
      month_end= ltime2.month;
2905 2906
      day_beg= ltime1.day;
      day_end= ltime2.day;
2907 2908 2909 2910
      second_beg= ltime1.hour * 3600 + ltime1.minute * 60 + ltime1.second;
      second_end= ltime2.hour * 3600 + ltime2.minute * 60 + ltime2.second;
      microsecond_beg= ltime1.second_part;
      microsecond_end= ltime2.second_part;
2911 2912
    }

2913 2914 2915 2916
    /* calc years */
    years= year_end - year_beg;
    if (month_end < month_beg || (month_end == month_beg && day_end < day_beg))
      years-= 1;
2917

2918 2919 2920 2921 2922 2923
    /* calc months */
    months= 12*years;
    if (month_end < month_beg || (month_end == month_beg && day_end < day_beg))
      months+= 12 - (month_beg - month_end);
    else
      months+= (month_end - month_beg);
2924

2925 2926
    if (day_end < day_beg)
      months-= 1;
2927 2928 2929 2930
    else if ((day_end == day_beg) &&
	     ((second_end < second_beg) ||
	      (second_end == second_beg && microsecond_end < microsecond_beg)))
      months-= 1;
2931 2932 2933 2934
  }

  switch (int_type) {
  case INTERVAL_YEAR:
2935
    return months/12*neg;
2936
  case INTERVAL_QUARTER:
2937
    return months/3*neg;
2938
  case INTERVAL_MONTH:
2939
    return months*neg;
2940
  case INTERVAL_WEEK:          
2941
    return seconds / SECONDS_IN_24H / 7L * neg;
2942
  case INTERVAL_DAY:		
2943
    return seconds / SECONDS_IN_24H * neg;
2944 2945 2946 2947 2948 2949 2950
  case INTERVAL_HOUR:		
    return seconds/3600L*neg;
  case INTERVAL_MINUTE:		
    return seconds/60L*neg;
  case INTERVAL_SECOND:		
    return seconds*neg;
  case INTERVAL_MICROSECOND:
2951 2952 2953 2954 2955
    /*
      In MySQL difference between any two valid datetime values
      in microseconds fits into longlong.
    */
    return (seconds*1000000L+microseconds)*neg;
2956 2957 2958 2959 2960 2961 2962 2963 2964 2965
  default:
    break;
  }

null_date:
  null_value=1;
  return 0;
}


2966
void Item_func_timestamp_diff::print(String *str, enum_query_type query_type)
2967 2968 2969 2970 2971 2972
{
  str->append(func_name());
  str->append('(');

  switch (int_type) {
  case INTERVAL_YEAR:
2973
    str->append(STRING_WITH_LEN("YEAR"));
2974 2975
    break;
  case INTERVAL_QUARTER:
2976
    str->append(STRING_WITH_LEN("QUARTER"));
2977 2978
    break;
  case INTERVAL_MONTH:
2979
    str->append(STRING_WITH_LEN("MONTH"));
2980 2981
    break;
  case INTERVAL_WEEK:          
2982
    str->append(STRING_WITH_LEN("WEEK"));
2983 2984
    break;
  case INTERVAL_DAY:		
2985
    str->append(STRING_WITH_LEN("DAY"));
2986 2987
    break;
  case INTERVAL_HOUR:
2988
    str->append(STRING_WITH_LEN("HOUR"));
2989 2990
    break;
  case INTERVAL_MINUTE:		
2991
    str->append(STRING_WITH_LEN("MINUTE"));
2992 2993
    break;
  case INTERVAL_SECOND:
2994
    str->append(STRING_WITH_LEN("SECOND"));
2995 2996
    break;		
  case INTERVAL_MICROSECOND:
2997
    str->append(STRING_WITH_LEN("MICROSECOND"));
2998 2999 3000 3001 3002 3003 3004 3005
    break;
  default:
    break;
  }

  for (uint i=0 ; i < 2 ; i++)
  {
    str->append(',');
3006
    args[i]->print(str, query_type);
3007 3008 3009
  }
  str->append(')');
}
unknown's avatar
unknown committed
3010 3011


3012
String *Item_func_get_format::val_str_ascii(String *str)
3013
{
3014
  DBUG_ASSERT(fixed == 1);
3015 3016
  const char *format_name;
  KNOWN_DATE_TIME_FORMAT *format;
3017
  String *val= args[0]->val_str_ascii(str);
3018
  ulong val_len;
3019

3020 3021 3022 3023 3024 3025 3026
  if ((null_value= args[0]->null_value))
    return 0;    

  val_len= val->length();
  for (format= &known_date_time_formats[0];
       (format_name= format->format_name);
       format++)
3027
  {
3028
    uint format_name_len;
3029
    format_name_len= (uint) strlen(format_name);
3030 3031 3032 3033
    if (val_len == format_name_len &&
	!my_strnncoll(&my_charset_latin1, 
		      (const uchar *) val->ptr(), val_len, 
		      (const uchar *) format_name, val_len))
3034
    {
3035
      const char *format_str= get_date_time_format_str(format, type);
3036
      str->set(format_str, (uint) strlen(format_str), &my_charset_numeric);
3037
      return str;
3038 3039 3040
    }
  }

3041 3042 3043 3044 3045
  null_value= 1;
  return 0;
}


3046
void Item_func_get_format::print(String *str, enum_query_type query_type)
3047 3048 3049 3050 3051
{
  str->append(func_name());
  str->append('(');

  switch (type) {
3052
  case MYSQL_TIMESTAMP_DATE:
3053
    str->append(STRING_WITH_LEN("DATE, "));
3054
    break;
3055
  case MYSQL_TIMESTAMP_DATETIME:
3056
    str->append(STRING_WITH_LEN("DATETIME, "));
3057
    break;
3058
  case MYSQL_TIMESTAMP_TIME:
3059
    str->append(STRING_WITH_LEN("TIME, "));
3060 3061 3062 3063
    break;
  default:
    DBUG_ASSERT(0);
  }
3064
  args[0]->print(str, query_type);
3065 3066 3067 3068
  str->append(')');
}


unknown's avatar
unknown committed
3069
/**
3070 3071 3072
  Get type of datetime value (DATE/TIME/...) which will be produced
  according to format string.

unknown's avatar
unknown committed
3073 3074
  @param format   format string
  @param length   length of format string
3075

unknown's avatar
unknown committed
3076
  @note
3077 3078 3079
    We don't process day format's characters('D', 'd', 'e') because day
    may be a member of all date/time types.

unknown's avatar
unknown committed
3080
  @note
3081 3082 3083
    Format specifiers supported by this function should be in sync with
    specifiers supported by extract_date_time() function.

unknown's avatar
unknown committed
3084
  @return
3085
    One of date_time_format_types values:
unknown's avatar
unknown committed
3086 3087 3088 3089 3090
    - DATE_TIME_MICROSECOND
    - DATE_TIME
    - DATE_ONLY
    - TIME_MICROSECOND
    - TIME_ONLY
3091 3092
*/

3093 3094
static date_time_format_types
get_date_time_result_type(const char *format, uint length)
3095 3096
{
  const char *time_part_frms= "HISThiklrs";
3097
  const char *date_part_frms= "MVUXYWabcjmvuxyw";
3098 3099 3100 3101 3102
  bool date_part_used= 0, time_part_used= 0, frac_second_used= 0;
  
  const char *val= format;
  const char *end= format + length;

3103
  for (; val != end; val++)
3104 3105 3106 3107
  {
    if (*val == '%' && val+1 != end)
    {
      val++;
3108 3109 3110
      if (*val == 'f')
        frac_second_used= time_part_used= 1;
      else if (!time_part_used && strchr(time_part_frms, *val))
3111 3112 3113
	time_part_used= 1;
      else if (!date_part_used && strchr(date_part_frms, *val))
	date_part_used= 1;
3114 3115 3116 3117 3118 3119
      if (date_part_used && frac_second_used)
      {
        /*
          frac_second_used implies time_part_used, and thus we already
          have all types of date-time components and can end our search.
        */
3120
	return DATE_TIME_MICROSECOND;
3121
      }
3122 3123 3124
    }
  }

3125 3126 3127
  /* We don't have all three types of date-time components */
  if (frac_second_used)
    return TIME_MICROSECOND;
3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139
  if (time_part_used)
  {
    if (date_part_used)
      return DATE_TIME;
    return TIME_ONLY;
  }
  return DATE_ONLY;
}


void Item_func_str_to_date::fix_length_and_dec()
{
3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150
  if (agg_arg_charsets(collation, args, 2, MY_COLL_ALLOW_CONV, 1))
    return;
  if (collation.collation->mbminlen > 1)
  {
#if MYSQL_VERSION_ID > 50500
    internal_charset= &my_charset_utf8mb4_general_ci;
#else
    internal_charset= &my_charset_utf8_general_ci;
#endif
  }

3151
  cached_field_type= MYSQL_TYPE_DATETIME;
3152
  decimals= TIME_SECOND_PART_DIGITS;
unknown's avatar
unknown committed
3153
  if ((const_item= args[1]->const_item()))
3154
  {
unknown's avatar
unknown committed
3155 3156
    char format_buff[64];
    String format_str(format_buff, sizeof(format_buff), &my_charset_bin);
3157 3158
    String *format= args[1]->val_str(&format_str, &format_converter,
                                     internal_charset);
3159
    decimals= 0;
unknown's avatar
unknown committed
3160 3161
    if (!args[1]->null_value)
    {
3162 3163
      date_time_format_types cached_format_type=
        get_date_time_result_type(format->ptr(), format->length());
unknown's avatar
unknown committed
3164 3165 3166 3167 3168
      switch (cached_format_type) {
      case DATE_ONLY:
        cached_field_type= MYSQL_TYPE_DATE; 
        break;
      case TIME_MICROSECOND:
3169 3170 3171
        decimals= 6;
        /* fall through */
      case TIME_ONLY:
unknown's avatar
unknown committed
3172 3173
        cached_field_type= MYSQL_TYPE_TIME; 
        break;
3174 3175 3176 3177
      case DATE_TIME_MICROSECOND:
        decimals= 6;
        /* fall through */
      case DATE_TIME:
unknown's avatar
unknown committed
3178 3179 3180
        cached_field_type= MYSQL_TYPE_DATETIME; 
        break;
      }
3181 3182
    }
  }
Sergei Golubchik's avatar
Sergei Golubchik committed
3183 3184
  cached_timestamp_type= mysql_type_to_time_type(cached_field_type);
  Item_temporal_func::fix_length_and_dec();
3185 3186
}

unknown's avatar
unknown committed
3187

3188
bool Item_func_str_to_date::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
3189 3190 3191
{
  DATE_TIME_FORMAT date_time_format;
  char val_buff[64], format_buff[64];
3192
  String val_string(val_buff, sizeof(val_buff), &my_charset_bin), *val;
Michael Widenius's avatar
Michael Widenius committed
3193 3194
  String format_str(format_buff, sizeof(format_buff), &my_charset_bin),
    *format;
3195

3196 3197
  val=    args[0]->val_str(&val_string, &subject_converter, internal_charset);
  format= args[1]->val_str(&format_str, &format_converter, internal_charset);
3198
  if (args[0]->null_value || args[1]->null_value)
Sergei Golubchik's avatar
Sergei Golubchik committed
3199
    return (null_value=1);
3200 3201 3202 3203

  date_time_format.format.str=    (char*) format->ptr();
  date_time_format.format.length= format->length();
  if (extract_date_time(&date_time_format, val->ptr(), val->length(),
3204
			ltime, cached_timestamp_type, 0, "datetime",
Sergei Golubchik's avatar
cleanup  
Sergei Golubchik committed
3205
                        fuzzy_date | sql_mode_for_dates(current_thd)))
Sergei Golubchik's avatar
Sergei Golubchik committed
3206
    return (null_value=1);
3207
  if (cached_timestamp_type == MYSQL_TIMESTAMP_TIME && ltime->day)
3208 3209 3210 3211 3212 3213 3214 3215 3216
  {
    /*
      Day part for time type can be nonzero value and so 
      we should add hours from day part to hour part to
      keep valid time value.
    */
    ltime->hour+= ltime->day*24;
    ltime->day= 0;
  }
Sergei Golubchik's avatar
Sergei Golubchik committed
3217
  return (null_value= 0);
3218 3219 3220
}


3221
bool Item_func_last_day::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
unknown's avatar
unknown committed
3222
{
Sergei Golubchik's avatar
merge  
Sergei Golubchik committed
3223
  if (get_arg0_date(ltime, fuzzy_date) ||
3224
      (ltime->month == 0))
Sergei Golubchik's avatar
Sergei Golubchik committed
3225
    return (null_value=1);
3226 3227 3228 3229
  uint month_idx= ltime->month-1;
  ltime->day= days_in_month[month_idx];
  if ( month_idx == 1 && calc_days_in_year(ltime->year) == 366)
    ltime->day= 29;
3230 3231
  ltime->hour= ltime->minute= ltime->second= 0;
  ltime->second_part= 0;
3232
  ltime->time_type= MYSQL_TIMESTAMP_DATE;
Sergei Golubchik's avatar
Sergei Golubchik committed
3233
  return (null_value= 0);
unknown's avatar
unknown committed
3234
}