drizzle
C++ MySQL-protocol-compatible database server
Loading...
Searching...
No Matches
type/time.cc
1/* Copyright (C) 2004-2006 MySQL AB
2
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; version 2 of the License.
6
7 This program is distributed in the hope that it will be useful,
8 but WITHOUT ANY WARRANTY; without even the implied warranty of
9 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 GNU General Public License for more details.
11
12 You should have received a copy of the GNU General Public License
13 along with this program; if not, write to the Free Software
14 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15
16#include <config.h>
17
18#include <drizzled/type/time.h>
19
20#include <drizzled/util/gmtime.h>
21
22#include <drizzled/internal/m_string.h>
23#include <drizzled/charset.h>
24#include <drizzled/util/test.h>
26#include <drizzled/sql_string.h>
27
28#include <cstdio>
29#include <algorithm>
30
31using namespace std;
32
33namespace drizzled {
34
35static int check_time_range(type::Time *my_time, int *warning);
36
37/* Windows version of localtime_r() is declared in my_ptrhead.h */
38
39uint64_t log_10_int[20]=
40{
41 1, 10, 100, 1000, 10000UL, 100000UL, 1000000UL, 10000000UL,
42 100000000ULL, 1000000000ULL, 10000000000ULL, 100000000000ULL,
43 1000000000000ULL, 10000000000000ULL, 100000000000000ULL,
44 1000000000000000ULL, 10000000000000000ULL, 100000000000000000ULL,
45 1000000000000000000ULL, 10000000000000000000ULL
46};
47
48
49/* Position for YYYY-DD-MM HH-MM-DD.FFFFFF AM in default format */
50
51static unsigned char internal_format_positions[]=
52{0, 1, 2, 3, 4, 5, 6, (unsigned char) 255};
53
54static char time_separator=':';
55
56static uint32_t const days_at_timestart=719528; /* daynr at 1970.01.01 */
57unsigned char days_in_month[]= {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0};
58
59/*
60 Offset of system time zone from UTC in seconds used to speed up
61 work of my_system_gmt_sec() function.
62*/
63static long my_time_zone=0;
64
65
66/* Calc days in one year. works with 0 <= year <= 99 */
67
68uint32_t calc_days_in_year(uint32_t year)
69{
70 return ((year & 3) == 0 && (year%100 || (year%400 == 0 && year)) ?
71 366 : 365);
72}
73
74
75namespace type {
96
97bool Time::check(bool not_zero_date, uint32_t flags, type::cut_t &was_cut) const
98{
99 if (not_zero_date)
100 {
101 if ((((flags & TIME_NO_ZERO_IN_DATE) || !(flags & TIME_FUZZY_DATE)) &&
102 (month == 0 || day == 0)) ||
103 (not (flags & TIME_INVALID_DATES) &&
104 month && day > days_in_month[month-1] &&
105 (month != 2 || calc_days_in_year(year) != 366 ||
106 day != 29)))
107 {
108 was_cut= type::INVALID;
109 return true;
110 }
111 }
112 else if (flags & TIME_NO_ZERO_DATE)
113 {
114 /*
115 We don't set &was_cut here to signal that the problem was a zero date
116 and not an invalid date
117 */
118 return true;
119 }
120 return false;
121}
122
123/*
124 Convert a timestamp string to a type::Time value.
125
126 SYNOPSIS
127 store()
128 str String to parse
129 length Length of string
130 l_time Date is stored here
131 flags Bitmap of following items
132 TIME_FUZZY_DATE Set if we should allow partial dates
133 TIME_DATETIME_ONLY Set if we only allow full datetimes.
134 TIME_NO_ZERO_IN_DATE Don't allow partial dates
135 TIME_NO_ZERO_DATE Don't allow 0000-00-00 date
136 TIME_INVALID_DATES Allow 2000-02-31
137 was_cut 0 Value OK
138 1 If value was cut during conversion
139 2 check(date,flags) considers date invalid
140
141 DESCRIPTION
142 At least the following formats are recogniced (based on number of digits)
143 YYMMDD, YYYYMMDD, YYMMDDHHMMSS, YYYYMMDDHHMMSS
144 YY-MM-DD, YYYY-MM-DD, YY-MM-DD HH.MM.SS
145 YYYYMMDDTHHMMSS where T is a the character T (ISO8601)
146 Also dates where all parts are zero are allowed
147
148 The second part may have an optional .###### fraction part.
149
150 NOTES
151 This function should work with a format position vector as long as the
152 following things holds:
153 - All date are kept together and all time parts are kept together
154 - Date and time parts must be separated by blank
155 - Second fractions must come after second part and be separated
156 by a '.'. (The second fractions are optional)
157 - AM/PM must come after second fractions (or after seconds if no fractions)
158 - Year must always been specified.
159 - If time is before date, then we will use datetime format only if
160 the argument consist of two parts, separated by space.
161 Otherwise we will assume the argument is a date.
162 - The hour part must be specified in hour-minute-second order.
163
164 RETURN VALUES
165 DRIZZLE_TIMESTAMP_NONE String wasn't a timestamp, like
166 [DD [HH:[MM:[SS]]]].fraction.
167 l_time is not changed.
168 DRIZZLE_TIMESTAMP_DATE DATE string (YY MM and DD parts ok)
169 DRIZZLE_TIMESTAMP_DATETIME Full timestamp
170 DRIZZLE_TIMESTAMP_ERROR Timestamp with wrong values.
171 All elements in l_time is set to 0
172*/
173
174#define MAX_DATE_PARTS 8
175
176type::timestamp_t Time::store(const char *str, uint32_t length, uint32_t flags, type::cut_t &was_cut)
177{
178 uint32_t field_length, year_length=4, digits, i, number_of_fields;
179 uint32_t date[MAX_DATE_PARTS], date_len[MAX_DATE_PARTS];
180 uint32_t add_hours= 0, start_loop;
181 uint32_t not_zero_date, allow_space;
182 bool is_internal_format;
183 const char *pos, *last_field_pos=NULL;
184 const char *end=str+length;
185 const unsigned char *format_position;
186 bool found_delimitier= 0, found_space= 0;
187 uint32_t frac_pos, frac_len;
188
189 was_cut= type::VALID;
190
191 /* Skip space at start */
192 for (; str != end && my_charset_utf8_general_ci.isspace(*str) ; str++)
193 ;
194
195 if (str == end || not my_charset_utf8_general_ci.isdigit(*str))
196 {
197 was_cut= type::CUT;
198 return(type::DRIZZLE_TIMESTAMP_NONE);
199 }
200
201 is_internal_format= 0;
202 /* This has to be changed if want to activate different timestamp formats */
203 format_position= internal_format_positions;
204
205 /*
206 Calculate number of digits in first part.
207 If length= 8 or >= 14 then year is of format YYYY.
208 (YYYY-MM-DD, YYYYMMDD, YYYYYMMDDHHMMSS)
209 */
210 for (pos=str;
211 pos != end && (my_charset_utf8_general_ci.isdigit(*pos) || *pos == 'T');
212 pos++)
213 ;
214
215 digits= (uint32_t) (pos-str);
216 start_loop= 0; /* Start of scan loop */
217 date_len[format_position[0]]= 0; /* Length of year field */
218 if (pos == end || *pos == '.')
219 {
220 /* Found date in internal format (only numbers like YYYYMMDD) */
221 year_length= (digits == 4 || digits == 8 || digits >= 14) ? 4 : 2;
222 field_length= year_length;
223 is_internal_format= 1;
224 format_position= internal_format_positions;
225 }
226 else
227 {
228 if (format_position[0] >= 3) /* If year is after HHMMDD */
229 {
230 /*
231 If year is not in first part then we have to determinate if we got
232 a date field or a datetime field.
233 We do this by checking if there is two numbers separated by
234 space in the input.
235 */
236 while (pos < end && not my_charset_utf8_general_ci.isspace(*pos))
237 pos++;
238 while (pos < end && not my_charset_utf8_general_ci.isdigit(*pos))
239 pos++;
240 if (pos == end)
241 {
242 if (flags & TIME_DATETIME_ONLY)
243 {
244 was_cut= type::CUT;
245 return(type::DRIZZLE_TIMESTAMP_NONE); /* Can't be a full datetime */
246 }
247 /* Date field. Set hour, minutes and seconds to 0 */
248 date[0]= date[1]= date[2]= date[3]= date[4]= 0;
249 start_loop= 5; /* Start with first date part */
250 }
251 }
252
253 field_length= format_position[0] == 0 ? 4 : 2;
254 }
255
256 /*
257 Only allow space in the first "part" of the datetime field and:
258 - after days, part seconds
259 - before and after AM/PM (handled by code later)
260
261 2003-03-03 20:00:20 AM
262 20:00:20.000000 AM 03-03-2000
263 */
264 i= max((uint32_t) format_position[0], (uint32_t) format_position[1]);
265 set_if_bigger(i, (uint32_t) format_position[2]);
266 allow_space= ((1 << i) | (1 << format_position[6]));
267 allow_space&= (1 | 2 | 4 | 8);
268
269 not_zero_date= 0;
270 for (i = start_loop;
271 i < MAX_DATE_PARTS-1 && str != end &&
272 my_charset_utf8_general_ci.isdigit(*str);
273 i++)
274 {
275 const char *start= str;
276 uint32_t tmp_value= (uint32_t) (unsigned char) (*str++ - '0');
277 while (str != end && my_charset_utf8_general_ci.isdigit(str[0]) &&
278 (!is_internal_format || --field_length))
279 {
280 tmp_value=tmp_value*10 + (uint32_t) (unsigned char) (*str - '0');
281 str++;
282 }
283 date_len[i]= (uint32_t) (str - start);
284 if (tmp_value > 999999) /* Impossible date part */
285 {
286 was_cut= type::CUT;
287 return(type::DRIZZLE_TIMESTAMP_NONE);
288 }
289 date[i]=tmp_value;
290 not_zero_date|= tmp_value;
291
292 /* Length of next field */
293 field_length= format_position[i+1] == 0 ? 4 : 2;
294
295 if ((last_field_pos= str) == end)
296 {
297 i++; /* Register last found part */
298 break;
299 }
300 /* Allow a 'T' after day to allow CCYYMMDDT type of fields */
301 if (i == format_position[2] && *str == 'T')
302 {
303 str++; /* ISO8601: CCYYMMDDThhmmss */
304 continue;
305 }
306 if (i == format_position[5]) /* Seconds */
307 {
308 if (*str == '.') /* Followed by part seconds */
309 {
310 str++;
311 field_length= 6; /* 6 digits */
312 }
313 continue;
314 }
315 while (str != end &&
316 (my_charset_utf8_general_ci.ispunct(*str) ||
317 my_charset_utf8_general_ci.isspace(*str)))
318 {
319 if (my_charset_utf8_general_ci.isspace(*str))
320 {
321 if (!(allow_space & (1 << i)))
322 {
323 was_cut= type::CUT;
324 return(type::DRIZZLE_TIMESTAMP_NONE);
325 }
326 found_space= 1;
327 }
328 str++;
329 found_delimitier= 1; /* Should be a 'normal' date */
330 }
331 /* Check if next position is AM/PM */
332 if (i == format_position[6]) /* Seconds, time for AM/PM */
333 {
334 i++; /* Skip AM/PM part */
335 if (format_position[7] != 255) /* If using AM/PM */
336 {
337 if (str+2 <= end && (str[1] == 'M' || str[1] == 'm'))
338 {
339 if (str[0] == 'p' || str[0] == 'P')
340 add_hours= 12;
341 else if (str[0] != 'a' || str[0] != 'A')
342 continue; /* Not AM/PM */
343 str+= 2; /* Skip AM/PM */
344 /* Skip space after AM/PM */
345 while (str != end && my_charset_utf8_general_ci.isspace(*str))
346 str++;
347 }
348 }
349 }
350 last_field_pos= str;
351 }
352 if (found_delimitier && !found_space && (flags & TIME_DATETIME_ONLY))
353 {
354 was_cut= type::CUT;
355 return(type::DRIZZLE_TIMESTAMP_NONE); /* Can't be a datetime */
356 }
357
358 str= last_field_pos;
359
360 number_of_fields= i - start_loop;
361 while (i < MAX_DATE_PARTS)
362 {
363 date_len[i]= 0;
364 date[i++]= 0;
365 }
366
367 do
368 {
369 if (not is_internal_format)
370 {
371 year_length= date_len[(uint32_t) format_position[0]];
372 if (!year_length) /* Year must be specified */
373 {
374 was_cut= type::CUT;
375 return(type::DRIZZLE_TIMESTAMP_NONE);
376 }
377
378 this->year= date[(uint32_t) format_position[0]];
379 this->month= date[(uint32_t) format_position[1]];
380 this->day= date[(uint32_t) format_position[2]];
381 this->hour= date[(uint32_t) format_position[3]];
382 this->minute= date[(uint32_t) format_position[4]];
383 this->second= date[(uint32_t) format_position[5]];
384
385 frac_pos= (uint32_t) format_position[6];
386 frac_len= date_len[frac_pos];
387 if (frac_len < 6)
388 date[frac_pos]*= (uint32_t) log_10_int[6 - frac_len];
389 this->second_part= date[frac_pos];
390
391 if (format_position[7] != (unsigned char) 255)
392 {
393 if (this->hour > 12)
394 {
395 was_cut= type::CUT;
396 break;
397 }
398 this->hour= this->hour%12 + add_hours;
399 }
400 }
401 else
402 {
403 this->year= date[0];
404 this->month= date[1];
405 this->day= date[2];
406 this->hour= date[3];
407 this->minute= date[4];
408 this->second= date[5];
409 if (date_len[6] < 6)
410 date[6]*= (uint32_t) log_10_int[6 - date_len[6]];
411 this->second_part=date[6];
412 }
413 this->neg= 0;
414
415 if (year_length == 2 && not_zero_date)
416 this->year+= (this->year < YY_PART_YEAR ? 2000 : 1900);
417
418 if (number_of_fields < 3 ||
419 this->year > 9999 || this->month > 12 ||
420 this->day > 31 || this->hour > 23 ||
421 this->minute > 59 || this->second > 59)
422 {
423 /* Only give warning for a zero date if there is some garbage after */
424 if (!not_zero_date) /* If zero date */
425 {
426 for (; str != end ; str++)
427 {
428 if (not my_charset_utf8_general_ci.isspace(*str))
429 {
430 not_zero_date= 1; /* Give warning */
431 break;
432 }
433 }
434 }
435 was_cut= test(not_zero_date) ? type::CUT : type::VALID;
436 break;
437 }
438
439 if (check(not_zero_date != 0, flags, was_cut))
440 {
441 break;
442 }
443
444 this->time_type= (number_of_fields <= 3 ?
445 type::DRIZZLE_TIMESTAMP_DATE : type::DRIZZLE_TIMESTAMP_DATETIME);
446
447 for (; str != end ; str++)
448 {
449 if (not my_charset_utf8_general_ci.isspace(*str))
450 {
451 was_cut= type::CUT;
452 break;
453 }
454 }
455
456 return(time_type= (number_of_fields <= 3 ? type::DRIZZLE_TIMESTAMP_DATE : type::DRIZZLE_TIMESTAMP_DATETIME));
457 } while (0);
458
459 reset();
460
461 return type::DRIZZLE_TIMESTAMP_ERROR;
462}
463
464type::timestamp_t Time::store(const char *str, uint32_t length, uint32_t flags)
465{
466 type::cut_t was_cut;
467 return store(str, length, flags, was_cut);
468}
469
470/*
471 Convert a time string to a type::Time struct.
472
473 SYNOPSIS
474 str_to_time()
475 str A string in full TIMESTAMP format or
476 [-] DAYS [H]H:MM:SS, [H]H:MM:SS, [M]M:SS, [H]HMMSS,
477 [M]MSS or [S]S
478 There may be an optional [.second_part] after seconds
479 length Length of str
480 l_time Store result here
481 warning Set DRIZZLE_TIME_WARN_TRUNCATED flag if the input string
482 was cut during conversion, and/or
483 DRIZZLE_TIME_WARN_OUT_OF_RANGE flag, if the value is
484 out of range.
485
486 NOTES
487 Because of the extra days argument, this function can only
488 work with times where the time arguments are in the above order.
489
490 RETURN
491 0 ok
492 1 error
493*/
494
495bool Time::store(const char *str, uint32_t length, int &warning, type::timestamp_t arg)
496{
497 (void)arg;
498 uint32_t date[5];
499 uint64_t value;
500 const char *end=str+length, *end_of_days;
501 bool found_days,found_hours;
502 uint32_t state;
503
504 assert(arg == DRIZZLE_TIMESTAMP_TIME);
505
506 this->neg=0;
507 warning= 0;
508 for (; str != end && my_charset_utf8_general_ci.isspace(*str) ; str++)
509 {
510 length--;
511 }
512
513 if (str != end && *str == '-')
514 {
515 this->neg=1;
516 str++;
517 length--;
518 }
519
520 if (str == end)
521 {
522 return true;
523 }
524
525 /* Check first if this is a full TIMESTAMP */
526 if (length >= 12)
527 { /* Probably full timestamp */
528 type::cut_t was_cut;
529 type::timestamp_t res= this->store(str, length, (TIME_FUZZY_DATE | TIME_DATETIME_ONLY), was_cut);
530 if ((int) res >= (int) type::DRIZZLE_TIMESTAMP_ERROR)
531 {
532 if (was_cut != type::VALID)
533 warning|= DRIZZLE_TIME_WARN_TRUNCATED;
534
535 return res == type::DRIZZLE_TIMESTAMP_ERROR;
536 }
537 }
538
539 /* Not a timestamp. Try to get this as a DAYS_TO_SECOND string */
540 for (value=0; str != end && my_charset_utf8_general_ci.isdigit(*str) ; str++)
541 {
542 value= value*10L + (long) (*str - '0');
543 }
544
545 /* Skip all space after 'days' */
546 end_of_days= str;
547 for (; str != end && my_charset_utf8_general_ci.isspace(str[0]) ; str++)
548 ;
549
550 found_days=found_hours=0;
551 if ((uint32_t) (end-str) > 1 and str != end_of_days and
552 my_charset_utf8_general_ci.isdigit(*str))
553 { /* Found days part */
554 date[0]= (uint32_t) value;
555 state= 1; /* Assume next is hours */
556 found_days= 1;
557 }
558 else if ((end-str) > 1 && *str == time_separator &&
559 my_charset_utf8_general_ci.isdigit(str[1]))
560 {
561 date[0]= 0; /* Assume we found hours */
562 date[1]= (uint32_t) value;
563 state=2;
564 found_hours=1;
565 str++; /* skip ':' */
566 }
567 else
568 {
569 /* String given as one number; assume HHMMSS format */
570 date[0]= 0;
571 date[1]= (uint32_t) (value/10000);
572 date[2]= (uint32_t) (value/100 % 100);
573 date[3]= (uint32_t) (value % 100);
574 state=4;
575 goto fractional;
576 }
577
578 /* Read hours, minutes and seconds */
579 for (;;)
580 {
581 for (value=0; str != end && my_charset_utf8_general_ci.isdigit(*str) ; str++)
582 value=value*10L + (long) (*str - '0');
583 date[state++]= (uint32_t) value;
584 if (state == 4 || (end-str) < 2 || *str != time_separator ||
585 !my_charset_utf8_general_ci.isdigit(str[1]))
586 break;
587 str++; /* Skip time_separator (':') */
588 }
589
590 if (state != 4)
591 { /* Not HH:MM:SS */
592 /* Fix the date to assume that seconds was given */
593 if (!found_hours && !found_days)
594 {
595 internal::bmove_upp((unsigned char*) (date+4), (unsigned char*) (date+state),
596 sizeof(long)*(state-1));
597 memset(date, 0, sizeof(long)*(4-state));
598 }
599 else
600 memset(date+state, 0, sizeof(long)*(4-state));
601 }
602
603fractional:
604 /* Get fractional second part */
605 if ((end-str) >= 2 && *str == '.' && my_charset_utf8_general_ci.isdigit(str[1]))
606 {
607 int field_length= 5;
608 str++; value=(uint32_t) (unsigned char) (*str - '0');
609 while (++str != end && my_charset_utf8_general_ci.isdigit(*str))
610 {
611 if (field_length-- > 0)
612 value= value*10 + (uint32_t) (unsigned char) (*str - '0');
613 }
614 if (field_length > 0)
615 {
616 value*= (long) log_10_int[field_length];
617 }
618 else if (field_length < 0)
619 {
620 warning|= DRIZZLE_TIME_WARN_TRUNCATED;
621 }
622
623 date[4]= (uint32_t) value;
624 }
625 else
626 {
627 date[4]=0;
628 }
629
630 /* Check for exponent part: E<gigit> | E<sign><digit> */
631 /* (may occur as result of %g formatting of time value) */
632 if ((end - str) > 1 &&
633 (*str == 'e' || *str == 'E') &&
634 (my_charset_utf8_general_ci.isdigit(str[1]) ||
635 ((str[1] == '-' || str[1] == '+') &&
636 (end - str) > 2 &&
637 my_charset_utf8_general_ci.isdigit(str[2]))))
638 return 1;
639
640 if (internal_format_positions[7] != 255)
641 {
642 /* Read a possible AM/PM */
643 while (str != end && my_charset_utf8_general_ci.isspace(*str))
644 str++;
645 if (str+2 <= end && (str[1] == 'M' || str[1] == 'm'))
646 {
647 if (str[0] == 'p' || str[0] == 'P')
648 {
649 str+= 2;
650 date[1]= date[1]%12 + 12;
651 }
652 else if (str[0] == 'a' || str[0] == 'A')
653 str+=2;
654 }
655 }
656
657 /* Integer overflow checks */
658 if (date[0] > UINT_MAX || date[1] > UINT_MAX ||
659 date[2] > UINT_MAX || date[3] > UINT_MAX ||
660 date[4] > UINT_MAX)
661 return 1;
662
663 this->year= 0; /* For protocol::store_time */
664 this->month= 0;
665 this->day= date[0];
666 this->hour= date[1];
667 this->minute= date[2];
668 this->second= date[3];
669 this->second_part= date[4];
670 this->time_type= type::DRIZZLE_TIMESTAMP_TIME;
671
672 /* Check if the value is valid and fits into type::Time range */
673 if (check_time_range(this, &warning))
674 {
675 return 1;
676 }
677
678 /* Check if there is garbage at end of the type::Time specification */
679 if (str != end)
680 {
681 do
682 {
683 if (not my_charset_utf8_general_ci.isspace(*str))
684 {
685 warning|= DRIZZLE_TIME_WARN_TRUNCATED;
686 break;
687 }
688 } while (++str != end);
689 }
690 return 0;
691}
692
693} // namespace type
694
695
696
697/*
698 Check 'time' value to lie in the type::Time range
699
700 SYNOPSIS:
701 check_time_range()
702 time pointer to type::Time value
703 warning set DRIZZLE_TIME_WARN_OUT_OF_RANGE flag if the value is out of range
704
705 DESCRIPTION
706 If the time value lies outside of the range [-838:59:59, 838:59:59],
707 set it to the closest endpoint of the range and set
708 DRIZZLE_TIME_WARN_OUT_OF_RANGE flag in the 'warning' variable.
709
710 RETURN
711 0 time value is valid, but was possibly truncated
712 1 time value is invalid
713*/
714
715static int check_time_range(type::Time *my_time, int *warning)
716{
717 int64_t hour;
718
719 if (my_time->minute >= 60 || my_time->second >= 60)
720 return 1;
721
722 hour= my_time->hour + (24*my_time->day);
723 if (hour <= TIME_MAX_HOUR &&
724 (hour != TIME_MAX_HOUR || my_time->minute != TIME_MAX_MINUTE ||
725 my_time->second != TIME_MAX_SECOND || !my_time->second_part))
726 return 0;
727
728 my_time->day= 0;
729 my_time->hour= TIME_MAX_HOUR;
730 my_time->minute= TIME_MAX_MINUTE;
731 my_time->second= TIME_MAX_SECOND;
732 my_time->second_part= 0;
733 *warning|= DRIZZLE_TIME_WARN_OUT_OF_RANGE;
734 return 0;
735}
736
737
738/*
739 Prepare offset of system time zone from UTC for my_system_gmt_sec() func.
740
741 SYNOPSIS
742 init_time()
743*/
744void init_time(void)
745{
746 type::Time my_time;
747 type::epoch_t epoch;
748
749 time_t seconds= time(NULL);
750 tm tm_tmp;
751 localtime_r(&seconds, &tm_tmp);
752 tm* l_time= &tm_tmp;
753 my_time_zone= 3600; /* Comp. for -3600 in my_gmt_sec */
754 my_time.year= (uint32_t) l_time->tm_year+1900;
755 my_time.month= (uint32_t) l_time->tm_mon+1;
756 my_time.day= (uint32_t) l_time->tm_mday;
757 my_time.hour= (uint32_t) l_time->tm_hour;
758 my_time.minute= (uint32_t) l_time->tm_min;
759 my_time.second= (uint32_t) l_time->tm_sec;
760 my_time.time_type= type::DRIZZLE_TIMESTAMP_NONE;
761 my_time.second_part= 0;
762 my_time.neg= false;
763 my_time.convert(epoch, &my_time_zone); /* Init my_time_zone */
764}
765
766
767/*
768 Handle 2 digit year conversions
769
770 SYNOPSIS
771 year_2000_handling()
772 year 2 digit year
773
774 RETURN
775 Year between 1970-2069
776*/
777
778uint32_t year_2000_handling(uint32_t year)
779{
780 if ((year=year+1900) < 1900+YY_PART_YEAR)
781 year+=100;
782 return year;
783}
784
785
786/*
787 Calculate nr of day since year 0 in new date-system (from 1615)
788
789 SYNOPSIS
790 calc_daynr()
791 year Year (exact 4 digit year, no year conversions)
792 month Month
793 day Day
794
795 NOTES: 0000-00-00 is a valid date, and will return 0
796
797 RETURN
798 Days since 0000-00-00
799*/
800
801long calc_daynr(uint32_t year,uint32_t month,uint32_t day)
802{
803 long delsum;
804 int temp;
805
806 if (year == 0 && month == 0 && day == 0)
807 return 0; /* Skip errors */
808 delsum= (long) (365L * year+ 31*(month-1) +day);
809 if (month <= 2)
810 year--;
811 else
812 delsum-= (long) (month*4+23)/10;
813 temp=(int) ((year/100+1)*3)/4;
814 return(delsum+(int) year/4-temp);
815} /* calc_daynr */
816
817
818namespace type {
819/*
820 Convert time in type::Time representation in system time zone to its
821 time_t form (number of seconds in UTC since begginning of Unix Epoch).
822
823 SYNOPSIS
824 my_system_gmt_sec()
825 t - time value to be converted
826 my_timezone - pointer to long where offset of system time zone
827 from UTC will be stored for caching
828 in_dst_time_gap - set to true if time falls into spring time-gap
829
830 NOTES
831 The idea is to cache the time zone offset from UTC (including daylight
832 saving time) for the next call to make things faster. But currently we
833 just calculate this offset during startup (by calling init_time()
834 function) and use it all the time.
835 Time value provided should be legal time value (e.g. '2003-01-01 25:00:00'
836 is not allowed).
837
838 RETURN VALUE
839 Time in UTC seconds since Unix Epoch representation.
840*/
841void Time::convert(epoch_t &epoch, long *my_timezone) const
842{
843 int shift= 0;
844 struct tm *l_time,tm_tmp;
845 long diff;
846
847 /*
848 Use temp variable to avoid trashing input data, which could happen in
849 case of shift required for boundary dates processing.
850 */
851 type::Time tmp_time= *this;
852 type::Time* t= &tmp_time;
853
854 if (not t->isValidEpoch())
855 {
856 epoch= 0;
857 return;
858 }
859
860 /*
861 Calculate the gmt time based on current time and timezone
862 The -1 on the end is to ensure that if have a date that exists twice
863 (like 2002-10-27 02:00:0 MET), we will find the initial date.
864
865 By doing -3600 we will have to call localtime_r() several times, but
866 I couldn't come up with a better way to get a repeatable result :(
867
868 We can't use mktime() as it's buggy on many platforms and not thread safe.
869
870 Note: this code assumes that our time_t estimation is not too far away
871 from real value (we assume that localtime_r(epoch) will return something
872 within 24 hrs from t) which is probably true for all current time zones.
873
874 Note2: For the dates, which have time_t representation close to
875 MAX_INT32 (efficient time_t limit for supported platforms), we should
876 do a small trick to avoid overflow. That is, convert the date, which is
877 two days earlier, and then add these days to the final value.
878
879 The same trick is done for the values close to 0 in time_t
880 representation for platfroms with unsigned time_t (QNX).
881
882 To be more verbose, here is a sample (extracted from the code below):
883 (calc_daynr(2038, 1, 19) - (long) days_at_timestart)*86400L + 4*3600L
884 would return -2147480896 because of the long type overflow. In result
885 we would get 1901 year in localtime_r(), which is an obvious error.
886
887 Alike problem raises with the dates close to Epoch. E.g.
888 (calc_daynr(1969, 12, 31) - (long) days_at_timestart)*86400L + 23*3600L
889 will give -3600.
890
891 On some platforms, (E.g. on QNX) time_t is unsigned and localtime(-3600)
892 wil give us a date around 2106 year. Which is no good.
893
894 Theoreticaly, there could be problems with the latter conversion:
895 there are at least two timezones, which had time switches near 1 Jan
896 of 1970 (because of political reasons). These are America/Hermosillo and
897 America/Mazatlan time zones. They changed their offset on
898 1970-01-01 08:00:00 UTC from UTC-8 to UTC-7. For these zones
899 the code below will give incorrect results for dates close to
900 1970-01-01, in the case OS takes into account these historical switches.
901 Luckily, it seems that we support only one platform with unsigned
902 time_t. It's QNX. And QNX does not support historical timezone data at all.
903 E.g. there are no /usr/share/zoneinfo/ files or any other mean to supply
904 historical information for localtime_r() etc. That is, the problem is not
905 relevant to QNX.
906
907 We are safe with shifts close to MAX_INT32, as there are no known
908 time switches on Jan 2038 yet :)
909 */
910#ifdef TIME_T_UNSIGNED
911 {
912 /*
913 We can get 0 in time_t representaion only on 1969, 31 of Dec or on
914 1970, 1 of Jan. For both dates we use shift, which is added
915 to t->day in order to step out a bit from the border.
916 This is required for platforms, where time_t is unsigned.
917 As far as I know, among the platforms we support it's only QNX.
918 Note: the order of below if-statements is significant.
919 */
920
921 if ((t->year == TIMESTAMP_MIN_YEAR + 1) && (t->month == 1)
922 && (t->day <= 10))
923 {
924 t->day+= 2;
925 shift= -2;
926 }
927
928 if ((t->year == TIMESTAMP_MIN_YEAR) && (t->month == 12)
929 && (t->day == 31))
930 {
931 t->year++;
932 t->month= 1;
933 t->day= 2;
934 shift= -2;
935 }
936 }
937#endif
938
939 epoch= (type::epoch_t) (((calc_daynr((uint32_t) t->year, (uint32_t) t->month, (uint32_t) t->day) -
940 (long) days_at_timestart)*86400L + (long) t->hour*3600L +
941 (long) (t->minute*60 + t->second)) + (time_t) my_time_zone -
942 3600);
943
944 long current_timezone= my_time_zone;
945 util::gmtime(epoch, &tm_tmp);
946 l_time= &tm_tmp;
947 int loop= 0;
948 for (; loop < 2 &&
949 (t->hour != (uint32_t) l_time->tm_hour ||
950 t->minute != (uint32_t) l_time->tm_min ||
951 t->second != (uint32_t) l_time->tm_sec);
952 loop++)
953 { /* One check should be enough ? */
954 /* Get difference in days */
955 int days= t->day - l_time->tm_mday;
956 if (days < -1)
957 days= 1; /* Month has wrapped */
958 else if (days > 1)
959 days= -1;
960 diff=(3600L*(long) (days*24+((int) t->hour - (int) l_time->tm_hour)) +
961 (long) (60*((int) t->minute - (int) l_time->tm_min)) +
962 (long) ((int) t->second - (int) l_time->tm_sec));
963 current_timezone+= diff+3600; /* Compensate for -3600 above */
964 epoch+= (time_t) diff;
965 util::gmtime(epoch, &tm_tmp);
966 l_time=&tm_tmp;
967 }
968 /*
969 Fix that if we are in the non existing daylight saving time hour
970 we move the start of the next real hour.
971
972 This code doesn't handle such exotical thing as time-gaps whose length
973 is more than one hour or non-integer (latter can theoretically happen
974 if one of seconds will be removed due leap correction, or because of
975 general time correction like it happened for Africa/Monrovia time zone
976 in year 1972).
977 */
978 if (loop == 2 && t->hour != (uint32_t) l_time->tm_hour)
979 {
980 int days= t->day - l_time->tm_mday;
981 if (days < -1)
982 days=1; /* Month has wrapped */
983 else if (days > 1)
984 days= -1;
985 diff=(3600L*(long) (days*24+((int) t->hour - (int) l_time->tm_hour))+
986 (long) (60*((int) t->minute - (int) l_time->tm_min)) +
987 (long) ((int) t->second - (int) l_time->tm_sec));
988 if (diff == 3600)
989 epoch+=3600 - t->minute*60 - t->second; /* Move to next hour */
990 else if (diff == -3600)
991 epoch-=t->minute*60 + t->second; /* Move to previous hour */
992 }
993 *my_timezone= current_timezone;
994
995
996 /* shift back, if we were dealing with boundary dates */
997 epoch+= shift*86400L;
998
999 /*
1000 This is possible for dates, which slightly exceed boundaries.
1001 Conversion will pass ok for them, but we don't allow them.
1002 First check will pass for platforms with signed time_t.
1003 instruction above (epoch+= shift*86400L) could exceed
1004 MAX_INT32 (== TIMESTAMP_MAX_VALUE) and overflow will happen.
1005 So, epoch < TIMESTAMP_MIN_VALUE will be triggered.
1006 */
1007 if (epoch < TIMESTAMP_MIN_VALUE)
1008 {
1009 epoch= 0;
1010 }
1011} /* my_system_gmt_sec */
1012
1013
1014void Time::store(const struct tm &from)
1015{
1016 neg= 0;
1017 second_part= 0;
1018 year= (int32_t) ((from.tm_year+1900) % 10000);
1019 month= (int32_t) from.tm_mon+1;
1020 day= (int32_t) from.tm_mday;
1021 hour= (int32_t) from.tm_hour;
1022 minute= (int32_t) from.tm_min;
1023 second= (int32_t) from.tm_sec;
1024
1025 time_type= DRIZZLE_TIMESTAMP_DATETIME;
1026}
1027
1028void Time::store(const struct timeval &from)
1029{
1030 store(from.tv_sec, (usec_t)from.tv_usec);
1031 time_type= type::DRIZZLE_TIMESTAMP_DATETIME;
1032}
1033
1034
1035void Time::store(type::epoch_t from)
1036{
1037 store(from, 0);
1038}
1039
1040void Time::store(type::epoch_t from_arg, usec_t from_fractional_seconds)
1041{
1042 epoch_t from= from_arg;
1043 util::gmtime(from, *this);
1044
1045 // Since time_t/epoch_t doesn't have fractional seconds, we have to
1046 // collect them outside of the gmtime function.
1047 second_part= from_fractional_seconds;
1048 time_type= DRIZZLE_TIMESTAMP_DATETIME;
1049}
1050
1051// Only implemented for one case, extend as needed.
1052void Time::truncate(const timestamp_t arg)
1053{
1054 assert(arg == type::DRIZZLE_TIMESTAMP_TIME);
1055 year= month= day= 0;
1056
1057 time_type= arg;
1058}
1059
1060void Time::convert(String &str, timestamp_t arg)
1061{
1062 str.alloc(MAX_STRING_LENGTH);
1063 size_t length= MAX_STRING_LENGTH;
1064
1065 convert(str.c_ptr(), length, arg);
1066
1067 str.length(length);
1068 str.set_charset(&my_charset_bin);
1069}
1070
1071void Time::convert(char *str, size_t &to_length, timestamp_t arg)
1072{
1073 int32_t length= 0;
1074 switch (arg) {
1075 case DRIZZLE_TIMESTAMP_DATETIME:
1076 length= snprintf(str, to_length,
1077 "%04" PRIu32 "-%02" PRIu32 "-%02" PRIu32
1078 " %02" PRIu32 ":%02" PRIu32 ":%02" PRIu32 ".%06" PRIu32,
1079 year,
1080 month,
1081 day,
1082 hour,
1083 minute,
1084 second,
1085 second_part);
1086 break;
1087
1088 case DRIZZLE_TIMESTAMP_DATE:
1089 length= snprintf(str, to_length, "%04u-%02u-%02u",
1090 year,
1091 month,
1092 day);
1093 break;
1094
1095 case DRIZZLE_TIMESTAMP_TIME:
1096 {
1097 uint32_t extra_hours= 0;
1098
1099 length= snprintf(str, to_length,
1100 "%s%02u:%02u:%02u",
1101 (neg ? "-" : ""),
1102 extra_hours+ hour,
1103 minute,
1104 second);
1105 }
1106 break;
1107
1108 case DRIZZLE_TIMESTAMP_NONE:
1109 case DRIZZLE_TIMESTAMP_ERROR:
1110 assert(0);
1111 break;
1112 }
1113
1114 if (length < 0)
1115 {
1116 to_length= 0;
1117 return;
1118 }
1119
1120 to_length= length;
1121}
1122
1123}
1124
1125/*
1126 Convert datetime value specified as number to broken-down TIME
1127 representation and form value of DATETIME type as side-effect.
1128
1129 SYNOPSIS
1130 number_to_datetime()
1131 nr - datetime value as number
1132 time_res - pointer for structure for broken-down representation
1133 flags - flags to use in validating date, as in store()
1134 was_cut 0 Value ok
1135 1 If value was cut during conversion
1136 2 check(date,flags) considers date invalid
1137
1138 DESCRIPTION
1139 Convert a datetime value of formats YYMMDD, YYYYMMDD, YYMMDDHHMSS,
1140 YYYYMMDDHHMMSS to broken-down type::Time representation. Return value in
1141 YYYYMMDDHHMMSS format as side-effect.
1142
1143 This function also checks if datetime value fits in DATETIME range.
1144
1145 RETURN VALUE
1146 -1 Timestamp with wrong values
1147 anything else DATETIME as integer in YYYYMMDDHHMMSS format
1148 Datetime value in YYYYMMDDHHMMSS format.
1149*/
1150
1151static int64_t number_to_datetime(int64_t nr, type::Time *time_res,
1152 uint32_t flags, type::cut_t &was_cut)
1153{
1154 long part1,part2;
1155
1156 was_cut= type::VALID;
1157 time_res->reset();
1158 time_res->time_type=type::DRIZZLE_TIMESTAMP_DATE;
1159
1160 if (nr == 0LL || nr >= 10000101000000LL)
1161 {
1162 time_res->time_type= type::DRIZZLE_TIMESTAMP_DATETIME;
1163 goto ok;
1164 }
1165 if (nr < 101)
1166 goto err;
1167 if (nr <= (YY_PART_YEAR-1)*10000L+1231L)
1168 {
1169 nr= (nr+20000000L)*1000000L; /* YYMMDD, year: 2000-2069 */
1170 goto ok;
1171 }
1172 if (nr < (YY_PART_YEAR)*10000L+101L)
1173 goto err;
1174 if (nr <= 991231L)
1175 {
1176 nr= (nr+19000000L)*1000000L; /* YYMMDD, year: 1970-1999 */
1177 goto ok;
1178 }
1179 if (nr < 10000101L)
1180 goto err;
1181 if (nr <= 99991231L)
1182 {
1183 nr= nr*1000000L;
1184 goto ok;
1185 }
1186 if (nr < 101000000L)
1187 goto err;
1188
1189 time_res->time_type= type::DRIZZLE_TIMESTAMP_DATETIME;
1190
1191 if (nr <= (YY_PART_YEAR-1) * 10000000000LL + 1231235959LL)
1192 {
1193 nr= nr + 20000000000000LL; /* YYMMDDHHMMSS, 2000-2069 */
1194 goto ok;
1195 }
1196 if (nr < YY_PART_YEAR * 10000000000LL + 101000000LL)
1197 goto err;
1198 if (nr <= 991231235959LL)
1199 nr= nr + 19000000000000LL; /* YYMMDDHHMMSS, 1970-1999 */
1200
1201 ok:
1202 part1=(long) (nr / 1000000LL);
1203 part2=(long) (nr - (int64_t) part1 * 1000000LL);
1204 time_res->year= (int) (part1/10000L); part1%=10000L;
1205 time_res->month= (int) part1 / 100;
1206 time_res->day= (int) part1 % 100;
1207 time_res->hour= (int) (part2/10000L); part2%=10000L;
1208 time_res->minute=(int) part2 / 100;
1209 time_res->second=(int) part2 % 100;
1210
1211 if (time_res->year <= 9999 && time_res->month <= 12 &&
1212 time_res->day <= 31 && time_res->hour <= 23 &&
1213 time_res->minute <= 59 && time_res->second <= 59 &&
1214 not time_res->check((nr != 0), flags, was_cut))
1215 {
1216 return nr;
1217 }
1218
1219 /* Don't want to have was_cut get set if NO_ZERO_DATE was violated. */
1220 if (!nr && (flags & TIME_NO_ZERO_DATE))
1221 return -1LL;
1222
1223 err:
1224 was_cut= type::CUT;
1225 return -1LL;
1226}
1227
1228
1229namespace type {
1230
1231void Time::convert(datetime_t &ret, int64_t nr, uint32_t flags)
1232{
1233 type::cut_t was_cut;
1234 ret= number_to_datetime(nr, this, flags, was_cut);
1235}
1236
1237void Time::convert(datetime_t &ret, int64_t nr, uint32_t flags, type::cut_t &was_cut)
1238{
1239 ret= number_to_datetime(nr, this, flags, was_cut);
1240}
1241
1242/*
1243 Convert struct type::Time (date and time split into year/month/day/hour/...
1244 to a number in format YYYYMMDDHHMMSS (DATETIME),
1245 YYYYMMDD (DATE) or HHMMSS (TIME).
1246*/
1247
1248
1249void Time::convert(datetime_t &datetime, timestamp_t arg)
1250{
1251 switch (arg)
1252 {
1253 // Convert to YYYYMMDDHHMMSS format
1254 case type::DRIZZLE_TIMESTAMP_DATETIME:
1255 datetime= ((int64_t) (year * 10000UL + month * 100UL + day) * 1000000ULL +
1256 (int64_t) (hour * 10000UL + minute * 100UL + second));
1257 break;
1258
1259 // Convert to YYYYMMDD
1260 case type::DRIZZLE_TIMESTAMP_DATE:
1261 datetime= (year * 10000UL + month * 100UL + day);
1262 break;
1263
1264 // Convert to HHMMSS
1265 case type::DRIZZLE_TIMESTAMP_TIME:
1266 datetime= (hour * 10000UL + minute * 100UL + second);
1267 break;
1268
1269 case type::DRIZZLE_TIMESTAMP_NONE:
1270 case type::DRIZZLE_TIMESTAMP_ERROR:
1271 datetime= 0;
1272 }
1273}
1274
1275} // namespace type
1276
1277} /* namespace drizzled */
bool check(bool not_zero_date, uint32_t flags, type::cut_t &was_cut) const
Check datetime value for validity according to flags.
Definition type/time.cc:97
Convert from decimal to binary representation.
Definition common_fwd.h:215
TODO: Rename this file - func.h is stupid.
STL namespace.