item_timefunc.cc 92 KB
Newer Older
1
/* Copyright (C) 2000-2003 MySQL AB
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3 4
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
5
   the Free Software Foundation; version 2 of the License.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
6

bk@work.mysql.com's avatar
bk@work.mysql.com committed
7 8 9 10
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
11

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


17 18 19 20 21 22 23 24 25
/**
  @file

  @brief
  This file defines all time functions

  @todo
    Move month and days to language files
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
26

27
#ifdef USE_PRAGMA_IMPLEMENTATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
28 29 30
#pragma implementation				// gcc: Class implementation
#endif

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
#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,
                                 // make_time, get_date_from_daynr,
                                 // calc_weekday, calc_week,
                                 // convert_month_to_period,
                                 // convert_period_to_month,
                                 // TIME_to_timestamp, make_date,
                                 // calc_time_diff,
                                 // calc_time_from_sec,
                                 // known_date_time_format,
                                 // get_date_time_format_str
#include "tztime.h"              // struct Time_zone
#include "sql_class.h"           // THD
bk@work.mysql.com's avatar
bk@work.mysql.com committed
53 54 55
#include <m_ctype.h>
#include <time.h>

56
/** Day number for Dec 31st, 9999. */
57 58
#define MAX_DAY_NUMBER 3652424L

59 60 61 62 63 64 65
/**
  @todo
  OPTIMIZATION
  - Replace the switch with a function that should be called for each
  date type.
  - Remove sprintf and opencode the conversion, like we do in
  Field_datetime.
66 67 68 69 70 71 72 73 74 75 76

  The reason for this functions existence is that as we don't have a
  way to know if a datetime/time value has microseconds in them
  we are now only adding microseconds to the output if the
  value has microseconds.

  We can't use a standard make_date_time() for this as we don't know
  if someone will use %f in the format specifier in which case we would get
  the microseconds twice.
*/

77
static bool make_datetime(date_time_format_types format, MYSQL_TIME *ltime,
78
			  String *str)
79
{
80
  char *buff;
81
  CHARSET_INFO *cs= &my_charset_numeric;
82
  uint length= MAX_DATE_STRING_REP_LENGTH;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
83

84 85 86
  if (str->alloc(length))
    return 1;
  buff= (char*) str->ptr();
87

88 89 90 91 92 93 94
  switch (format) {
  case TIME_ONLY:
    length= cs->cset->snprintf(cs, buff, length, "%s%02d:%02d:%02d",
			       ltime->neg ? "-" : "",
			       ltime->hour, ltime->minute, ltime->second);
    break;
  case TIME_MICROSECOND:
95
    length= cs->cset->snprintf(cs, buff, length, "%s%02d:%02d:%02d.%06ld",
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
			       ltime->neg ? "-" : "",
			       ltime->hour, ltime->minute, ltime->second,
			       ltime->second_part);
    break;
  case DATE_ONLY:
    length= cs->cset->snprintf(cs, buff, length, "%04d-%02d-%02d",
			       ltime->year, ltime->month, ltime->day);
    break;
  case DATE_TIME:
    length= cs->cset->snprintf(cs, buff, length,
			       "%04d-%02d-%02d %02d:%02d:%02d",
			       ltime->year, ltime->month, ltime->day,
			       ltime->hour, ltime->minute, ltime->second);
    break;
  case DATE_TIME_MICROSECOND:
    length= cs->cset->snprintf(cs, buff, length,
112
			       "%04d-%02d-%02d %02d:%02d:%02d.%06ld",
113 114 115 116
			       ltime->year, ltime->month, ltime->day,
			       ltime->hour, ltime->minute, ltime->second,
			       ltime->second_part);
    break;
117
  }
118 119 120 121

  str->length(length);
  str->set_charset(cs);
  return 0;
122
}
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
123 124


125
/*
126
  Wrapper over make_datetime() with validation of the input MYSQL_TIME value
127 128 129 130 131 132 133 134 135

  NOTE
    see make_datetime() for more information

  RETURN
    1    if there was an error during converion
    0    otherwise
*/

136
static bool make_datetime_with_warn(date_time_format_types format, MYSQL_TIME *ltime,
137 138 139 140 141 142 143 144 145 146 147
                                    String *str)
{
  int warning= 0;

  if (make_datetime(format, ltime, str))
    return 1;
  if (check_time_range(ltime, &warning))
    return 1;
  if (!warning)
    return 0;

148 149
  make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                               str->ptr(), str->length(),
150
                               MYSQL_TIMESTAMP_TIME, NullS);
151 152 153 154 155
  return make_datetime(format, ltime, str);
}


/*
156
  Wrapper over make_time() with validation of the input MYSQL_TIME value
157 158 159 160 161 162 163 164 165 166

  NOTE
    see make_time() for more info

  RETURN
    1    if there was an error during conversion
    0    otherwise
*/

static bool make_time_with_warn(const DATE_TIME_FORMAT *format,
167
                                MYSQL_TIME *l_time, String *str)
168 169 170 171 172 173 174
{
  int warning= 0;
  make_time(format, l_time, str);
  if (check_time_range(l_time, &warning))
    return 1;
  if (warning)
  {
175 176
    make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                                 str->ptr(), str->length(),
177
                                 MYSQL_TIMESTAMP_TIME, NullS);
178 179 180 181 182 183 184 185
    make_time(format, l_time, str);
  }

  return 0;
}


/*
186
  Convert seconds to MYSQL_TIME value with overflow checking
187 188 189 190 191

  SYNOPSIS:
    sec_to_time()
    seconds          number of seconds
    unsigned_flag    1, if 'seconds' is unsigned, 0, otherwise
192
    ltime            output MYSQL_TIME value
193 194

  DESCRIPTION
195
    If the 'seconds' argument is inside MYSQL_TIME data range, convert it to a
196 197 198 199 200 201 202 203 204
    corresponding value.
    Otherwise, truncate the resulting value to the nearest endpoint, and
    produce a warning message.

  RETURN
    1                if the value was truncated during conversion
    0                otherwise
*/
  
205
static bool sec_to_time(longlong seconds, bool unsigned_flag, MYSQL_TIME *ltime)
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
{
  uint sec;

  bzero((char *)ltime, sizeof(*ltime));
  
  if (seconds < 0)
  {
    if (unsigned_flag)
      goto overflow;
    ltime->neg= 1;
    if (seconds < -3020399)
      goto overflow;
    seconds= -seconds;
  }
  else if (seconds > 3020399)
    goto overflow;
  
  sec= (uint) ((ulonglong) seconds % 3600);
  ltime->hour= (uint) (seconds/3600);
  ltime->minute= sec/60;
  ltime->second= sec % 60;

  return 0;

overflow:
  ltime->hour= TIME_MAX_HOUR;
  ltime->minute= TIME_MAX_MINUTE;
  ltime->second= TIME_MAX_SECOND;

  char buf[22];
  int len= (int)(longlong10_to_str(seconds, buf, unsigned_flag ? 10 : -10)
                 - buf);
238 239
  make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                               buf, len, MYSQL_TIMESTAMP_TIME,
240
                               NullS);
241 242 243 244 245
  
  return 1;
}


246 247 248 249 250 251 252
/*
  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,
253
                                           {(char *)"%I:%i:%S %p", 11}};
254
static DATE_TIME_FORMAT time_24hrs_format= {{0}, '\0', 0,
255 256
                                            {(char *)"%H:%i:%S", 8}};

257
/**
258
  Extract datetime value to MYSQL_TIME struct from string value
259
  according to format string.
260

261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
  @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
288
*/
289 290

static bool extract_date_time(DATE_TIME_FORMAT *format,
291
			      const char *val, uint length, MYSQL_TIME *l_time,
292
                              timestamp_type cached_timestamp_type,
293 294
                              const char **sub_pattern_end,
                              const char *date_time_type)
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
295
{
296
  int weekday= 0, yearday= 0, daypart= 0;
297
  int week_number= -1;
298
  int error= 0;
299
  int  strict_week_number_year= -1;
300
  int frac_part;
301
  bool usa_time= 0;
302 303 304
  bool UNINIT_VAR(sunday_first_n_first_week_non_iso);
  bool UNINIT_VAR(strict_week_number);
  bool UNINIT_VAR(strict_week_number_year_type);
305
  const char *val_begin= val;
306 307
  const char *val_end= val + length;
  const char *ptr= format->format.str;
308
  const char *end= ptr + format->format.length;
309
  CHARSET_INFO *cs= &my_charset_bin;
310
  DBUG_ENTER("extract_date_time");
311

312 313
  if (!sub_pattern_end)
    bzero((char*) l_time, sizeof(*l_time));
314 315

  for (; ptr != end && val != val_end; ptr++)
316
  {
317 318 319 320
    /* Skip pre-space between each argument */
    while (val != val_end && my_isspace(cs, *val))
      val++;

321 322
    if (*ptr == '%' && ptr+1 != end)
    {
323 324 325
      int val_len;
      char *tmp;

326
      error= 0;
327 328

      val_len= (uint) (val_end - val);
329
      switch (*++ptr) {
330
	/* Year */
331
      case 'Y':
332 333
	tmp= (char*) val + min(4, val_len);
	l_time->year= (int) my_strtoll10(val, &tmp, &error);
334 335
        if ((int) (tmp-val) <= 2)
          l_time->year= year_2000_handling(l_time->year);
336
	val= tmp;
337 338
	break;
      case 'y':
339 340 341
	tmp= (char*) val + min(2, val_len);
	l_time->year= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
342
        l_time->year= year_2000_handling(l_time->year);
343
	break;
344 345

	/* Month */
346
      case 'm':
347 348 349 350 351 352
      case 'c':
	tmp= (char*) val + min(2, val_len);
	l_time->month= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
	break;
      case 'M':
bar@mysql.com's avatar
bar@mysql.com committed
353 354 355 356
	if ((l_time->month= check_word(my_locale_en_US.month_names,
				       val, val_end, &val)) <= 0)
	  goto err;
	break;
357
      case 'b':
bar@mysql.com's avatar
bar@mysql.com committed
358
	if ((l_time->month= check_word(my_locale_en_US.ab_month_names,
359 360
				       val, val_end, &val)) <= 0)
	  goto err;
361
	break;
362
	/* Day */
363
      case 'd':
364 365 366 367
      case 'e':
	tmp= (char*) val + min(2, val_len);
	l_time->day= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
368 369
	break;
      case 'D':
370 371 372
	tmp= (char*) val + min(2, val_len);
	l_time->day= (int) my_strtoll10(val, &tmp, &error);
	/* Skip 'st, 'nd, 'th .. */
373
	val= tmp + min((int) (val_end-tmp), 2);
374 375 376 377 378 379 380 381 382 383 384 385 386
	break;

	/* Hour */
      case 'h':
      case 'I':
      case 'l':
	usa_time= 1;
	/* fall through */
      case 'k':
      case 'H':
	tmp= (char*) val + min(2, val_len);
	l_time->hour= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
387
	break;
388 389

	/* Minute */
390
      case 'i':
391 392 393
	tmp= (char*) val + min(2, val_len);
	l_time->minute= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
394
	break;
395 396

	/* Second */
397 398
      case 's':
      case 'S':
399 400 401
	tmp= (char*) val + min(2, val_len);
	l_time->second= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
402
	break;
403 404 405 406

	/* Second part */
      case 'f':
	tmp= (char*) val_end;
407 408
	if (tmp - val > 6)
	  tmp= (char*) val + 6;
monty@mysql.com's avatar
monty@mysql.com committed
409
	l_time->second_part= (int) my_strtoll10(val, &tmp, &error);
410
	frac_part= 6 - (int) (tmp - val);
411 412
	if (frac_part > 0)
	  l_time->second_part*= (ulong) log_10_int[frac_part];
413
	val= tmp;
414
	break;
415 416 417 418 419 420 421 422 423 424 425 426 427

	/* 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;
428
	val+= 2;
429
	break;
430 431

	/* Exotic things */
432
      case 'W':
bar@mysql.com's avatar
bar@mysql.com committed
433 434 435
	if ((weekday= check_word(my_locale_en_US.day_names, val, val_end, &val)) <= 0)
	  goto err;
	break;
436
      case 'a':
bar@mysql.com's avatar
bar@mysql.com committed
437
	if ((weekday= check_word(my_locale_en_US.ab_day_names, val, val_end, &val)) <= 0)
438
	  goto err;
439 440
	break;
      case 'w':
441
	tmp= (char*) val + 1;
442
	if ((weekday= (int) my_strtoll10(val, &tmp, &error)) < 0 ||
443 444
	    weekday >= 7)
	  goto err;
445 446 447
        /* We should use the same 1 - 7 scale for %w as for %W */
        if (!weekday)
          weekday= 7;
448
	val= tmp;
449 450
	break;
      case 'j':
451 452 453
	tmp= (char*) val + min(val_len, 3);
	yearday= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
454
	break;
455

456 457
        /* Week numbers */
      case 'V':
458
      case 'U':
459
      case 'v':
460
      case 'u':
461 462
        sunday_first_n_first_week_non_iso= (*ptr=='U' || *ptr== 'V');
        strict_week_number= (*ptr=='V' || *ptr=='v');
463
	tmp= (char*) val + min(val_len, 2);
464
	if ((week_number= (int) my_strtoll10(val, &tmp, &error)) < 0 ||
465
            (strict_week_number && !week_number) ||
466 467
            week_number > 53)
          goto err;
468
	val= tmp;
469
	break;
470

471 472 473 474 475 476 477 478 479 480 481
        /* Year used with 'strict' %V and %v week numbers */
      case 'X':
      case 'x':
        strict_week_number_year_type= (*ptr=='X');
        tmp= (char*) val + min(4, val_len);
        strict_week_number_year= (int) my_strtoll10(val, &tmp, &error);
        val= tmp;
        break;

        /* Time in AM/PM notation */
      case 'r':
482 483 484 485 486 487 488 489
        /*
          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,
                              cached_timestamp_type, &val, "time"))
          DBUG_RETURN(1);
490 491 492 493
        break;

        /* Time in 24-hour notation */
      case 'T':
494 495 496 497
        if (extract_date_time(&time_24hrs_format, val,
                              (uint)(val_end - val), l_time,
                              cached_timestamp_type, &val, "time"))
          DBUG_RETURN(1);
498 499 500
        break;

        /* Conversion specifiers that match classes of characters */
501 502 503 504 505 506 507 508 509 510 511 512
      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;
513
      default:
514
	goto err;
515
      }
516 517
      if (error)				// Error from my_strtoll10
	goto err;
518
    }
519
    else if (!my_isspace(cs, *ptr))
520
    {
521 522 523
      if (*val != *ptr)
	goto err;
      val++;
524 525 526 527 528
    }
  }
  if (usa_time)
  {
    if (l_time->hour > 12 || l_time->hour < 1)
529
      goto err;
530 531
    l_time->hour= l_time->hour%12+daypart;
  }
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
532

533 534 535 536 537 538 539 540 541 542
  /*
    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);
  }

543 544
  if (yearday > 0)
  {
545 546
    uint days;
    days= calc_daynr(l_time->year,1,1) +  yearday - 1;
547
    if (days <= 0 || days > MAX_DAY_NUMBER)
548 549
      goto err;
    get_date_from_daynr(days,&l_time->year,&l_time->month,&l_time->day);
550
  }
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
551

552 553
  if (week_number >= 0 && weekday)
  {
554
    int days;
555 556
    uint weekday_b;

557 558 559 560
    /*
      %V,%v require %X,%x resprectively,
      %U,%u should be used with %Y and not %X or %x
    */
561
    if ((strict_week_number &&
562
        (strict_week_number_year < 0 ||
563 564
         strict_week_number_year_type != sunday_first_n_first_week_non_iso)) ||
        (!strict_week_number && strict_week_number_year >= 0))
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
      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)
