item_timefunc.cc 63.3 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 5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
7

bk@work.mysql.com's avatar
bk@work.mysql.com committed
8 9 10 11
   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
12

bk@work.mysql.com's avatar
bk@work.mysql.com committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
   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 */


/* This file defines all time functions */

#ifdef __GNUC__
#pragma implementation				// gcc: Class implementation
#endif

#include "mysql_priv.h"
#include <m_ctype.h>
#include <time.h>

28
/* TODO: Move month and days to language files */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
29

30 31
#define MAX_DAY_NUMBER 3652424L

32 33 34 35
static const char *month_names[]=
{
  "January", "February", "March", "April", "May", "June", "July", "August",
  "September", "October", "November", "December", NullS
36
};
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

TYPELIB month_names_typelib=
{ array_elements(month_names)-1,"", month_names };

static const char *day_names[]=
{
  "Monday", "Tuesday", "Wednesday",
  "Thursday", "Friday", "Saturday" ,"Sunday", NullS
};

TYPELIB day_names_typelib=
{ array_elements(day_names)-1,"", day_names};


/*
  OPTIMIZATION TODO:
   - 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.

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

static bool make_datetime(date_time_format_types format, TIME *ltime,
			  String *str)
70
{
71 72 73
  char *buff;
  CHARSET_INFO *cs= &my_charset_bin;
  uint length= 30;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
74

75 76 77
  if (str->alloc(length))
    return 1;
  buff= (char*) str->ptr();
78

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
  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:
    length= cs->cset->snprintf(cs, buff, length, "%s%02d:%02d:%02d.%06d",
			       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,
			       "%04d-%02d-%02d %02d:%02d:%02d.%06d",
			       ltime->year, ltime->month, ltime->day,
			       ltime->hour, ltime->minute, ltime->second,
			       ltime->second_part);
    break;
108
  }
109 110 111 112

  str->length(length);
  str->set_charset(cs);
  return 0;
113
}
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
114 115


116
/*
117 118
  Extract datetime value to TIME struct from string value
  according to format string. 
119 120 121 122 123 124 125

  SYNOPSIS
    extract_date_time()
    format		date/time format specification
    val			String to decode
    length		Length of string
    l_time		Store result here
126 127 128
    cached_timestamp_type 
                       It uses to get an appropriate warning
                       in the case when the value is truncated.
129 130 131 132

    RETURN
      0	ok
      1	error
133
*/
134 135

static bool extract_date_time(DATE_TIME_FORMAT *format,
136 137
			      const char *val, uint length, TIME *l_time,
			      timestamp_type cached_timestamp_type)
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
138
{
139
  int weekday= 0, yearday= 0, daypart= 0;
140
  int week_number= -1;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
141
  CHARSET_INFO *cs= &my_charset_bin;
142
  int error= 0;
143 144
  bool usa_time= 0;
  bool sunday_first= 0;
145 146
  int frac_part;
  const char *val_begin= val;
147 148
  const char *val_end= val + length;
  const char *ptr= format->format.str;
149
  const char *end= ptr + format->format.length;
150
  DBUG_ENTER("extract_date_time");
151

152 153 154
  bzero((char*) l_time, sizeof(*l_time));

  for (; ptr != end && val != val_end; ptr++)
155
  {
156

157 158
    if (*ptr == '%' && ptr+1 != end)
    {
159 160 161 162 163 164 165 166
      int val_len;
      char *tmp;

      /* Skip pre-space between each argument */
      while (my_isspace(cs, *val) && val != val_end)
	val++;

      val_len= (uint) (val_end - val);
167
      switch (*++ptr) {
168
	/* Year */
169
      case 'Y':
170 171 172
	tmp= (char*) val + min(4, val_len);
	l_time->year= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
173 174
	break;
      case 'y':
175 176 177
	tmp= (char*) val + min(2, val_len);
	l_time->year= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
178 179
	l_time->year+= (l_time->year < YY_PART_YEAR ? 2000 : 1900);
	break;
180 181

	/* Month */
182
      case 'm':
183 184 185 186 187 188 189 190 191 192
      case 'c':
	tmp= (char*) val + min(2, val_len);
	l_time->month= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
	break;
      case 'M':
      case 'b':
	if ((l_time->month= check_word(&month_names_typelib,
				       val, val_end, &val)) <= 0)
	  goto err;
193
	break;
194
	/* Day */
195
      case 'd':
196 197 198 199
      case 'e':
	tmp= (char*) val + min(2, val_len);
	l_time->day= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
200 201
	break;
      case 'D':
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
	tmp= (char*) val + min(2, val_len);
	l_time->day= (int) my_strtoll10(val, &tmp, &error);
	/* Skip 'st, 'nd, 'th .. */
	val= tmp + min((int) (end-tmp), 2);
	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;
219
	break;
220 221

	/* Minute */
222
      case 'i':
223 224 225
	tmp= (char*) val + min(2, val_len);
	l_time->minute= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
226
	break;
227 228

	/* Second */
229 230
      case 's':
      case 'S':
231 232 233
	tmp= (char*) val + min(2, val_len);
	l_time->second= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
234
	break;
235 236 237 238

	/* Second part */
      case 'f':
	tmp= (char*) val_end;
239 240
	if (tmp - val > 6)
	  tmp= (char*) val + 6;
monty@mysql.com's avatar
monty@mysql.com committed
241
	l_time->second_part= (int) my_strtoll10(val, &tmp, &error);
242 243 244
	frac_part= 6 - (tmp - val);
	if (frac_part > 0)
	  l_time->second_part*= (ulong) log_10_int[frac_part];
245
	val= tmp;
246
	break;
247 248 249 250 251 252 253 254 255 256 257 258 259

	/* 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;
260
	val+= 2;
261
	break;
262 263

	/* Exotic things */
264 265
      case 'W':
      case 'a':
266 267
	if ((weekday= check_word(&day_names_typelib, val, val_end, &val)) <= 0)
	  goto err;
268 269
	break;
      case 'w':
270 271 272 273 274
	tmp= (char*) val + 1;
	if ((weekday= (int) my_strtoll10(val, &tmp, &error)) <= 0 ||
	    weekday >= 7)
	  goto err;
	val= tmp;
275 276
	break;
      case 'j':
277 278 279
	tmp= (char*) val + min(val_len, 3);
	yearday= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
280
	break;
281

282 283
      case 'U':
	sunday_first= 1;
284
	/* Fall through */
285
      case 'u':
286 287 288
	tmp= (char*) val + min(val_len, 2);
	week_number= (int) my_strtoll10(val, &tmp, &error);
	val= tmp;
289
	break;
290

291 292 293 294 295 296 297 298 299 300 301 302
      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;
303
      default:
304
	goto err;
305
      }
306 307
      if (error)				// Error from my_strtoll10
	goto err;
308
    }
309
    else if (!my_isspace(cs, *ptr))
310
    {
311 312 313
      if (*val != *ptr)
	goto err;
      val++;
314 315 316 317 318
    }
  }
  if (usa_time)
  {
    if (l_time->hour > 12 || l_time->hour < 1)
319
      goto err;
320 321
    l_time->hour= l_time->hour%12+daypart;
  }
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
322

323 324 325
  if (yearday > 0)
  {
    uint days= calc_daynr(l_time->year,1,1) +  yearday - 1;
326 327 328
    if (days <= 0 || days >= MAX_DAY_NUMBER)
      goto err;
    get_date_from_daynr(days,&l_time->year,&l_time->month,&l_time->day);
329
  }
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
330

331 332 333 334 335 336
  if (week_number >= 0 && weekday)
  {
    int days= calc_daynr(l_time->year,1,1);
    uint weekday_b;
    
    if (weekday > 7 || weekday < 0)
337
	goto err;
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    if (sunday_first)
      weekday = weekday%7;

    if (week_number == 53)
    {
      days+= (week_number - 1)*7;
      weekday_b= calc_weekday(days, sunday_first);
      weekday = weekday - weekday_b - !sunday_first;
      days+= weekday;
    }
    else if (week_number == 0)
    {
      weekday_b= calc_weekday(days, sunday_first);
      weekday = weekday - weekday_b - !sunday_first;
      days+= weekday;
    }
    else
    {
      days+= (week_number - !sunday_first)*7;
      weekday_b= calc_weekday(days, sunday_first);
      weekday =weekday - weekday_b - !sunday_first;
      days+= weekday;
    }
361 362 363
    if (days <= 0 || days >= MAX_DAY_NUMBER)
      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
364 365
  }

366 367
  if (l_time->month > 12 || l_time->day > 31 || l_time->hour > 23 || 
      l_time->minute > 59 || l_time->second > 59)
368
    goto err;
369

370 371 372 373 374 375 376 377 378 379 380 381
  if (val != val_end)
  {
    do
    {
      if (!my_isspace(&my_charset_latin1,*val))
      {
	make_truncated_value_warning(current_thd, val_begin, length,
				     cached_timestamp_type);
	break;
      }
    } while (++val != val_end);
  }
382 383
  DBUG_RETURN(0);

384 385 386
err:
  DBUG_RETURN(1);
}
387 388 389