581
    {
582 583 584
      days+= ((weekday_b == 0) ? 0 : 7) - weekday_b +
             (week_number - 1) * 7 +
             weekday % 7;
585 586 587
    }
    else
    {
588 589 590
      days+= ((weekday_b <= 3) ? 0 : 7) - weekday_b +
             (week_number - 1) * 7 +
             (weekday - 1);
591
    }
592

593
    if (days <= 0 || days > MAX_DAY_NUMBER)
594 595
      goto err;
    get_date_from_daynr(days,&l_time->year,&l_time->month,&l_time->day);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
596 597
  }

598 599
  if (l_time->month > 12 || l_time->day > 31 || l_time->hour > 23 || 
      l_time->minute > 59 || l_time->second > 59)
600
    goto err;
601

602 603 604 605 606 607
  if (val != val_end)
  {
    do
    {
      if (!my_isspace(&my_charset_latin1,*val))
      {
608 609
	make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                                     val_begin, length,
610
				     cached_timestamp_type, NullS);
611 612 613 614
	break;
      }
    } while (++val != val_end);
  }
615 616
  DBUG_RETURN(0);

617
err:
618 619 620
  {
    char buff[128];
    strmake(buff, val_begin, min(length, sizeof(buff)-1));
Marc Alff's avatar
Marc Alff committed
621
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
622
                        ER_WRONG_VALUE_FOR_TYPE, ER(ER_WRONG_VALUE_FOR_TYPE),
623
                        date_time_type, buff, "str_to_date");
624
  }
625 626
  DBUG_RETURN(1);
}
627 628


629 630
/**
  Create a formated date/time value in a string.
631 632
*/

633
bool make_date_time(DATE_TIME_FORMAT *format, MYSQL_TIME *l_time,
634
		    timestamp_type type, String *str)
635 636 637 638 639
{
  char intbuff[15];
  uint hours_i;
  uint weekday;
  ulong length;
640
  const char *ptr, *end;
bar@mysql.com's avatar
bar@mysql.com committed
641
  THD *thd= current_thd;
642
  MY_LOCALE *locale= thd->variables.lc_time_names;
643 644 645

  str->length(0);

646
  if (l_time->neg)
647
    str->append('-');
648 649
  
  end= (ptr= format->format.str) + format->format.length;
650 651 652 653 654 655 656 657
  for (; ptr != end ; ptr++)
  {
    if (*ptr != '%' || ptr+1 == end)
      str->append(*ptr);
    else
    {
      switch (*++ptr) {
      case 'M':
658 659 660
        if (!l_time->month)
          return 1;
        str->append(locale->month_names->type_names[l_time->month-1],
661
                    (uint) strlen(locale->month_names->type_names[l_time->month-1]),
662 663
                    system_charset_info);
        break;
664
      case 'b':
665 666 667
        if (!l_time->month)
          return 1;
        str->append(locale->ab_month_names->type_names[l_time->month-1],
668
                    (uint) strlen(locale->ab_month_names->type_names[l_time->month-1]),
669 670
                    system_charset_info);
        break;
671
      case 'W':
672 673 674 675 676
        if (type == MYSQL_TIMESTAMP_TIME)
          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],
677
                    (uint) strlen(locale->day_names->type_names[weekday]),
678 679
                    system_charset_info);
        break;
680
      case 'a':
681 682 683 684 685
        if (type == MYSQL_TIMESTAMP_TIME)
          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],
686
                    (uint) strlen(locale->ab_day_names->type_names[weekday]),
687 688
                    system_charset_info);
        break;
689
      case 'D':
690
	if (type == MYSQL_TIMESTAMP_TIME)
691
	  return 1;
692
	length= (uint) (int10_to_str(l_time->day, intbuff, 10) - intbuff);
693 694
	str->append_with_prefill(intbuff, length, 1, '0');
	if (l_time->day >= 10 &&  l_time->day <= 19)
695
	  str->append(STRING_WITH_LEN("th"));
696 697 698 699
	else
	{
	  switch (l_time->day %10) {
	  case 1:
700
	    str->append(STRING_WITH_LEN("st"));
701 702
	    break;
	  case 2:
703
	    str->append(STRING_WITH_LEN("nd"));
704 705
	    break;
	  case 3:
706
	    str->append(STRING_WITH_LEN("rd"));
707 708
	    break;
	  default:
709
	    str->append(STRING_WITH_LEN("th"));
710 711 712 713 714
	    break;
	  }
	}
	break;
      case 'Y':
715
	length= (uint) (int10_to_str(l_time->year, intbuff, 10) - intbuff);
716 717 718
	str->append_with_prefill(intbuff, length, 4, '0');
	break;
      case 'y':
719
	length= (uint) (int10_to_str(l_time->year%100, intbuff, 10) - intbuff);
720 721 722
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'm':
723
	length= (uint) (int10_to_str(l_time->month, intbuff, 10) - intbuff);
724 725 726
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'c':
727
	length= (uint) (int10_to_str(l_time->month, intbuff, 10) - intbuff);
728 729 730
	str->append_with_prefill(intbuff, length, 1, '0');
	break;
      case 'd':
731
	length= (uint) (int10_to_str(l_time->day, intbuff, 10) - intbuff);
732 733 734
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'e':
735
	length= (uint) (int10_to_str(l_time->day, intbuff, 10) - intbuff);
736 737 738
	str->append_with_prefill(intbuff, length, 1, '0');
	break;
      case 'f':
739
	length= (uint) (int10_to_str(l_time->second_part, intbuff, 10) - intbuff);
740 741 742
	str->append_with_prefill(intbuff, length, 6, '0');
	break;
      case 'H':
743
	length= (uint) (int10_to_str(l_time->hour, intbuff, 10) - intbuff);
744 745 746 747
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'h':
      case 'I':
748
	hours_i= (l_time->hour%24 + 11)%12+1;
749
	length= (uint) (int10_to_str(hours_i, intbuff, 10) - intbuff);
750 751 752
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'i':					/* minutes */
753
	length= (uint) (int10_to_str(l_time->minute, intbuff, 10) - intbuff);
754 755 756
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'j':
757
	if (type == MYSQL_TIMESTAMP_TIME)
758
	  return 1;
759
	length= (uint) (int10_to_str(calc_daynr(l_time->year,l_time->month,
760
					l_time->day) - 
761
		     calc_daynr(l_time->year,1,1) + 1, intbuff, 10) - intbuff);
762 763 764
	str->append_with_prefill(intbuff, length, 3, '0');
	break;
      case 'k':
765
	length= (uint) (int10_to_str(l_time->hour, intbuff, 10) - intbuff);
766 767 768
	str->append_with_prefill(intbuff, length, 1, '0');
	break;
      case 'l':
769
	hours_i= (l_time->hour%24 + 11)%12+1;
770
	length= (uint) (int10_to_str(hours_i, intbuff, 10) - intbuff);
771 772 773 774 775 776 777
	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':
778 779 780 781 782
	length= sprintf(intbuff, ((l_time->hour % 24) < 12) ?
                        "%02d:%02d:%02d AM" : "%02d:%02d:%02d PM",
		        (l_time->hour+11)%12+1,
		        l_time->minute,
		        l_time->second);
783 784 785 786
	str->append(intbuff, length);
	break;
      case 'S':
      case 's':
787
	length= (uint) (int10_to_str(l_time->second, intbuff, 10) - intbuff);
788 789 790
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'T':
791 792
	length= sprintf(intbuff,  "%02d:%02d:%02d",
                        l_time->hour, l_time->minute, l_time->second);
793 794 795 796 797 798
	str->append(intbuff, length);
	break;
      case 'U':
      case 'u':
      {
	uint year;
799
	if (type == MYSQL_TIMESTAMP_TIME)
800
	  return 1;
801
	length= (uint) (int10_to_str(calc_week(l_time,
monty@mysql.com's avatar
monty@mysql.com committed
802 803 804
				       (*ptr) == 'U' ?
				       WEEK_FIRST_WEEKDAY : WEEK_MONDAY_FIRST,
				       &year),
805
			     intbuff, 10) - intbuff);
806 807 808 809 810 811 812
	str->append_with_prefill(intbuff, length, 2, '0');
      }
      break;
      case 'v':
      case 'V':
      {
	uint year;
813
	if (type == MYSQL_TIMESTAMP_TIME)
814
	  return 1;
815
	length= (uint) (int10_to_str(calc_week(l_time,
monty@mysql.com's avatar
monty@mysql.com committed
816 817 818 819
				       ((*ptr) == 'V' ?
					(WEEK_YEAR | WEEK_FIRST_WEEKDAY) :
					(WEEK_YEAR | WEEK_MONDAY_FIRST)),
				       &year),
820
			     intbuff, 10) - intbuff);
821 822 823 824 825 826 827
	str->append_with_prefill(intbuff, length, 2, '0');
      }
      break;
      case 'x':
      case 'X':
      {
	uint year;
828
	if (type == MYSQL_TIMESTAMP_TIME)
829
	  return 1;
monty@mysql.com's avatar
monty@mysql.com committed
830 831 832 833 834
	(void) calc_week(l_time,
			 ((*ptr) == 'X' ?
			  WEEK_YEAR | WEEK_FIRST_WEEKDAY :
			  WEEK_YEAR | WEEK_MONDAY_FIRST),
			 &year);
835
	length= (uint) (int10_to_str(year, intbuff, 10) - intbuff);
836 837 838 839
	str->append_with_prefill(intbuff, length, 4, '0');
      }
      break;
      case 'w':
840
	if (type == MYSQL_TIMESTAMP_TIME)
841 842 843
	  return 1;
	weekday=calc_weekday(calc_daynr(l_time->year,l_time->month,
					l_time->day),1);
844
	length= (uint) (int10_to_str(weekday, intbuff, 10) - intbuff);
845 846
	str->append_with_prefill(intbuff, length, 1, '0');
	break;
847

848 849 850 851 852 853
      default:
	str->append(*ptr);
	break;
      }
    }
  }
854
  return 0;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
855 856
}

857

858 859
/**
  @details
860 861 862 863 864 865 866
  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.

867 868 869 870 871 872 873 874
  @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'
bk@work.mysql.com's avatar
bk@work.mysql.com committed
875 876
*/

monty@mysql.com's avatar
monty@mysql.com committed
877
static bool get_interval_info(const char *str,uint length,CHARSET_INFO *cs,
monty@mysql.com's avatar
monty@mysql.com committed
878 879
                              uint count, ulonglong *values,
                              bool transform_msec)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