/*
390
  Create a formated date/time value in a string
391 392
*/

393 394
bool make_date_time(DATE_TIME_FORMAT *format, TIME *l_time,
		    timestamp_type type, String *str)
395 396 397 398 399 400
{
  char intbuff[15];
  uint days_i;
  uint hours_i;
  uint weekday;
  ulong length;
401 402 403 404 405
  const char *ptr, *end;

  str->length(0);
  str->set_charset(&my_charset_bin);

406 407
  if (l_time->neg)
    str->append("-", 1);
408 409
  
  end= (ptr= format->format.str) + format->format.length;
410 411 412 413 414 415 416 417 418
  for (; ptr != end ; ptr++)
  {
    if (*ptr != '%' || ptr+1 == end)
      str->append(*ptr);
    else
    {
      switch (*++ptr) {
      case 'M':
	if (!l_time->month)
419
	  return 1;
420 421 422 423
	str->append(month_names[l_time->month-1]);
	break;
      case 'b':
	if (!l_time->month)
424 425
	  return 1;
	str->append(month_names[l_time->month-1],3);
426 427
	break;
      case 'W':
428 429 430 431
	if (type == TIMESTAMP_TIME)
	  return 1;
	weekday= calc_weekday(calc_daynr(l_time->year,l_time->month,
					 l_time->day),0);
432 433 434
	str->append(day_names[weekday]);
	break;
      case 'a':
435 436 437 438 439
	if (type == TIMESTAMP_TIME)
	  return 1;
	weekday=calc_weekday(calc_daynr(l_time->year,l_time->month,
					l_time->day),0);
	str->append(day_names[weekday],3);
440 441
	break;
      case 'D':
442 443
	if (type == TIMESTAMP_TIME)
	  return 1;
444 445 446
	length= int10_to_str(l_time->day, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 1, '0');
	if (l_time->day >= 10 &&  l_time->day <= 19)
447
	  str->append("th", 2);
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
	else
	{
	  switch (l_time->day %10) {
	  case 1:
	    str->append("st",2);
	    break;
	  case 2:
	    str->append("nd",2);
	    break;
	  case 3:
	    str->append("rd",2);
	    break;
	  default:
	    str->append("th",2);
	    break;
	  }
	}
	break;
      case 'Y':
	length= int10_to_str(l_time->year, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 4, '0');
	break;
      case 'y':
	length= int10_to_str(l_time->year%100, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'm':
	length= int10_to_str(l_time->month, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'c':
	length= int10_to_str(l_time->month, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 1, '0');
	break;
      case 'd':
	length= int10_to_str(l_time->day, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'e':
	length= int10_to_str(l_time->day, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 1, '0');
	break;
      case 'f':
	length= int10_to_str(l_time->second_part, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 6, '0');
	break;
      case 'H':
	length= int10_to_str(l_time->hour, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'h':
      case 'I':
	days_i= l_time->hour/24;
	hours_i= (l_time->hour%24 + 11)%12+1 + 24*days_i;
	length= int10_to_str(hours_i, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'i':					/* minutes */
	length= int10_to_str(l_time->minute, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'j':
510 511 512 513
	if (type == TIMESTAMP_TIME)
	  return 1;
	length= int10_to_str(calc_daynr(l_time->year,l_time->month,
					l_time->day) - 
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
		     calc_daynr(l_time->year,1,1) + 1, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 3, '0');
	break;
      case 'k':
	length= int10_to_str(l_time->hour, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 1, '0');
	break;
      case 'l':
	days_i= l_time->hour/24;
	hours_i= (l_time->hour%24 + 11)%12+1 + 24*days_i;
	length= int10_to_str(hours_i, intbuff, 10) - intbuff;
	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':
	length= my_sprintf(intbuff, 
		   (intbuff, 
		    (l_time->hour < 12) ? "%02d:%02d:%02d AM" : "%02d:%02d:%02d PM",
		    (l_time->hour+11)%12+1,
		    l_time->minute,
		    l_time->second));
	str->append(intbuff, length);
	break;
      case 'S':
      case 's':
	length= int10_to_str(l_time->second, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 2, '0');
	break;
      case 'T':
	length= my_sprintf(intbuff, 
		   (intbuff, 
		    "%02d:%02d:%02d", 
		    l_time->hour, 
		    l_time->minute,
		    l_time->second));
	str->append(intbuff, length);
	break;
      case 'U':
      case 'u':
      {
	uint year;
558 559
	if (type == TIMESTAMP_TIME)
	  return 1;
monty@mysql.com's avatar
monty@mysql.com committed
560 561 562 563 564
	length= int10_to_str(calc_week(l_time,
				       (*ptr) == 'U' ?
				       WEEK_FIRST_WEEKDAY : WEEK_MONDAY_FIRST,
				       &year),
			     intbuff, 10) - intbuff;
565 566 567 568 569 570 571
	str->append_with_prefill(intbuff, length, 2, '0');
      }
      break;
      case 'v':
      case 'V':
      {
	uint year;
572 573
	if (type == TIMESTAMP_TIME)
	  return 1;
monty@mysql.com's avatar
monty@mysql.com committed
574 575 576 577 578 579
	length= int10_to_str(calc_week(l_time,
				       ((*ptr) == 'V' ?
					(WEEK_YEAR | WEEK_FIRST_WEEKDAY) :
					(WEEK_YEAR | WEEK_MONDAY_FIRST)),
				       &year),
			     intbuff, 10) - intbuff;
580 581 582 583 584 585 586
	str->append_with_prefill(intbuff, length, 2, '0');
      }
      break;
      case 'x':
      case 'X':
      {
	uint year;
587 588
	if (type == TIMESTAMP_TIME)
	  return 1;
monty@mysql.com's avatar
monty@mysql.com committed
589 590 591 592 593
	(void) calc_week(l_time,
			 ((*ptr) == 'X' ?
			  WEEK_YEAR | WEEK_FIRST_WEEKDAY :
			  WEEK_YEAR | WEEK_MONDAY_FIRST),
			 &year);
594 595 596 597 598
	length= int10_to_str(year, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 4, '0');
      }
      break;
      case 'w':
599 600 601 602
	if (type == TIMESTAMP_TIME)
	  return 1;
	weekday=calc_weekday(calc_daynr(l_time->year,l_time->month,
					l_time->day),1);
603 604 605
	length= int10_to_str(weekday, intbuff, 10) - intbuff;
	str->append_with_prefill(intbuff, length, 1, '0');
	break;
606

607 608 609 610 611 612
      default:
	str->append(*ptr);
	break;
      }
    }
  }
613
  return 0;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
614 615
}

616

bk@work.mysql.com's avatar
bk@work.mysql.com committed
617
/*
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
  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.

  SYNOPSIS
    str:            string value
    length:         length of str
    cs:             charset of str
    values:         array of results
    count:          count of elements in result array
    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
635 636
*/

637
bool get_interval_info(const char *str,uint length,CHARSET_INFO *cs,
638
                       uint count, long *values, bool transform_msec)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
639 640 641
{
  const char *end=str+length;
  uint i;
642
  while (str != end && !my_isdigit(cs,*str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
643 644 645 646 647
    str++;

  for (i=0 ; i < count ; i++)
  {
    long value;
648
    const char *start= str;
649
    for (value=0; str != end && my_isdigit(cs,*str) ; str++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
650
      value=value*10L + (long) (*str - '0');
651 652 653 654 655 656
    if (transform_msec && i == count - 1) // microseconds always last
    {
      long msec_length= 6 - (str - start);
      if (msec_length > 0)
	value*= (long) log_10_int[msec_length];
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
657
    values[i]= value;
658
    while (str != end && !my_isdigit(cs,*str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
      str++;
    if (str == end && i != count-1)
    {
      i++;
      /* Change values[0...i-1] -> values[0...count-1] */
      bmove_upp((char*) (values+count), (char*) (values+i),
		sizeof(long)*i);
      bzero((char*) values, sizeof(long)*(count-i));
      break;
    }
  }
  return (str != end);
}

longlong Item_func_period_add::val_int()
{
675
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
676 677 678 679 680 681 682 683 684 685 686 687 688 689
  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()
{
690
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
691 692 693 694 695 696 697 698 699 700 701 702 703
  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()
{
704
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
705 706 707 708 709 710 711 712
  TIME ltime;
  if (get_arg0_date(&ltime,0))
    return 0;
  return (longlong) calc_daynr(ltime.year,ltime.month,ltime.day);
}

longlong Item_func_dayofyear::val_int()
{
713
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
714 715 716 717 718 719 720 721 722
  TIME ltime;
  if (get_arg0_date(&ltime,0))
    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()
{
723
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
724 725 726 727 728 729 730
  TIME ltime;
  (void) get_arg0_date(&ltime,1);
  return (longlong) ltime.day;
}

longlong Item_func_month::val_int()
{
731
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
732 733 734 735 736
  TIME ltime;
  (void) get_arg0_date(&ltime,1);
  return (longlong) ltime.month;
}

737

bk@work.mysql.com's avatar
bk@work.mysql.com committed
738 739
String* Item_func_monthname::val_str(String* str)
{
740
  DBUG_ASSERT(fixed == 1);
741
  const char *month_name;
742
  uint   month=(uint) Item_func_month::val_int();
743

744
  if (!month)					// This is also true for NULL
745 746
  {
    null_value=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
747
    return (String*) 0;
748 749
  }
  null_value=0;
750 751
  month_name= month_names[month-1];
  str->set(month_name, strlen(month_name), system_charset_info);
752
  return str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
753 754
}

755

bk@work.mysql.com's avatar
bk@work.mysql.com committed
756 757 758 759
// Returns the quarter of the year

longlong Item_func_quarter::val_int()
{
760
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
761 762 763 764 765 766 767
  TIME ltime;
  (void) get_arg0_date(&ltime,1);
  return (longlong) ((ltime.month+2)/3);
}

longlong Item_func_hour::val_int()
{
768
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
769 770 771 772 773 774 775
  TIME ltime;
  (void) get_arg0_time(&ltime);
  return ltime.hour;
}

longlong Item_func_minute::val_int()
{
776
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
777 778 779 780 781 782 783 784
  TIME ltime;
  (void) get_arg0_time(&ltime);
  return ltime.minute;
}
// Returns the second in time_exp in the range of 0 - 59

longlong Item_func_second::val_int()
{
785
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
786 787 788 789 790 791
  TIME ltime;
  (void) get_arg0_time(&ltime);
  return ltime.second;
}


792 793 794 795 796 797 798
uint week_mode(uint mode)
{
  uint week_format= (mode & 7);
  if (!(week_format & WEEK_MONDAY_FIRST))
    week_format^= WEEK_FIRST_WEEKDAY;
  return week_format;
}
799

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
/*
  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.
827
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
828 829 830

longlong Item_func_week::val_int()
{
831
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
832 833 834 835
  uint year;
  TIME ltime;
  if (get_arg0_date(&ltime,0))
    return 0;
836 837
  return (longlong) calc_week(&ltime,
			      week_mode((uint) args[1]->val_int()),
838
			      &year);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
839 840 841 842 843
}


longlong Item_func_yearweek::val_int()
{
844
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
845 846 847 848
  uint year,week;
  TIME ltime;
  if (get_arg0_date(&ltime,0))
    return 0;
849 850 851
  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
852 853 854 855 856 857 858 859
  return week+year*100;
}


/* weekday() has a automatic to_days() on item */

longlong Item_func_weekday::val_int()
{
860
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
861 862 863 864 865 866 867
  ulong tmp_value=(ulong) args[0]->val_int();
  if ((null_value=(args[0]->null_value || !tmp_value)))
    return 0; /* purecov: inspected */

  return (longlong) calc_weekday(tmp_value,odbc_type)+test(odbc_type);
}

868

bk@work.mysql.com's avatar
bk@work.mysql.com committed
869 870
String* Item_func_dayname::val_str(String* str)
{
871
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
872
  uint weekday=(uint) val_int();		// Always Item_func_daynr()
873 874
  const char *name;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
875 876
  if (null_value)
    return (String*) 0;
877
  
878 879
  name= day_names[weekday];
  str->set(name, strlen(name), system_charset_info);
880
  return str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
881 882 883 884 885
}


longlong Item_func_year::val_int()
{
886
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
887 888 889 890 891 892 893 894
  TIME ltime;
  (void) get_arg0_date(&ltime,1);
  return (longlong) ltime.year;
}


longlong Item_func_unix_timestamp::val_int()
{
895
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
896
  if (arg_count == 0)
897
    return (longlong) current_thd->query_start();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
898 899 900 901 902 903 904 905 906 907 908
  if (args[0]->type() == FIELD_ITEM)
  {						// Optimize timestamp field
    Field *field=((Item_field*) args[0])->field;
    if (field->type() == FIELD_TYPE_TIMESTAMP)
      return ((Field_timestamp*) field)->get_timestamp();
  }
  String *str=args[0]->val_str(&value);
  if ((null_value=args[0]->null_value))
  {
    return 0; /* purecov: inspected */
  }
909
  return (longlong) str_to_timestamp(str->ptr(),str->length());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
910 911 912 913 914
}


longlong Item_func_time_to_sec::val_int()
{
915
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
916
  TIME ltime;
917
  longlong seconds;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
918
  (void) get_arg0_time(&ltime);
919 920
  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
921 922 923 924
}


/*
925 926
  Convert a string to a interval value
  To make code easy, allow interval objects without separators.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
927 928 929
*/

static bool get_interval_value(Item *args,interval_type int_type,
930
			       String *str_value, INTERVAL *interval)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
931
{
932
  long array[5],value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
933 934
  const char *str;
  uint32 length;
935
  CHARSET_INFO *cs=str_value->charset();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
936

937 938 939 940 941
  LINT_INIT(value);
  LINT_INIT(str);
  LINT_INIT(length);

  bzero((char*) interval,sizeof(*interval));
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
942
  if ((int) int_type <= INTERVAL_MICROSECOND)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
943 944 945 946 947 948
  {
    value=(long) args->val_int();
    if (args->null_value)
      return 1;
    if (value < 0)
    {
949
      interval->neg=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
950 951 952 953 954 955 956 957 958
      value= -value;
    }
  }
  else
  {
    String *res;
    if (!(res=args->val_str(str_value)))
      return (1);

959
    /* record negative intervalls in interval->neg */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
960 961
    str=res->ptr();
    const char *end=str+res->length();
962
    while (str != end && my_isspace(cs,*str))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
963 964 965
      str++;
    if (str != end && *str == '-')
    {
966
      interval->neg=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
967 968 969 970 971 972 973
      str++;
    }
    length=(uint32) (end-str);		// Set up pointers to new str
  }

  switch (int_type) {
  case INTERVAL_YEAR:
974
    interval->year=value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
975 976
    break;
  case INTERVAL_MONTH:
977
    interval->month=value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
978 979
    break;
  case INTERVAL_DAY:
980
    interval->day=value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
981 982
    break;
  case INTERVAL_HOUR:
983
    interval->hour=value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
984
    break;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
985
  case INTERVAL_MICROSECOND:
986
    interval->second_part=value;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
987
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
988
  case INTERVAL_MINUTE:
989
    interval->minute=value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
990 991
    break;
  case INTERVAL_SECOND:
992
    interval->second=value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
993 994
    break;
  case INTERVAL_YEAR_MONTH:			// Allow YEAR-MONTH YYYYYMM
995
    if (get_interval_info(str,length,cs,2,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
996
      return (1);
997 998
    interval->year=array[0];
    interval->month=array[1];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
999 1000
    break;
  case INTERVAL_DAY_HOUR:
1001
    if (get_interval_info(str,length,cs,2,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1002
      return (1);
1003 1004
    interval->day=array[0];
    interval->hour=array[1];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1005
    break;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1006
  case INTERVAL_DAY_MICROSECOND:
1007
    if (get_interval_info(str,length,cs,5,array,1))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1008
      return (1);
1009 1010 1011 1012 1013
    interval->day=array[0];
    interval->hour=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
1014
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1015
  case INTERVAL_DAY_MINUTE:
1016
    if (get_interval_info(str,length,cs,3,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1017
      return (1);
1018 1019 1020
    interval->day=array[0];
    interval->hour=array[1];
    interval->minute=array[2];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1021 1022
    break;
  case INTERVAL_DAY_SECOND:
1023
    if (get_interval_info(str,length,cs,4,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1024
      return (1);
1025 1026 1027 1028
    interval->day=array[0];
    interval->hour=array[1];
    interval->minute=array[2];
    interval->second=array[3];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1029
    break;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1030
  case INTERVAL_HOUR_MICROSECOND:
1031
    if (get_interval_info(str,length,cs,4,array,1))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1032
      return (1);
1033 1034 1035 1036
    interval->hour=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
1037
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1038
  case INTERVAL_HOUR_MINUTE:
1039
    if (get_interval_info(str,length,cs,2,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1040
      return (1);
1041 1042
    interval->hour=array[0];
    interval->minute=array[1];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1043 1044
    break;
  case INTERVAL_HOUR_SECOND:
1045
    if (get_interval_info(str,length,cs,3,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1046
      return (1);
1047 1048 1049
    interval->hour=array[0];
    interval->minute=array[1];
    interval->second=array[2];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1050
    break;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1051
  case INTERVAL_MINUTE_MICROSECOND:
1052
    if (get_interval_info(str,length,cs,3,array,1))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1053
      return (1);
1054 1055 1056
    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
1057
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1058
  case INTERVAL_MINUTE_SECOND:
1059
    if (get_interval_info(str,length,cs,2,array,0))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1060
      return (1);
1061 1062
    interval->minute=array[0];
    interval->second=array[1];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1063
    break;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1064
  case INTERVAL_SECOND_MICROSECOND:
1065
    if (get_interval_info(str,length,cs,2,array,1))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1066
      return (1);
1067 1068
    interval->second=array[0];
    interval->second_part=array[1];
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1069
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1070 1071 1072 1073 1074 1075 1076
  }
  return 0;
}


String *Item_date::val_str(String *str)
{
1077
  DBUG_ASSERT(fixed == 1);
1078
  TIME ltime;
1079 1080
  if (get_date(&ltime, TIME_FUZZY_DATE))
    return (String *) 0;
1081 1082 1083 1084 1085 1086 1087
  if (str->alloc(11))
  {
    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
1088 1089 1090
}


monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1091
int Item_date::save_in_field(Field *field, bool no_conversions)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1092 1093
{
  TIME ltime;
1094
  if (get_date(&ltime, TIME_FUZZY_DATE))
1095
    return set_field_to_null(field);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1096
  field->set_notnull();
1097
  field->store_time(&ltime, TIMESTAMP_DATE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1098 1099 1100 1101
  return 0;
}


1102 1103
longlong Item_date::val_int()
{
1104
  DBUG_ASSERT(fixed == 1);
1105 1106 1107 1108 1109 1110 1111 1112
  TIME ltime;
  if (get_date(&ltime, TIME_FUZZY_DATE))
    return 0;
  return (longlong) (ltime.year*10000L+ltime.month*100+ltime.day);
}


bool Item_func_from_days::get_date(TIME *ltime, uint fuzzy_date)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1113 1114 1115
{
  longlong value=args[0]->val_int();
  if ((null_value=args[0]->null_value))
1116
    return 1;
1117
  bzero(ltime, sizeof(TIME));
1118 1119 1120
  get_date_from_daynr((long) value, &ltime->year, &ltime->month, &ltime->day);
  ltime->time_type= TIMESTAMP_DATE;
  return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1121 1122 1123 1124 1125
}


void Item_func_curdate::fix_length_and_dec()
{
1126
  struct tm start;
1127
  
1128
  collation.set(&my_charset_bin);
1129
  decimals=0; 
1130
  max_length=MAX_DATE_WIDTH*MY_CHARSET_BIN_MB_MAXLEN;
1131

1132
  store_now_in_tm(current_thd->query_start(),&start);
1133 1134 1135 1136
  
  value=(longlong) ((ulong) ((uint) start.tm_year+1900)*10000L+
		    ((uint) start.tm_mon+1)*100+
		    (uint) start.tm_mday);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1137
  /* For getdate */
1138 1139 1140
  ltime.year=	start.tm_year+1900;
  ltime.month=	start.tm_mon+1;
  ltime.day=	start.tm_mday;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1141 1142 1143 1144 1145
  ltime.hour=	0;
  ltime.minute=	0;
  ltime.second=	0;
  ltime.second_part=0;
  ltime.neg=0;
1146
  ltime.time_type=TIMESTAMP_DATE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1147 1148
}

1149 1150
String *Item_func_curdate::val_str(String *str)
{
1151
  DBUG_ASSERT(fixed == 1);
1152 1153 1154 1155 1156 1157 1158 1159
  if (str->alloc(11))
  {
    null_value= 1;
    return (String *) 0;
  }
  make_date((DATE_TIME_FORMAT *) 0, &ltime, str);
  return str;
}
1160

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1161
bool Item_func_curdate::get_date(TIME *res,
1162
				 uint fuzzy_date __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1163 1164 1165 1166 1167
{
  *res=ltime;
  return 0;
}

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188

/*
    Converts time in time_t to struct tm represenatation for local timezone.
    Defines timezone (local) used for whole CURDATE function
*/
void Item_func_curdate_local::store_now_in_tm(time_t now, struct tm *now_tm)
{
  localtime_r(&now,now_tm);
}


/*
    Converts time in time_t to struct tm represenatation for UTC
    Defines timezone (UTC) used for whole UTC_DATE function
*/
void Item_func_curdate_utc::store_now_in_tm(time_t now, struct tm *now_tm)
{
  gmtime_r(&now,now_tm);
}


1189
String *Item_func_curtime::val_str(String *str)
1190 1191
{
  DBUG_ASSERT(fixed == 1);
1192
  str_value.set(buff, buff_length, &my_charset_bin);
1193 1194 1195
  return &str_value;
}

1196

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1197 1198
void Item_func_curtime::fix_length_and_dec()
{
1199
  struct tm start;
1200
  String tmp((char*) buff,sizeof(buff), &my_charset_bin);
1201
  TIME ltime;
1202 1203

  decimals=0; 
1204
  store_now_in_tm(current_thd->query_start(),&start);
1205 1206 1207
  value=(longlong) ((ulong) ((uint) start.tm_hour)*10000L+
		    (ulong) (((uint) start.tm_min)*100L+
			     (uint) start.tm_sec));
1208 1209 1210 1211 1212 1213
  ltime.day=	0;
  ltime.hour=	start.tm_hour;
  ltime.minute=	start.tm_min;
  ltime.second=	start.tm_sec;
  ltime.second_part= 0;
  ltime.neg= 0;
1214 1215
  make_time((DATE_TIME_FORMAT *) 0, &ltime, &tmp);
  max_length= buff_length= tmp.length();
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
}


/*
    Converts time in time_t to struct tm represenatation for local timezone.
    Defines timezone (local) used for whole CURTIME function
*/
void Item_func_curtime_local::store_now_in_tm(time_t now, struct tm *now_tm)
{
  localtime_r(&now,now_tm);
}


/*
    Converts time in time_t to struct tm represenatation for UTC.
    Defines timezone (UTC) used for whole UTC_TIME function
*/
void Item_func_curtime_utc::store_now_in_tm(time_t now, struct tm *now_tm)
{
  gmtime_r(&now,now_tm);
1236 1237
}

1238

1239 1240
String *Item_func_now::val_str(String *str)
{
1241
  DBUG_ASSERT(fixed == 1);
1242
  str_value.set(buff,buff_length, &my_charset_bin);
1243
  return &str_value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1244 1245
}

1246

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1247 1248
void Item_func_now::fix_length_and_dec()
{
1249
  struct tm start;
1250
  String tmp((char*) buff,sizeof(buff),&my_charset_bin);
1251

1252
  decimals=0;
1253 1254 1255
  collation.set(&my_charset_bin);

  store_now_in_tm(current_thd->query_start(),&start);
1256 1257 1258 1259 1260 1261
  value=((longlong) ((ulong) ((uint) start.tm_year+1900)*10000L+
		     (((uint) start.tm_mon+1)*100+
		      (uint) start.tm_mday))*(longlong) 1000000L+
	 (longlong) ((ulong) ((uint) start.tm_hour)*10000L+
		     (ulong) (((uint) start.tm_min)*100L+
			    (uint) start.tm_sec)));
1262
  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1263
  /* For getdate */
1264 1265 1266 1267 1268 1269
  ltime.year=	start.tm_year+1900;
  ltime.month=	start.tm_mon+1;
  ltime.day=	start.tm_mday;
  ltime.hour=	start.tm_hour;
  ltime.minute=	start.tm_min;
  ltime.second=	start.tm_sec;
1270 1271
  ltime.second_part= 0;
  ltime.neg= 0;
1272
  ltime.time_type= TIMESTAMP_DATETIME;
1273

1274 1275
  make_datetime((DATE_TIME_FORMAT *) 0, &ltime, &tmp);
  max_length= buff_length= tmp.length();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1276 1277
}

1278

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1279
bool Item_func_now::get_date(TIME *res,
1280
			     uint fuzzy_date __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1281 1282 1283 1284 1285 1286
{
  *res=ltime;
  return 0;
}


monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1287
int Item_func_now::save_in_field(Field *to, bool no_conversions)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1288 1289
{
  to->set_notnull();
1290
  to->store_time(&ltime,TIMESTAMP_DATETIME);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1291 1292 1293 1294
  return 0;
}


1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
/*
    Converts time in time_t to struct tm represenatation for local timezone.
    Defines timezone (local) used for whole CURRENT_TIMESTAMP function
*/
void Item_func_now_local::store_now_in_tm(time_t now, struct tm *now_tm)
{
  localtime_r(&now,now_tm);
}


/*
    Converts time in time_t to struct tm represenatation for UTC.
    Defines timezone (UTC) used for whole UTC_TIMESTAMP function
*/
void Item_func_now_utc::store_now_in_tm(time_t now, struct tm *now_tm)
{
  gmtime_r(&now,now_tm);
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1315 1316
String *Item_func_sec_to_time::val_str(String *str)
{
1317
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1318
  longlong seconds=(longlong) args[0]->val_int();
1319 1320 1321
  uint sec;
  TIME ltime;

1322 1323 1324 1325 1326
  if ((null_value=args[0]->null_value) || str->alloc(19))
  {
    null_value= 1;
    return (String*) 0;
  }
1327 1328

  ltime.neg= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1329 1330 1331
  if (seconds < 0)
  {
    seconds= -seconds;
1332
    ltime.neg= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1333
  }
1334 1335 1336

  sec= (uint) ((ulonglong) seconds % 3600);
  ltime.day= 0;
monty@mysql.com's avatar
monty@mysql.com committed
1337
  ltime.hour= (uint) (seconds/3600);
1338 1339 1340
  ltime.minute= sec/60;
  ltime.second= sec % 60;

1341 1342
  make_time((DATE_TIME_FORMAT *) 0, &ltime, str);
  return str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1343 1344 1345 1346 1347
}


longlong Item_func_sec_to_time::val_int()
{
1348
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
  longlong seconds=args[0]->val_int();
  longlong sign=1;
  if ((null_value=args[0]->null_value))
    return 0;
  if (seconds < 0)
  {
    seconds= -seconds;
    sign= -1;
  }
  return sign*((seconds / 3600)*10000+((seconds/60) % 60)*100+ (seconds % 60));
}


void Item_func_date_format::fix_length_and_dec()
{
  decimals=0;
1365
  collation.set(&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1366 1367 1368
  if (args[1]->type() == STRING_ITEM)
  {						// Optimize the normal case
    fixed_length=1;
1369 1370 1371 1372 1373
    /*
      The result is a binary string (no reason to use collation->mbmaxlen
      This is becasue make_date_time() only returns binary strings
    */
    max_length= format_length(((Item_string*) args[1])->const_string());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1374 1375 1376 1377
  }
  else
  {
    fixed_length=0;
1378 1379
    /* The result is a binary string (no reason to use collation->mbmaxlen */
    max_length=args[1]->max_length*10;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
    set_if_smaller(max_length,MAX_BLOB_WIDTH);
  }
  maybe_null=1;					// If wrong date
}


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 */
	size += 9;
	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) */
      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 'H': /* hour (00..23) */
      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 'k': /* hour ( 0..23) */
      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;
      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
1440 1441 1442
      case 'f': /* microseconds */
	size += 6;
	break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
      case 'w': /* day (of the week), numeric */
      case '%':
      default:
	size++;
	break;
      }
    }
  }
  return size;
}


String *Item_func_date_format::val_str(String *str)
{
1457
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1458 1459
  String *format;
  TIME l_time;
1460
  uint size;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1461

1462
  if (!is_time_format)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1463 1464 1465 1466 1467 1468 1469
  {
    if (get_arg0_date(&l_time,1))
      return 0;
  }
  else
  {
    String *res;
1470 1471
    if (!(res=args[0]->val_str(str)) ||
	(str_to_time(res->ptr(),res->length(),&l_time)))
1472 1473
      goto null_date;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1474 1475 1476 1477 1478
    l_time.year=l_time.month=l_time.day=0;
    null_value=0;
  }

  if (!(format = args[1]->val_str(str)) || !format->length())
1479
    goto null_date;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1480 1481 1482 1483 1484 1485

  if (fixed_length)
    size=max_length;
  else
    size=format_length(format);
  if (format == str)
monty@hundin.mysql.fi's avatar
merge  
monty@hundin.mysql.fi committed
1486
    str= &value;				// Save result here
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1487
  if (str->alloc(size))
1488 1489
    goto null_date;

1490 1491 1492
  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
1493 1494

  /* Create the result string */
1495 1496
  if (!make_date_time(&date_time_format, &l_time,
		      is_time_format ? TIMESTAMP_TIME : TIMESTAMP_DATE, str))
1497
    return str;
1498

1499 1500 1501
null_date:
  null_value=1;
  return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1502 1503 1504 1505 1506
}


String *Item_func_from_unixtime::val_str(String *str)
{
1507
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1508 1509
  struct tm tm_tmp,*start;
  time_t tmp=(time_t) args[0]->val_int();
1510
  TIME ltime;
1511
  
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1512
  if ((null_value=args[0]->null_value))
1513 1514
    goto null_date;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1515 1516
  localtime_r(&tmp,&tm_tmp);
  start=&tm_tmp;
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526

  ltime.year= start->tm_year+1900;
  ltime.month= start->tm_mon+1;
  ltime.day= start->tm_mday;
  ltime.hour= start->tm_hour;
  ltime.minute= start->tm_min;
  ltime.second= start->tm_sec;
  ltime.second_part= 0;
  ltime.neg=0;

1527 1528 1529 1530 1531
  if (str->alloc(20*MY_CHARSET_BIN_MB_MAXLEN))
    goto null_date;
  make_datetime((DATE_TIME_FORMAT *) 0, &ltime, str);
  return str;

1532
null_date:
1533
  null_value=1;
1534
  return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1535 1536 1537 1538 1539
}


longlong Item_func_from_unixtime::val_int()
{
1540
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
  time_t tmp=(time_t) (ulong) args[0]->val_int();
  if ((null_value=args[0]->null_value))
    return 0;
  struct tm tm_tmp,*start;
  localtime_r(&tmp,&tm_tmp);
  start= &tm_tmp;
  return ((longlong) ((ulong) ((uint) start->tm_year+1900)*10000L+
		      (((uint) start->tm_mon+1)*100+
		       (uint) start->tm_mday))*LL(1000000)+
	  (longlong) ((ulong) ((uint) start->tm_hour)*10000L+
		      (ulong) (((uint) start->tm_min)*100L+
			       (uint) start->tm_sec)));
}

bool Item_func_from_unixtime::get_date(TIME *ltime,
1556
				       uint fuzzy_date __attribute__((unused)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
{
  time_t tmp=(time_t) (ulong) args[0]->val_int();
  if ((null_value=args[0]->null_value))
    return 1;
  struct tm tm_tmp,*start;
  localtime_r(&tmp,&tm_tmp);
  start= &tm_tmp;
  ltime->year=	start->tm_year+1900;
  ltime->month=	start->tm_mon+1;
  ltime->day=	start->tm_mday;
  ltime->hour=	start->tm_hour;
  ltime->minute=start->tm_min;
  ltime->second=start->tm_sec;
  ltime->second_part=0;
  ltime->neg=0;
  return 0;
}

1575 1576 1577 1578

void Item_date_add_interval::fix_length_and_dec()
{
  enum_field_types arg0_field_type;
1579 1580

  collation.set(&my_charset_bin);
1581
  maybe_null=1;
1582 1583
  max_length=MAX_DATETIME_FULL_WIDTH*MY_CHARSET_BIN_MB_MAXLEN;
  value.alloc(max_length);
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602

  /*
    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
      (This is because you can't know if the string contains a DATE, TIME or
      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)
  {
1603
    if (int_type <= INTERVAL_DAY || int_type == INTERVAL_YEAR_MONTH)
1604 1605 1606 1607 1608 1609 1610 1611
      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
1612

1613
bool Item_date_add_interval::get_date(TIME *ltime, uint fuzzy_date)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1614 1615 1616
{
  long period,sign;
  INTERVAL interval;
1617

1618
  ltime->neg= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
  if (args[0]->get_date(ltime,0) ||
      get_interval_value(args[1],int_type,&value,&interval))
    goto null_date;
  sign= (interval.neg ? -1 : 1);
  if (date_sub_interval)
    sign = -sign;

  null_value=0;
  switch (int_type) {
  case INTERVAL_SECOND:
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1629 1630
  case INTERVAL_SECOND_MICROSECOND:
  case INTERVAL_MICROSECOND:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1631 1632
  case INTERVAL_MINUTE:
  case INTERVAL_HOUR:
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1633
  case INTERVAL_MINUTE_MICROSECOND:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1634
  case INTERVAL_MINUTE_SECOND:
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1635
  case INTERVAL_HOUR_MICROSECOND:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1636 1637
  case INTERVAL_HOUR_SECOND:
  case INTERVAL_HOUR_MINUTE:
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1638
  case INTERVAL_DAY_MICROSECOND:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1639 1640 1641
  case INTERVAL_DAY_SECOND:
  case INTERVAL_DAY_MINUTE:
  case INTERVAL_DAY_HOUR:
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1642
    long sec,days,daynr,microseconds,extra_sec;
1643
    ltime->time_type=TIMESTAMP_DATETIME;		// Return full date
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1644 1645 1646
    microseconds= ltime->second_part + sign*interval.second_part;
    extra_sec= microseconds/1000000L;
    microseconds= microseconds%1000000L;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1647 1648 1649 1650

    sec=((ltime->day-1)*3600*24L+ltime->hour*3600+ltime->minute*60+
	 ltime->second +
	 sign*(interval.day*3600*24L +
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1651 1652 1653 1654 1655 1656 1657 1658
	       interval.hour*3600+interval.minute*60+interval.second))+
      extra_sec;

    if (microseconds < 0)
    {
      microseconds+= 1000000L;	
      sec--;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1659 1660 1661 1662 1663 1664
    days=sec/(3600*24L); sec=sec-days*3600*24L;
    if (sec < 0)
    {
      days--;
      sec+=3600*24L;
    }
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1665
    ltime->second_part= microseconds;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1666 1667 1668 1669 1670
    ltime->second=sec % 60;
    ltime->minute=sec/60 % 60;
    ltime->hour=sec/3600;
    daynr= calc_daynr(ltime->year,ltime->month,1) + days;
    get_date_from_daynr(daynr,&ltime->year,&ltime->month,&ltime->day);
1671
    if (daynr < 0 || daynr >= MAX_DAY_NUMBER) // Day number from year 0 to 9999-12-31
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1672 1673 1674 1675 1676
      goto null_date;
    break;
  case INTERVAL_DAY:
    period= calc_daynr(ltime->year,ltime->month,ltime->day) +
      sign*interval.day;
1677
    if (period < 0 || period >= MAX_DAY_NUMBER) // Daynumber from year 0 to 9999-12-31
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
      goto null_date;
    get_date_from_daynr((long) period,&ltime->year,&ltime->month,&ltime->day);
    break;
  case INTERVAL_YEAR:
    ltime->year += sign*interval.year;
    if ((int) ltime->year < 0 || ltime->year >= 10000L)
      goto null_date;
    if (ltime->month == 2 && ltime->day == 29 &&
	calc_days_in_year(ltime->year) != 366)
      ltime->day=28;				// Was leap-year
    break;
  case INTERVAL_YEAR_MONTH:
  case INTERVAL_MONTH:
    period= (ltime->year*12 + sign*interval.year*12 +
	     ltime->month-1 + sign*interval.month);
    if (period < 0 || period >= 120000L)
      goto null_date;
    ltime->year= (uint) (period / 12);
    ltime->month= (uint) (period % 12L)+1;
    /* Adjust day if the new month doesn't have enough days */
    if (ltime->day > days_in_month[ltime->month-1])
    {
      ltime->day = days_in_month[ltime->month-1];
      if (ltime->month == 2 && calc_days_in_year(ltime->year) == 366)
	ltime->day++;				// Leap-year
    }
    break;
  default:
    goto null_date;
  }
  return 0;					// Ok

 null_date:
  return (null_value=1);
}


String *Item_date_add_interval::val_str(String *str)
{
1717
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1718
  TIME ltime;
1719
  enum date_time_format_types format;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1720 1721 1722

  if (Item_date_add_interval::get_date(&ltime,0))
    return 0;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1723

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1724
  if (ltime.time_type == TIMESTAMP_DATE)
1725 1726 1727 1728 1729 1730 1731
    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
1732
    return str;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1733 1734 1735 1736 1737

  null_value=1;
  return 0;
}

1738

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1739 1740
longlong Item_date_add_interval::val_int()
{
1741
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1742
  TIME ltime;
1743
  longlong date;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1744 1745
  if (Item_date_add_interval::get_date(&ltime,0))
    return (longlong) 0;
1746 1747 1748
  date = (ltime.year*100L + ltime.month)*100L + ltime.day;
  return ltime.time_type == TIMESTAMP_DATE ? date :
    ((date*100L + ltime.hour)*100L+ ltime.minute)*100L + ltime.second;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1749 1750
}

1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
static const char *interval_names[]=
{
  "year", "month", "day", "hour", "minute",
  "second", "microsecond", "year_month",
  "day_hour", "day_minute", "day_second",
  "hour_minute", "hour_second", "minute_second",
  "day_microsecond", "hour_microsecond",
  "minute_microsecond", "second_microsecond"
};

void Item_date_add_interval::print(String *str)
{
  str->append('(');
  args[0]->print(str);
  str->append(date_sub_interval?" - interval ":" + interval ");
  args[1]->print(str);
1767
  str->append(' ');
1768 1769 1770 1771 1772 1773
  str->append(interval_names[int_type]);
  str->append(')');
}

void Item_extract::print(String *str)
{
1774
  str->append("extract(", 8);
1775
  str->append(interval_names[int_type]);
1776
  str->append(" from ", 6);
1777 1778 1779 1780
  args[0]->print(str);
  str->append(')');
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
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;
  case INTERVAL_MONTH:		max_length=2; date_value=1; break;
  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
1800 1801 1802 1803 1804
  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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1805 1806 1807 1808 1809 1810
  }
}


longlong Item_extract::val_int()
{
1811
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
  TIME ltime;
  long neg;
  if (date_value)
  {
    if (get_arg0_date(&ltime,1))
      return 0;
    neg=1;
  }
  else
  {
    String *res= args[0]->val_str(&value);
1823
    if (!res || str_to_time(res->ptr(),res->length(),&ltime))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
    {
      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;
  case INTERVAL_MONTH:		return ltime.month;
  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
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
  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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1866 1867 1868
  }
  return 0;					// Impossible
}
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1869

hf@deer.(none)'s avatar
hf@deer.(none) committed
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885
bool Item_extract::eq(const Item *item, bool binary_cmp) const
{
  if (this == item)
    return 1;
  if (item->type() != FUNC_ITEM ||
      func_name() != ((Item_func*)item)->func_name())
    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
1886

1887

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1888 1889
void Item_typecast::print(String *str)
{
1890
  str->append("cast(", 5);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1891
  args[0]->print(str);
1892
  str->append(" as ", 4);
1893 1894 1895 1896
  str->append(cast_type());
  str->append(')');
}

1897

1898 1899
void Item_char_typecast::print(String *str)
{
1900
  str->append("cast(", 5);
1901
  args[0]->print(str);
1902
  str->append(" as char", 8);
1903 1904 1905
  if (cast_length >= 0)
  {
    str->append('(');
1906
    char buffer[20];
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
1907 1908 1909
    // my_charset_bin is good enough for numbers
    String st(buffer, sizeof(buffer), &my_charset_bin);
    st.set((ulonglong)cast_length, &my_charset_bin);
1910
    str->append(st);
1911 1912 1913 1914
    str->append(')');
  }
  if (cast_cs)
  {
1915
    str->append(" charset ", 9);
1916 1917
    str->append(cast_cs->name);
  }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1918 1919
  str->append(')');
}
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
1920

1921 1922
String *Item_char_typecast::val_str(String *str)
{
1923
  DBUG_ASSERT(fixed == 1);
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942
  String *res, *res1;
  uint32 length;

  if (!charset_conversion && !(res= args[0]->val_str(str)))
  {
    null_value= 1;
    return 0;
  }
  else
  {
    // Convert character set if differ
    if (!(res1= args[0]->val_str(&tmp_value)) ||
	str->copy(res1->ptr(), res1->length(),res1->charset(), cast_cs))
    {
      null_value= 1;
      return 0;
    }
    res= str;
  }
1943 1944

  res->set_charset(cast_cs);
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
  
  /*
     Cut the tail if cast with length
     and the result is longer than cast length, e.g.
     CAST('string' AS CHAR(1))
  */
  if (cast_length >= 0 && 
      (res->length() > (length= (uint32) res->charpos(cast_length))))
  {						// Safe even if const arg
    if (!res->alloced_length())
    {						// Don't change const str
      str_value= *res;				// Not malloced string
      res= &str_value;
    }
    res->length((uint) length);
  } 
  null_value= 0;
  return res;
}

void Item_char_typecast::fix_length_and_dec()
{
  uint32 char_length;
  charset_conversion= !my_charset_same(args[0]->collation.collation, cast_cs) &&
		      args[0]->collation.collation != &my_charset_bin &&
		      cast_cs != &my_charset_bin;
  collation.set(cast_cs, DERIVATION_IMPLICIT);
  char_length= (cast_length >= 0) ? cast_length : 
	       args[0]->max_length/args[0]->collation.collation->mbmaxlen;
  max_length= char_length * cast_cs->mbmaxlen;
}

1977

1978 1979
String *Item_datetime_typecast::val_str(String *str)
{
1980
  DBUG_ASSERT(fixed == 1);
1981 1982
  TIME ltime;
  if (!get_arg0_date(&ltime,1) &&
1983 1984
      !make_datetime(ltime.second_part ? DATE_TIME_MICROSECOND : DATE_TIME, 
		     &ltime, str))
monty@mysql.com's avatar
monty@mysql.com committed
1985
    return str;
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001

  null_value=1;
  return 0;
}


bool Item_time_typecast::get_time(TIME *ltime)
{
  bool res= get_arg0_time(ltime);
  ltime->time_type= TIMESTAMP_TIME;
  return res;
}


String *Item_time_typecast::val_str(String *str)
{
2002
  DBUG_ASSERT(fixed == 1);
2003 2004 2005
  TIME ltime;

  if (!get_arg0_time(&ltime) &&
2006 2007
      !make_datetime(ltime.second_part ? TIME_MICROSECOND : TIME_ONLY,
		     &ltime, str))
2008 2009 2010 2011 2012 2013 2014
    return str;

  null_value=1;
  return 0;
}


2015
bool Item_date_typecast::get_date(TIME *ltime, uint fuzzy_date)
2016 2017 2018 2019 2020 2021 2022 2023 2024
{
  bool res= get_arg0_date(ltime,1);
  ltime->time_type= TIMESTAMP_DATE;
  return res;
}


String *Item_date_typecast::val_str(String *str)
{
2025
  DBUG_ASSERT(fixed == 1);
2026 2027
  TIME ltime;

2028 2029 2030 2031 2032
  if (!get_arg0_date(&ltime,1) && !str->alloc(11))
  {
    make_date((DATE_TIME_FORMAT *) 0,&ltime, str);
    return str;
  }
2033 2034 2035 2036 2037

  null_value=1;
  return 0;
}

2038

gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2039 2040 2041 2042 2043 2044 2045
/*
  MAKEDATE(a,b) is a date function that creates a date value 
  from a year and day value.
*/

String *Item_func_makedate::val_str(String *str)
{
2046
  DBUG_ASSERT(fixed == 1);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2047
  TIME l_time;
monty@mysql.com's avatar
monty@mysql.com committed
2048 2049
  long daynr=  (long) args[1]->val_int();
  long yearnr= (long) args[0]->val_int();
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2050 2051 2052 2053
  long days;

  if (args[0]->null_value || args[1]->null_value ||
      yearnr < 0 || daynr <= 0)
2054
    goto err;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2055 2056

  days= calc_daynr(yearnr,1,1) + daynr - 1;
monty@mysql.com's avatar
monty@mysql.com committed
2057
  /* Day number from year 0 to 9999-12-31 */
2058
  if (days >= 0 && days < MAX_DAY_NUMBER)
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2059 2060 2061
  {
    null_value=0;
    get_date_from_daynr(days,&l_time.year,&l_time.month,&l_time.day);
2062 2063 2064 2065
    if (str->alloc(11))
      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
2066 2067
  }

2068
err:
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2069 2070 2071 2072 2073 2074 2075 2076 2077
  null_value=1;
  return 0;
}


void Item_func_add_time::fix_length_and_dec()
{
  enum_field_types arg0_field_type;
  decimals=0;
2078
  max_length=MAX_DATETIME_FULL_WIDTH*MY_CHARSET_BIN_MB_MAXLEN;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2079 2080

  /*
2081 2082
    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
2083 2084 2085 2086 2087 2088 2089 2090 2091

    - 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();
2092 2093
  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
2094 2095 2096 2097 2098 2099 2100
      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;
}

/*
2101 2102
  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
2103 2104 2105 2106 2107 2108 2109 2110 2111

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

String *Item_func_add_time::val_str(String *str)
{
2112
  DBUG_ASSERT(fixed == 1);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2113
  TIME l_time1, l_time2, l_time3;
2114
  bool is_time= 0;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2115 2116 2117 2118 2119
  long microseconds, seconds, days= 0;
  int l_sign= sign;

  null_value=0;
  l_time3.neg= 0;
2120 2121 2122 2123 2124 2125 2126 2127 2128
  if (is_date)                        // TIMESTAMP function
  {
    if (get_arg0_date(&l_time1,1) || 
        args[1]->get_time(&l_time2) ||
        l_time1.time_type == TIMESTAMP_TIME || 
        l_time2.time_type != TIMESTAMP_TIME)
      goto null_date;
  }
  else                                // ADDTIME function
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2129
  {
2130 2131
    if (args[0]->get_time(&l_time1) || 
        args[1]->get_time(&l_time2) ||
2132
        l_time2.time_type == TIMESTAMP_DATETIME)
2133 2134 2135
      goto null_date;
    is_time= (l_time1.time_type == TIMESTAMP_TIME);
    if (is_time && (l_time2.neg == l_time1.neg && l_time1.neg))
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
      l_time3.neg= 1;
  }
  if (l_time1.neg != l_time2.neg)
    l_sign= -l_sign;

  microseconds= l_time1.second_part + l_sign*l_time2.second_part;
  seconds= (l_time1.hour*3600L + l_time1.minute*60L + l_time1.second +
	    (l_time2.day*86400L + l_time2.hour*3600L +
	     l_time2.minute*60L + l_time2.second)*l_sign);
  if (is_time)
    seconds+= l_time1.day*86400L;
  else
2148 2149
    days+= calc_daynr((uint) l_time1.year,(uint) l_time1.month,
		      (uint) l_time1.day);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
  seconds= seconds + microseconds/1000000L;
  microseconds= microseconds%1000000L;
  days+= seconds/86400L;
  seconds= seconds%86400L;

  if (microseconds < 0)
  {
    microseconds+= 1000000L;
    seconds--;
  }
  if (seconds < 0)
  {
    days+= seconds/86400L - 1;
    seconds+= 86400L;
  }
  if (days < 0)
  {
    if (!is_time)
      goto null_date;
    if (microseconds)
    {
      microseconds= 1000000L - microseconds;
      seconds++; 
    }
    seconds= 86400L - seconds;
    days= -(++days);
    l_time3.neg= 1;
  }

  calc_time_from_sec(&l_time3, seconds, microseconds);
  if (!is_time)
  {
    get_date_from_daynr(days,&l_time3.year,&l_time3.month,&l_time3.day);
    if (l_time3.day &&
2184 2185 2186
	!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
2187 2188 2189
      return str;
    goto null_date;
  }
2190
  
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2191
  l_time3.hour+= days*24;
2192 2193 2194
  if (!make_datetime(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
2195 2196 2197 2198 2199 2200 2201
    return str;

null_date:
  null_value=1;
  return 0;
}

2202 2203 2204 2205 2206 2207

void Item_func_add_time::print(String *str)
{
  if (is_date)
  {
    DBUG_ASSERT(sign > 0);
2208
    str->append("timestamp(", 10);
2209 2210 2211 2212
  }
  else
  {
    if (sign > 0)
2213
      str->append("addtime(", 8);
2214
    else
2215
      str->append("subtime(", 8);
2216 2217 2218 2219 2220 2221 2222 2223
  }
  args[0]->print(str);
  str->append(',');
  args[0]->print(str);
  str->append(')');
}


gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
/*
  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)
{
2234
  DBUG_ASSERT(fixed == 1);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262
  longlong seconds;
  long microseconds;
  long days;
  int l_sign= 1;
  TIME l_time1 ,l_time2, l_time3;

  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;

  if (l_time1.time_type == TIMESTAMP_TIME)  // Time value
    days= l_time1.day - l_sign*l_time2.day;
  else                                      // DateTime value
    days= (calc_daynr((uint) l_time1.year,
		      (uint) l_time1.month,
		      (uint) l_time1.day) - 
	   l_sign*calc_daynr((uint) l_time2.year,
			     (uint) l_time2.month,
			     (uint) l_time2.day));

  microseconds= l_time1.second_part - l_sign*l_time2.second_part;
  seconds= ((longlong) days*86400L + l_time1.hour*3600L + 
	    l_time1.minute*60L + l_time1.second + microseconds/1000000L -
monty@mysql.com's avatar
monty@mysql.com committed
2263 2264
	    (longlong)l_sign*(l_time2.hour*3600L+l_time2.minute*60L+
			      l_time2.second));
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284

  l_time3.neg= 0;
  if (seconds < 0)
  {
    seconds= -seconds;
    l_time3.neg= 1;
  }
  else if (seconds == 0 && microseconds < 0)
  {
    microseconds= -microseconds;
    l_time3.neg= 1;
  }
  if (microseconds < 0)
  {
    microseconds+= 1000000L;
    seconds--;
  }
  if ((l_time2.neg == l_time1.neg) && l_time1.neg)
    l_time3.neg= l_time3.neg ? 0 : 1;

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

2287 2288 2289
  if (!make_datetime(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
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
    return str;

null_date:
  null_value=1;
  return 0;
}

/*
  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)
{
2305
  DBUG_ASSERT(fixed == 1);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2306 2307
  TIME ltime;

monty@mysql.com's avatar
monty@mysql.com committed
2308 2309 2310
  long hour=   (long) args[0]->val_int();
  long minute= (long) args[1]->val_int();
  long second= (long) args[2]->val_int();
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2311 2312 2313 2314 2315

  if ((null_value=(args[0]->null_value || 
		   args[1]->null_value ||
		   args[2]->null_value || 
		   minute > 59 || minute < 0 || 
2316 2317 2318
		   second > 59 || second < 0 ||
		   str->alloc(19))))
    return 0;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2319 2320 2321 2322 2323 2324 2325

  ltime.neg= 0;
  if (hour < 0)
  {
    ltime.neg= 1;
    hour= -hour;
  }
monty@mysql.com's avatar
monty@mysql.com committed
2326 2327 2328
  ltime.hour=   (ulong) hour;
  ltime.minute= (ulong) minute;
  ltime.second= (ulong) second;
2329 2330
  make_time((DATE_TIME_FORMAT *) 0, &ltime, str);
  return str;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2331 2332
}

2333

gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2334
/*
2335 2336
  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
2337 2338 2339 2340

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

gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2342 2343
longlong Item_func_microsecond::val_int()
{
2344
  DBUG_ASSERT(fixed == 1);
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2345 2346 2347 2348 2349
  TIME ltime;
  if (!get_arg0_time(&ltime))
    return ltime.second_part;
  return 0;
}
2350 2351 2352 2353


String *Item_func_get_format::val_str(String *str)
{
2354
  DBUG_ASSERT(fixed == 1);
2355 2356 2357 2358
  const char *format_name;
  KNOWN_DATE_TIME_FORMAT *format;
  String *val= args[0]->val_str(str);
  ulong val_len;
2359

2360 2361 2362 2363 2364 2365 2366
  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++)
2367
  {
2368 2369 2370 2371 2372 2373
    uint format_name_len;
    format_name_len= strlen(format_name);
    if (val_len == format_name_len &&
	!my_strnncoll(&my_charset_latin1, 
		      (const uchar *) val->ptr(), val_len, 
		      (const uchar *) format_name, val_len))
2374
    {
2375 2376 2377
      const char *format_str= get_date_time_format_str(format, type);
      str->set(format_str, strlen(format_str), &my_charset_bin);
      return str;
2378 2379 2380
    }
  }

2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
  null_value= 1;
  return 0;
}


void Item_func_get_format::print(String *str)
{
  str->append(func_name());
  str->append('(');

  switch (type) {
  case TIMESTAMP_DATE:
    str->append("DATE, ");
    break;
  case TIMESTAMP_DATETIME:
    str->append("DATETIME, ");
    break;
  case TIMESTAMP_TIME:
    str->append("TIME, ");
    break;
  default:
    DBUG_ASSERT(0);
  }
  args[0]->print(str);
  str->append(')');
}


2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505
/*
  check_result_type(s, l) returns DATE/TIME type
  according to format string

  s: DATE/TIME format string
  l: length of s
  Result: date_time_format_types value:
          DATE_TIME_MICROSECOND, DATE_TIME,
          TIME_MICROSECOND, TIME_ONLY

  We don't process day format's characters('D', 'd', 'e')
  because day may be a member of all date/time types.
  If only day format's character and no time part present
  the result type is MYSQL_TYPE_DATE
*/

date_time_format_types  check_result_type(const char *format, uint length)
{
  const char *time_part_frms= "HISThiklrs";
  const char *date_part_frms= "MUYWabcjmuyw";
  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++;
      if ((frac_second_used= (*val == 'f')) ||
	  (!time_part_used && strchr(time_part_frms, *val)))
	time_part_used= 1;
      else if (!date_part_used && strchr(date_part_frms, *val))
	date_part_used= 1;
      if (time_part_used && date_part_used && frac_second_used)
	return DATE_TIME_MICROSECOND;
    }
  }

  if (time_part_used)
  {
    if (date_part_used)
      return DATE_TIME;
    if (frac_second_used)
      return TIME_MICROSECOND;
    return TIME_ONLY;
  }
  return DATE_ONLY;
}


Field *Item_func_str_to_date::tmp_table_field(TABLE *t_arg)
{
  if (cached_field_type == MYSQL_TYPE_TIME)
    return (new Field_time(maybe_null, name, t_arg, &my_charset_bin));
  if (cached_field_type == MYSQL_TYPE_DATE)
    return (new Field_date(maybe_null, name, t_arg, &my_charset_bin));
  if (cached_field_type == MYSQL_TYPE_DATETIME)
    return (new Field_datetime(maybe_null, name, t_arg, &my_charset_bin));
  return (new Field_string(max_length, maybe_null, name, t_arg, &my_charset_bin));
}


void Item_func_str_to_date::fix_length_and_dec()
{
  char format_buff[64];
  String format_str(format_buff, sizeof(format_buff), &my_charset_bin), *format;
  maybe_null= 1;
  decimals=0;
  cached_field_type= MYSQL_TYPE_STRING;
  max_length= MAX_DATETIME_FULL_WIDTH*MY_CHARSET_BIN_MB_MAXLEN;
  cached_timestamp_type= TIMESTAMP_NONE;
  if ((const_item= args[1]->const_item()))
  {
    format= args[1]->val_str(&format_str);
    cached_format_type= check_result_type(format->ptr(), format->length());
    switch (cached_format_type) {
    case DATE_ONLY:
      cached_timestamp_type= 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= TIMESTAMP_TIME;
      cached_field_type= MYSQL_TYPE_TIME; 
      max_length= MAX_TIME_WIDTH*MY_CHARSET_BIN_MB_MAXLEN;
      break;
    default:
      cached_timestamp_type= TIMESTAMP_DATETIME;
      cached_field_type= MYSQL_TYPE_DATETIME; 
      break;
    }
  }
}

2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
bool Item_func_str_to_date::get_date(TIME *ltime, uint fuzzy_date)
{
  DATE_TIME_FORMAT date_time_format;
  char val_buff[64], format_buff[64];
  String val_str(val_buff, sizeof(val_buff), &my_charset_bin), *val;
  String format_str(format_buff, sizeof(format_buff), &my_charset_bin), *format;

  val=    args[0]->val_str(&val_str);
  format= args[1]->val_str(&format_str);
  if (args[0]->null_value || args[1]->null_value)
    goto null_date;

2518
  null_value= 0;
2519 2520 2521 2522
  bzero((char*) ltime, sizeof(ltime));
  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(),
2523
			ltime, cached_timestamp_type))
2524
    goto null_date;
2525 2526 2527 2528 2529 2530 2531 2532 2533 2534
  if (cached_timestamp_type == TIMESTAMP_TIME && ltime->day)
  {
    /*
      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;
  }
2535 2536 2537 2538
  return 0;

null_date:
  return (null_value=1);
2539 2540 2541 2542 2543
}


String *Item_func_str_to_date::val_str(String *str)
{
2544
  DBUG_ASSERT(fixed == 1);
2545 2546
  TIME ltime;

2547 2548
  if (Item_func_str_to_date::get_date(&ltime, TIME_FUZZY_DATE))
    return 0;
2549

2550 2551
  if (!make_datetime((const_item ? cached_format_type :
		     (ltime.second_part ? DATE_TIME_MICROSECOND : DATE_TIME)),
2552 2553
		     &ltime, str))
    return str;
2554 2555
  return 0;
}
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2556 2557


2558
bool Item_func_last_day::get_date(TIME *ltime, uint fuzzy_date)
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2559
{
2560 2561 2562 2563 2564 2565 2566
  if (get_arg0_date(ltime,fuzzy_date))
    return 1;
  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;
  ltime->time_type= TIMESTAMP_DATE;
gluh@gluh.mysql.r18.ru's avatar
gluh@gluh.mysql.r18.ru committed
2567 2568
  return 0;
}