880 881 882
{
  const char *end=str+length;
  uint i;
883 884
  long msec_length= 0;

885
  while (str != end && !my_isdigit(cs,*str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
886 887 888 889
    str++;

  for (i=0 ; i < count ; i++)
  {
890
    longlong value;
891
    const char *start= str;
892
    for (value=0; str != end && my_isdigit(cs,*str) ; str++)
monty@mysql.com's avatar
monty@mysql.com committed
893
      value= value*LL(10) + (longlong) (*str - '0');
Evgeny Potemkin's avatar
Evgeny Potemkin committed
894
    msec_length= 6 - (str - start);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
895
    values[i]= value;
896
    while (str != end && !my_isdigit(cs,*str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
897 898 899 900 901
      str++;
    if (str == end && i != count-1)
    {
      i++;
      /* Change values[0...i-1] -> values[0...count-1] */
902
      bmove_upp((uchar*) (values+count), (uchar*) (values+i),
903
		sizeof(*values)*i);
904
      bzero((uchar*) values, sizeof(*values)*(count-i));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
905 906 907
      break;
    }
  }
908 909 910 911

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
912 913 914
  return (str != end);
}

monty@mysql.com's avatar
monty@mysql.com committed
915

bk@work.mysql.com's avatar
bk@work.mysql.com committed
916 917
longlong Item_func_period_add::val_int()
{
918
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
919 920 921 922 923 924 925 926 927 928 929 930 931 932
  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()
{
933
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
934 935 936 937 938 939 940 941 942 943 944 945 946
  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()
{
947
  DBUG_ASSERT(fixed == 1);
948
  MYSQL_TIME ltime;
949
  if (get_arg0_date(&ltime, TIME_NO_ZERO_DATE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
950 951 952 953
    return 0;
  return (longlong) calc_daynr(ltime.year,ltime.month,ltime.day);
}

954

955 956 957
longlong Item_func_to_seconds::val_int_endpoint(bool left_endp,
                                                bool *incl_endp)
{
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
  DBUG_ASSERT(fixed == 1);
  MYSQL_TIME ltime;
  longlong seconds;
  longlong days;
  int dummy;                                /* unused */
  if (get_arg0_date(&ltime, TIME_FUZZY_DATE))
  {
    /* 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;
981 982 983 984 985 986 987 988 989 990
}

longlong Item_func_to_seconds::val_int()
{
  DBUG_ASSERT(fixed == 1);
  MYSQL_TIME ltime;
  longlong seconds;
  longlong days;
  if (get_arg0_date(&ltime, TIME_NO_ZERO_DATE))
    return 0;
991
  seconds= ltime.hour * 3600L + ltime.minute * 60 + ltime.second;
992
  seconds=ltime.neg ? -seconds : seconds;
993 994
  days= (longlong) calc_daynr(ltime.year, ltime.month, ltime.day);
  return seconds + days * 24L * 3600L;
995 996
}

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
/*
  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.
*/

1011 1012 1013 1014 1015
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)
1016
      return MONOTONIC_STRICT_INCREASING_NOT_NULL;
1017
    if (args[0]->field_type() == MYSQL_TYPE_DATETIME)
1018
      return MONOTONIC_INCREASING_NOT_NULL;
1019 1020 1021 1022
  }
  return NON_MONOTONIC;
}

1023 1024 1025 1026
enum_monotonicity_info Item_func_to_seconds::get_monotonicity_info() const
{
  if (args[0]->type() == Item::FIELD_ITEM)
  {
1027 1028 1029
    if (args[0]->field_type() == MYSQL_TYPE_DATE ||
        args[0]->field_type() == MYSQL_TYPE_DATETIME)
      return MONOTONIC_STRICT_INCREASING_NOT_NULL;
1030 1031 1032 1033
  }
  return NON_MONOTONIC;
}

1034

1035 1036 1037 1038 1039
longlong Item_func_to_days::val_int_endpoint(bool left_endp, bool *incl_endp)
{
  DBUG_ASSERT(fixed == 1);
  MYSQL_TIME ltime;
  longlong res;
1040 1041
  int dummy;                                /* unused */
  if (get_arg0_date(&ltime, TIME_FUZZY_DATE))
1042 1043 1044 1045 1046
  {
    /* got NULL, leave the incl_endp intact */
    return LONGLONG_MIN;
  }
  res=(longlong) calc_daynr(ltime.year,ltime.month,ltime.day);
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
  /* 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);
  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;
  }
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
  
  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')
1073
      col > '2007-09-15 23:59:59'  -> TO_DAYS(col) >  TO_DAYS('2007-09-15')
1074 1075 1076 1077 1078 1079

    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')
  */
1080 1081 1082 1083 1084 1085
  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 */
    ;
1086 1087 1088 1089 1090 1091
  else
    *incl_endp= TRUE;
  return res;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1092 1093
longlong Item_func_dayofyear::val_int()
{
1094
  DBUG_ASSERT(fixed == 1);
1095
  MYSQL_TIME ltime;
1096
  if (get_arg0_date(&ltime,TIME_NO_ZERO_DATE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1097 1098 1099 1100 1101 1102 1103
    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()
{
1104
  DBUG_ASSERT(fixed == 1);
1105
  MYSQL_TIME ltime;
1106
  (void) get_arg0_date(&ltime, TIME_FUZZY_DATE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1107 1108 1109 1110 1111
  return (longlong) ltime.day;
}

longlong Item_func_month::val_int()
{
1112
  DBUG_ASSERT(fixed == 1);
1113
  MYSQL_TIME ltime;
1114
  (void) get_arg0_date(&ltime, TIME_FUZZY_DATE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1115 1116 1117
  return (longlong) ltime.month;
}

1118

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
void Item_func_monthname::fix_length_and_dec()
{
  THD* thd= current_thd;
  CHARSET_INFO *cs= thd->variables.collation_connection;
  uint32 repertoire= my_charset_repertoire(cs);
  locale= thd->variables.lc_time_names;  
  collation.set(cs, DERIVATION_COERCIBLE, repertoire);
  decimals=0;
  max_length= locale->max_month_name_length * collation.collation->mbmaxlen;
  maybe_null=1; 
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1132 1133
String* Item_func_monthname::val_str(String* str)
{
1134
  DBUG_ASSERT(fixed == 1);
1135
  const char *month_name;
1136 1137
  uint month= (uint) val_int();
  uint err;
1138

1139
  if (null_value || !month)
1140 1141
  {
    null_value=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1142
    return (String*) 0;
1143 1144
  }
  null_value=0;
1145
  month_name= locale->month_names->type_names[month-1];
1146
  str->copy(month_name, (uint) strlen(month_name), &my_charset_utf8_bin,
1147
	    collation.collation, &err);
1148
  return str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1149 1150
}

1151

1152 1153 1154
/**
  Returns the quarter of the year.
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1155 1156 1157

longlong Item_func_quarter::val_int()
{
1158
  DBUG_ASSERT(fixed == 1);
1159
  MYSQL_TIME ltime;
1160 1161
  if (get_arg0_date(&ltime, TIME_FUZZY_DATE))
    return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1162 1163 1164 1165 1166
  return (longlong) ((ltime.month+2)/3);
}

longlong Item_func_hour::val_int()
{
1167
  DBUG_ASSERT(fixed == 1);
1168
  MYSQL_TIME ltime;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1169 1170 1171 1172 1173 1174
  (void) get_arg0_time(&ltime);
  return ltime.hour;
}

longlong Item_func_minute::val_int()
{
1175
  DBUG_ASSERT(fixed == 1);
1176
  MYSQL_TIME ltime;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1177 1178 1179 1180
  (void) get_arg0_time(&ltime);
  return ltime.minute;
}

1181 1182 1183
/**
  Returns the second in time_exp in the range of 0 - 59.
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1184 1185
longlong Item_func_second::val_int()
{
1186
  DBUG_ASSERT(fixed == 1);
1187
  MYSQL_TIME ltime;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1188 1189 1190 1191 1192
  (void) get_arg0_time(&ltime);
  return ltime.second;
}


1193 1194 1195 1196 1197 1198 1199
uint week_mode(uint mode)
{
  uint week_format= (mode & 7);
  if (!(week_format & WEEK_MONDAY_FIRST))
    week_format^= WEEK_FIRST_WEEKDAY;
  return week_format;
}
1200

1201 1202
/**
 @verbatim
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
  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.
1229
 @endverbatim
1230
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1231 1232 1233

longlong Item_func_week::val_int()
{
1234
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1235
  uint year;
1236
  MYSQL_TIME ltime;
1237
  if (get_arg0_date(&ltime, TIME_NO_ZERO_DATE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1238
    return 0;
1239 1240
  return (longlong) calc_week(&ltime,
			      week_mode((uint) args[1]->val_int()),
1241
			      &year);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1242 1243 1244 1245 1246
}


longlong Item_func_yearweek::val_int()
{
1247
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1248
  uint year,week;
1249
  MYSQL_TIME ltime;
1250
  if (get_arg0_date(&ltime, TIME_NO_ZERO_DATE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1251
    return 0;
1252 1253 1254
  week= calc_week(&ltime, 
		  (week_mode((uint) args[1]->val_int()) | WEEK_YEAR),
		  &year);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1255 1256 1257 1258 1259 1260
  return week+year*100;
}


longlong Item_func_weekday::val_int()
{
1261
  DBUG_ASSERT(fixed == 1);
1262
  MYSQL_TIME ltime;
1263 1264 1265
  
  if (get_arg0_date(&ltime, TIME_NO_ZERO_DATE))
    return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1266

1267 1268 1269
  return (longlong) calc_weekday(calc_daynr(ltime.year, ltime.month,
                                            ltime.day),
                                 odbc_type) + test(odbc_type);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1270 1271
}

1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
void Item_func_dayname::fix_length_and_dec()
{
  THD* thd= current_thd;
  CHARSET_INFO *cs= thd->variables.collation_connection;
  uint32 repertoire= my_charset_repertoire(cs);
  locale= thd->variables.lc_time_names;  
  collation.set(cs, DERIVATION_COERCIBLE, repertoire);
  decimals=0;
  max_length= locale->max_day_name_length * collation.collation->mbmaxlen;
  maybe_null=1; 
}

1284

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1285 1286
String* Item_func_dayname::val_str(String* str)
{
1287
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1288
  uint weekday=(uint) val_int();		// Always Item_func_daynr()
1289
  const char *day_name;
1290
  uint err;
1291

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1292 1293
  if (null_value)
    return (String*) 0;
1294
  
1295
  day_name= locale->day_names->type_names[weekday];
1296
  str->copy(day_name, (uint) strlen(day_name), &my_charset_utf8_bin,
1297
	    collation.collation, &err);
1298
  return str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1299 1300 1301 1302 1303
}


longlong Item_func_year::val_int()
{
1304
  DBUG_ASSERT(fixed == 1);
1305
  MYSQL_TIME ltime;
1306
  (void) get_arg0_date(&ltime, TIME_FUZZY_DATE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1307 1308 1309
  return (longlong) ltime.year;
}

1310 1311 1312 1313 1314

/*
  Get information about this Item tree monotonicity

  SYNOPSIS
1315
    Item_func_year::get_monotonicity_info()
1316 1317 1318 1319 1320 1321 1322 1323 1324

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

  RETURN
    See enum_monotonicity_info.
*/

1325 1326 1327 1328 1329 1330 1331 1332
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;
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1333

1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364

longlong Item_func_year::val_int_endpoint(bool left_endp, bool *incl_endp)
{
  DBUG_ASSERT(fixed == 1);
  MYSQL_TIME ltime;
  if (get_arg0_date(&ltime, TIME_FUZZY_DATE))
  {
    /* 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;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1365 1366
longlong Item_func_unix_timestamp::val_int()
{
1367
  MYSQL_TIME ltime;
1368
  my_bool not_used;
1369
  
1370
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1371
  if (arg_count == 0)
1372
    return (longlong) current_thd->query_start();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1373 1374 1375
  if (args[0]->type() == FIELD_ITEM)
  {						// Optimize timestamp field
    Field *field=((Item_field*) args[0])->field;
1376
    if (field->type() == MYSQL_TYPE_TIMESTAMP)
1377
      return ((Field_timestamp*) field)->get_timestamp(&null_value);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1378
  }
1379 1380
  
  if (get_arg0_date(&ltime, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1381
  {
1382 1383 1384 1385 1386 1387 1388
    /*
      We have to set null_value again because get_arg0_date will also set it
      to true if we have wrong datetime parameter (and we should return 0 in 
      this case).
    */
    null_value= args[0]->null_value;
    return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1389
  }
1390 1391
  
  return (longlong) TIME_to_timestamp(current_thd, &ltime, &not_used);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1392 1393 1394 1395 1396
}


longlong Item_func_time_to_sec::val_int()
{
1397
  DBUG_ASSERT(fixed == 1);
1398
  MYSQL_TIME ltime;
1399
  longlong seconds;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1400
  (void) get_arg0_time(&ltime);
1401 1402
  seconds=ltime.hour*3600L+ltime.minute*60+ltime.second;
  return ltime.neg ? -seconds : seconds;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1403 1404 1405
}


1406 1407 1408
/**
  Convert a string to a interval value.

1409
  To make code easy, allow interval objects without separators.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1410 1411
*/

1412
bool get_interval_value(Item *args,interval_type int_type,
1413
			       String *str_value, INTERVAL *interval)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1414
{
monty@mysql.com's avatar
monty@mysql.com committed
1415
  ulonglong array[5];
1416 1417 1418
  longlong UNINIT_VAR(value);
  const char *UNINIT_VAR(str);
  size_t UNINIT_VAR(length);
1419
  CHARSET_INFO *cs=str_value->charset();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1420

1421
  bzero((char*) interval,sizeof(*interval));
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1422
  if ((int) int_type <= INTERVAL_MICROSECOND)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1423
  {
1424
    value= args->val_int();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1425 1426 1427 1428
    if (args->null_value)
      return 1;
    if (value < 0)
    {
1429
      interval->neg=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1430 1431 1432 1433 1434 1435 1436 1437 1438
      value= -value;
    }
  }
  else
  {
    String *res;
    if (!(res=args->val_str(str_value)))
      return (1);

1439
    /* record negative intervalls in interval->neg */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1440 1441
    str=res->ptr();
    const char *end=str+res->length();
1442
    while (str != end && my_isspace(cs,*str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1443 1444 1445
      str++;
    if (str != end && *str == '-')
    {
1446
      interval->neg=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1447 1448
      str++;
    }
1449
    length= (size_t) (end-str);		// Set up pointers to new str
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1450 1451 1452 1453
  }

  switch (int_type) {
  case INTERVAL_YEAR:
monty@mysql.com's avatar
monty@mysql.com committed
1454
    interval->year= (ulong) value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1455
    break;
1456
  case INTERVAL_QUARTER:
1457
    interval->month= (ulong)(value*3);
1458
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1459
  case INTERVAL_MONTH:
monty@mysql.com's avatar
monty@mysql.com committed
1460
    interval->month= (ulong) value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1461
    break;
1462
  case INTERVAL_WEEK:
1463
    interval->day= (ulong)(value*7);
1464
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1465
  case INTERVAL_DAY:
monty@mysql.com's avatar
monty@mysql.com committed
1466
    interval->day= (ulong) value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1467 1468
    break;
  case INTERVAL_HOUR:
monty@mysql.com's avatar
monty@mysql.com committed
1469
    interval->hour= (ulong) value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1470
    break;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1471
  case INTERVAL_MICROSECOND:
1472
    interval->second_part=value;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1473
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1474
  case INTERVAL_MINUTE:
1475
    interval->minute=value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1476 1477
    break;
  case INTERVAL_SECOND:
1478
    interval->second=value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1479 1480
    break;
  case INTERVAL_YEAR_MONTH:			// Allow YEAR-MONTH YYYYYMM
1481
    if (get_interval_info(str,length,cs,2,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1482
      return (1);
monty@mysql.com's avatar
monty@mysql.com committed
1483 1484
    interval->year=  (ulong) array[0];
    interval->month= (ulong) array[1];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1485 1486
    break;
  case INTERVAL_DAY_HOUR:
1487
    if (get_interval_info(str,length,cs,2,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1488
      return (1);
monty@mysql.com's avatar
monty@mysql.com committed
1489 1490
    interval->day=  (ulong) array[0];
    interval->hour= (ulong) array[1];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1491
    break;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1492
  case INTERVAL_DAY_MICROSECOND:
1493
    if (get_interval_info(str,length,cs,5,array,1))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1494
      return (1);
monty@mysql.com's avatar
monty@mysql.com committed
1495 1496 1497 1498 1499
    interval->day=    (ulong) array[0];
    interval->hour=   (ulong) array[1];
    interval->minute= array[2];
    interval->second= array[3];
    interval->second_part= array[4];
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1500
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1501
  case INTERVAL_DAY_MINUTE:
1502
    if (get_interval_info(str,length,cs,3,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1503
      return (1);
monty@mysql.com's avatar
monty@mysql.com committed
1504 1505 1506
    interval->day=    (ulong) array[0];
    interval->hour=   (ulong) array[1];
    interval->minute= array[2];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1507 1508
    break;
  case INTERVAL_DAY_SECOND:
1509
    if (get_interval_info(str,length,cs,4,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1510
      return (1);
monty@mysql.com's avatar
monty@mysql.com committed
1511 1512 1513 1514
    interval->day=    (ulong) array[0];
    interval->hour=   (ulong) array[1];
    interval->minute= array[2];
    interval->second= array[3];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1515
    break;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1516
  case INTERVAL_HOUR_MICROSECOND:
1517
    if (get_interval_info(str,length,cs,4,array,1))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1518
      return (1);
monty@mysql.com's avatar
monty@mysql.com committed
1519 1520 1521 1522
    interval->hour=   (ulong) array[0];
    interval->minute= array[1];
    interval->second= array[2];
    interval->second_part= array[3];
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1523
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1524
  case INTERVAL_HOUR_MINUTE:
1525
    if (get_interval_info(str,length,cs,2,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1526
      return (1);
monty@mysql.com's avatar
monty@mysql.com committed
1527 1528
    interval->hour=   (ulong) array[0];
    interval->minute= array[1];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1529 1530
    break;
  case INTERVAL_HOUR_SECOND:
1531
    if (get_interval_info(str,length,cs,3,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1532
      return (1);
monty@mysql.com's avatar
monty@mysql.com committed
1533 1534 1535
    interval->hour=   (ulong) array[0];
    interval->minute= array[1];
    interval->second= array[2];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1536
    break;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1537
  case INTERVAL_MINUTE_MICROSECOND:
1538
    if (get_interval_info(str,length,cs,3,array,1))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1539
      return (1);
monty@mysql.com's avatar
monty@mysql.com committed
1540 1541 1542
    interval->minute= array[0];
    interval->second= array[1];
    interval->second_part= array[2];
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1543
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1544
  case INTERVAL_MINUTE_SECOND:
1545
    if (get_interval_info(str,length,cs,2,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1546
      return (1);
monty@mysql.com's avatar
monty@mysql.com committed
1547 1548
    interval->minute= array[0];
    interval->second= array[1];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1549
    break;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1550
  case INTERVAL_SECOND_MICROSECOND:
1551
    if (get_interval_info(str,length,cs,2,array,1))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1552
      return (1);
monty@mysql.com's avatar
monty@mysql.com committed
1553 1554
    interval->second= array[0];
    interval->second_part= array[1];
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1555
    break;
1556 1557 1558
  case INTERVAL_LAST: /* purecov: begin deadcode */
    DBUG_ASSERT(0); 
    break;            /* purecov: end */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1559 1560 1561 1562 1563 1564 1565
  }
  return 0;
}


String *Item_date::val_str(String *str)
{
1566
  DBUG_ASSERT(fixed == 1);
1567
  MYSQL_TIME ltime;
1568 1569
  if (get_date(&ltime, TIME_FUZZY_DATE))
    return (String *) 0;
1570
  if (str->alloc(MAX_DATE_STRING_REP_LENGTH))
1571 1572 1573 1574 1575 1576
  {
    null_value= 1;
    return (String *) 0;
  }
  make_date((DATE_TIME_FORMAT *) 0, &ltime, str);
  return str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1577 1578 1579
}


1580 1581
longlong Item_date::val_int()
{
1582
  DBUG_ASSERT(fixed == 1);
1583
  MYSQL_TIME ltime;
1584 1585 1586 1587 1588 1589
  if (get_date(&ltime, TIME_FUZZY_DATE))
    return 0;
  return (longlong) (ltime.year*10000L+ltime.month*100+ltime.day);
}


1590
bool Item_func_from_days::get_date(MYSQL_TIME *ltime, uint fuzzy_date)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1591 1592 1593
{
  longlong value=args[0]->val_int();
  if ((null_value=args[0]->null_value))
1594
    return 1;
1595
  bzero(ltime, sizeof(MYSQL_TIME));
1596
  get_date_from_daynr((long) value, &ltime->year, &ltime->month, &ltime->day);
1597
  ltime->time_type= MYSQL_TIMESTAMP_DATE;
1598
  return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1599 1600 1601 1602 1603
}


void Item_func_curdate::fix_length_and_dec()
{
1604
  Item_date::fix_length_and_dec();
1605

1606
  store_now_in_TIME(&ltime);
1607
  
1608 1609
  /* We don't need to set second_part and neg because they already 0 */
  ltime.hour= ltime.minute= ltime.second= 0;
1610
  ltime.time_type= MYSQL_TIMESTAMP_DATE;
1611
  value= (longlong) TIME_to_ulonglong_date(&ltime);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1612 1613
}

1614 1615
String *Item_func_curdate::val_str(String *str)
{
1616
  DBUG_ASSERT(fixed == 1);
1617
  if (str->alloc(MAX_DATE_STRING_REP_LENGTH))
1618 1619 1620 1621 1622 1623 1624
  {
    null_value= 1;
    return (String *) 0;
  }
  make_date((DATE_TIME_FORMAT *) 0, &ltime, str);
  return str;
}
1625

1626
/**
1627
    Converts current time in my_time_t to MYSQL_TIME represenatation for local
1628 1629
    time zone. Defines time zone (local) used for whole CURDATE function.
*/
1630
void Item_func_curdate_local::store_now_in_TIME(MYSQL_TIME *now_time)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1631
{
1632 1633 1634 1635
  THD *thd= current_thd;
  thd->variables.time_zone->gmt_sec_to_TIME(now_time, 
                                             (my_time_t)thd->query_start());
  thd->time_zone_used= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1636 1637
}

1638

1639
/**
1640
    Converts current time in my_time_t to MYSQL_TIME represenatation for UTC
1641
    time zone. Defines time zone (UTC) used for whole UTC_DATE function.
1642
*/
1643
void Item_func_curdate_utc::store_now_in_TIME(MYSQL_TIME *now_time)
1644
{
1645 1646 1647 1648 1649 1650
  my_tz_UTC->gmt_sec_to_TIME(now_time, 
                             (my_time_t)(current_thd->query_start()));
  /* 
    We are not flagging this query as using time zone, since it uses fixed
    UTC-SYSTEM time-zone.
  */
1651 1652 1653
}


1654
bool Item_func_curdate::get_date(MYSQL_TIME *res,
1655
				 uint fuzzy_date __attribute__((unused)))
1656
{
1657 1658
  *res=ltime;
  return 0;
1659 1660 1661
}


1662
String *Item_func_curtime::val_str(String *str)
1663 1664
{
  DBUG_ASSERT(fixed == 1);
1665
  str_value.set(buff, buff_length, &my_charset_latin1);
1666 1667 1668
  return &str_value;
}

1669

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1670 1671
void Item_func_curtime::fix_length_and_dec()
{
1672
  MYSQL_TIME ltime;
1673

1674
  decimals= DATETIME_DEC;
1675
  store_now_in_TIME(&ltime);
1676
  value= TIME_to_ulonglong_time(&ltime);
1677
  buff_length= (uint) my_time_to_str(&ltime, buff);
1678
  fix_length_and_charset_datetime(buff_length);
1679 1680 1681
}


1682
/**
1683
    Converts current time in my_time_t to MYSQL_TIME represenatation for local
1684
    time zone. Defines time zone (local) used for whole CURTIME function.
1685
*/
1686
void Item_func_curtime_local::store_now_in_TIME(MYSQL_TIME *now_time)
1687
{
1688 1689 1690 1691
  THD *thd= current_thd;
  thd->variables.time_zone->gmt_sec_to_TIME(now_time, 
                                             (my_time_t)thd->query_start());
  thd->time_zone_used= 1;
1692 1693 1694
}


1695
/**
1696
    Converts current time in my_time_t to MYSQL_TIME represenatation for UTC
1697
    time zone. Defines time zone (UTC) used for whole UTC_TIME function.
1698
*/
1699
void Item_func_curtime_utc::store_now_in_TIME(MYSQL_TIME *now_time)
1700
{
1701 1702 1703 1704 1705 1706
  my_tz_UTC->gmt_sec_to_TIME(now_time, 
                             (my_time_t)(current_thd->query_start()));
  /* 
    We are not flagging this query as using time zone, since it uses fixed
    UTC-SYSTEM time-zone.
  */
1707 1708
}

1709

1710 1711
String *Item_func_now::val_str(String *str)
{
1712
  DBUG_ASSERT(fixed == 1);
1713
  str_value.set(buff, buff_length, &my_charset_numeric);
1714
  return &str_value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1715 1716
}

1717

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1718 1719
void Item_func_now::fix_length_and_dec()
{
1720
  decimals= DATETIME_DEC;
1721

1722
  store_now_in_TIME(&ltime);
1723
  value= (longlong) TIME_to_ulonglong_datetime(&ltime);
1724

1725
  buff_length= (uint) my_datetime_to_str(&ltime, buff);
1726
  fix_length_and_charset_datetime(buff_length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1727 1728
}

1729

1730
/**
1731
    Converts current time in my_time_t to MYSQL_TIME represenatation for local
1732 1733
    time zone. Defines time zone (local) used for whole NOW function.
*/
1734
void Item_func_now_local::store_now_in_TIME(MYSQL_TIME *now_time)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1735
{
1736 1737 1738 1739
  THD *thd= current_thd;
  thd->variables.time_zone->gmt_sec_to_TIME(now_time, 
                                             (my_time_t)thd->query_start());
  thd->time_zone_used= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1740 1741 1742
}


1743
/**
1744
    Converts current time in my_time_t to MYSQL_TIME represenatation for UTC
1745 1746
    time zone. Defines time zone (UTC) used for whole UTC_TIMESTAMP function.
*/
1747
void Item_func_now_utc::store_now_in_TIME(MYSQL_TIME *now_time)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1748
{
1749 1750 1751 1752 1753 1754
  my_tz_UTC->gmt_sec_to_TIME(now_time, 
                             (my_time_t)(current_thd->query_start()));
  /* 
    We are not flagging this query as using time zone, since it uses fixed
    UTC-SYSTEM time-zone.
  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1755 1756 1757
}


1758
bool Item_func_now::get_date(MYSQL_TIME *res,
1759
                             uint fuzzy_date __attribute__((unused)))
1760
{
1761
  *res= ltime;
1762
  return 0;
1763 1764 1765
}


1766
int Item_func_now::save_in_field(Field *to, bool no_conversions)
1767
{
1768
  to->set_notnull();
1769
  return to->store_time(&ltime, MYSQL_TIMESTAMP_DATETIME);
1770 1771 1772
}


1773
/**
1774
    Converts current time in my_time_t to MYSQL_TIME represenatation for local
1775 1776
    time zone. Defines time zone (local) used for whole SYSDATE function.
*/
1777
void Item_func_sysdate_local::store_now_in_TIME(MYSQL_TIME *now_time)
1778 1779
{
  THD *thd= current_thd;
1780
  thd->variables.time_zone->gmt_sec_to_TIME(now_time, (my_time_t) my_time(0));
1781 1782 1783 1784 1785 1786 1787 1788 1789
  thd->time_zone_used= 1;
}


String *Item_func_sysdate_local::val_str(String *str)
{
  DBUG_ASSERT(fixed == 1);
  store_now_in_TIME(&ltime);
  buff_length= (uint) my_datetime_to_str(&ltime, buff);
1790
  str_value.set(buff, buff_length, &my_charset_numeric);
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
  return &str_value;
}


longlong Item_func_sysdate_local::val_int()
{
  DBUG_ASSERT(fixed == 1);
  store_now_in_TIME(&ltime);
  return (longlong) TIME_to_ulonglong_datetime(&ltime);
}


double Item_func_sysdate_local::val_real()
{
  DBUG_ASSERT(fixed == 1);
  store_now_in_TIME(&ltime);
1807
  return ulonglong2double(TIME_to_ulonglong_datetime(&ltime));
1808 1809 1810 1811 1812 1813
}


void Item_func_sysdate_local::fix_length_and_dec()
{
  decimals= 0;
1814
  fix_length_and_charset_datetime(MAX_DATETIME_WIDTH);
1815 1816 1817
}


1818
bool Item_func_sysdate_local::get_date(MYSQL_TIME *res,
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
                                       uint fuzzy_date __attribute__((unused)))
{
  store_now_in_TIME(&ltime);
  *res= ltime;
  return 0;
}


int Item_func_sysdate_local::save_in_field(Field *to, bool no_conversions)
{
  store_now_in_TIME(&ltime);
  to->set_notnull();
  to->store_time(&ltime, MYSQL_TIMESTAMP_DATETIME);
  return 0;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1836 1837
String *Item_func_sec_to_time::val_str(String *str)
{
1838
  DBUG_ASSERT(fixed == 1);
1839
  MYSQL_TIME ltime;
1840
  longlong arg_val= args[0]->val_int(); 
1841

1842 1843
  if ((null_value=args[0]->null_value) ||
      str->alloc(MAX_DATE_STRING_REP_LENGTH))
1844 1845 1846 1847
  {
    null_value= 1;
    return (String*) 0;
  }
1848

1849
  sec_to_time(arg_val, args[0]->unsigned_flag, &ltime);
1850
  
1851 1852
  make_time((DATE_TIME_FORMAT *) 0, &ltime, str);
  return str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1853 1854 1855 1856 1857
}


longlong Item_func_sec_to_time::val_int()
{
1858
  DBUG_ASSERT(fixed == 1);
1859
  MYSQL_TIME ltime;
1860
  longlong arg_val= args[0]->val_int(); 
1861
  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1862 1863
  if ((null_value=args[0]->null_value))
    return 0;
1864

1865
  sec_to_time(arg_val, args[0]->unsigned_flag, &ltime);
1866 1867

  return (ltime.neg ? -1 : 1) *
1868
    (longlong) ((ltime.hour)*10000 + ltime.minute*100 + ltime.second);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1869 1870 1871 1872 1873
}


void Item_func_date_format::fix_length_and_dec()
{
1874
  THD* thd= current_thd;
1875 1876 1877 1878 1879 1880
  /*
    Must use this_item() in case it's a local SP variable
    (for ->max_length and ->str_value)
  */
  Item *arg1= args[1]->this_item();

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1881
  decimals=0;
1882 1883 1884 1885 1886
  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);
1887
  if (arg1->type() == STRING_ITEM)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1888 1889
  {						// Optimize the normal case
    fixed_length=1;
1890
    max_length= format_length(&arg1->str_value) *
1891
                collation.collation->mbmaxlen;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1892 1893 1894 1895
  }
  else
  {
    fixed_length=0;
1896 1897
    max_length=min(arg1->max_length, MAX_BLOB_WIDTH) * 10 *
                   collation.collation->mbmaxlen;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1898 1899 1900 1901 1902 1903
    set_if_smaller(max_length,MAX_BLOB_WIDTH);
  }
  maybe_null=1;					// If wrong date
}


1904 1905 1906
bool Item_func_date_format::eq(const Item *item, bool binary_cmp) const
{
  Item_func_date_format *item_func;
1907

1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
  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;
}



bk@work.mysql.com's avatar
bk@work.mysql.com committed
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
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 */
bar@mysql.com's avatar
bar@mysql.com committed
1944
	size += 64; /* large for UTF8 locale data */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1945 1946 1947 1948 1949 1950 1951 1952 1953
	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) */
bar@mysql.com's avatar
bar@mysql.com committed
1954 1955
	size += 32; /* large for UTF8 locale data */
	break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
      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;
1977 1978 1979 1980
      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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1981 1982 1983 1984 1985 1986
      case 'r': /* time, 12-hour (hh:mm:ss [AP]M) */
	size += 11;
	break;
      case 'T': /* time, 24-hour (hh:mm:ss) */
	size += 8;
	break;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1987 1988 1989
      case 'f': /* microseconds */
	size += 6;
	break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
      case 'w': /* day (of the week), numeric */
      case '%':
      default:
	size++;
	break;
      }
    }
  }
  return size;
}


String *Item_func_date_format::val_str(String *str)
{
  String *format;
2005
  MYSQL_TIME l_time;
2006
  uint size;
2007
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2008

2009
  if (!is_time_format)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2010
  {
2011
    if (get_arg0_date(&l_time, TIME_FUZZY_DATE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2012 2013 2014 2015 2016
      return 0;
  }
  else
  {
    String *res;
2017
    if (!(res=args[0]->val_str(str)) ||
2018 2019
	(str_to_time_with_warn(res->charset(), res->ptr(), res->length(),
	                       &l_time)))
2020 2021
      goto null_date;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2022 2023 2024 2025 2026
    l_time.year=l_time.month=l_time.day=0;
    null_value=0;
  }

  if (!(format = args[1]->val_str(str)) || !format->length())
2027
    goto null_date;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2028 2029 2030 2031 2032

  if (fixed_length)
    size=max_length;
  else
    size=format_length(format);
2033 2034 2035 2036

  if (size < MAX_DATE_STRING_REP_LENGTH)
    size= MAX_DATE_STRING_REP_LENGTH;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2037
  if (format == str)
monty@hundin.mysql.fi's avatar
merge  
monty@hundin.mysql.fi committed
2038
    str= &value;				// Save result here
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2039
  if (str->alloc(size))
2040 2041
    goto null_date;

2042 2043 2044
  DATE_TIME_FORMAT date_time_format;
  date_time_format.format.str=    (char*) format->ptr();
  date_time_format.format.length= format->length(); 
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2045 2046

  /* Create the result string */
2047
  str->set_charset(collation.collation);
2048
  if (!make_date_time(&date_time_format, &l_time,
2049 2050 2051
                      is_time_format ? MYSQL_TIMESTAMP_TIME :
                                       MYSQL_TIMESTAMP_DATE,
                      str))
2052
    return str;
2053

2054 2055 2056
null_date:
  null_value=1;
  return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2057 2058 2059
}


2060 2061 2062
void Item_func_from_unixtime::fix_length_and_dec()
{ 
  thd= current_thd;
2063
  decimals= DATETIME_DEC;
2064
  fix_length_and_charset_datetime(MAX_DATETIME_WIDTH);
2065
  maybe_null= 1;
2066 2067 2068 2069
  thd->time_zone_used= 1;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2070 2071
String *Item_func_from_unixtime::val_str(String *str)
{
2072
  MYSQL_TIME time_tmp;
2073

2074
  DBUG_ASSERT(fixed == 1);
2075 2076

  if (get_date(&time_tmp, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2077
    return 0;
2078

2079
  if (str->alloc(MAX_DATE_STRING_REP_LENGTH))
2080 2081 2082 2083 2084
  {
    null_value= 1;
    return 0;
  }

2085
  make_datetime((DATE_TIME_FORMAT *) 0, &time_tmp, str);
2086

2087
  return str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2088 2089 2090 2091 2092
}


longlong Item_func_from_unixtime::val_int()
{
2093
  MYSQL_TIME time_tmp;
2094

2095
  DBUG_ASSERT(fixed == 1);
2096

2097
  if (get_date(&time_tmp, 0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2098
    return 0;
2099

2100
  return (longlong) TIME_to_ulonglong_datetime(&time_tmp);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2101 2102
}

2103
bool Item_func_from_unixtime::get_date(MYSQL_TIME *ltime,
2104
				       uint fuzzy_date __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2105
{
2106
  ulonglong tmp= (ulonglong)(args[0]->val_int());
2107
  /*
2108 2109
    "tmp > TIMESTAMP_MAX_VALUE" check also covers case of negative
    from_unixtime() argument since tmp is unsigned.
2110
  */
2111
  if ((null_value= (args[0]->null_value || tmp > TIMESTAMP_MAX_VALUE)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2112
    return 1;
2113 2114

  thd->variables.time_zone->gmt_sec_to_TIME(ltime, (my_time_t)tmp);
2115 2116 2117 2118 2119 2120

  return 0;
}


void Item_func_convert_tz::fix_length_and_dec()
2121
{
2122
  decimals= 0;
2123
  fix_length_and_charset_datetime(MAX_DATETIME_WIDTH);
2124
  maybe_null= 1;
2125 2126 2127
}


2128 2129
String *Item_func_convert_tz::val_str(String *str)
{
2130
  MYSQL_TIME time_tmp;
2131 2132 2133

  if (get_date(&time_tmp, 0))
    return 0;
2134 2135

  if (str->alloc(MAX_DATE_STRING_REP_LENGTH))
2136 2137 2138 2139
  {
    null_value= 1;
    return 0;
  }
2140

2141
  make_datetime((DATE_TIME_FORMAT *) 0, &time_tmp, str);
2142

2143 2144 2145 2146 2147 2148
  return str;
}


longlong Item_func_convert_tz::val_int()
{
2149
  MYSQL_TIME time_tmp;
2150 2151 2152 2153 2154 2155 2156 2157

  if (get_date(&time_tmp, 0))
    return 0;
  
  return (longlong)TIME_to_ulonglong_datetime(&time_tmp);
}


2158
bool Item_func_convert_tz::get_date(MYSQL_TIME *ltime,
2159
                                    uint fuzzy_date __attribute__((unused)))
2160 2161 2162
{
  my_time_t my_time_tmp;
  String str;
2163
  THD *thd= current_thd;
2164 2165 2166

  if (!from_tz_cached)
  {
2167
    from_tz= my_tz_find(thd, args[1]->val_str_ascii(&str));
2168 2169 2170 2171 2172
    from_tz_cached= args[1]->const_item();
  }

  if (!to_tz_cached)
  {
2173
    to_tz= my_tz_find(thd, args[2]->val_str_ascii(&str));
2174 2175 2176
    to_tz_cached= args[2]->const_item();
  }

2177
  if (from_tz==0 || to_tz==0 || get_arg0_date(ltime, TIME_NO_ZERO_DATE))
2178 2179 2180 2181 2182 2183
  {
    null_value= 1;
    return 1;
  }

  {
2184
    my_bool not_used;
2185
    my_time_tmp= from_tz->TIME_to_gmt_sec(ltime, &not_used);
2186 2187
    /* my_time_tmp is guranteed to be in the allowed range */
    if (my_time_tmp)
2188 2189
      to_tz->gmt_sec_to_TIME(ltime, my_time_tmp);
  }
2190

2191
  null_value= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2192 2193 2194
  return 0;
}

2195

2196 2197 2198 2199 2200 2201 2202
void Item_func_convert_tz::cleanup()
{
  from_tz_cached= to_tz_cached= 0;
  Item_date_func::cleanup();
}


2203 2204 2205
void Item_date_add_interval::fix_length_and_dec()
{
  enum_field_types arg0_field_type;
2206

2207
  maybe_null=1;
2208
  fix_length_and_charset_datetime(MAX_DATETIME_FULL_WIDTH);
2209
  value.alloc(max_length);
2210 2211 2212 2213 2214 2215 2216 2217 2218

  /*
    The field type for the result of an Item_date function is defined as
    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,
      minutes or seconds then type is MYSQL_TYPE_DATETIME.
    - Otherwise the result is MYSQL_TYPE_STRING
2219
      (This is because you can't know if the string contains a DATE, MYSQL_TIME or
2220 2221 2222 2223 2224 2225 2226 2227 2228
      DATETIME argument)
  */
  cached_field_type= MYSQL_TYPE_STRING;
  arg0_field_type= args[0]->field_type();
  if (arg0_field_type == MYSQL_TYPE_DATETIME ||
      arg0_field_type == MYSQL_TYPE_TIMESTAMP)
    cached_field_type= MYSQL_TYPE_DATETIME;
  else if (arg0_field_type == MYSQL_TYPE_DATE)
  {
2229
    if (int_type <= INTERVAL_DAY || int_type == INTERVAL_YEAR_MONTH)
2230 2231 2232 2233 2234 2235 2236 2237
      cached_field_type= arg0_field_type;
    else
      cached_field_type= MYSQL_TYPE_DATETIME;
  }
}


/* Here arg[1] is a Item_interval object */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2238

2239
bool Item_date_add_interval::get_date(MYSQL_TIME *ltime, uint fuzzy_date)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2240 2241
{
  INTERVAL interval;
2242

2243
  if (args[0]->get_date(ltime, TIME_NO_ZERO_DATE) ||
2244 2245
      get_interval_value(args[1], int_type, &value, &interval))
    return (null_value=1);
2246

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2247
  if (date_sub_interval)
2248
    interval.neg = !interval.neg;
2249

2250 2251 2252
  if ((null_value= date_add_interval(ltime, int_type, interval)))
    return 1;
  return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2253 2254 2255 2256 2257
}


String *Item_date_add_interval::val_str(String *str)
{
2258
  DBUG_ASSERT(fixed == 1);
2259
  MYSQL_TIME ltime;
2260
  enum date_time_format_types format;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2261

2262
  if (Item_date_add_interval::get_date(&ltime, TIME_NO_ZERO_DATE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2263
    return 0;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2264

2265
  if (ltime.time_type == MYSQL_TIMESTAMP_DATE)
2266 2267 2268 2269 2270 2271 2272
    format= DATE_ONLY;
  else if (ltime.second_part)
    format= DATE_TIME_MICROSECOND;
  else
    format= DATE_TIME;

  if (!make_datetime(format, &ltime, str))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2273
    return str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2274 2275 2276 2277 2278

  null_value=1;
  return 0;
}

2279

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2280 2281
longlong Item_date_add_interval::val_int()
{
2282
  DBUG_ASSERT(fixed == 1);
2283
  MYSQL_TIME ltime;
2284
  longlong date;
2285
  if (Item_date_add_interval::get_date(&ltime, TIME_NO_ZERO_DATE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2286
    return (longlong) 0;
2287
  date = (ltime.year*100L + ltime.month)*100L + ltime.day;
2288
  return ltime.time_type == MYSQL_TIMESTAMP_DATE ? date :
2289
    ((date*100L + ltime.hour)*100L+ ltime.minute)*100L + ltime.second;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2290 2291
}

2292 2293 2294 2295 2296


bool Item_date_add_interval::eq(const Item *item, bool binary_cmp) const
{
  Item_date_add_interval *other= (Item_date_add_interval*) item;
2297 2298 2299 2300
  if (!Item_func::eq(item, binary_cmp))
    return 0;
  return ((int_type == other->int_type) &&
          (date_sub_interval == other->date_sub_interval));
2301 2302
}

2303 2304 2305 2306
/*
   'interval_names' reflects the order of the enumeration interval_type.
   See item_timefunc.h
 */
2307

2308 2309
static const char *interval_names[]=
{
2310 2311
  "year", "quarter", "month", "week", "day",  
  "hour", "minute", "second", "microsecond",
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2312 2313 2314 2315 2316
  "year_month", "day_hour", "day_minute", 
  "day_second", "hour_minute", "hour_second",
  "minute_second", "day_microsecond",
  "hour_microsecond", "minute_microsecond",
  "second_microsecond"
2317 2318
};

2319
void Item_date_add_interval::print(String *str, enum_query_type query_type)
2320 2321
{
  str->append('(');
2322
  args[0]->print(str, query_type);
2323
  str->append(date_sub_interval?" - interval ":" + interval ");
2324
  args[1]->print(str, query_type);
2325
  str->append(' ');
2326 2327 2328 2329
  str->append(interval_names[int_type]);
  str->append(')');
}

2330
void Item_extract::print(String *str, enum_query_type query_type)
2331
{
2332
  str->append(STRING_WITH_LEN("extract("));
2333
  str->append(interval_names[int_type]);
2334
  str->append(STRING_WITH_LEN(" from "));
2335
  args[0]->print(str, query_type);
2336 2337 2338
  str->append(')');
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2339 2340 2341 2342 2343 2344 2345 2346
void Item_extract::fix_length_and_dec()
{
  value.alloc(32);				// alloc buffer

  maybe_null=1;					// If wrong date
  switch (int_type) {
  case INTERVAL_YEAR:		max_length=4; date_value=1; break;
  case INTERVAL_YEAR_MONTH:	max_length=6; date_value=1; break;
2347
  case INTERVAL_QUARTER:        max_length=2; date_value=1; break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2348
  case INTERVAL_MONTH:		max_length=2; date_value=1; break;
2349
  case INTERVAL_WEEK:		max_length=2; date_value=1; break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
  case INTERVAL_DAY:		max_length=2; date_value=1; break;
  case INTERVAL_DAY_HOUR:	max_length=9; date_value=0; break;
  case INTERVAL_DAY_MINUTE:	max_length=11; date_value=0; break;
  case INTERVAL_DAY_SECOND:	max_length=13; date_value=0; break;
  case INTERVAL_HOUR:		max_length=2; date_value=0; break;
  case INTERVAL_HOUR_MINUTE:	max_length=4; date_value=0; break;
  case INTERVAL_HOUR_SECOND:	max_length=6; date_value=0; break;
  case INTERVAL_MINUTE:		max_length=2; date_value=0; break;
  case INTERVAL_MINUTE_SECOND:	max_length=4; date_value=0; break;
  case INTERVAL_SECOND:		max_length=2; date_value=0; break;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2360 2361 2362 2363 2364
  case INTERVAL_MICROSECOND:	max_length=2; date_value=0; break;
  case INTERVAL_DAY_MICROSECOND: max_length=20; date_value=0; break;
  case INTERVAL_HOUR_MICROSECOND: max_length=13; date_value=0; break;
  case INTERVAL_MINUTE_MICROSECOND: max_length=11; date_value=0; break;
  case INTERVAL_SECOND_MICROSECOND: max_length=9; date_value=0; break;
2365
  case INTERVAL_LAST: DBUG_ASSERT(0); break; /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2366 2367 2368 2369 2370 2371
  }
}


longlong Item_extract::val_int()
{
2372
  DBUG_ASSERT(fixed == 1);
2373
  MYSQL_TIME ltime;
2374 2375
  uint year;
  ulong week_format;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2376 2377 2378
  long neg;
  if (date_value)
  {
2379
    if (get_arg0_date(&ltime, TIME_FUZZY_DATE))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2380 2381 2382 2383 2384 2385
      return 0;
    neg=1;
  }
  else
  {
    String *res= args[0]->val_str(&value);
2386 2387 2388
    if (!res ||
        str_to_time_with_warn(res->charset(), res->ptr(), res->length(),
                              &ltime))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
    {
      null_value=1;
      return 0;
    }
    neg= ltime.neg ? -1 : 1;
    null_value=0;
  }
  switch (int_type) {
  case INTERVAL_YEAR:		return ltime.year;
  case INTERVAL_YEAR_MONTH:	return ltime.year*100L+ltime.month;
2399
  case INTERVAL_QUARTER:	return (ltime.month+2)/3;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2400
  case INTERVAL_MONTH:		return ltime.month;
2401 2402 2403
  case INTERVAL_WEEK:
  {
    week_format= current_thd->variables.default_week_format;
pem@mysql.comhem.se's avatar
pem@mysql.comhem.se committed
2404
    return calc_week(&ltime, week_mode(week_format), &year);
2405
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
  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;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
  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;
2437
  case INTERVAL_LAST: DBUG_ASSERT(0); break;  /* purecov: deadcode */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2438 2439 2440
  }
  return 0;					// Impossible
}
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2441

hf@deer.(none)'s avatar
hf@deer.(none) committed
2442 2443 2444 2445 2446
bool Item_extract::eq(const Item *item, bool binary_cmp) const
{
  if (this == item)
    return 1;
  if (item->type() != FUNC_ITEM ||
2447
      functype() != ((Item_func*)item)->functype())
hf@deer.(none)'s avatar
hf@deer.(none) committed
2448 2449 2450 2451 2452 2453 2454 2455 2456 2457
    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;
}
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2458

2459

2460 2461 2462 2463 2464
bool Item_char_typecast::eq(const Item *item, bool binary_cmp) const
{
  if (this == item)
    return 1;
  if (item->type() != FUNC_ITEM ||
2465
      functype() != ((Item_func*)item)->functype())
2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
    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;
}
2477

2478
void Item_typecast::print(String *str, enum_query_type query_type)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2479
{
2480
  str->append(STRING_WITH_LEN("cast("));
2481
  args[0]->print(str, query_type);
2482
  str->append(STRING_WITH_LEN(" as "));
2483 2484 2485 2486
  str->append(cast_type());
  str->append(')');
}

2487

2488
void Item_char_typecast::print(String *str, enum_query_type query_type)
2489
{
2490
  str->append(STRING_WITH_LEN("cast("));
2491
  args[0]->print(str, query_type);
2492
  str->append(STRING_WITH_LEN(" as char"));
2493 2494 2495
  if (cast_length >= 0)
  {
    str->append('(');
2496
    char buffer[20];
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2497 2498 2499
    // my_charset_bin is good enough for numbers
    String st(buffer, sizeof(buffer), &my_charset_bin);
    st.set((ulonglong)cast_length, &my_charset_bin);
2500
    str->append(st);
2501 2502 2503 2504
    str->append(')');
  }
  if (cast_cs)
  {
2505
    str->append(STRING_WITH_LEN(" charset "));
2506
    str->append(cast_cs->csname);
2507
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2508 2509
  str->append(')');
}
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2510

2511 2512
String *Item_char_typecast::val_str(String *str)
{
2513
  DBUG_ASSERT(fixed == 1);
2514
  String *res;
2515 2516
  uint32 length;

2517
  if (!charset_conversion)
2518
  {
2519 2520 2521 2522 2523
    if (!(res= args[0]->val_str(str)))
    {
      null_value= 1;
      return 0;
    }
2524 2525 2526 2527
  }
  else
  {
    // Convert character set if differ
2528
    uint dummy_errors;
2529
    if (!(res= args[0]->val_str(&tmp_value)) ||
2530 2531
        str->copy(res->ptr(), res->length(), from_cs,
        cast_cs, &dummy_errors))
2532 2533 2534 2535 2536 2537
    {
      null_value= 1;
      return 0;
    }
    res= str;
  }
2538 2539

  res->set_charset(cast_cs);
2540

2541
  /*
2542 2543 2544
    Cut the tail if cast with length
    and the result is longer than cast length, e.g.
    CAST('string' AS CHAR(1))
2545
  */
2546 2547 2548 2549 2550
  if (cast_length >= 0)
  {
    if (res->length() > (length= (uint32) res->charpos(cast_length)))
    {                                           // Safe even if const arg
      char char_type[40];
bar@mysql.com's avatar
bar@mysql.com committed
2551
      my_snprintf(char_type, sizeof(char_type), "%s(%lu)",
2552 2553
                  cast_cs == &my_charset_bin ? "BINARY" : "CHAR",
                  (ulong) length);
2554 2555 2556 2557 2558 2559

      if (!res->alloced_length())
      {                                         // Don't change const str
        str_value= *res;                        // Not malloced string
        res= &str_value;
      }
2560
      ErrConvString err(res);
2561 2562 2563
      push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                          ER_TRUNCATED_WRONG_VALUE,
                          ER(ER_TRUNCATED_WRONG_VALUE), char_type,
2564
                          err.ptr());
2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577
      res->length((uint) length);
    }
    else if (cast_cs == &my_charset_bin && res->length() < (uint) cast_length)
    {
      if (res->alloced_length() < (uint) cast_length)
      {
        str->alloc(cast_length);
        str->copy(*res);
        res= str;
      }
      bzero((char*) res->ptr() + res->length(),
            (uint) cast_length - res->length());
      res->length(cast_length);
2578
    }
2579
  }
2580 2581 2582 2583
  null_value= 0;
  return res;
}

2584

2585 2586 2587
void Item_char_typecast::fix_length_and_dec()
{
  uint32 char_length;
bar@mysql.com's avatar
bar@mysql.com committed
2588 2589 2590 2591 2592 2593 2594
  /* 
     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. 
2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608
     
     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.
2609 2610

       Note (TODO): we could use repertoire technique here.
bar@mysql.com's avatar
bar@mysql.com committed
2611
  */
2612
  from_cs= (args[0]->result_type() == INT_RESULT || 
bar@mysql.com's avatar
bar@mysql.com committed
2613
            args[0]->result_type() == DECIMAL_RESULT ||
2614 2615 2616
            args[0]->result_type() == REAL_RESULT) ?
           (cast_cs->mbminlen == 1 ? cast_cs : &my_charset_latin1) :
           args[0]->collation.collation;
bar@mysql.com's avatar
bar@mysql.com committed
2617
  charset_conversion= (cast_cs->mbmaxlen > 1) ||
2618 2619 2620
                      (!my_charset_same(from_cs, cast_cs) &&
                       from_cs != &my_charset_bin &&
                       cast_cs != &my_charset_bin);
2621
  collation.set(cast_cs, DERIVATION_IMPLICIT);
2622 2623 2624
  char_length= (cast_length >= 0) ? cast_length :
                args[0]->max_length /
                (cast_cs == &my_charset_bin ? 1 : args[0]->collation.collation->mbmaxlen);
2625 2626 2627
  max_length= char_length * cast_cs->mbmaxlen;
}

2628

2629 2630
String *Item_datetime_typecast::val_str(String *str)
{
2631
  DBUG_ASSERT(fixed == 1);
2632
  MYSQL_TIME ltime;
2633

2634
  if (!get_arg0_date(&ltime, TIME_FUZZY_DATE) &&
2635 2636
      !make_datetime(ltime.second_part ? DATE_TIME_MICROSECOND : DATE_TIME, 
		     &ltime, str))
monty@mysql.com's avatar
monty@mysql.com committed
2637
    return str;
2638 2639 2640 2641 2642 2643

  null_value=1;
  return 0;
}


2644 2645 2646
longlong Item_datetime_typecast::val_int()
{
  DBUG_ASSERT(fixed == 1);
2647
  MYSQL_TIME ltime;
2648 2649 2650 2651 2652 2653 2654 2655 2656 2657
  if (get_arg0_date(&ltime,1))
  {
    null_value= 1;
    return 0;
  }

  return TIME_to_ulonglong_datetime(&ltime);
}


2658
bool Item_time_typecast::get_time(MYSQL_TIME *ltime)
2659 2660
{
  bool res= get_arg0_time(ltime);
2661 2662 2663 2664 2665 2666
  /*
    For MYSQL_TIMESTAMP_TIME value we can have non-zero day part,
    which we should not lose.
  */
  if (ltime->time_type == MYSQL_TIMESTAMP_DATETIME)
    ltime->year= ltime->month= ltime->day= 0;
2667
  ltime->time_type= MYSQL_TIMESTAMP_TIME;
2668 2669 2670 2671
  return res;
}


2672 2673
longlong Item_time_typecast::val_int()
{
2674
  MYSQL_TIME ltime;
2675 2676 2677 2678 2679
  if (get_time(&ltime))
  {
    null_value= 1;
    return 0;
  }
2680 2681
  return (ltime.neg ? -1 : 1) *
    (longlong) ((ltime.hour)*10000 + ltime.minute*100 + ltime.second);
2682 2683
}

2684 2685
String *Item_time_typecast::val_str(String *str)
{
2686
  DBUG_ASSERT(fixed == 1);
2687
  MYSQL_TIME ltime;
2688 2689

  if (!get_arg0_time(&ltime) &&
2690 2691
      !make_datetime(ltime.second_part ? TIME_MICROSECOND : TIME_ONLY,
		     &ltime, str))
2692 2693 2694 2695 2696 2697 2698
    return str;

  null_value=1;
  return 0;
}


2699
bool Item_date_typecast::get_date(MYSQL_TIME *ltime, uint fuzzy_date)
2700
{
2701
  bool res= get_arg0_date(ltime, TIME_FUZZY_DATE);
2702
  ltime->hour= ltime->minute= ltime->second= ltime->second_part= 0;
2703
  ltime->time_type= MYSQL_TIMESTAMP_DATE;
2704 2705 2706 2707
  return res;
}


2708 2709 2710 2711 2712 2713 2714
bool Item_date_typecast::get_time(MYSQL_TIME *ltime)
{
  bzero((char *)ltime, sizeof(MYSQL_TIME));
  return args[0]->null_value;
}


2715 2716
String *Item_date_typecast::val_str(String *str)
{
2717
  DBUG_ASSERT(fixed == 1);
2718
  MYSQL_TIME ltime;
2719

2720 2721
  if (!get_arg0_date(&ltime, TIME_FUZZY_DATE) &&
      !str->alloc(MAX_DATE_STRING_REP_LENGTH))
2722
  {
2723
    make_date((DATE_TIME_FORMAT *) 0, &ltime, str);
2724 2725
    return str;
  }
2726 2727 2728 2729 2730

  null_value=1;
  return 0;
}

2731 2732 2733
longlong Item_date_typecast::val_int()
{
  DBUG_ASSERT(fixed == 1);
2734
  MYSQL_TIME ltime;
2735
  if ((null_value= args[0]->get_date(&ltime, TIME_FUZZY_DATE)))
2736 2737 2738
    return 0;
  return (longlong) (ltime.year * 10000L + ltime.month * 100 + ltime.day);
}
2739

2740
/**
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2741 2742
  MAKEDATE(a,b) is a date function that creates a date value 
  from a year and day value.
2743 2744 2745 2746 2747

  NOTES:
    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
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2748 2749 2750 2751
*/

String *Item_func_makedate::val_str(String *str)
{
2752
  DBUG_ASSERT(fixed == 1);
2753
  MYSQL_TIME l_time;
monty@mysql.com's avatar
monty@mysql.com committed
2754
  long daynr=  (long) args[1]->val_int();
2755
  long year= (long) args[0]->val_int();
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2756 2757 2758
  long days;

  if (args[0]->null_value || args[1]->null_value ||
2759
      year < 0 || daynr <= 0)
2760
    goto err;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2761

2762 2763 2764 2765
  if (year < 100)
    year= year_2000_handling(year);

  days= calc_daynr(year,1,1) + daynr - 1;
monty@mysql.com's avatar
monty@mysql.com committed
2766
  /* Day number from year 0 to 9999-12-31 */
2767
  if (days >= 0 && days <= MAX_DAY_NUMBER)
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2768 2769 2770
  {
    null_value=0;
    get_date_from_daynr(days,&l_time.year,&l_time.month,&l_time.day);
2771
    if (str->alloc(MAX_DATE_STRING_REP_LENGTH))
2772 2773 2774
      goto err;
    make_date((DATE_TIME_FORMAT *) 0, &l_time, str);
    return str;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2775 2776
  }

2777
err:
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2778 2779 2780 2781 2782
  null_value=1;
  return 0;
}


2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
/*
  MAKEDATE(a,b) is a date function that creates a date value 
  from a year and day value.

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

2793 2794 2795
longlong Item_func_makedate::val_int()
{
  DBUG_ASSERT(fixed == 1);
2796
  MYSQL_TIME l_time;
2797
  long daynr=  (long) args[1]->val_int();
2798
  long year= (long) args[0]->val_int();
2799 2800 2801
  long days;

  if (args[0]->null_value || args[1]->null_value ||
2802
      year < 0 || daynr <= 0)
2803 2804
    goto err;

2805 2806 2807 2808
  if (year < 100)
    year= year_2000_handling(year);

  days= calc_daynr(year,1,1) + daynr - 1;
2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822
  /* Day number from year 0 to 9999-12-31 */
  if (days >= 0 && days < MAX_DAY_NUMBER)
  {
    null_value=0;
    get_date_from_daynr(days,&l_time.year,&l_time.month,&l_time.day);
    return (longlong) (l_time.year * 10000L + l_time.month * 100 + l_time.day);
  }

err:
  null_value= 1;
  return 0;
}


gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2823 2824 2825 2826
void Item_func_add_time::fix_length_and_dec()
{
  enum_field_types arg0_field_type;
  decimals=0;
2827
  fix_length_and_charset_datetime(MAX_DATETIME_FULL_WIDTH);
monty@mysql.com's avatar
monty@mysql.com committed
2828
  maybe_null= 1;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2829 2830

  /*
2831 2832
    The field type for the result of an Item_func_add_time function is defined
    as follows:
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2833 2834 2835 2836 2837 2838 2839 2840 2841

    - 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();
2842 2843
  if (arg0_field_type == MYSQL_TYPE_DATE ||
      arg0_field_type == MYSQL_TYPE_DATETIME ||
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2844 2845 2846 2847 2848 2849
      arg0_field_type == MYSQL_TYPE_TIMESTAMP)
    cached_field_type= MYSQL_TYPE_DATETIME;
  else if (arg0_field_type == MYSQL_TYPE_TIME)
    cached_field_type= MYSQL_TYPE_TIME;
}

2850
/**
2851 2852
  ADDTIME(t,a) and SUBTIME(t,a) are time functions that calculate a
  time/datetime value 
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2853 2854 2855 2856 2857 2858 2859 2860 2861

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

String *Item_func_add_time::val_str(String *str)
{
2862
  DBUG_ASSERT(fixed == 1);
2863
  MYSQL_TIME l_time1, l_time2, l_time3;
2864
  bool is_time= 0;
2865 2866
  long days, microseconds;
  longlong seconds;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2867 2868 2869
  int l_sign= sign;

  null_value=0;
2870 2871
  if (is_date)                        // TIMESTAMP function
  {
2872
    if (get_arg0_date(&l_time1, TIME_FUZZY_DATE) || 
2873
        args[1]->get_time(&l_time2) ||
2874 2875
        l_time1.time_type == MYSQL_TIMESTAMP_TIME || 
        l_time2.time_type != MYSQL_TIMESTAMP_TIME)
2876 2877 2878
      goto null_date;
  }
  else                                // ADDTIME function
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2879
  {
2880 2881
    if (args[0]->get_time(&l_time1) || 
        args[1]->get_time(&l_time2) ||
2882
        l_time2.time_type == MYSQL_TIMESTAMP_DATETIME)
2883
      goto null_date;
2884
    is_time= (l_time1.time_type == MYSQL_TIMESTAMP_TIME);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2885 2886 2887
  }
  if (l_time1.neg != l_time2.neg)
    l_sign= -l_sign;
2888 2889 2890
  
  bzero((char *)&l_time3, sizeof(l_time3));
  
2891 2892
  l_time3.neg= calc_time_diff(&l_time1, &l_time2, -l_sign,
			      &seconds, &microseconds);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2893

2894 2895 2896 2897 2898 2899
  /*
    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))
    l_time3.neg= 1-l_time3.neg;         // Swap sign of result
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2900

2901 2902 2903 2904
  if (!is_time && l_time3.neg)
    goto null_date;

  days= (long)(seconds/86400L);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2905

2906
  calc_time_from_sec(&l_time3, (long)(seconds%86400L), microseconds);
2907

gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2908 2909 2910 2911
  if (!is_time)
  {
    get_date_from_daynr(days,&l_time3.year,&l_time3.month,&l_time3.day);
    if (l_time3.day &&
2912 2913 2914
	!make_datetime(l_time1.second_part || l_time2.second_part ?
		       DATE_TIME_MICROSECOND : DATE_TIME,
		       &l_time3, str))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2915 2916 2917
      return str;
    goto null_date;
  }
2918
  
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2919
  l_time3.hour+= days*24;
2920 2921 2922
  if (!make_datetime_with_warn(l_time1.second_part || l_time2.second_part ?
                               TIME_MICROSECOND : TIME_ONLY,
                               &l_time3, str))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2923 2924 2925 2926 2927 2928 2929
    return str;

null_date:
  null_value=1;
  return 0;
}

2930

2931
void Item_func_add_time::print(String *str, enum_query_type query_type)
2932 2933 2934 2935
{
  if (is_date)
  {
    DBUG_ASSERT(sign > 0);
2936
    str->append(STRING_WITH_LEN("timestamp("));
2937 2938 2939 2940
  }
  else
  {
    if (sign > 0)
2941
      str->append(STRING_WITH_LEN("addtime("));
2942
    else
2943
      str->append(STRING_WITH_LEN("subtime("));
2944
  }
2945
  args[0]->print(str, query_type);
2946
  str->append(',');
2947
  args[1]->print(str, query_type);
2948 2949 2950 2951
  str->append(')');
}


2952
/**
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2953 2954 2955 2956 2957 2958 2959 2960 2961
  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
*/

String *Item_func_timediff::val_str(String *str)
{
2962
  DBUG_ASSERT(fixed == 1);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2963 2964 2965
  longlong seconds;
  long microseconds;
  int l_sign= 1;
2966
  MYSQL_TIME l_time1 ,l_time2, l_time3;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2967 2968 2969 2970 2971 2972 2973 2974 2975 2976

  null_value= 0;  
  if (args[0]->get_time(&l_time1) ||
      args[1]->get_time(&l_time2) ||
      l_time1.time_type != l_time2.time_type)
    goto null_date;

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

2977 2978
  bzero((char *)&l_time3, sizeof(l_time3));
  
2979
  l_time3.neg= calc_time_diff(&l_time1, &l_time2, l_sign,
2980
			      &seconds, &microseconds);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2981

2982
  /*
monty@mysql.com's avatar
monty@mysql.com committed
2983
    For MYSQL_TIMESTAMP_TIME only:
2984
      If first argument was negative and diff between arguments
2985
      is non-zero we need to swap sign to get proper result.
2986
  */
2987
  if (l_time1.neg && (seconds || microseconds))
2988
    l_time3.neg= 1-l_time3.neg;         // Swap sign of result
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2989

monty@mysql.com's avatar
monty@mysql.com committed
2990
  calc_time_from_sec(&l_time3, (long) seconds, microseconds);
2991

2992 2993 2994
  if (!make_datetime_with_warn(l_time1.second_part || l_time2.second_part ?
                               TIME_MICROSECOND : TIME_ONLY,
                               &l_time3, str))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2995 2996 2997 2998 2999 3000 3001
    return str;

null_date:
  null_value=1;
  return 0;
}

3002
/**
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3003 3004 3005 3006 3007 3008 3009
  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
*/

String *Item_func_maketime::val_str(String *str)
{
3010
  DBUG_ASSERT(fixed == 1);
3011
  MYSQL_TIME ltime;
3012
  bool overflow= 0;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3013

3014 3015 3016
  longlong hour=   args[0]->val_int();
  longlong minute= args[1]->val_int();
  longlong second= args[2]->val_int();
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3017 3018

  if ((null_value=(args[0]->null_value || 
3019 3020 3021 3022
                   args[1]->null_value ||
                   args[2]->null_value ||
                   minute < 0 || minute > 59 ||
                   second < 0 || second > 59 ||
3023
                   str->alloc(MAX_DATE_STRING_REP_LENGTH))))
3024
    return 0;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3025

3026
  bzero((char *)&ltime, sizeof(ltime));
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3027
  ltime.neg= 0;
3028 3029

  /* Check for integer overflows */
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3030 3031
  if (hour < 0)
  {
3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053
    if (args[0]->unsigned_flag)
      overflow= 1;
    else
      ltime.neg= 1;
  }
  if (-hour > UINT_MAX || hour > UINT_MAX)
    overflow= 1;

  if (!overflow)
  {
    ltime.hour=   (uint) ((hour < 0 ? -hour : hour));
    ltime.minute= (uint) minute;
    ltime.second= (uint) second;
  }
  else
  {
    ltime.hour= TIME_MAX_HOUR;
    ltime.minute= TIME_MAX_MINUTE;
    ltime.second= TIME_MAX_SECOND;
    char buf[28];
    char *ptr= longlong10_to_str(hour, buf, args[0]->unsigned_flag ? 10 : -10);
    int len = (int)(ptr - buf) +
3054
      sprintf(ptr, ":%02u:%02u", (uint) minute, (uint) second);
3055 3056
    make_truncated_value_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                                 buf, len, MYSQL_TIMESTAMP_TIME,
3057
                                 NullS);
3058
  }
3059

3060 3061 3062 3063
  if (make_time_with_warn((DATE_TIME_FORMAT *) 0, &ltime, str))
  {
    null_value= 1;
    return 0;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3064
  }
3065
  return str;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3066 3067
}

3068

3069
/**
3070 3071
  MICROSECOND(a) is a function ( extraction) that extracts the microseconds
  from a.
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3072 3073 3074 3075

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

gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3077 3078
longlong Item_func_microsecond::val_int()
{
3079
  DBUG_ASSERT(fixed == 1);
3080
  MYSQL_TIME ltime;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3081 3082 3083 3084
  if (!get_arg0_time(&ltime))
    return ltime.second_part;
  return 0;
}
3085 3086


3087 3088
longlong Item_func_timestamp_diff::val_int()
{
3089
  MYSQL_TIME ltime1, ltime2;
3090 3091 3092 3093 3094 3095
  longlong seconds;
  long microseconds;
  long months= 0;
  int neg= 1;

  null_value= 0;  
3096 3097
  if (args[0]->get_date(&ltime1, TIME_NO_ZERO_DATE) ||
      args[1]->get_date(&ltime2, TIME_NO_ZERO_DATE))
3098 3099 3100 3101 3102 3103 3104 3105 3106 3107
    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)
  {
3108 3109
    uint year_beg, year_end, month_beg, month_end, day_beg, day_end;
    uint years= 0;
3110 3111
    uint second_beg, second_end, microsecond_beg, microsecond_end;

3112 3113 3114 3115 3116 3117
    if (neg == -1)
    {
      year_beg= ltime2.year;
      year_end= ltime1.year;
      month_beg= ltime2.month;
      month_end= ltime1.month;
3118 3119
      day_beg= ltime2.day;
      day_end= ltime1.day;
3120 3121 3122 3123
      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;
3124 3125 3126 3127 3128 3129 3130
    }
    else
    {
      year_beg= ltime1.year;
      year_end= ltime2.year;
      month_beg= ltime1.month;
      month_end= ltime2.month;
3131 3132
      day_beg= ltime1.day;
      day_end= ltime2.day;
3133 3134 3135 3136
      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;
3137 3138
    }

3139 3140 3141 3142
    /* calc years */
    years= year_end - year_beg;
    if (month_end < month_beg || (month_end == month_beg && day_end < day_beg))
      years-= 1;
3143

3144 3145 3146 3147 3148 3149
    /* 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);
3150

3151 3152
    if (day_end < day_beg)
      months-= 1;
3153 3154 3155 3156
    else if ((day_end == day_beg) &&
	     ((second_end < second_beg) ||
	      (second_end == second_beg && microsecond_end < microsecond_beg)))
      months-= 1;
3157 3158 3159 3160
  }

  switch (int_type) {
  case INTERVAL_YEAR:
3161
    return months/12*neg;
3162
  case INTERVAL_QUARTER:
3163
    return months/3*neg;
3164
  case INTERVAL_MONTH:
3165
    return months*neg;
3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176
  case INTERVAL_WEEK:          
    return seconds/86400L/7L*neg;
  case INTERVAL_DAY:		
    return seconds/86400L*neg;
  case INTERVAL_HOUR:		
    return seconds/3600L*neg;
  case INTERVAL_MINUTE:		
    return seconds/60L*neg;
  case INTERVAL_SECOND:		
    return seconds*neg;
  case INTERVAL_MICROSECOND:
3177 3178 3179 3180 3181
    /*
      In MySQL difference between any two valid datetime values
      in microseconds fits into longlong.
    */
    return (seconds*1000000L+microseconds)*neg;
3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
  default:
    break;
  }

null_date:
  null_value=1;
  return 0;
}


3192
void Item_func_timestamp_diff::print(String *str, enum_query_type query_type)
3193 3194 3195 3196 3197 3198
{
  str->append(func_name());
  str->append('(');

  switch (int_type) {
  case INTERVAL_YEAR:
3199
    str->append(STRING_WITH_LEN("YEAR"));
3200 3201
    break;
  case INTERVAL_QUARTER:
3202
    str->append(STRING_WITH_LEN("QUARTER"));
3203 3204
    break;
  case INTERVAL_MONTH:
3205
    str->append(STRING_WITH_LEN("MONTH"));
3206 3207
    break;
  case INTERVAL_WEEK:          
3208
    str->append(STRING_WITH_LEN("WEEK"));
3209 3210
    break;
  case INTERVAL_DAY:		
3211
    str->append(STRING_WITH_LEN("DAY"));
3212 3213
    break;
  case INTERVAL_HOUR:
3214
    str->append(STRING_WITH_LEN("HOUR"));
3215 3216
    break;
  case INTERVAL_MINUTE:		
3217
    str->append(STRING_WITH_LEN("MINUTE"));
3218 3219
    break;
  case INTERVAL_SECOND:
3220
    str->append(STRING_WITH_LEN("SECOND"));
3221 3222
    break;		
  case INTERVAL_MICROSECOND:
3223
    str->append(STRING_WITH_LEN("SECOND_FRAC"));
3224 3225 3226 3227 3228 3229 3230 3231
    break;
  default:
    break;
  }

  for (uint i=0 ; i < 2 ; i++)
  {
    str->append(',');
3232
    args[i]->print(str, query_type);
3233 3234 3235
  }
  str->append(')');
}
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3236 3237


3238
String *Item_func_get_format::val_str_ascii(String *str)
3239
{
3240
  DBUG_ASSERT(fixed == 1);
3241 3242
  const char *format_name;
  KNOWN_DATE_TIME_FORMAT *format;
3243
  String *val= args[0]->val_str_ascii(str);
3244
  ulong val_len;
3245

3246 3247 3248 3249 3250 3251 3252
  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++)
3253
  {
3254
    uint format_name_len;
3255
    format_name_len= (uint) strlen(format_name);
3256 3257 3258 3259
    if (val_len == format_name_len &&
	!my_strnncoll(&my_charset_latin1, 
		      (const uchar *) val->ptr(), val_len, 
		      (const uchar *) format_name, val_len))
3260
    {
3261
      const char *format_str= get_date_time_format_str(format, type);
3262
      str->set(format_str, (uint) strlen(format_str), &my_charset_numeric);
3263
      return str;
3264 3265 3266
    }
  }

3267 3268 3269 3270 3271
  null_value= 1;
  return 0;
}


3272
void Item_func_get_format::print(String *str, enum_query_type query_type)
3273 3274 3275 3276 3277
{
  str->append(func_name());
  str->append('(');

  switch (type) {
3278
  case MYSQL_TIMESTAMP_DATE:
3279
    str->append(STRING_WITH_LEN("DATE, "));
3280
    break;
3281
  case MYSQL_TIMESTAMP_DATETIME:
3282
    str->append(STRING_WITH_LEN("DATETIME, "));
3283
    break;
3284
  case MYSQL_TIMESTAMP_TIME:
3285
    str->append(STRING_WITH_LEN("TIME, "));
3286 3287 3288 3289
    break;
  default:
    DBUG_ASSERT(0);
  }
3290
  args[0]->print(str, query_type);
3291 3292 3293 3294
  str->append(')');
}


3295
/**
3296 3297 3298
  Get type of datetime value (DATE/TIME/...) which will be produced
  according to format string.

3299 3300
  @param format   format string
  @param length   length of format string
3301

3302
  @note
3303 3304 3305
    We don't process day format's characters('D', 'd', 'e') because day
    may be a member of all date/time types.

3306
  @note
3307 3308 3309
    Format specifiers supported by this function should be in sync with
    specifiers supported by extract_date_time() function.

3310
  @return
3311
    One of date_time_format_types values:
3312 3313 3314 3315 3316
    - DATE_TIME_MICROSECOND
    - DATE_TIME
    - DATE_ONLY
    - TIME_MICROSECOND
    - TIME_ONLY
3317 3318
*/

3319 3320
static date_time_format_types
get_date_time_result_type(const char *format, uint length)
3321 3322
{
  const char *time_part_frms= "HISThiklrs";
3323
  const char *date_part_frms= "MVUXYWabcjmvuxyw";
3324 3325 3326 3327 3328 3329 3330 3331 3332 3333
  bool date_part_used= 0, time_part_used= 0, frac_second_used= 0;
  
  const char *val= format;
  const char *end= format + length;

  for (; val != end && val != end; val++)
  {
    if (*val == '%' && val+1 != end)
    {
      val++;
3334 3335 3336
      if (*val == 'f')
        frac_second_used= time_part_used= 1;
      else if (!time_part_used && strchr(time_part_frms, *val))
3337 3338 3339
	time_part_used= 1;
      else if (!date_part_used && strchr(date_part_frms, *val))
	date_part_used= 1;
3340 3341 3342 3343 3344 3345
      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.
        */
3346 3347 3348
	return DATE_TIME_MICROSECOND;
    }
  }
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
3349
  }
3350

3351 3352 3353
  /* We don't have all three types of date-time components */
  if (frac_second_used)
    return TIME_MICROSECOND;
3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367
  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()
{
  maybe_null= 1;
  decimals=0;
3368
  cached_field_type= MYSQL_TYPE_DATETIME;
3369
  max_length= MAX_DATETIME_FULL_WIDTH*MY_CHARSET_BIN_MB_MAXLEN;
3370
  cached_timestamp_type= MYSQL_TIMESTAMP_NONE;
3371 3372
  sql_mode= (current_thd->variables.sql_mode &
             (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE));
3373
  if ((const_item= args[1]->const_item()))
3374
  {
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398
    char format_buff[64];
    String format_str(format_buff, sizeof(format_buff), &my_charset_bin);
    String *format= args[1]->val_str(&format_str);
    if (!args[1]->null_value)
    {
      cached_format_type= get_date_time_result_type(format->ptr(),
                                                    format->length());
      switch (cached_format_type) {
      case DATE_ONLY:
        cached_timestamp_type= MYSQL_TIMESTAMP_DATE;
        cached_field_type= MYSQL_TYPE_DATE; 
        max_length= MAX_DATE_WIDTH * MY_CHARSET_BIN_MB_MAXLEN;
        break;
      case TIME_ONLY:
      case TIME_MICROSECOND:
        cached_timestamp_type= MYSQL_TIMESTAMP_TIME;
        cached_field_type= MYSQL_TYPE_TIME; 
        max_length= MAX_TIME_WIDTH * MY_CHARSET_BIN_MB_MAXLEN;
        break;
      default:
        cached_timestamp_type= MYSQL_TIMESTAMP_DATETIME;
        cached_field_type= MYSQL_TYPE_DATETIME; 
        break;
      }
3399 3400 3401 3402
    }
  }
}

3403

3404
bool Item_func_str_to_date::get_date(MYSQL_TIME *ltime, uint fuzzy_date)
3405 3406 3407
{
  DATE_TIME_FORMAT date_time_format;
  char val_buff[64], format_buff[64];
3408
  String val_string(val_buff, sizeof(val_buff), &my_charset_bin), *val;
3409 3410
  String format_str(format_buff, sizeof(format_buff), &my_charset_bin), *format;

3411
  val=    args[0]->val_str(&val_string);
3412 3413 3414 3415
  format= args[1]->val_str(&format_str);
  if (args[0]->null_value || args[1]->null_value)
    goto null_date;

3416
  null_value= 0;
3417
  bzero((char*) ltime, sizeof(*ltime));
3418 3419 3420
  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(),
3421 3422 3423
			ltime, cached_timestamp_type, 0, "datetime") ||
      ((fuzzy_date & TIME_NO_ZERO_DATE) &&
       (ltime->year == 0 || ltime->month == 0 || ltime->day == 0)))
3424
    goto null_date;
3425
  if (cached_timestamp_type == MYSQL_TIMESTAMP_TIME && ltime->day)
3426 3427 3428 3429 3430 3431 3432 3433 3434
  {
    /*
      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;
  }
3435 3436 3437
  return 0;

null_date:
3438 3439 3440 3441 3442 3443 3444 3445
  if (fuzzy_date & TIME_NO_ZERO_DATE)
  {
    char buff[128];
    strmake(buff, val->ptr(), min(val->length(), sizeof(buff)-1));
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_WRONG_VALUE_FOR_TYPE, ER(ER_WRONG_VALUE_FOR_TYPE),
                        "datetime", buff, "str_to_date");
  }
3446
  return (null_value=1);
3447 3448 3449 3450 3451
}


String *Item_func_str_to_date::val_str(String *str)
{
3452
  DBUG_ASSERT(fixed == 1);
3453
  MYSQL_TIME ltime;
3454

3455
  if (Item_func_str_to_date::get_date(&ltime, TIME_FUZZY_DATE | sql_mode))
3456
    return 0;
3457

3458 3459
  if (!make_datetime((const_item ? cached_format_type :
		     (ltime.second_part ? DATE_TIME_MICROSECOND : DATE_TIME)),
3460 3461
		     &ltime, str))
    return str;
3462 3463
  return 0;
}
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3464 3465


3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488
longlong Item_func_str_to_date::val_int()
{
  DBUG_ASSERT(fixed == 1);
  MYSQL_TIME ltime;

  if (Item_func_str_to_date::get_date(&ltime, TIME_FUZZY_DATE | sql_mode))
    return 0;

  if (const_item)
  {
    switch (cached_field_type) {
    case MYSQL_TYPE_DATE:
      return TIME_to_ulonglong_date(&ltime);
    case MYSQL_TYPE_TIME:
      return TIME_to_ulonglong_time(&ltime);
    default:
      return TIME_to_ulonglong_datetime(&ltime);
    }
  }
  return TIME_to_ulonglong_datetime(&ltime);
}


3489
bool Item_func_last_day::get_date(MYSQL_TIME *ltime, uint fuzzy_date)
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3490
{
3491 3492
  if (get_arg0_date(ltime, fuzzy_date & ~TIME_FUZZY_DATE) ||
      (ltime->month == 0))
3493 3494
  {
    null_value= 1;
3495
    return 1;
3496 3497
  }
  null_value= 0;
3498 3499 3500 3501
  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;
3502 3503
  ltime->hour= ltime->minute= ltime->second= 0;
  ltime->second_part= 0;
3504
  ltime->time_type= MYSQL_TIMESTAMP_DATE;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
3505 3506
  return 0;
}