Don't use 'return' where you should use 'PG_RETURN_xxx'.
[PostgreSQL.git] / src / backend / utils / adt / datetime.c
blob78b1c2612b22dd78b370df495078a68819226e88
1 /*-------------------------------------------------------------------------
3 * datetime.c
4 * Support functions for date/time types.
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * $PostgreSQL$
13 *-------------------------------------------------------------------------
15 #include "postgres.h"
17 #include <ctype.h>
18 #include <float.h>
19 #include <limits.h>
20 #include <math.h>
22 #include "access/xact.h"
23 #include "catalog/pg_type.h"
24 #include "funcapi.h"
25 #include "miscadmin.h"
26 #include "utils/builtins.h"
27 #include "utils/date.h"
28 #include "utils/datetime.h"
29 #include "utils/memutils.h"
30 #include "utils/tzparser.h"
33 static int DecodeNumber(int flen, char *field, bool haveTextMonth,
34 int fmask, int *tmask,
35 struct pg_tm * tm, fsec_t *fsec, bool *is2digits);
36 static int DecodeNumberField(int len, char *str,
37 int fmask, int *tmask,
38 struct pg_tm * tm, fsec_t *fsec, bool *is2digits);
39 static int DecodeTime(char *str, int fmask, int range,
40 int *tmask, struct pg_tm * tm, fsec_t *fsec);
41 static int DecodeTimezone(char *str, int *tzp);
42 static const datetkn *datebsearch(const char *key, const datetkn *base, int nel);
43 static int DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
44 struct pg_tm * tm);
45 static int ValidateDate(int fmask, bool is2digits, bool bc,
46 struct pg_tm * tm);
47 static void TrimTrailingZeros(char *str);
48 static void AppendSeconds(char *cp, int sec, fsec_t fsec,
49 int precision, bool fillzeros);
50 static void AdjustFractSeconds(double frac, struct pg_tm * tm, fsec_t *fsec,
51 int scale);
52 static void AdjustFractDays(double frac, struct pg_tm * tm, fsec_t *fsec,
53 int scale);
56 const int day_tab[2][13] =
58 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
59 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}
62 char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
63 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
65 char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
66 "Thursday", "Friday", "Saturday", NULL};
69 /*****************************************************************************
70 * PRIVATE ROUTINES *
71 *****************************************************************************/
74 * Definitions for squeezing values into "value"
75 * We set aside a high bit for a sign, and scale the timezone offsets
76 * in minutes by a factor of 15 (so can represent quarter-hour increments).
78 #define ABS_SIGNBIT ((char) 0200)
79 #define VALMASK ((char) 0177)
80 #define POS(n) (n)
81 #define NEG(n) ((n)|ABS_SIGNBIT)
82 #define SIGNEDCHAR(c) ((c)&ABS_SIGNBIT? -((c)&VALMASK): (c))
83 #define FROMVAL(tp) (-SIGNEDCHAR((tp)->value) * 15) /* uncompress */
84 #define TOVAL(tp, v) ((tp)->value = ((v) < 0? NEG((-(v))/15): POS(v)/15))
87 * datetktbl holds date/time keywords.
89 * Note that this table must be strictly alphabetically ordered to allow an
90 * O(ln(N)) search algorithm to be used.
92 * The text field is NOT guaranteed to be NULL-terminated.
94 * To keep this table reasonably small, we divide the lexval for TZ and DTZ
95 * entries by 15 (so they are on 15 minute boundaries) and truncate the text
96 * field at TOKMAXLEN characters.
97 * Formerly, we divided by 10 rather than 15 but there are a few time zones
98 * which are 30 or 45 minutes away from an even hour, most are on an hour
99 * boundary, and none on other boundaries.
101 * The static table contains no TZ or DTZ entries, rather those are loaded
102 * from configuration files and stored in timezonetktbl, which has the same
103 * format as the static datetktbl.
105 static datetkn *timezonetktbl = NULL;
107 static int sztimezonetktbl = 0;
109 static const datetkn datetktbl[] = {
110 /* text, token, lexval */
111 {EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
112 {DA_D, ADBC, AD}, /* "ad" for years > 0 */
113 {"allballs", RESERV, DTK_ZULU}, /* 00:00:00 */
114 {"am", AMPM, AM},
115 {"apr", MONTH, 4},
116 {"april", MONTH, 4},
117 {"at", IGNORE_DTF, 0}, /* "at" (throwaway) */
118 {"aug", MONTH, 8},
119 {"august", MONTH, 8},
120 {DB_C, ADBC, BC}, /* "bc" for years <= 0 */
121 {DCURRENT, RESERV, DTK_CURRENT}, /* "current" is always now */
122 {"d", UNITS, DTK_DAY}, /* "day of month" for ISO input */
123 {"dec", MONTH, 12},
124 {"december", MONTH, 12},
125 {"dow", RESERV, DTK_DOW}, /* day of week */
126 {"doy", RESERV, DTK_DOY}, /* day of year */
127 {"dst", DTZMOD, 6},
128 {EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
129 {"feb", MONTH, 2},
130 {"february", MONTH, 2},
131 {"fri", DOW, 5},
132 {"friday", DOW, 5},
133 {"h", UNITS, DTK_HOUR}, /* "hour" */
134 {LATE, RESERV, DTK_LATE}, /* "infinity" reserved for "late time" */
135 {INVALID, RESERV, DTK_INVALID}, /* "invalid" reserved for bad time */
136 {"isodow", RESERV, DTK_ISODOW}, /* ISO day of week, Sunday == 7 */
137 {"isoyear", UNITS, DTK_ISOYEAR}, /* year in terms of the ISO week date */
138 {"j", UNITS, DTK_JULIAN},
139 {"jan", MONTH, 1},
140 {"january", MONTH, 1},
141 {"jd", UNITS, DTK_JULIAN},
142 {"jul", MONTH, 7},
143 {"julian", UNITS, DTK_JULIAN},
144 {"july", MONTH, 7},
145 {"jun", MONTH, 6},
146 {"june", MONTH, 6},
147 {"m", UNITS, DTK_MONTH}, /* "month" for ISO input */
148 {"mar", MONTH, 3},
149 {"march", MONTH, 3},
150 {"may", MONTH, 5},
151 {"mm", UNITS, DTK_MINUTE}, /* "minute" for ISO input */
152 {"mon", DOW, 1},
153 {"monday", DOW, 1},
154 {"nov", MONTH, 11},
155 {"november", MONTH, 11},
156 {NOW, RESERV, DTK_NOW}, /* current transaction time */
157 {"oct", MONTH, 10},
158 {"october", MONTH, 10},
159 {"on", IGNORE_DTF, 0}, /* "on" (throwaway) */
160 {"pm", AMPM, PM},
161 {"s", UNITS, DTK_SECOND}, /* "seconds" for ISO input */
162 {"sat", DOW, 6},
163 {"saturday", DOW, 6},
164 {"sep", MONTH, 9},
165 {"sept", MONTH, 9},
166 {"september", MONTH, 9},
167 {"sun", DOW, 0},
168 {"sunday", DOW, 0},
169 {"t", ISOTIME, DTK_TIME}, /* Filler for ISO time fields */
170 {"thu", DOW, 4},
171 {"thur", DOW, 4},
172 {"thurs", DOW, 4},
173 {"thursday", DOW, 4},
174 {TODAY, RESERV, DTK_TODAY}, /* midnight */
175 {TOMORROW, RESERV, DTK_TOMORROW}, /* tomorrow midnight */
176 {"tue", DOW, 2},
177 {"tues", DOW, 2},
178 {"tuesday", DOW, 2},
179 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
180 {"wed", DOW, 3},
181 {"wednesday", DOW, 3},
182 {"weds", DOW, 3},
183 {"y", UNITS, DTK_YEAR}, /* "year" for ISO input */
184 {YESTERDAY, RESERV, DTK_YESTERDAY} /* yesterday midnight */
187 static int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];
189 static datetkn deltatktbl[] = {
190 /* text, token, lexval */
191 {"@", IGNORE_DTF, 0}, /* postgres relative prefix */
192 {DAGO, AGO, 0}, /* "ago" indicates negative time offset */
193 {"c", UNITS, DTK_CENTURY}, /* "century" relative */
194 {"cent", UNITS, DTK_CENTURY}, /* "century" relative */
195 {"centuries", UNITS, DTK_CENTURY}, /* "centuries" relative */
196 {DCENTURY, UNITS, DTK_CENTURY}, /* "century" relative */
197 {"d", UNITS, DTK_DAY}, /* "day" relative */
198 {DDAY, UNITS, DTK_DAY}, /* "day" relative */
199 {"days", UNITS, DTK_DAY}, /* "days" relative */
200 {"dec", UNITS, DTK_DECADE}, /* "decade" relative */
201 {DDECADE, UNITS, DTK_DECADE}, /* "decade" relative */
202 {"decades", UNITS, DTK_DECADE}, /* "decades" relative */
203 {"decs", UNITS, DTK_DECADE}, /* "decades" relative */
204 {"h", UNITS, DTK_HOUR}, /* "hour" relative */
205 {DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */
206 {"hours", UNITS, DTK_HOUR}, /* "hours" relative */
207 {"hr", UNITS, DTK_HOUR}, /* "hour" relative */
208 {"hrs", UNITS, DTK_HOUR}, /* "hours" relative */
209 {INVALID, RESERV, DTK_INVALID}, /* reserved for invalid time */
210 {"m", UNITS, DTK_MINUTE}, /* "minute" relative */
211 {"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
212 {"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
213 {"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
214 {DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
215 {"millisecon", UNITS, DTK_MILLISEC}, /* relative */
216 {"mils", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
217 {"min", UNITS, DTK_MINUTE}, /* "minute" relative */
218 {"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */
219 {DMINUTE, UNITS, DTK_MINUTE}, /* "minute" relative */
220 {"minutes", UNITS, DTK_MINUTE}, /* "minutes" relative */
221 {"mon", UNITS, DTK_MONTH}, /* "months" relative */
222 {"mons", UNITS, DTK_MONTH}, /* "months" relative */
223 {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
224 {"months", UNITS, DTK_MONTH},
225 {"ms", UNITS, DTK_MILLISEC},
226 {"msec", UNITS, DTK_MILLISEC},
227 {DMILLISEC, UNITS, DTK_MILLISEC},
228 {"mseconds", UNITS, DTK_MILLISEC},
229 {"msecs", UNITS, DTK_MILLISEC},
230 {"qtr", UNITS, DTK_QUARTER}, /* "quarter" relative */
231 {DQUARTER, UNITS, DTK_QUARTER}, /* "quarter" relative */
232 {"s", UNITS, DTK_SECOND},
233 {"sec", UNITS, DTK_SECOND},
234 {DSECOND, UNITS, DTK_SECOND},
235 {"seconds", UNITS, DTK_SECOND},
236 {"secs", UNITS, DTK_SECOND},
237 {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
238 {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
239 {"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */
240 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
241 {"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
242 {"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
243 {DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */
244 {"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
245 {"usecs", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
246 {"w", UNITS, DTK_WEEK}, /* "week" relative */
247 {DWEEK, UNITS, DTK_WEEK}, /* "week" relative */
248 {"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
249 {"y", UNITS, DTK_YEAR}, /* "year" relative */
250 {DYEAR, UNITS, DTK_YEAR}, /* "year" relative */
251 {"years", UNITS, DTK_YEAR}, /* "years" relative */
252 {"yr", UNITS, DTK_YEAR}, /* "year" relative */
253 {"yrs", UNITS, DTK_YEAR} /* "years" relative */
256 static int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];
258 static const datetkn *datecache[MAXDATEFIELDS] = {NULL};
260 static const datetkn *deltacache[MAXDATEFIELDS] = {NULL};
264 * strtoi --- just like strtol, but returns int not long
266 static int
267 strtoi(const char *nptr, char **endptr, int base)
269 long val;
271 val = strtol(nptr, endptr, base);
272 #ifdef HAVE_LONG_INT_64
273 if (val != (long) ((int32) val))
274 errno = ERANGE;
275 #endif
276 return (int) val;
281 * Calendar time to Julian date conversions.
282 * Julian date is commonly used in astronomical applications,
283 * since it is numerically accurate and computationally simple.
284 * The algorithms here will accurately convert between Julian day
285 * and calendar date for all non-negative Julian days
286 * (i.e. from Nov 24, -4713 on).
288 * These routines will be used by other date/time packages
289 * - thomas 97/02/25
291 * Rewritten to eliminate overflow problems. This now allows the
292 * routines to work correctly for all Julian day counts from
293 * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming
294 * a 32-bit integer. Longer types should also work to the limits
295 * of their precision.
299 date2j(int y, int m, int d)
301 int julian;
302 int century;
304 if (m > 2)
306 m += 1;
307 y += 4800;
309 else
311 m += 13;
312 y += 4799;
315 century = y / 100;
316 julian = y * 365 - 32167;
317 julian += y / 4 - century + century / 4;
318 julian += 7834 * m / 256 + d;
320 return julian;
321 } /* date2j() */
323 void
324 j2date(int jd, int *year, int *month, int *day)
326 unsigned int julian;
327 unsigned int quad;
328 unsigned int extra;
329 int y;
331 julian = jd;
332 julian += 32044;
333 quad = julian / 146097;
334 extra = (julian - quad * 146097) * 4 + 3;
335 julian += 60 + quad * 3 + extra / 146097;
336 quad = julian / 1461;
337 julian -= quad * 1461;
338 y = julian * 4 / 1461;
339 julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
340 + 123;
341 y += quad * 4;
342 *year = y - 4800;
343 quad = julian * 2141 / 65536;
344 *day = julian - 7834 * quad / 256;
345 *month = (quad + 10) % 12 + 1;
347 return;
348 } /* j2date() */
352 * j2day - convert Julian date to day-of-week (0..6 == Sun..Sat)
354 * Note: various places use the locution j2day(date - 1) to produce a
355 * result according to the convention 0..6 = Mon..Sun. This is a bit of
356 * a crock, but will work as long as the computation here is just a modulo.
359 j2day(int date)
361 unsigned int day;
363 day = date;
365 day += 1;
366 day %= 7;
368 return (int) day;
369 } /* j2day() */
373 * GetCurrentDateTime()
375 * Get the transaction start time ("now()") broken down as a struct pg_tm.
377 void
378 GetCurrentDateTime(struct pg_tm * tm)
380 int tz;
381 fsec_t fsec;
383 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, &fsec,
384 NULL, NULL);
385 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
389 * GetCurrentTimeUsec()
391 * Get the transaction start time ("now()") broken down as a struct pg_tm,
392 * including fractional seconds and timezone offset.
394 void
395 GetCurrentTimeUsec(struct pg_tm * tm, fsec_t *fsec, int *tzp)
397 int tz;
399 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, fsec,
400 NULL, NULL);
401 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
402 if (tzp != NULL)
403 *tzp = tz;
407 /* TrimTrailingZeros()
408 * ... resulting from printing numbers with full precision.
410 * Before Postgres 8.4, this always left at least 2 fractional digits,
411 * but conversations on the lists suggest this isn't desired
412 * since showing '0.10' is misleading with values of precision(1).
414 static void
415 TrimTrailingZeros(char *str)
417 int len = strlen(str);
419 while (len > 1 && *(str + len - 1) == '0' && *(str + len - 2) != '.')
421 len--;
422 *(str + len) = '\0';
427 * Append sections and fractional seconds (if any) at *cp.
428 * precision is the max number of fraction digits, fillzeros says to
429 * pad to two integral-seconds digits.
430 * Note that any sign is stripped from the input seconds values.
432 static void
433 AppendSeconds(char *cp, int sec, fsec_t fsec, int precision, bool fillzeros)
435 if (fsec == 0)
437 if (fillzeros)
438 sprintf(cp, "%02d", abs(sec));
439 else
440 sprintf(cp, "%d", abs(sec));
442 else
444 #ifdef HAVE_INT64_TIMESTAMP
445 if (fillzeros)
446 sprintf(cp, "%02d.%0*d", abs(sec), precision, (int) Abs(fsec));
447 else
448 sprintf(cp, "%d.%0*d", abs(sec), precision, (int) Abs(fsec));
449 #else
450 if (fillzeros)
451 sprintf(cp, "%0*.*f", precision + 3, precision, fabs(sec + fsec));
452 else
453 sprintf(cp, "%.*f", precision, fabs(sec + fsec));
454 #endif
455 TrimTrailingZeros(cp);
459 /* Variant of above that's specialized to timestamp case */
460 static void
461 AppendTimestampSeconds(char *cp, struct pg_tm * tm, fsec_t fsec)
464 * In float mode, don't print fractional seconds before 1 AD, since it's
465 * unlikely there's any precision left ...
467 #ifndef HAVE_INT64_TIMESTAMP
468 if (tm->tm_year <= 0)
469 fsec = 0;
470 #endif
471 AppendSeconds(cp, tm->tm_sec, fsec, MAX_TIMESTAMP_PRECISION, true);
475 * Multiply frac by scale (to produce seconds) and add to *tm & *fsec.
476 * We assume the input frac is less than 1 so overflow is not an issue.
478 static void
479 AdjustFractSeconds(double frac, struct pg_tm * tm, fsec_t *fsec, int scale)
481 int sec;
483 if (frac == 0)
484 return;
485 frac *= scale;
486 sec = (int) frac;
487 tm->tm_sec += sec;
488 frac -= sec;
489 #ifdef HAVE_INT64_TIMESTAMP
490 *fsec += rint(frac * 1000000);
491 #else
492 *fsec += frac;
493 #endif
496 /* As above, but initial scale produces days */
497 static void
498 AdjustFractDays(double frac, struct pg_tm * tm, fsec_t *fsec, int scale)
500 int extra_days;
502 if (frac == 0)
503 return;
504 frac *= scale;
505 extra_days = (int) frac;
506 tm->tm_mday += extra_days;
507 frac -= extra_days;
508 AdjustFractSeconds(frac, tm, fsec, SECS_PER_DAY);
511 /* Fetch a fractional-second value with suitable error checking */
512 static int
513 ParseFractionalSecond(char *cp, fsec_t *fsec)
515 double frac;
517 /* Caller should always pass the start of the fraction part */
518 Assert(*cp == '.');
519 errno = 0;
520 frac = strtod(cp, &cp);
521 /* check for parse failure */
522 if (*cp != '\0' || errno != 0)
523 return DTERR_BAD_FORMAT;
524 #ifdef HAVE_INT64_TIMESTAMP
525 *fsec = rint(frac * 1000000);
526 #else
527 *fsec = frac;
528 #endif
529 return 0;
533 /* ParseDateTime()
534 * Break string into tokens based on a date/time context.
535 * Returns 0 if successful, DTERR code if bogus input detected.
537 * timestr - the input string
538 * workbuf - workspace for field string storage. This must be
539 * larger than the largest legal input for this datetime type --
540 * some additional space will be needed to NUL terminate fields.
541 * buflen - the size of workbuf
542 * field[] - pointers to field strings are returned in this array
543 * ftype[] - field type indicators are returned in this array
544 * maxfields - dimensions of the above two arrays
545 * *numfields - set to the actual number of fields detected
547 * The fields extracted from the input are stored as separate,
548 * null-terminated strings in the workspace at workbuf. Any text is
549 * converted to lower case.
551 * Several field types are assigned:
552 * DTK_NUMBER - digits and (possibly) a decimal point
553 * DTK_DATE - digits and two delimiters, or digits and text
554 * DTK_TIME - digits, colon delimiters, and possibly a decimal point
555 * DTK_STRING - text (no digits or punctuation)
556 * DTK_SPECIAL - leading "+" or "-" followed by text
557 * DTK_TZ - leading "+" or "-" followed by digits (also eats ':', '.', '-')
559 * Note that some field types can hold unexpected items:
560 * DTK_NUMBER can hold date fields (yy.ddd)
561 * DTK_STRING can hold months (January) and time zones (PST)
562 * DTK_DATE can hold time zone names (America/New_York, GMT-8)
565 ParseDateTime(const char *timestr, char *workbuf, size_t buflen,
566 char **field, int *ftype, int maxfields, int *numfields)
568 int nf = 0;
569 const char *cp = timestr;
570 char *bufp = workbuf;
571 const char *bufend = workbuf + buflen;
574 * Set the character pointed-to by "bufptr" to "newchar", and increment
575 * "bufptr". "end" gives the end of the buffer -- we return an error if
576 * there is no space left to append a character to the buffer. Note that
577 * "bufptr" is evaluated twice.
579 #define APPEND_CHAR(bufptr, end, newchar) \
580 do \
582 if (((bufptr) + 1) >= (end)) \
583 return DTERR_BAD_FORMAT; \
584 *(bufptr)++ = newchar; \
585 } while (0)
587 /* outer loop through fields */
588 while (*cp != '\0')
590 /* Ignore spaces between fields */
591 if (isspace((unsigned char) *cp))
593 cp++;
594 continue;
597 /* Record start of current field */
598 if (nf >= maxfields)
599 return DTERR_BAD_FORMAT;
600 field[nf] = bufp;
602 /* leading digit? then date or time */
603 if (isdigit((unsigned char) *cp))
605 APPEND_CHAR(bufp, bufend, *cp++);
606 while (isdigit((unsigned char) *cp))
607 APPEND_CHAR(bufp, bufend, *cp++);
609 /* time field? */
610 if (*cp == ':')
612 ftype[nf] = DTK_TIME;
613 APPEND_CHAR(bufp, bufend, *cp++);
614 while (isdigit((unsigned char) *cp) ||
615 (*cp == ':') || (*cp == '.'))
616 APPEND_CHAR(bufp, bufend, *cp++);
618 /* date field? allow embedded text month */
619 else if (*cp == '-' || *cp == '/' || *cp == '.')
621 /* save delimiting character to use later */
622 char delim = *cp;
624 APPEND_CHAR(bufp, bufend, *cp++);
625 /* second field is all digits? then no embedded text month */
626 if (isdigit((unsigned char) *cp))
628 ftype[nf] = ((delim == '.') ? DTK_NUMBER : DTK_DATE);
629 while (isdigit((unsigned char) *cp))
630 APPEND_CHAR(bufp, bufend, *cp++);
633 * insist that the delimiters match to get a three-field
634 * date.
636 if (*cp == delim)
638 ftype[nf] = DTK_DATE;
639 APPEND_CHAR(bufp, bufend, *cp++);
640 while (isdigit((unsigned char) *cp) || *cp == delim)
641 APPEND_CHAR(bufp, bufend, *cp++);
644 else
646 ftype[nf] = DTK_DATE;
647 while (isalnum((unsigned char) *cp) || *cp == delim)
648 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
653 * otherwise, number only and will determine year, month, day, or
654 * concatenated fields later...
656 else
657 ftype[nf] = DTK_NUMBER;
659 /* Leading decimal point? Then fractional seconds... */
660 else if (*cp == '.')
662 APPEND_CHAR(bufp, bufend, *cp++);
663 while (isdigit((unsigned char) *cp))
664 APPEND_CHAR(bufp, bufend, *cp++);
666 ftype[nf] = DTK_NUMBER;
670 * text? then date string, month, day of week, special, or timezone
672 else if (isalpha((unsigned char) *cp))
674 bool is_date;
676 ftype[nf] = DTK_STRING;
677 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
678 while (isalpha((unsigned char) *cp))
679 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
682 * Dates can have embedded '-', '/', or '.' separators. It could
683 * also be a timezone name containing embedded '/', '+', '-', '_',
684 * or ':' (but '_' or ':' can't be the first punctuation). If the
685 * next character is a digit or '+', we need to check whether what
686 * we have so far is a recognized non-timezone keyword --- if so,
687 * don't believe that this is the start of a timezone.
689 is_date = false;
690 if (*cp == '-' || *cp == '/' || *cp == '.')
691 is_date = true;
692 else if (*cp == '+' || isdigit((unsigned char) *cp))
694 *bufp = '\0'; /* null-terminate current field value */
695 /* we need search only the core token table, not TZ names */
696 if (datebsearch(field[nf], datetktbl, szdatetktbl) == NULL)
697 is_date = true;
699 if (is_date)
701 ftype[nf] = DTK_DATE;
704 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
705 } while (*cp == '+' || *cp == '-' ||
706 *cp == '/' || *cp == '_' ||
707 *cp == '.' || *cp == ':' ||
708 isalnum((unsigned char) *cp));
711 /* sign? then special or numeric timezone */
712 else if (*cp == '+' || *cp == '-')
714 APPEND_CHAR(bufp, bufend, *cp++);
715 /* soak up leading whitespace */
716 while (isspace((unsigned char) *cp))
717 cp++;
718 /* numeric timezone? */
719 /* note that "DTK_TZ" could also be a signed float or yyyy-mm */
720 if (isdigit((unsigned char) *cp))
722 ftype[nf] = DTK_TZ;
723 APPEND_CHAR(bufp, bufend, *cp++);
724 while (isdigit((unsigned char) *cp) ||
725 *cp == ':' || *cp == '.' || *cp == '-')
726 APPEND_CHAR(bufp, bufend, *cp++);
728 /* special? */
729 else if (isalpha((unsigned char) *cp))
731 ftype[nf] = DTK_SPECIAL;
732 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
733 while (isalpha((unsigned char) *cp))
734 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
736 /* otherwise something wrong... */
737 else
738 return DTERR_BAD_FORMAT;
740 /* ignore other punctuation but use as delimiter */
741 else if (ispunct((unsigned char) *cp))
743 cp++;
744 continue;
746 /* otherwise, something is not right... */
747 else
748 return DTERR_BAD_FORMAT;
750 /* force in a delimiter after each field */
751 *bufp++ = '\0';
752 nf++;
755 *numfields = nf;
757 return 0;
761 /* DecodeDateTime()
762 * Interpret previously parsed fields for general date and time.
763 * Return 0 if full date, 1 if only time, and negative DTERR code if problems.
764 * (Currently, all callers treat 1 as an error return too.)
766 * External format(s):
767 * "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
768 * "Fri Feb-7-1997 15:23:27"
769 * "Feb-7-1997 15:23:27"
770 * "2-7-1997 15:23:27"
771 * "1997-2-7 15:23:27"
772 * "1997.038 15:23:27" (day of year 1-366)
773 * Also supports input in compact time:
774 * "970207 152327"
775 * "97038 152327"
776 * "20011225T040506.789-07"
778 * Use the system-provided functions to get the current time zone
779 * if not specified in the input string.
781 * If the date is outside the range of pg_time_t (in practice that could only
782 * happen if pg_time_t is just 32 bits), then assume UTC time zone - thomas
783 * 1997-05-27
786 DecodeDateTime(char **field, int *ftype, int nf,
787 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
789 int fmask = 0,
790 tmask,
791 type;
792 int ptype = 0; /* "prefix type" for ISO y2001m02d04 format */
793 int i;
794 int val;
795 int dterr;
796 int mer = HR24;
797 bool haveTextMonth = FALSE;
798 bool is2digits = FALSE;
799 bool bc = FALSE;
800 pg_tz *namedTz = NULL;
803 * We'll insist on at least all of the date fields, but initialize the
804 * remaining fields in case they are not set later...
806 *dtype = DTK_DATE;
807 tm->tm_hour = 0;
808 tm->tm_min = 0;
809 tm->tm_sec = 0;
810 *fsec = 0;
811 /* don't know daylight savings time status apriori */
812 tm->tm_isdst = -1;
813 if (tzp != NULL)
814 *tzp = 0;
816 for (i = 0; i < nf; i++)
818 switch (ftype[i])
820 case DTK_DATE:
821 /***
822 * Integral julian day with attached time zone?
823 * All other forms with JD will be separated into
824 * distinct fields, so we handle just this case here.
825 ***/
826 if (ptype == DTK_JULIAN)
828 char *cp;
829 int val;
831 if (tzp == NULL)
832 return DTERR_BAD_FORMAT;
834 errno = 0;
835 val = strtoi(field[i], &cp, 10);
836 if (errno == ERANGE)
837 return DTERR_FIELD_OVERFLOW;
839 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
840 /* Get the time zone from the end of the string */
841 dterr = DecodeTimezone(cp, tzp);
842 if (dterr)
843 return dterr;
845 tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
846 ptype = 0;
847 break;
849 /***
850 * Already have a date? Then this might be a time zone name
851 * with embedded punctuation (e.g. "America/New_York") or a
852 * run-together time with trailing time zone (e.g. hhmmss-zz).
853 * - thomas 2001-12-25
855 * We consider it a time zone if we already have month & day.
856 * This is to allow the form "mmm dd hhmmss tz year", which
857 * we've historically accepted.
858 ***/
859 else if (ptype != 0 ||
860 ((fmask & (DTK_M(MONTH) | DTK_M(DAY))) ==
861 (DTK_M(MONTH) | DTK_M(DAY))))
863 /* No time zone accepted? Then quit... */
864 if (tzp == NULL)
865 return DTERR_BAD_FORMAT;
867 if (isdigit((unsigned char) *field[i]) || ptype != 0)
869 char *cp;
871 if (ptype != 0)
873 /* Sanity check; should not fail this test */
874 if (ptype != DTK_TIME)
875 return DTERR_BAD_FORMAT;
876 ptype = 0;
880 * Starts with a digit but we already have a time
881 * field? Then we are in trouble with a date and time
882 * already...
884 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
885 return DTERR_BAD_FORMAT;
887 if ((cp = strchr(field[i], '-')) == NULL)
888 return DTERR_BAD_FORMAT;
890 /* Get the time zone from the end of the string */
891 dterr = DecodeTimezone(cp, tzp);
892 if (dterr)
893 return dterr;
894 *cp = '\0';
897 * Then read the rest of the field as a concatenated
898 * time
900 dterr = DecodeNumberField(strlen(field[i]), field[i],
901 fmask,
902 &tmask, tm,
903 fsec, &is2digits);
904 if (dterr < 0)
905 return dterr;
908 * modify tmask after returning from
909 * DecodeNumberField()
911 tmask |= DTK_M(TZ);
913 else
915 namedTz = pg_tzset(field[i]);
916 if (!namedTz)
919 * We should return an error code instead of
920 * ereport'ing directly, but then there is no way
921 * to report the bad time zone name.
923 ereport(ERROR,
924 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
925 errmsg("time zone \"%s\" not recognized",
926 field[i])));
928 /* we'll apply the zone setting below */
929 tmask = DTK_M(TZ);
932 else
934 dterr = DecodeDate(field[i], fmask,
935 &tmask, &is2digits, tm);
936 if (dterr)
937 return dterr;
939 break;
941 case DTK_TIME:
942 dterr = DecodeTime(field[i], fmask, INTERVAL_FULL_RANGE,
943 &tmask, tm, fsec);
944 if (dterr)
945 return dterr;
948 * Check upper limit on hours; other limits checked in
949 * DecodeTime()
951 /* test for > 24:00:00 */
952 if (tm->tm_hour > 24 ||
953 (tm->tm_hour == 24 &&
954 (tm->tm_min > 0 || tm->tm_sec > 0 || *fsec > 0)))
955 return DTERR_FIELD_OVERFLOW;
956 break;
958 case DTK_TZ:
960 int tz;
962 if (tzp == NULL)
963 return DTERR_BAD_FORMAT;
965 dterr = DecodeTimezone(field[i], &tz);
966 if (dterr)
967 return dterr;
968 *tzp = tz;
969 tmask = DTK_M(TZ);
971 break;
973 case DTK_NUMBER:
976 * Was this an "ISO date" with embedded field labels? An
977 * example is "y2001m02d04" - thomas 2001-02-04
979 if (ptype != 0)
981 char *cp;
982 int val;
984 errno = 0;
985 val = strtoi(field[i], &cp, 10);
986 if (errno == ERANGE)
987 return DTERR_FIELD_OVERFLOW;
990 * only a few kinds are allowed to have an embedded
991 * decimal
993 if (*cp == '.')
994 switch (ptype)
996 case DTK_JULIAN:
997 case DTK_TIME:
998 case DTK_SECOND:
999 break;
1000 default:
1001 return DTERR_BAD_FORMAT;
1002 break;
1004 else if (*cp != '\0')
1005 return DTERR_BAD_FORMAT;
1007 switch (ptype)
1009 case DTK_YEAR:
1010 tm->tm_year = val;
1011 tmask = DTK_M(YEAR);
1012 break;
1014 case DTK_MONTH:
1017 * already have a month and hour? then assume
1018 * minutes
1020 if ((fmask & DTK_M(MONTH)) != 0 &&
1021 (fmask & DTK_M(HOUR)) != 0)
1023 tm->tm_min = val;
1024 tmask = DTK_M(MINUTE);
1026 else
1028 tm->tm_mon = val;
1029 tmask = DTK_M(MONTH);
1031 break;
1033 case DTK_DAY:
1034 tm->tm_mday = val;
1035 tmask = DTK_M(DAY);
1036 break;
1038 case DTK_HOUR:
1039 tm->tm_hour = val;
1040 tmask = DTK_M(HOUR);
1041 break;
1043 case DTK_MINUTE:
1044 tm->tm_min = val;
1045 tmask = DTK_M(MINUTE);
1046 break;
1048 case DTK_SECOND:
1049 tm->tm_sec = val;
1050 tmask = DTK_M(SECOND);
1051 if (*cp == '.')
1053 dterr = ParseFractionalSecond(cp, fsec);
1054 if (dterr)
1055 return dterr;
1056 tmask = DTK_ALL_SECS_M;
1058 break;
1060 case DTK_TZ:
1061 tmask = DTK_M(TZ);
1062 dterr = DecodeTimezone(field[i], tzp);
1063 if (dterr)
1064 return dterr;
1065 break;
1067 case DTK_JULIAN:
1068 /***
1069 * previous field was a label for "julian date"?
1070 ***/
1071 tmask = DTK_DATE_M;
1072 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1073 /* fractional Julian Day? */
1074 if (*cp == '.')
1076 double time;
1078 errno = 0;
1079 time = strtod(cp, &cp);
1080 if (*cp != '\0' || errno != 0)
1081 return DTERR_BAD_FORMAT;
1083 #ifdef HAVE_INT64_TIMESTAMP
1084 time *= USECS_PER_DAY;
1085 #else
1086 time *= SECS_PER_DAY;
1087 #endif
1088 dt2time(time,
1089 &tm->tm_hour, &tm->tm_min,
1090 &tm->tm_sec, fsec);
1091 tmask |= DTK_TIME_M;
1093 break;
1095 case DTK_TIME:
1096 /* previous field was "t" for ISO time */
1097 dterr = DecodeNumberField(strlen(field[i]), field[i],
1098 (fmask | DTK_DATE_M),
1099 &tmask, tm,
1100 fsec, &is2digits);
1101 if (dterr < 0)
1102 return dterr;
1103 if (tmask != DTK_TIME_M)
1104 return DTERR_BAD_FORMAT;
1105 break;
1107 default:
1108 return DTERR_BAD_FORMAT;
1109 break;
1112 ptype = 0;
1113 *dtype = DTK_DATE;
1115 else
1117 char *cp;
1118 int flen;
1120 flen = strlen(field[i]);
1121 cp = strchr(field[i], '.');
1123 /* Embedded decimal and no date yet? */
1124 if (cp != NULL && !(fmask & DTK_DATE_M))
1126 dterr = DecodeDate(field[i], fmask,
1127 &tmask, &is2digits, tm);
1128 if (dterr)
1129 return dterr;
1131 /* embedded decimal and several digits before? */
1132 else if (cp != NULL && flen - strlen(cp) > 2)
1135 * Interpret as a concatenated date or time Set the
1136 * type field to allow decoding other fields later.
1137 * Example: 20011223 or 040506
1139 dterr = DecodeNumberField(flen, field[i], fmask,
1140 &tmask, tm,
1141 fsec, &is2digits);
1142 if (dterr < 0)
1143 return dterr;
1145 else if (flen > 4)
1147 dterr = DecodeNumberField(flen, field[i], fmask,
1148 &tmask, tm,
1149 fsec, &is2digits);
1150 if (dterr < 0)
1151 return dterr;
1153 /* otherwise it is a single date/time field... */
1154 else
1156 dterr = DecodeNumber(flen, field[i],
1157 haveTextMonth, fmask,
1158 &tmask, tm,
1159 fsec, &is2digits);
1160 if (dterr)
1161 return dterr;
1164 break;
1166 case DTK_STRING:
1167 case DTK_SPECIAL:
1168 type = DecodeSpecial(i, field[i], &val);
1169 if (type == IGNORE_DTF)
1170 continue;
1172 tmask = DTK_M(type);
1173 switch (type)
1175 case RESERV:
1176 switch (val)
1178 case DTK_CURRENT:
1179 ereport(ERROR,
1180 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1181 errmsg("date/time value \"current\" is no longer supported")));
1183 return DTERR_BAD_FORMAT;
1184 break;
1186 case DTK_NOW:
1187 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1188 *dtype = DTK_DATE;
1189 GetCurrentTimeUsec(tm, fsec, tzp);
1190 break;
1192 case DTK_YESTERDAY:
1193 tmask = DTK_DATE_M;
1194 *dtype = DTK_DATE;
1195 GetCurrentDateTime(tm);
1196 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - 1,
1197 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1198 tm->tm_hour = 0;
1199 tm->tm_min = 0;
1200 tm->tm_sec = 0;
1201 break;
1203 case DTK_TODAY:
1204 tmask = DTK_DATE_M;
1205 *dtype = DTK_DATE;
1206 GetCurrentDateTime(tm);
1207 tm->tm_hour = 0;
1208 tm->tm_min = 0;
1209 tm->tm_sec = 0;
1210 break;
1212 case DTK_TOMORROW:
1213 tmask = DTK_DATE_M;
1214 *dtype = DTK_DATE;
1215 GetCurrentDateTime(tm);
1216 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1,
1217 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1218 tm->tm_hour = 0;
1219 tm->tm_min = 0;
1220 tm->tm_sec = 0;
1221 break;
1223 case DTK_ZULU:
1224 tmask = (DTK_TIME_M | DTK_M(TZ));
1225 *dtype = DTK_DATE;
1226 tm->tm_hour = 0;
1227 tm->tm_min = 0;
1228 tm->tm_sec = 0;
1229 if (tzp != NULL)
1230 *tzp = 0;
1231 break;
1233 default:
1234 *dtype = val;
1237 break;
1239 case MONTH:
1242 * already have a (numeric) month? then see if we can
1243 * substitute...
1245 if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
1246 !(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 &&
1247 tm->tm_mon <= 31)
1249 tm->tm_mday = tm->tm_mon;
1250 tmask = DTK_M(DAY);
1252 haveTextMonth = TRUE;
1253 tm->tm_mon = val;
1254 break;
1256 case DTZMOD:
1259 * daylight savings time modifier (solves "MET DST"
1260 * syntax)
1262 tmask |= DTK_M(DTZ);
1263 tm->tm_isdst = 1;
1264 if (tzp == NULL)
1265 return DTERR_BAD_FORMAT;
1266 *tzp += val * MINS_PER_HOUR;
1267 break;
1269 case DTZ:
1272 * set mask for TZ here _or_ check for DTZ later when
1273 * getting default timezone
1275 tmask |= DTK_M(TZ);
1276 tm->tm_isdst = 1;
1277 if (tzp == NULL)
1278 return DTERR_BAD_FORMAT;
1279 *tzp = val * MINS_PER_HOUR;
1280 break;
1282 case TZ:
1283 tm->tm_isdst = 0;
1284 if (tzp == NULL)
1285 return DTERR_BAD_FORMAT;
1286 *tzp = val * MINS_PER_HOUR;
1287 break;
1289 case IGNORE_DTF:
1290 break;
1292 case AMPM:
1293 mer = val;
1294 break;
1296 case ADBC:
1297 bc = (val == BC);
1298 break;
1300 case DOW:
1301 tm->tm_wday = val;
1302 break;
1304 case UNITS:
1305 tmask = 0;
1306 ptype = val;
1307 break;
1309 case ISOTIME:
1312 * This is a filler field "t" indicating that the next
1313 * field is time. Try to verify that this is sensible.
1315 tmask = 0;
1317 /* No preceding date? Then quit... */
1318 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1319 return DTERR_BAD_FORMAT;
1321 /***
1322 * We will need one of the following fields:
1323 * DTK_NUMBER should be hhmmss.fff
1324 * DTK_TIME should be hh:mm:ss.fff
1325 * DTK_DATE should be hhmmss-zz
1326 ***/
1327 if (i >= nf - 1 ||
1328 (ftype[i + 1] != DTK_NUMBER &&
1329 ftype[i + 1] != DTK_TIME &&
1330 ftype[i + 1] != DTK_DATE))
1331 return DTERR_BAD_FORMAT;
1333 ptype = val;
1334 break;
1336 case UNKNOWN_FIELD:
1339 * Before giving up and declaring error, check to see
1340 * if it is an all-alpha timezone name.
1342 namedTz = pg_tzset(field[i]);
1343 if (!namedTz)
1344 return DTERR_BAD_FORMAT;
1345 /* we'll apply the zone setting below */
1346 tmask = DTK_M(TZ);
1347 break;
1349 default:
1350 return DTERR_BAD_FORMAT;
1352 break;
1354 default:
1355 return DTERR_BAD_FORMAT;
1358 if (tmask & fmask)
1359 return DTERR_BAD_FORMAT;
1360 fmask |= tmask;
1361 } /* end loop over fields */
1363 /* do final checking/adjustment of Y/M/D fields */
1364 dterr = ValidateDate(fmask, is2digits, bc, tm);
1365 if (dterr)
1366 return dterr;
1368 /* handle AM/PM */
1369 if (mer != HR24 && tm->tm_hour > 12)
1370 return DTERR_FIELD_OVERFLOW;
1371 if (mer == AM && tm->tm_hour == 12)
1372 tm->tm_hour = 0;
1373 else if (mer == PM && tm->tm_hour != 12)
1374 tm->tm_hour += 12;
1376 /* do additional checking for full date specs... */
1377 if (*dtype == DTK_DATE)
1379 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1381 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1382 return 1;
1383 return DTERR_BAD_FORMAT;
1387 * If we had a full timezone spec, compute the offset (we could not do
1388 * it before, because we need the date to resolve DST status).
1390 if (namedTz != NULL)
1392 /* daylight savings time modifier disallowed with full TZ */
1393 if (fmask & DTK_M(DTZMOD))
1394 return DTERR_BAD_FORMAT;
1396 *tzp = DetermineTimeZoneOffset(tm, namedTz);
1399 /* timezone not specified? then find local timezone if possible */
1400 if (tzp != NULL && !(fmask & DTK_M(TZ)))
1403 * daylight savings time modifier but no standard timezone? then
1404 * error
1406 if (fmask & DTK_M(DTZMOD))
1407 return DTERR_BAD_FORMAT;
1409 *tzp = DetermineTimeZoneOffset(tm, session_timezone);
1413 return 0;
1417 /* DetermineTimeZoneOffset()
1419 * Given a struct pg_tm in which tm_year, tm_mon, tm_mday, tm_hour, tm_min, and
1420 * tm_sec fields are set, attempt to determine the applicable time zone
1421 * (ie, regular or daylight-savings time) at that time. Set the struct pg_tm's
1422 * tm_isdst field accordingly, and return the actual timezone offset.
1424 * Note: it might seem that we should use mktime() for this, but bitter
1425 * experience teaches otherwise. This code is much faster than most versions
1426 * of mktime(), anyway.
1429 DetermineTimeZoneOffset(struct pg_tm * tm, pg_tz *tzp)
1431 int date,
1432 sec;
1433 pg_time_t day,
1434 mytime,
1435 prevtime,
1436 boundary,
1437 beforetime,
1438 aftertime;
1439 long int before_gmtoff,
1440 after_gmtoff;
1441 int before_isdst,
1442 after_isdst;
1443 int res;
1445 if (tzp == session_timezone && HasCTZSet)
1447 tm->tm_isdst = 0; /* for lack of a better idea */
1448 return CTimeZone;
1452 * First, generate the pg_time_t value corresponding to the given
1453 * y/m/d/h/m/s taken as GMT time. If this overflows, punt and decide the
1454 * timezone is GMT. (We only need to worry about overflow on machines
1455 * where pg_time_t is 32 bits.)
1457 if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
1458 goto overflow;
1459 date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - UNIX_EPOCH_JDATE;
1461 day = ((pg_time_t) date) * SECS_PER_DAY;
1462 if (day / SECS_PER_DAY != date)
1463 goto overflow;
1464 sec = tm->tm_sec + (tm->tm_min + tm->tm_hour * MINS_PER_HOUR) * SECS_PER_MINUTE;
1465 mytime = day + sec;
1466 /* since sec >= 0, overflow could only be from +day to -mytime */
1467 if (mytime < 0 && day > 0)
1468 goto overflow;
1471 * Find the DST time boundary just before or following the target time. We
1472 * assume that all zones have GMT offsets less than 24 hours, and that DST
1473 * boundaries can't be closer together than 48 hours, so backing up 24
1474 * hours and finding the "next" boundary will work.
1476 prevtime = mytime - SECS_PER_DAY;
1477 if (mytime < 0 && prevtime > 0)
1478 goto overflow;
1480 res = pg_next_dst_boundary(&prevtime,
1481 &before_gmtoff, &before_isdst,
1482 &boundary,
1483 &after_gmtoff, &after_isdst,
1484 tzp);
1485 if (res < 0)
1486 goto overflow; /* failure? */
1488 if (res == 0)
1490 /* Non-DST zone, life is simple */
1491 tm->tm_isdst = before_isdst;
1492 return -(int) before_gmtoff;
1496 * Form the candidate pg_time_t values with local-time adjustment
1498 beforetime = mytime - before_gmtoff;
1499 if ((before_gmtoff > 0 &&
1500 mytime < 0 && beforetime > 0) ||
1501 (before_gmtoff <= 0 &&
1502 mytime > 0 && beforetime < 0))
1503 goto overflow;
1504 aftertime = mytime - after_gmtoff;
1505 if ((after_gmtoff > 0 &&
1506 mytime < 0 && aftertime > 0) ||
1507 (after_gmtoff <= 0 &&
1508 mytime > 0 && aftertime < 0))
1509 goto overflow;
1512 * If both before or both after the boundary time, we know what to do
1514 if (beforetime <= boundary && aftertime < boundary)
1516 tm->tm_isdst = before_isdst;
1517 return -(int) before_gmtoff;
1519 if (beforetime > boundary && aftertime >= boundary)
1521 tm->tm_isdst = after_isdst;
1522 return -(int) after_gmtoff;
1526 * It's an invalid or ambiguous time due to timezone transition. Prefer
1527 * the standard-time interpretation.
1529 if (after_isdst == 0)
1531 tm->tm_isdst = after_isdst;
1532 return -(int) after_gmtoff;
1534 tm->tm_isdst = before_isdst;
1535 return -(int) before_gmtoff;
1537 overflow:
1538 /* Given date is out of range, so assume UTC */
1539 tm->tm_isdst = 0;
1540 return 0;
1544 /* DecodeTimeOnly()
1545 * Interpret parsed string as time fields only.
1546 * Returns 0 if successful, DTERR code if bogus input detected.
1548 * Note that support for time zone is here for
1549 * SQL92 TIME WITH TIME ZONE, but it reveals
1550 * bogosity with SQL92 date/time standards, since
1551 * we must infer a time zone from current time.
1552 * - thomas 2000-03-10
1553 * Allow specifying date to get a better time zone,
1554 * if time zones are allowed. - thomas 2001-12-26
1557 DecodeTimeOnly(char **field, int *ftype, int nf,
1558 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
1560 int fmask = 0,
1561 tmask,
1562 type;
1563 int ptype = 0; /* "prefix type" for ISO h04mm05s06 format */
1564 int i;
1565 int val;
1566 int dterr;
1567 bool is2digits = FALSE;
1568 bool bc = FALSE;
1569 int mer = HR24;
1570 pg_tz *namedTz = NULL;
1572 *dtype = DTK_TIME;
1573 tm->tm_hour = 0;
1574 tm->tm_min = 0;
1575 tm->tm_sec = 0;
1576 *fsec = 0;
1577 /* don't know daylight savings time status apriori */
1578 tm->tm_isdst = -1;
1580 if (tzp != NULL)
1581 *tzp = 0;
1583 for (i = 0; i < nf; i++)
1585 switch (ftype[i])
1587 case DTK_DATE:
1590 * Time zone not allowed? Then should not accept dates or time
1591 * zones no matter what else!
1593 if (tzp == NULL)
1594 return DTERR_BAD_FORMAT;
1596 /* Under limited circumstances, we will accept a date... */
1597 if (i == 0 && nf >= 2 &&
1598 (ftype[nf - 1] == DTK_DATE || ftype[1] == DTK_TIME))
1600 dterr = DecodeDate(field[i], fmask,
1601 &tmask, &is2digits, tm);
1602 if (dterr)
1603 return dterr;
1605 /* otherwise, this is a time and/or time zone */
1606 else
1608 if (isdigit((unsigned char) *field[i]))
1610 char *cp;
1613 * Starts with a digit but we already have a time
1614 * field? Then we are in trouble with time already...
1616 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1617 return DTERR_BAD_FORMAT;
1620 * Should not get here and fail. Sanity check only...
1622 if ((cp = strchr(field[i], '-')) == NULL)
1623 return DTERR_BAD_FORMAT;
1625 /* Get the time zone from the end of the string */
1626 dterr = DecodeTimezone(cp, tzp);
1627 if (dterr)
1628 return dterr;
1629 *cp = '\0';
1632 * Then read the rest of the field as a concatenated
1633 * time
1635 dterr = DecodeNumberField(strlen(field[i]), field[i],
1636 (fmask | DTK_DATE_M),
1637 &tmask, tm,
1638 fsec, &is2digits);
1639 if (dterr < 0)
1640 return dterr;
1641 ftype[i] = dterr;
1643 tmask |= DTK_M(TZ);
1645 else
1647 namedTz = pg_tzset(field[i]);
1648 if (!namedTz)
1651 * We should return an error code instead of
1652 * ereport'ing directly, but then there is no way
1653 * to report the bad time zone name.
1655 ereport(ERROR,
1656 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1657 errmsg("time zone \"%s\" not recognized",
1658 field[i])));
1660 /* we'll apply the zone setting below */
1661 ftype[i] = DTK_TZ;
1662 tmask = DTK_M(TZ);
1665 break;
1667 case DTK_TIME:
1668 dterr = DecodeTime(field[i], (fmask | DTK_DATE_M),
1669 INTERVAL_FULL_RANGE,
1670 &tmask, tm, fsec);
1671 if (dterr)
1672 return dterr;
1673 break;
1675 case DTK_TZ:
1677 int tz;
1679 if (tzp == NULL)
1680 return DTERR_BAD_FORMAT;
1682 dterr = DecodeTimezone(field[i], &tz);
1683 if (dterr)
1684 return dterr;
1685 *tzp = tz;
1686 tmask = DTK_M(TZ);
1688 break;
1690 case DTK_NUMBER:
1693 * Was this an "ISO time" with embedded field labels? An
1694 * example is "h04m05s06" - thomas 2001-02-04
1696 if (ptype != 0)
1698 char *cp;
1699 int val;
1701 /* Only accept a date under limited circumstances */
1702 switch (ptype)
1704 case DTK_JULIAN:
1705 case DTK_YEAR:
1706 case DTK_MONTH:
1707 case DTK_DAY:
1708 if (tzp == NULL)
1709 return DTERR_BAD_FORMAT;
1710 default:
1711 break;
1714 errno = 0;
1715 val = strtoi(field[i], &cp, 10);
1716 if (errno == ERANGE)
1717 return DTERR_FIELD_OVERFLOW;
1720 * only a few kinds are allowed to have an embedded
1721 * decimal
1723 if (*cp == '.')
1724 switch (ptype)
1726 case DTK_JULIAN:
1727 case DTK_TIME:
1728 case DTK_SECOND:
1729 break;
1730 default:
1731 return DTERR_BAD_FORMAT;
1732 break;
1734 else if (*cp != '\0')
1735 return DTERR_BAD_FORMAT;
1737 switch (ptype)
1739 case DTK_YEAR:
1740 tm->tm_year = val;
1741 tmask = DTK_M(YEAR);
1742 break;
1744 case DTK_MONTH:
1747 * already have a month and hour? then assume
1748 * minutes
1750 if ((fmask & DTK_M(MONTH)) != 0 &&
1751 (fmask & DTK_M(HOUR)) != 0)
1753 tm->tm_min = val;
1754 tmask = DTK_M(MINUTE);
1756 else
1758 tm->tm_mon = val;
1759 tmask = DTK_M(MONTH);
1761 break;
1763 case DTK_DAY:
1764 tm->tm_mday = val;
1765 tmask = DTK_M(DAY);
1766 break;
1768 case DTK_HOUR:
1769 tm->tm_hour = val;
1770 tmask = DTK_M(HOUR);
1771 break;
1773 case DTK_MINUTE:
1774 tm->tm_min = val;
1775 tmask = DTK_M(MINUTE);
1776 break;
1778 case DTK_SECOND:
1779 tm->tm_sec = val;
1780 tmask = DTK_M(SECOND);
1781 if (*cp == '.')
1783 dterr = ParseFractionalSecond(cp, fsec);
1784 if (dterr)
1785 return dterr;
1786 tmask = DTK_ALL_SECS_M;
1788 break;
1790 case DTK_TZ:
1791 tmask = DTK_M(TZ);
1792 dterr = DecodeTimezone(field[i], tzp);
1793 if (dterr)
1794 return dterr;
1795 break;
1797 case DTK_JULIAN:
1798 /***
1799 * previous field was a label for "julian date"?
1800 ***/
1801 tmask = DTK_DATE_M;
1802 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1803 if (*cp == '.')
1805 double time;
1807 errno = 0;
1808 time = strtod(cp, &cp);
1809 if (*cp != '\0' || errno != 0)
1810 return DTERR_BAD_FORMAT;
1812 #ifdef HAVE_INT64_TIMESTAMP
1813 time *= USECS_PER_DAY;
1814 #else
1815 time *= SECS_PER_DAY;
1816 #endif
1817 dt2time(time,
1818 &tm->tm_hour, &tm->tm_min,
1819 &tm->tm_sec, fsec);
1820 tmask |= DTK_TIME_M;
1822 break;
1824 case DTK_TIME:
1825 /* previous field was "t" for ISO time */
1826 dterr = DecodeNumberField(strlen(field[i]), field[i],
1827 (fmask | DTK_DATE_M),
1828 &tmask, tm,
1829 fsec, &is2digits);
1830 if (dterr < 0)
1831 return dterr;
1832 ftype[i] = dterr;
1834 if (tmask != DTK_TIME_M)
1835 return DTERR_BAD_FORMAT;
1836 break;
1838 default:
1839 return DTERR_BAD_FORMAT;
1840 break;
1843 ptype = 0;
1844 *dtype = DTK_DATE;
1846 else
1848 char *cp;
1849 int flen;
1851 flen = strlen(field[i]);
1852 cp = strchr(field[i], '.');
1854 /* Embedded decimal? */
1855 if (cp != NULL)
1858 * Under limited circumstances, we will accept a
1859 * date...
1861 if (i == 0 && nf >= 2 && ftype[nf - 1] == DTK_DATE)
1863 dterr = DecodeDate(field[i], fmask,
1864 &tmask, &is2digits, tm);
1865 if (dterr)
1866 return dterr;
1868 /* embedded decimal and several digits before? */
1869 else if (flen - strlen(cp) > 2)
1872 * Interpret as a concatenated date or time Set
1873 * the type field to allow decoding other fields
1874 * later. Example: 20011223 or 040506
1876 dterr = DecodeNumberField(flen, field[i],
1877 (fmask | DTK_DATE_M),
1878 &tmask, tm,
1879 fsec, &is2digits);
1880 if (dterr < 0)
1881 return dterr;
1882 ftype[i] = dterr;
1884 else
1885 return DTERR_BAD_FORMAT;
1887 else if (flen > 4)
1889 dterr = DecodeNumberField(flen, field[i],
1890 (fmask | DTK_DATE_M),
1891 &tmask, tm,
1892 fsec, &is2digits);
1893 if (dterr < 0)
1894 return dterr;
1895 ftype[i] = dterr;
1897 /* otherwise it is a single date/time field... */
1898 else
1900 dterr = DecodeNumber(flen, field[i],
1901 FALSE,
1902 (fmask | DTK_DATE_M),
1903 &tmask, tm,
1904 fsec, &is2digits);
1905 if (dterr)
1906 return dterr;
1909 break;
1911 case DTK_STRING:
1912 case DTK_SPECIAL:
1913 type = DecodeSpecial(i, field[i], &val);
1914 if (type == IGNORE_DTF)
1915 continue;
1917 tmask = DTK_M(type);
1918 switch (type)
1920 case RESERV:
1921 switch (val)
1923 case DTK_CURRENT:
1924 ereport(ERROR,
1925 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1926 errmsg("date/time value \"current\" is no longer supported")));
1927 return DTERR_BAD_FORMAT;
1928 break;
1930 case DTK_NOW:
1931 tmask = DTK_TIME_M;
1932 *dtype = DTK_TIME;
1933 GetCurrentTimeUsec(tm, fsec, NULL);
1934 break;
1936 case DTK_ZULU:
1937 tmask = (DTK_TIME_M | DTK_M(TZ));
1938 *dtype = DTK_TIME;
1939 tm->tm_hour = 0;
1940 tm->tm_min = 0;
1941 tm->tm_sec = 0;
1942 tm->tm_isdst = 0;
1943 break;
1945 default:
1946 return DTERR_BAD_FORMAT;
1949 break;
1951 case DTZMOD:
1954 * daylight savings time modifier (solves "MET DST"
1955 * syntax)
1957 tmask |= DTK_M(DTZ);
1958 tm->tm_isdst = 1;
1959 if (tzp == NULL)
1960 return DTERR_BAD_FORMAT;
1961 *tzp += val * MINS_PER_HOUR;
1962 break;
1964 case DTZ:
1967 * set mask for TZ here _or_ check for DTZ later when
1968 * getting default timezone
1970 tmask |= DTK_M(TZ);
1971 tm->tm_isdst = 1;
1972 if (tzp == NULL)
1973 return DTERR_BAD_FORMAT;
1974 *tzp = val * MINS_PER_HOUR;
1975 ftype[i] = DTK_TZ;
1976 break;
1978 case TZ:
1979 tm->tm_isdst = 0;
1980 if (tzp == NULL)
1981 return DTERR_BAD_FORMAT;
1982 *tzp = val * MINS_PER_HOUR;
1983 ftype[i] = DTK_TZ;
1984 break;
1986 case IGNORE_DTF:
1987 break;
1989 case AMPM:
1990 mer = val;
1991 break;
1993 case ADBC:
1994 bc = (val == BC);
1995 break;
1997 case UNITS:
1998 tmask = 0;
1999 ptype = val;
2000 break;
2002 case ISOTIME:
2003 tmask = 0;
2005 /***
2006 * We will need one of the following fields:
2007 * DTK_NUMBER should be hhmmss.fff
2008 * DTK_TIME should be hh:mm:ss.fff
2009 * DTK_DATE should be hhmmss-zz
2010 ***/
2011 if (i >= nf - 1 ||
2012 (ftype[i + 1] != DTK_NUMBER &&
2013 ftype[i + 1] != DTK_TIME &&
2014 ftype[i + 1] != DTK_DATE))
2015 return DTERR_BAD_FORMAT;
2017 ptype = val;
2018 break;
2020 case UNKNOWN_FIELD:
2023 * Before giving up and declaring error, check to see
2024 * if it is an all-alpha timezone name.
2026 namedTz = pg_tzset(field[i]);
2027 if (!namedTz)
2028 return DTERR_BAD_FORMAT;
2029 /* we'll apply the zone setting below */
2030 tmask = DTK_M(TZ);
2031 break;
2033 default:
2034 return DTERR_BAD_FORMAT;
2036 break;
2038 default:
2039 return DTERR_BAD_FORMAT;
2042 if (tmask & fmask)
2043 return DTERR_BAD_FORMAT;
2044 fmask |= tmask;
2045 } /* end loop over fields */
2047 /* do final checking/adjustment of Y/M/D fields */
2048 dterr = ValidateDate(fmask, is2digits, bc, tm);
2049 if (dterr)
2050 return dterr;
2052 /* handle AM/PM */
2053 if (mer != HR24 && tm->tm_hour > 12)
2054 return DTERR_FIELD_OVERFLOW;
2055 if (mer == AM && tm->tm_hour == 12)
2056 tm->tm_hour = 0;
2057 else if (mer == PM && tm->tm_hour != 12)
2058 tm->tm_hour += 12;
2060 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2061 tm->tm_sec < 0 || tm->tm_sec > 60 || tm->tm_hour > 24 ||
2062 /* test for > 24:00:00 */
2063 (tm->tm_hour == 24 &&
2064 (tm->tm_min > 0 || tm->tm_sec > 0 || *fsec > 0)) ||
2065 #ifdef HAVE_INT64_TIMESTAMP
2066 *fsec < INT64CONST(0) || *fsec > USECS_PER_SEC
2067 #else
2068 *fsec < 0 || *fsec > 1
2069 #endif
2071 return DTERR_FIELD_OVERFLOW;
2073 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2074 return DTERR_BAD_FORMAT;
2077 * If we had a full timezone spec, compute the offset (we could not do it
2078 * before, because we may need the date to resolve DST status).
2080 if (namedTz != NULL)
2082 long int gmtoff;
2084 /* daylight savings time modifier disallowed with full TZ */
2085 if (fmask & DTK_M(DTZMOD))
2086 return DTERR_BAD_FORMAT;
2088 /* if non-DST zone, we do not need to know the date */
2089 if (pg_get_timezone_offset(namedTz, &gmtoff))
2091 *tzp = -(int) gmtoff;
2093 else
2095 /* a date has to be specified */
2096 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2097 return DTERR_BAD_FORMAT;
2098 *tzp = DetermineTimeZoneOffset(tm, namedTz);
2102 /* timezone not specified? then find local timezone if possible */
2103 if (tzp != NULL && !(fmask & DTK_M(TZ)))
2105 struct pg_tm tt,
2106 *tmp = &tt;
2109 * daylight savings time modifier but no standard timezone? then error
2111 if (fmask & DTK_M(DTZMOD))
2112 return DTERR_BAD_FORMAT;
2114 if ((fmask & DTK_DATE_M) == 0)
2115 GetCurrentDateTime(tmp);
2116 else
2118 tmp->tm_year = tm->tm_year;
2119 tmp->tm_mon = tm->tm_mon;
2120 tmp->tm_mday = tm->tm_mday;
2122 tmp->tm_hour = tm->tm_hour;
2123 tmp->tm_min = tm->tm_min;
2124 tmp->tm_sec = tm->tm_sec;
2125 *tzp = DetermineTimeZoneOffset(tmp, session_timezone);
2126 tm->tm_isdst = tmp->tm_isdst;
2129 return 0;
2132 /* DecodeDate()
2133 * Decode date string which includes delimiters.
2134 * Return 0 if okay, a DTERR code if not.
2136 * str: field to be parsed
2137 * fmask: bitmask for field types already seen
2138 * *tmask: receives bitmask for fields found here
2139 * *is2digits: set to TRUE if we find 2-digit year
2140 * *tm: field values are stored into appropriate members of this struct
2142 static int
2143 DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
2144 struct pg_tm * tm)
2146 fsec_t fsec;
2147 int nf = 0;
2148 int i,
2149 len;
2150 int dterr;
2151 bool haveTextMonth = FALSE;
2152 int type,
2153 val,
2154 dmask = 0;
2155 char *field[MAXDATEFIELDS];
2157 *tmask = 0;
2159 /* parse this string... */
2160 while (*str != '\0' && nf < MAXDATEFIELDS)
2162 /* skip field separators */
2163 while (!isalnum((unsigned char) *str))
2164 str++;
2166 field[nf] = str;
2167 if (isdigit((unsigned char) *str))
2169 while (isdigit((unsigned char) *str))
2170 str++;
2172 else if (isalpha((unsigned char) *str))
2174 while (isalpha((unsigned char) *str))
2175 str++;
2178 /* Just get rid of any non-digit, non-alpha characters... */
2179 if (*str != '\0')
2180 *str++ = '\0';
2181 nf++;
2184 /* look first for text fields, since that will be unambiguous month */
2185 for (i = 0; i < nf; i++)
2187 if (isalpha((unsigned char) *field[i]))
2189 type = DecodeSpecial(i, field[i], &val);
2190 if (type == IGNORE_DTF)
2191 continue;
2193 dmask = DTK_M(type);
2194 switch (type)
2196 case MONTH:
2197 tm->tm_mon = val;
2198 haveTextMonth = TRUE;
2199 break;
2201 default:
2202 return DTERR_BAD_FORMAT;
2204 if (fmask & dmask)
2205 return DTERR_BAD_FORMAT;
2207 fmask |= dmask;
2208 *tmask |= dmask;
2210 /* mark this field as being completed */
2211 field[i] = NULL;
2215 /* now pick up remaining numeric fields */
2216 for (i = 0; i < nf; i++)
2218 if (field[i] == NULL)
2219 continue;
2221 if ((len = strlen(field[i])) <= 0)
2222 return DTERR_BAD_FORMAT;
2224 dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2225 &dmask, tm,
2226 &fsec, is2digits);
2227 if (dterr)
2228 return dterr;
2230 if (fmask & dmask)
2231 return DTERR_BAD_FORMAT;
2233 fmask |= dmask;
2234 *tmask |= dmask;
2237 if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
2238 return DTERR_BAD_FORMAT;
2240 /* validation of the field values must wait until ValidateDate() */
2242 return 0;
2245 /* ValidateDate()
2246 * Check valid year/month/day values, handle BC and DOY cases
2247 * Return 0 if okay, a DTERR code if not.
2249 static int
2250 ValidateDate(int fmask, bool is2digits, bool bc, struct pg_tm * tm)
2252 if (fmask & DTK_M(YEAR))
2254 if (bc)
2256 /* there is no year zero in AD/BC notation */
2257 if (tm->tm_year <= 0)
2258 return DTERR_FIELD_OVERFLOW;
2259 /* internally, we represent 1 BC as year zero, 2 BC as -1, etc */
2260 tm->tm_year = -(tm->tm_year - 1);
2262 else if (is2digits)
2264 /* process 1 or 2-digit input as 1970-2069 AD, allow '0' and '00' */
2265 if (tm->tm_year < 0) /* just paranoia */
2266 return DTERR_FIELD_OVERFLOW;
2267 if (tm->tm_year < 70)
2268 tm->tm_year += 2000;
2269 else if (tm->tm_year < 100)
2270 tm->tm_year += 1900;
2272 else
2274 /* there is no year zero in AD/BC notation */
2275 if (tm->tm_year <= 0)
2276 return DTERR_FIELD_OVERFLOW;
2280 /* now that we have correct year, decode DOY */
2281 if (fmask & DTK_M(DOY))
2283 j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
2284 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2287 /* check for valid month */
2288 if (fmask & DTK_M(MONTH))
2290 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
2291 return DTERR_MD_FIELD_OVERFLOW;
2294 /* minimal check for valid day */
2295 if (fmask & DTK_M(DAY))
2297 if (tm->tm_mday < 1 || tm->tm_mday > 31)
2298 return DTERR_MD_FIELD_OVERFLOW;
2301 if ((fmask & DTK_DATE_M) == DTK_DATE_M)
2304 * Check for valid day of month, now that we know for sure the month
2305 * and year. Note we don't use MD_FIELD_OVERFLOW here, since it seems
2306 * unlikely that "Feb 29" is a YMD-order error.
2308 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2309 return DTERR_FIELD_OVERFLOW;
2312 return 0;
2316 /* DecodeTime()
2317 * Decode time string which includes delimiters.
2318 * Return 0 if okay, a DTERR code if not.
2320 * Only check the lower limit on hours, since this same code can be
2321 * used to represent time spans.
2323 static int
2324 DecodeTime(char *str, int fmask, int range,
2325 int *tmask, struct pg_tm * tm, fsec_t *fsec)
2327 char *cp;
2328 int dterr;
2330 *tmask = DTK_TIME_M;
2332 errno = 0;
2333 tm->tm_hour = strtoi(str, &cp, 10);
2334 if (errno == ERANGE)
2335 return DTERR_FIELD_OVERFLOW;
2336 if (*cp != ':')
2337 return DTERR_BAD_FORMAT;
2338 errno = 0;
2339 tm->tm_min = strtoi(cp + 1, &cp, 10);
2340 if (errno == ERANGE)
2341 return DTERR_FIELD_OVERFLOW;
2342 if (*cp == '\0')
2344 tm->tm_sec = 0;
2345 *fsec = 0;
2346 /* If it's a MINUTE TO SECOND interval, take 2 fields as being mm:ss */
2347 if (range == (INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND)))
2349 tm->tm_sec = tm->tm_min;
2350 tm->tm_min = tm->tm_hour;
2351 tm->tm_hour = 0;
2354 else if (*cp == '.')
2356 /* always assume mm:ss.sss is MINUTE TO SECOND */
2357 dterr = ParseFractionalSecond(cp, fsec);
2358 if (dterr)
2359 return dterr;
2360 tm->tm_sec = tm->tm_min;
2361 tm->tm_min = tm->tm_hour;
2362 tm->tm_hour = 0;
2364 else if (*cp == ':')
2366 errno = 0;
2367 tm->tm_sec = strtoi(cp + 1, &cp, 10);
2368 if (errno == ERANGE)
2369 return DTERR_FIELD_OVERFLOW;
2370 if (*cp == '\0')
2371 *fsec = 0;
2372 else if (*cp == '.')
2374 dterr = ParseFractionalSecond(cp, fsec);
2375 if (dterr)
2376 return dterr;
2378 else
2379 return DTERR_BAD_FORMAT;
2381 else
2382 return DTERR_BAD_FORMAT;
2384 /* do a sanity check */
2385 #ifdef HAVE_INT64_TIMESTAMP
2386 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2387 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < INT64CONST(0) ||
2388 *fsec > USECS_PER_SEC)
2389 return DTERR_FIELD_OVERFLOW;
2390 #else
2391 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2392 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < 0 || *fsec > 1)
2393 return DTERR_FIELD_OVERFLOW;
2394 #endif
2396 return 0;
2400 /* DecodeNumber()
2401 * Interpret plain numeric field as a date value in context.
2402 * Return 0 if okay, a DTERR code if not.
2404 static int
2405 DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask,
2406 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2408 int val;
2409 char *cp;
2410 int dterr;
2412 *tmask = 0;
2414 errno = 0;
2415 val = strtoi(str, &cp, 10);
2416 if (errno == ERANGE)
2417 return DTERR_FIELD_OVERFLOW;
2418 if (cp == str)
2419 return DTERR_BAD_FORMAT;
2421 if (*cp == '.')
2424 * More than two digits before decimal point? Then could be a date or
2425 * a run-together time: 2001.360 20011225 040506.789
2427 if (cp - str > 2)
2429 dterr = DecodeNumberField(flen, str,
2430 (fmask | DTK_DATE_M),
2431 tmask, tm,
2432 fsec, is2digits);
2433 if (dterr < 0)
2434 return dterr;
2435 return 0;
2438 dterr = ParseFractionalSecond(cp, fsec);
2439 if (dterr)
2440 return dterr;
2442 else if (*cp != '\0')
2443 return DTERR_BAD_FORMAT;
2445 /* Special case for day of year */
2446 if (flen == 3 && (fmask & DTK_DATE_M) == DTK_M(YEAR) && val >= 1 &&
2447 val <= 366)
2449 *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2450 tm->tm_yday = val;
2451 /* tm_mon and tm_mday can't actually be set yet ... */
2452 return 0;
2455 /* Switch based on what we have so far */
2456 switch (fmask & DTK_DATE_M)
2458 case 0:
2461 * Nothing so far; make a decision about what we think the input
2462 * is. There used to be lots of heuristics here, but the
2463 * consensus now is to be paranoid. It *must* be either
2464 * YYYY-MM-DD (with a more-than-two-digit year field), or the
2465 * field order defined by DateOrder.
2467 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2469 *tmask = DTK_M(YEAR);
2470 tm->tm_year = val;
2472 else if (DateOrder == DATEORDER_DMY)
2474 *tmask = DTK_M(DAY);
2475 tm->tm_mday = val;
2477 else
2479 *tmask = DTK_M(MONTH);
2480 tm->tm_mon = val;
2482 break;
2484 case (DTK_M(YEAR)):
2485 /* Must be at second field of YY-MM-DD */
2486 *tmask = DTK_M(MONTH);
2487 tm->tm_mon = val;
2488 break;
2490 case (DTK_M(MONTH)):
2491 if (haveTextMonth)
2494 * We are at the first numeric field of a date that included a
2495 * textual month name. We want to support the variants
2496 * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2497 * inputs. We will also accept MON-DD-YY or DD-MON-YY in
2498 * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2500 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2502 *tmask = DTK_M(YEAR);
2503 tm->tm_year = val;
2505 else
2507 *tmask = DTK_M(DAY);
2508 tm->tm_mday = val;
2511 else
2513 /* Must be at second field of MM-DD-YY */
2514 *tmask = DTK_M(DAY);
2515 tm->tm_mday = val;
2517 break;
2519 case (DTK_M(YEAR) | DTK_M(MONTH)):
2520 if (haveTextMonth)
2522 /* Need to accept DD-MON-YYYY even in YMD mode */
2523 if (flen >= 3 && *is2digits)
2525 /* Guess that first numeric field is day was wrong */
2526 *tmask = DTK_M(DAY); /* YEAR is already set */
2527 tm->tm_mday = tm->tm_year;
2528 tm->tm_year = val;
2529 *is2digits = FALSE;
2531 else
2533 *tmask = DTK_M(DAY);
2534 tm->tm_mday = val;
2537 else
2539 /* Must be at third field of YY-MM-DD */
2540 *tmask = DTK_M(DAY);
2541 tm->tm_mday = val;
2543 break;
2545 case (DTK_M(DAY)):
2546 /* Must be at second field of DD-MM-YY */
2547 *tmask = DTK_M(MONTH);
2548 tm->tm_mon = val;
2549 break;
2551 case (DTK_M(MONTH) | DTK_M(DAY)):
2552 /* Must be at third field of DD-MM-YY or MM-DD-YY */
2553 *tmask = DTK_M(YEAR);
2554 tm->tm_year = val;
2555 break;
2557 case (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY)):
2558 /* we have all the date, so it must be a time field */
2559 dterr = DecodeNumberField(flen, str, fmask,
2560 tmask, tm,
2561 fsec, is2digits);
2562 if (dterr < 0)
2563 return dterr;
2564 return 0;
2566 default:
2567 /* Anything else is bogus input */
2568 return DTERR_BAD_FORMAT;
2572 * When processing a year field, mark it for adjustment if it's only one
2573 * or two digits.
2575 if (*tmask == DTK_M(YEAR))
2576 *is2digits = (flen <= 2);
2578 return 0;
2582 /* DecodeNumberField()
2583 * Interpret numeric string as a concatenated date or time field.
2584 * Return a DTK token (>= 0) if successful, a DTERR code (< 0) if not.
2586 * Use the context of previously decoded fields to help with
2587 * the interpretation.
2589 static int
2590 DecodeNumberField(int len, char *str, int fmask,
2591 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2593 char *cp;
2596 * Have a decimal point? Then this is a date or something with a seconds
2597 * field...
2599 if ((cp = strchr(str, '.')) != NULL)
2602 * Can we use ParseFractionalSecond here? Not clear whether trailing
2603 * junk should be rejected ...
2605 double frac;
2607 errno = 0;
2608 frac = strtod(cp, NULL);
2609 if (errno != 0)
2610 return DTERR_BAD_FORMAT;
2611 #ifdef HAVE_INT64_TIMESTAMP
2612 *fsec = rint(frac * 1000000);
2613 #else
2614 *fsec = frac;
2615 #endif
2616 /* Now truncate off the fraction for further processing */
2617 *cp = '\0';
2618 len = strlen(str);
2620 /* No decimal point and no complete date yet? */
2621 else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2623 /* yyyymmdd? */
2624 if (len == 8)
2626 *tmask = DTK_DATE_M;
2628 tm->tm_mday = atoi(str + 6);
2629 *(str + 6) = '\0';
2630 tm->tm_mon = atoi(str + 4);
2631 *(str + 4) = '\0';
2632 tm->tm_year = atoi(str + 0);
2634 return DTK_DATE;
2636 /* yymmdd? */
2637 else if (len == 6)
2639 *tmask = DTK_DATE_M;
2640 tm->tm_mday = atoi(str + 4);
2641 *(str + 4) = '\0';
2642 tm->tm_mon = atoi(str + 2);
2643 *(str + 2) = '\0';
2644 tm->tm_year = atoi(str + 0);
2645 *is2digits = TRUE;
2647 return DTK_DATE;
2651 /* not all time fields are specified? */
2652 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2654 /* hhmmss */
2655 if (len == 6)
2657 *tmask = DTK_TIME_M;
2658 tm->tm_sec = atoi(str + 4);
2659 *(str + 4) = '\0';
2660 tm->tm_min = atoi(str + 2);
2661 *(str + 2) = '\0';
2662 tm->tm_hour = atoi(str + 0);
2664 return DTK_TIME;
2666 /* hhmm? */
2667 else if (len == 4)
2669 *tmask = DTK_TIME_M;
2670 tm->tm_sec = 0;
2671 tm->tm_min = atoi(str + 2);
2672 *(str + 2) = '\0';
2673 tm->tm_hour = atoi(str + 0);
2675 return DTK_TIME;
2679 return DTERR_BAD_FORMAT;
2683 /* DecodeTimezone()
2684 * Interpret string as a numeric timezone.
2686 * Return 0 if okay (and set *tzp), a DTERR code if not okay.
2688 * NB: this must *not* ereport on failure; see commands/variable.c.
2690 * Note: we allow timezone offsets up to 13:59. There are places that
2691 * use +1300 summer time.
2693 static int
2694 DecodeTimezone(char *str, int *tzp)
2696 int tz;
2697 int hr,
2698 min,
2699 sec = 0;
2700 char *cp;
2702 /* leading character must be "+" or "-" */
2703 if (*str != '+' && *str != '-')
2704 return DTERR_BAD_FORMAT;
2706 errno = 0;
2707 hr = strtoi(str + 1, &cp, 10);
2708 if (errno == ERANGE)
2709 return DTERR_TZDISP_OVERFLOW;
2711 /* explicit delimiter? */
2712 if (*cp == ':')
2714 errno = 0;
2715 min = strtoi(cp + 1, &cp, 10);
2716 if (errno == ERANGE)
2717 return DTERR_TZDISP_OVERFLOW;
2718 if (*cp == ':')
2720 errno = 0;
2721 sec = strtoi(cp + 1, &cp, 10);
2722 if (errno == ERANGE)
2723 return DTERR_TZDISP_OVERFLOW;
2726 /* otherwise, might have run things together... */
2727 else if (*cp == '\0' && strlen(str) > 3)
2729 min = hr % 100;
2730 hr = hr / 100;
2731 /* we could, but don't, support a run-together hhmmss format */
2733 else
2734 min = 0;
2736 if (hr < 0 || hr > 14)
2737 return DTERR_TZDISP_OVERFLOW;
2738 if (min < 0 || min >= 60)
2739 return DTERR_TZDISP_OVERFLOW;
2740 if (sec < 0 || sec >= 60)
2741 return DTERR_TZDISP_OVERFLOW;
2743 tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
2744 if (*str == '-')
2745 tz = -tz;
2747 *tzp = -tz;
2749 if (*cp != '\0')
2750 return DTERR_BAD_FORMAT;
2752 return 0;
2755 /* DecodeSpecial()
2756 * Decode text string using lookup table.
2758 * Implement a cache lookup since it is likely that dates
2759 * will be related in format.
2761 * NB: this must *not* ereport on failure;
2762 * see commands/variable.c.
2765 DecodeSpecial(int field, char *lowtoken, int *val)
2767 int type;
2768 const datetkn *tp;
2770 tp = datecache[field];
2771 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
2773 tp = datebsearch(lowtoken, timezonetktbl, sztimezonetktbl);
2774 if (tp == NULL)
2775 tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
2777 if (tp == NULL)
2779 type = UNKNOWN_FIELD;
2780 *val = 0;
2782 else
2784 datecache[field] = tp;
2785 type = tp->type;
2786 switch (type)
2788 case TZ:
2789 case DTZ:
2790 case DTZMOD:
2791 *val = FROMVAL(tp);
2792 break;
2794 default:
2795 *val = tp->value;
2796 break;
2800 return type;
2804 /* ClearPgTM
2806 * Zero out a pg_tm and associated fsec_t
2808 static inline void
2809 ClearPgTm(struct pg_tm * tm, fsec_t *fsec)
2811 tm->tm_year = 0;
2812 tm->tm_mon = 0;
2813 tm->tm_mday = 0;
2814 tm->tm_hour = 0;
2815 tm->tm_min = 0;
2816 tm->tm_sec = 0;
2817 *fsec = 0;
2821 /* DecodeInterval()
2822 * Interpret previously parsed fields for general time interval.
2823 * Returns 0 if successful, DTERR code if bogus input detected.
2824 * dtype, tm, fsec are output parameters.
2826 * Allow "date" field DTK_DATE since this could be just
2827 * an unsigned floating point number. - thomas 1997-11-16
2829 * Allow ISO-style time span, with implicit units on number of days
2830 * preceding an hh:mm:ss field. - thomas 1998-04-30
2833 DecodeInterval(char **field, int *ftype, int nf, int range,
2834 int *dtype, struct pg_tm * tm, fsec_t *fsec)
2836 bool is_before = FALSE;
2837 char *cp;
2838 int fmask = 0,
2839 tmask,
2840 type;
2841 int i;
2842 int dterr;
2843 int val;
2844 double fval;
2846 *dtype = DTK_DELTA;
2847 type = IGNORE_DTF;
2848 ClearPgTm(tm, fsec);
2850 /* read through list backwards to pick up units before values */
2851 for (i = nf - 1; i >= 0; i--)
2853 switch (ftype[i])
2855 case DTK_TIME:
2856 dterr = DecodeTime(field[i], fmask, range,
2857 &tmask, tm, fsec);
2858 if (dterr)
2859 return dterr;
2860 type = DTK_DAY;
2861 break;
2863 case DTK_TZ:
2866 * Timezone is a token with a leading sign character and at
2867 * least one digit; there could be ':', '.', '-' embedded in
2868 * it as well.
2870 Assert(*field[i] == '-' || *field[i] == '+');
2873 * Try for hh:mm or hh:mm:ss. If not, fall through to
2874 * DTK_NUMBER case, which can handle signed float numbers and
2875 * signed year-month values.
2877 if (strchr(field[i] + 1, ':') != NULL &&
2878 DecodeTime(field[i] + 1, fmask, INTERVAL_FULL_RANGE,
2879 &tmask, tm, fsec) == 0)
2881 if (*field[i] == '-')
2883 /* flip the sign on all fields */
2884 tm->tm_hour = -tm->tm_hour;
2885 tm->tm_min = -tm->tm_min;
2886 tm->tm_sec = -tm->tm_sec;
2887 *fsec = -(*fsec);
2891 * Set the next type to be a day, if units are not
2892 * specified. This handles the case of '1 +02:03' since we
2893 * are reading right to left.
2895 type = DTK_DAY;
2896 tmask = DTK_M(TZ);
2897 break;
2899 /* FALL THROUGH */
2901 case DTK_DATE:
2902 case DTK_NUMBER:
2903 if (type == IGNORE_DTF)
2905 /* use typmod to decide what rightmost field is */
2906 switch (range)
2908 case INTERVAL_MASK(YEAR):
2909 type = DTK_YEAR;
2910 break;
2911 case INTERVAL_MASK(MONTH):
2912 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
2913 type = DTK_MONTH;
2914 break;
2915 case INTERVAL_MASK(DAY):
2916 type = DTK_DAY;
2917 break;
2918 case INTERVAL_MASK(HOUR):
2919 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
2920 type = DTK_HOUR;
2921 break;
2922 case INTERVAL_MASK(MINUTE):
2923 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
2924 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
2925 type = DTK_MINUTE;
2926 break;
2927 case INTERVAL_MASK(SECOND):
2928 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2929 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2930 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2931 type = DTK_SECOND;
2932 break;
2933 default:
2934 type = DTK_SECOND;
2935 break;
2939 errno = 0;
2940 val = strtoi(field[i], &cp, 10);
2941 if (errno == ERANGE)
2942 return DTERR_FIELD_OVERFLOW;
2944 if (*cp == '-')
2946 /* SQL "years-months" syntax */
2947 int val2;
2949 val2 = strtoi(cp + 1, &cp, 10);
2950 if (errno == ERANGE || val2 < 0 || val2 >= MONTHS_PER_YEAR)
2951 return DTERR_FIELD_OVERFLOW;
2952 if (*cp != '\0')
2953 return DTERR_BAD_FORMAT;
2954 type = DTK_MONTH;
2955 if (*field[i] == '-')
2956 val2 = -val2;
2957 val = val * MONTHS_PER_YEAR + val2;
2958 fval = 0;
2960 else if (*cp == '.')
2962 errno = 0;
2963 fval = strtod(cp, &cp);
2964 if (*cp != '\0' || errno != 0)
2965 return DTERR_BAD_FORMAT;
2967 if (*field[i] == '-')
2968 fval = -fval;
2970 else if (*cp == '\0')
2971 fval = 0;
2972 else
2973 return DTERR_BAD_FORMAT;
2975 tmask = 0; /* DTK_M(type); */
2977 switch (type)
2979 case DTK_MICROSEC:
2980 #ifdef HAVE_INT64_TIMESTAMP
2981 *fsec += rint(val + fval);
2982 #else
2983 *fsec += (val + fval) * 1e-6;
2984 #endif
2985 tmask = DTK_M(MICROSECOND);
2986 break;
2988 case DTK_MILLISEC:
2989 #ifdef HAVE_INT64_TIMESTAMP
2990 *fsec += rint((val + fval) * 1000);
2991 #else
2992 *fsec += (val + fval) * 1e-3;
2993 #endif
2994 tmask = DTK_M(MILLISECOND);
2995 break;
2997 case DTK_SECOND:
2998 tm->tm_sec += val;
2999 #ifdef HAVE_INT64_TIMESTAMP
3000 *fsec += rint(fval * 1000000);
3001 #else
3002 *fsec += fval;
3003 #endif
3006 * If any subseconds were specified, consider this
3007 * microsecond and millisecond input as well.
3009 if (fval == 0)
3010 tmask = DTK_M(SECOND);
3011 else
3012 tmask = DTK_ALL_SECS_M;
3013 break;
3015 case DTK_MINUTE:
3016 tm->tm_min += val;
3017 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3018 tmask = DTK_M(MINUTE);
3019 break;
3021 case DTK_HOUR:
3022 tm->tm_hour += val;
3023 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3024 tmask = DTK_M(HOUR);
3025 type = DTK_DAY; /* set for next field */
3026 break;
3028 case DTK_DAY:
3029 tm->tm_mday += val;
3030 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3031 tmask = DTK_M(DAY);
3032 break;
3034 case DTK_WEEK:
3035 tm->tm_mday += val * 7;
3036 AdjustFractDays(fval, tm, fsec, 7);
3037 tmask = DTK_M(WEEK);
3038 break;
3040 case DTK_MONTH:
3041 tm->tm_mon += val;
3042 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3043 tmask = DTK_M(MONTH);
3044 break;
3046 case DTK_YEAR:
3047 tm->tm_year += val;
3048 if (fval != 0)
3049 tm->tm_mon += fval * MONTHS_PER_YEAR;
3050 tmask = DTK_M(YEAR);
3051 break;
3053 case DTK_DECADE:
3054 tm->tm_year += val * 10;
3055 if (fval != 0)
3056 tm->tm_mon += fval * MONTHS_PER_YEAR * 10;
3057 tmask = DTK_M(DECADE);
3058 break;
3060 case DTK_CENTURY:
3061 tm->tm_year += val * 100;
3062 if (fval != 0)
3063 tm->tm_mon += fval * MONTHS_PER_YEAR * 100;
3064 tmask = DTK_M(CENTURY);
3065 break;
3067 case DTK_MILLENNIUM:
3068 tm->tm_year += val * 1000;
3069 if (fval != 0)
3070 tm->tm_mon += fval * MONTHS_PER_YEAR * 1000;
3071 tmask = DTK_M(MILLENNIUM);
3072 break;
3074 default:
3075 return DTERR_BAD_FORMAT;
3077 break;
3079 case DTK_STRING:
3080 case DTK_SPECIAL:
3081 type = DecodeUnits(i, field[i], &val);
3082 if (type == IGNORE_DTF)
3083 continue;
3085 tmask = 0; /* DTK_M(type); */
3086 switch (type)
3088 case UNITS:
3089 type = val;
3090 break;
3092 case AGO:
3093 is_before = TRUE;
3094 type = val;
3095 break;
3097 case RESERV:
3098 tmask = (DTK_DATE_M || DTK_TIME_M);
3099 *dtype = val;
3100 break;
3102 default:
3103 return DTERR_BAD_FORMAT;
3105 break;
3107 default:
3108 return DTERR_BAD_FORMAT;
3111 if (tmask & fmask)
3112 return DTERR_BAD_FORMAT;
3113 fmask |= tmask;
3116 /* ensure that at least one time field has been found */
3117 if (fmask == 0)
3118 return DTERR_BAD_FORMAT;
3120 /* ensure fractional seconds are fractional */
3121 if (*fsec != 0)
3123 int sec;
3125 #ifdef HAVE_INT64_TIMESTAMP
3126 sec = *fsec / USECS_PER_SEC;
3127 *fsec -= sec * USECS_PER_SEC;
3128 #else
3129 TMODULO(*fsec, sec, 1.0);
3130 #endif
3131 tm->tm_sec += sec;
3134 /*----------
3135 * The SQL standard defines the interval literal
3136 * '-1 1:00:00'
3137 * to mean "negative 1 days and negative 1 hours", while Postgres
3138 * traditionally treats this as meaning "negative 1 days and positive
3139 * 1 hours". In SQL_STANDARD intervalstyle, we apply the leading sign
3140 * to all fields if there are no other explicit signs.
3142 * We leave the signs alone if there are additional explicit signs.
3143 * This protects us against misinterpreting postgres-style dump output,
3144 * since the postgres-style output code has always put an explicit sign on
3145 * all fields following a negative field. But note that SQL-spec output
3146 * is ambiguous and can be misinterpreted on load! (So it's best practice
3147 * to dump in postgres style, not SQL style.)
3148 *----------
3150 if (IntervalStyle == INTSTYLE_SQL_STANDARD && *field[0] == '-')
3152 /* Check for additional explicit signs */
3153 bool more_signs = false;
3155 for (i = 1; i < nf; i++)
3157 if (*field[i] == '-' || *field[i] == '+')
3159 more_signs = true;
3160 break;
3164 if (!more_signs)
3167 * Rather than re-determining which field was field[0], just force
3168 * 'em all negative.
3170 if (*fsec > 0)
3171 *fsec = -(*fsec);
3172 if (tm->tm_sec > 0)
3173 tm->tm_sec = -tm->tm_sec;
3174 if (tm->tm_min > 0)
3175 tm->tm_min = -tm->tm_min;
3176 if (tm->tm_hour > 0)
3177 tm->tm_hour = -tm->tm_hour;
3178 if (tm->tm_mday > 0)
3179 tm->tm_mday = -tm->tm_mday;
3180 if (tm->tm_mon > 0)
3181 tm->tm_mon = -tm->tm_mon;
3182 if (tm->tm_year > 0)
3183 tm->tm_year = -tm->tm_year;
3187 /* finally, AGO negates everything */
3188 if (is_before)
3190 *fsec = -(*fsec);
3191 tm->tm_sec = -tm->tm_sec;
3192 tm->tm_min = -tm->tm_min;
3193 tm->tm_hour = -tm->tm_hour;
3194 tm->tm_mday = -tm->tm_mday;
3195 tm->tm_mon = -tm->tm_mon;
3196 tm->tm_year = -tm->tm_year;
3199 return 0;
3204 * Helper functions to avoid duplicated code in DecodeISO8601Interval.
3206 * Parse a decimal value and break it into integer and fractional parts.
3207 * Returns 0 or DTERR code.
3209 static int
3210 ParseISO8601Number(char *str, char **endptr, int *ipart, double *fpart)
3212 double val;
3214 if (!(isdigit((unsigned char) *str) || *str == '-' || *str == '.'))
3215 return DTERR_BAD_FORMAT;
3216 errno = 0;
3217 val = strtod(str, endptr);
3218 /* did we not see anything that looks like a double? */
3219 if (*endptr == str || errno != 0)
3220 return DTERR_BAD_FORMAT;
3221 /* watch out for overflow */
3222 if (val < INT_MIN || val > INT_MAX)
3223 return DTERR_FIELD_OVERFLOW;
3224 /* be very sure we truncate towards zero (cf dtrunc()) */
3225 if (val >= 0)
3226 *ipart = (int) floor(val);
3227 else
3228 *ipart = (int) -floor(-val);
3229 *fpart = val - *ipart;
3230 return 0;
3234 * Determine number of integral digits in a valid ISO 8601 number field
3235 * (we should ignore sign and any fraction part)
3237 static int
3238 ISO8601IntegerWidth(char *fieldstart)
3240 /* We might have had a leading '-' */
3241 if (*fieldstart == '-')
3242 fieldstart++;
3243 return strspn(fieldstart, "0123456789");
3247 /* DecodeISO8601Interval()
3248 * Decode an ISO 8601 time interval of the "format with designators"
3249 * (section 4.4.3.2) or "alternative format" (section 4.4.3.3)
3250 * Examples: P1D for 1 day
3251 * PT1H for 1 hour
3252 * P2Y6M7DT1H30M for 2 years, 6 months, 7 days 1 hour 30 min
3253 * P0002-06-07T01:30:00 the same value in alternative format
3255 * Returns 0 if successful, DTERR code if bogus input detected.
3256 * Note: error code should be DTERR_BAD_FORMAT if input doesn't look like
3257 * ISO8601, otherwise this could cause unexpected error messages.
3258 * dtype, tm, fsec are output parameters.
3260 * A couple exceptions from the spec:
3261 * - a week field ('W') may coexist with other units
3262 * - allows decimals in fields other than the least significant unit.
3265 DecodeISO8601Interval(char *str,
3266 int *dtype, struct pg_tm * tm, fsec_t *fsec)
3268 bool datepart = true;
3269 bool havefield = false;
3271 *dtype = DTK_DELTA;
3272 ClearPgTm(tm, fsec);
3274 if (strlen(str) < 2 || str[0] != 'P')
3275 return DTERR_BAD_FORMAT;
3277 str++;
3278 while (*str)
3280 char *fieldstart;
3281 int val;
3282 double fval;
3283 char unit;
3284 int dterr;
3286 if (*str == 'T') /* T indicates the beginning of the time part */
3288 datepart = false;
3289 havefield = false;
3290 str++;
3291 continue;
3294 fieldstart = str;
3295 dterr = ParseISO8601Number(str, &str, &val, &fval);
3296 if (dterr)
3297 return dterr;
3300 * Note: we could step off the end of the string here. Code below
3301 * *must* exit the loop if unit == '\0'.
3303 unit = *str++;
3305 if (datepart)
3307 switch (unit) /* before T: Y M W D */
3309 case 'Y':
3310 tm->tm_year += val;
3311 tm->tm_mon += (fval * 12);
3312 break;
3313 case 'M':
3314 tm->tm_mon += val;
3315 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3316 break;
3317 case 'W':
3318 tm->tm_mday += val * 7;
3319 AdjustFractDays(fval, tm, fsec, 7);
3320 break;
3321 case 'D':
3322 tm->tm_mday += val;
3323 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3324 break;
3325 case 'T': /* ISO 8601 4.4.3.3 Alternative Format / Basic */
3326 case '\0':
3327 if (ISO8601IntegerWidth(fieldstart) == 8 && !havefield)
3329 tm->tm_year += val / 10000;
3330 tm->tm_mon += (val / 100) % 100;
3331 tm->tm_mday += val % 100;
3332 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3333 if (unit == '\0')
3334 return 0;
3335 datepart = false;
3336 havefield = false;
3337 continue;
3339 /* Else fall through to extended alternative format */
3340 case '-': /* ISO 8601 4.4.3.3 Alternative Format,
3341 * Extended */
3342 if (havefield)
3343 return DTERR_BAD_FORMAT;
3345 tm->tm_year += val;
3346 tm->tm_mon += (fval * 12);
3347 if (unit == '\0')
3348 return 0;
3349 if (unit == 'T')
3351 datepart = false;
3352 havefield = false;
3353 continue;
3356 dterr = ParseISO8601Number(str, &str, &val, &fval);
3357 if (dterr)
3358 return dterr;
3359 tm->tm_mon += val;
3360 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3361 if (*str == '\0')
3362 return 0;
3363 if (*str == 'T')
3365 datepart = false;
3366 havefield = false;
3367 continue;
3369 if (*str != '-')
3370 return DTERR_BAD_FORMAT;
3371 str++;
3373 dterr = ParseISO8601Number(str, &str, &val, &fval);
3374 if (dterr)
3375 return dterr;
3376 tm->tm_mday += val;
3377 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3378 if (*str == '\0')
3379 return 0;
3380 if (*str == 'T')
3382 datepart = false;
3383 havefield = false;
3384 continue;
3386 return DTERR_BAD_FORMAT;
3387 default:
3388 /* not a valid date unit suffix */
3389 return DTERR_BAD_FORMAT;
3392 else
3394 switch (unit) /* after T: H M S */
3396 case 'H':
3397 tm->tm_hour += val;
3398 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3399 break;
3400 case 'M':
3401 tm->tm_min += val;
3402 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3403 break;
3404 case 'S':
3405 tm->tm_sec += val;
3406 AdjustFractSeconds(fval, tm, fsec, 1);
3407 break;
3408 case '\0': /* ISO 8601 4.4.3.3 Alternative Format */
3409 if (ISO8601IntegerWidth(fieldstart) == 6 && !havefield)
3411 tm->tm_hour += val / 10000;
3412 tm->tm_min += (val / 100) % 100;
3413 tm->tm_sec += val % 100;
3414 AdjustFractSeconds(fval, tm, fsec, 1);
3415 return 0;
3417 /* Else fall through to extended alternative format */
3418 case ':': /* ISO 8601 4.4.3.3 Alternative Format,
3419 * Extended */
3420 if (havefield)
3421 return DTERR_BAD_FORMAT;
3423 tm->tm_hour += val;
3424 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3425 if (unit == '\0')
3426 return 0;
3428 dterr = ParseISO8601Number(str, &str, &val, &fval);
3429 if (dterr)
3430 return dterr;
3431 tm->tm_min += val;
3432 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3433 if (*str == '\0')
3434 return 0;
3435 if (*str != ':')
3436 return DTERR_BAD_FORMAT;
3437 str++;
3439 dterr = ParseISO8601Number(str, &str, &val, &fval);
3440 if (dterr)
3441 return dterr;
3442 tm->tm_sec += val;
3443 AdjustFractSeconds(fval, tm, fsec, 1);
3444 if (*str == '\0')
3445 return 0;
3446 return DTERR_BAD_FORMAT;
3448 default:
3449 /* not a valid time unit suffix */
3450 return DTERR_BAD_FORMAT;
3454 havefield = true;
3457 return 0;
3461 /* DecodeUnits()
3462 * Decode text string using lookup table.
3463 * This routine supports time interval decoding
3464 * (hence, it need not recognize timezone names).
3467 DecodeUnits(int field, char *lowtoken, int *val)
3469 int type;
3470 const datetkn *tp;
3472 tp = deltacache[field];
3473 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3475 tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
3477 if (tp == NULL)
3479 type = UNKNOWN_FIELD;
3480 *val = 0;
3482 else
3484 deltacache[field] = tp;
3485 type = tp->type;
3486 if (type == TZ || type == DTZ)
3487 *val = FROMVAL(tp);
3488 else
3489 *val = tp->value;
3492 return type;
3493 } /* DecodeUnits() */
3496 * Report an error detected by one of the datetime input processing routines.
3498 * dterr is the error code, str is the original input string, datatype is
3499 * the name of the datatype we were trying to accept.
3501 * Note: it might seem useless to distinguish DTERR_INTERVAL_OVERFLOW and
3502 * DTERR_TZDISP_OVERFLOW from DTERR_FIELD_OVERFLOW, but SQL99 mandates three
3503 * separate SQLSTATE codes, so ...
3505 void
3506 DateTimeParseError(int dterr, const char *str, const char *datatype)
3508 switch (dterr)
3510 case DTERR_FIELD_OVERFLOW:
3511 ereport(ERROR,
3512 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3513 errmsg("date/time field value out of range: \"%s\"",
3514 str)));
3515 break;
3516 case DTERR_MD_FIELD_OVERFLOW:
3517 /* <nanny>same as above, but add hint about DateStyle</nanny> */
3518 ereport(ERROR,
3519 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3520 errmsg("date/time field value out of range: \"%s\"",
3521 str),
3522 errhint("Perhaps you need a different \"datestyle\" setting.")));
3523 break;
3524 case DTERR_INTERVAL_OVERFLOW:
3525 ereport(ERROR,
3526 (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
3527 errmsg("interval field value out of range: \"%s\"",
3528 str)));
3529 break;
3530 case DTERR_TZDISP_OVERFLOW:
3531 ereport(ERROR,
3532 (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
3533 errmsg("time zone displacement out of range: \"%s\"",
3534 str)));
3535 break;
3536 case DTERR_BAD_FORMAT:
3537 default:
3538 ereport(ERROR,
3539 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
3540 errmsg("invalid input syntax for type %s: \"%s\"",
3541 datatype, str)));
3542 break;
3546 /* datebsearch()
3547 * Binary search -- from Knuth (6.2.1) Algorithm B. Special case like this
3548 * is WAY faster than the generic bsearch().
3550 static const datetkn *
3551 datebsearch(const char *key, const datetkn *base, int nel)
3553 const datetkn *last = base + nel - 1,
3554 *position;
3555 int result;
3557 while (last >= base)
3559 position = base + ((last - base) >> 1);
3560 result = key[0] - position->token[0];
3561 if (result == 0)
3563 result = strncmp(key, position->token, TOKMAXLEN);
3564 if (result == 0)
3565 return position;
3567 if (result < 0)
3568 last = position - 1;
3569 else
3570 base = position + 1;
3572 return NULL;
3575 /* EncodeTimezone()
3576 * Append representation of a numeric timezone offset to str.
3578 static void
3579 EncodeTimezone(char *str, int tz, int style)
3581 int hour,
3582 min,
3583 sec;
3585 sec = abs(tz);
3586 min = sec / SECS_PER_MINUTE;
3587 sec -= min * SECS_PER_MINUTE;
3588 hour = min / MINS_PER_HOUR;
3589 min -= hour * MINS_PER_HOUR;
3591 str += strlen(str);
3592 /* TZ is negated compared to sign we wish to display ... */
3593 *str++ = (tz <= 0 ? '+' : '-');
3595 if (sec != 0)
3596 sprintf(str, "%02d:%02d:%02d", hour, min, sec);
3597 else if (min != 0 || style == USE_XSD_DATES)
3598 sprintf(str, "%02d:%02d", hour, min);
3599 else
3600 sprintf(str, "%02d", hour);
3603 /* EncodeDateOnly()
3604 * Encode date as local time.
3606 void
3607 EncodeDateOnly(struct pg_tm * tm, int style, char *str)
3609 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3611 switch (style)
3613 case USE_ISO_DATES:
3614 case USE_XSD_DATES:
3615 /* compatible with ISO date formats */
3616 if (tm->tm_year > 0)
3617 sprintf(str, "%04d-%02d-%02d",
3618 tm->tm_year, tm->tm_mon, tm->tm_mday);
3619 else
3620 sprintf(str, "%04d-%02d-%02d %s",
3621 -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
3622 break;
3624 case USE_SQL_DATES:
3625 /* compatible with Oracle/Ingres date formats */
3626 if (DateOrder == DATEORDER_DMY)
3627 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3628 else
3629 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3630 if (tm->tm_year > 0)
3631 sprintf(str + 5, "/%04d", tm->tm_year);
3632 else
3633 sprintf(str + 5, "/%04d %s", -(tm->tm_year - 1), "BC");
3634 break;
3636 case USE_GERMAN_DATES:
3637 /* German-style date format */
3638 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3639 if (tm->tm_year > 0)
3640 sprintf(str + 5, ".%04d", tm->tm_year);
3641 else
3642 sprintf(str + 5, ".%04d %s", -(tm->tm_year - 1), "BC");
3643 break;
3645 case USE_POSTGRES_DATES:
3646 default:
3647 /* traditional date-only style for Postgres */
3648 if (DateOrder == DATEORDER_DMY)
3649 sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
3650 else
3651 sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
3652 if (tm->tm_year > 0)
3653 sprintf(str + 5, "-%04d", tm->tm_year);
3654 else
3655 sprintf(str + 5, "-%04d %s", -(tm->tm_year - 1), "BC");
3656 break;
3661 /* EncodeTimeOnly()
3662 * Encode time fields only.
3664 void
3665 EncodeTimeOnly(struct pg_tm * tm, fsec_t fsec, int *tzp, int style, char *str)
3667 sprintf(str, "%02d:%02d:", tm->tm_hour, tm->tm_min);
3668 str += strlen(str);
3670 AppendSeconds(str, tm->tm_sec, fsec, MAX_TIME_PRECISION, true);
3672 if (tzp != NULL)
3673 EncodeTimezone(str, *tzp, style);
3677 /* EncodeDateTime()
3678 * Encode date and time interpreted as local time.
3679 * Support several date styles:
3680 * Postgres - day mon hh:mm:ss yyyy tz
3681 * SQL - mm/dd/yyyy hh:mm:ss.ss tz
3682 * ISO - yyyy-mm-dd hh:mm:ss+/-tz
3683 * German - dd.mm.yyyy hh:mm:ss tz
3684 * XSD - yyyy-mm-ddThh:mm:ss.ss+/-tz
3685 * Variants (affects order of month and day for Postgres and SQL styles):
3686 * US - mm/dd/yyyy
3687 * European - dd/mm/yyyy
3689 void
3690 EncodeDateTime(struct pg_tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, char *str)
3692 int day;
3694 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3696 switch (style)
3698 case USE_ISO_DATES:
3699 case USE_XSD_DATES:
3700 /* Compatible with ISO-8601 date formats */
3702 if (style == USE_ISO_DATES)
3703 sprintf(str, "%04d-%02d-%02d %02d:%02d:",
3704 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3705 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3706 else
3707 sprintf(str, "%04d-%02d-%02dT%02d:%02d:",
3708 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3709 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3711 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3714 * tzp == NULL indicates that we don't want *any* time zone info
3715 * in the output string. *tzn != NULL indicates that we have alpha
3716 * time zone info available. tm_isdst != -1 indicates that we have
3717 * a valid time zone translation.
3719 if (tzp != NULL && tm->tm_isdst >= 0)
3720 EncodeTimezone(str, *tzp, style);
3722 if (tm->tm_year <= 0)
3723 sprintf(str + strlen(str), " BC");
3724 break;
3726 case USE_SQL_DATES:
3727 /* Compatible with Oracle/Ingres date formats */
3729 if (DateOrder == DATEORDER_DMY)
3730 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3731 else
3732 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3734 sprintf(str + 5, "/%04d %02d:%02d:",
3735 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3736 tm->tm_hour, tm->tm_min);
3738 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3740 if (tzp != NULL && tm->tm_isdst >= 0)
3742 if (*tzn != NULL)
3743 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3744 else
3745 EncodeTimezone(str, *tzp, style);
3748 if (tm->tm_year <= 0)
3749 sprintf(str + strlen(str), " BC");
3750 break;
3752 case USE_GERMAN_DATES:
3753 /* German variant on European style */
3755 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3757 sprintf(str + 5, ".%04d %02d:%02d:",
3758 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3759 tm->tm_hour, tm->tm_min);
3761 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3763 if (tzp != NULL && tm->tm_isdst >= 0)
3765 if (*tzn != NULL)
3766 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3767 else
3768 EncodeTimezone(str, *tzp, style);
3771 if (tm->tm_year <= 0)
3772 sprintf(str + strlen(str), " BC");
3773 break;
3775 case USE_POSTGRES_DATES:
3776 default:
3777 /* Backward-compatible with traditional Postgres abstime dates */
3779 day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3780 tm->tm_wday = j2day(day);
3782 strncpy(str, days[tm->tm_wday], 3);
3783 strcpy(str + 3, " ");
3785 if (DateOrder == DATEORDER_DMY)
3786 sprintf(str + 4, "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
3787 else
3788 sprintf(str + 4, "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);
3790 sprintf(str + 10, " %02d:%02d:", tm->tm_hour, tm->tm_min);
3792 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3794 sprintf(str + strlen(str), " %04d",
3795 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1));
3797 if (tzp != NULL && tm->tm_isdst >= 0)
3799 if (*tzn != NULL)
3800 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3801 else
3804 * We have a time zone, but no string version. Use the
3805 * numeric form, but be sure to include a leading space to
3806 * avoid formatting something which would be rejected by
3807 * the date/time parser later. - thomas 2001-10-19
3809 sprintf(str + strlen(str), " ");
3810 EncodeTimezone(str, *tzp, style);
3814 if (tm->tm_year <= 0)
3815 sprintf(str + strlen(str), " BC");
3816 break;
3822 * Helper functions to avoid duplicated code in EncodeInterval.
3825 /* Append an ISO-8601-style interval field, but only if value isn't zero */
3826 static char *
3827 AddISO8601IntPart(char *cp, int value, char units)
3829 if (value == 0)
3830 return cp;
3831 sprintf(cp, "%d%c", value, units);
3832 return cp + strlen(cp);
3835 /* Append a postgres-style interval field, but only if value isn't zero */
3836 static char *
3837 AddPostgresIntPart(char *cp, int value, const char *units,
3838 bool *is_zero, bool *is_before)
3840 if (value == 0)
3841 return cp;
3842 sprintf(cp, "%s%s%d %s%s",
3843 (!*is_zero) ? " " : "",
3844 (*is_before && value > 0) ? "+" : "",
3845 value,
3846 units,
3847 (value != 1) ? "s" : "");
3850 * Each nonzero field sets is_before for (only) the next one. This is a
3851 * tad bizarre but it's how it worked before...
3853 *is_before = (value < 0);
3854 *is_zero = FALSE;
3855 return cp + strlen(cp);
3858 /* Append a verbose-style interval field, but only if value isn't zero */
3859 static char *
3860 AddVerboseIntPart(char *cp, int value, const char *units,
3861 bool *is_zero, bool *is_before)
3863 if (value == 0)
3864 return cp;
3865 /* first nonzero value sets is_before */
3866 if (*is_zero)
3868 *is_before = (value < 0);
3869 value = abs(value);
3871 else if (*is_before)
3872 value = -value;
3873 sprintf(cp, " %d %s%s", value, units, (value == 1) ? "" : "s");
3874 *is_zero = FALSE;
3875 return cp + strlen(cp);
3879 /* EncodeInterval()
3880 * Interpret time structure as a delta time and convert to string.
3882 * Support "traditional Postgres" and ISO-8601 styles.
3883 * Actually, afaik ISO does not address time interval formatting,
3884 * but this looks similar to the spec for absolute date/time.
3885 * - thomas 1998-04-30
3887 * Actually, afaik, ISO 8601 does specify formats for "time
3888 * intervals...[of the]...format with time-unit designators", which
3889 * are pretty ugly. The format looks something like
3890 * P1Y1M1DT1H1M1.12345S
3891 * but useful for exchanging data with computers instead of humans.
3892 * - ron 2003-07-14
3894 * And ISO's SQL 2008 standard specifies standards for
3895 * "year-month literal"s (that look like '2-3') and
3896 * "day-time literal"s (that look like ('4 5:6:7')
3898 void
3899 EncodeInterval(struct pg_tm * tm, fsec_t fsec, int style, char *str)
3901 char *cp = str;
3902 int year = tm->tm_year;
3903 int mon = tm->tm_mon;
3904 int mday = tm->tm_mday;
3905 int hour = tm->tm_hour;
3906 int min = tm->tm_min;
3907 int sec = tm->tm_sec;
3908 bool is_before = FALSE;
3909 bool is_zero = TRUE;
3912 * The sign of year and month are guaranteed to match, since they are
3913 * stored internally as "month". But we'll need to check for is_before and
3914 * is_zero when determining the signs of day and hour/minute/seconds
3915 * fields.
3917 switch (style)
3919 /* SQL Standard interval format */
3920 case INTSTYLE_SQL_STANDARD:
3922 bool has_negative = year < 0 || mon < 0 ||
3923 mday < 0 || hour < 0 ||
3924 min < 0 || sec < 0 || fsec < 0;
3925 bool has_positive = year > 0 || mon > 0 ||
3926 mday > 0 || hour > 0 ||
3927 min > 0 || sec > 0 || fsec > 0;
3928 bool has_year_month = year != 0 || mon != 0;
3929 bool has_day_time = mday != 0 || hour != 0 ||
3930 min != 0 || sec != 0 || fsec != 0;
3931 bool has_day = mday != 0;
3932 bool sql_standard_value = !(has_negative && has_positive) &&
3933 !(has_year_month && has_day_time);
3936 * SQL Standard wants only 1 "<sign>" preceding the whole
3937 * interval ... but can't do that if mixed signs.
3939 if (has_negative && sql_standard_value)
3941 *cp++ = '-';
3942 year = -year;
3943 mon = -mon;
3944 mday = -mday;
3945 hour = -hour;
3946 min = -min;
3947 sec = -sec;
3948 fsec = -fsec;
3951 if (!has_negative && !has_positive)
3953 sprintf(cp, "0");
3955 else if (!sql_standard_value)
3958 * For non sql-standard interval values, force outputting
3959 * the signs to avoid ambiguities with intervals with
3960 * mixed sign components.
3962 char year_sign = (year < 0 || mon < 0) ? '-' : '+';
3963 char day_sign = (mday < 0) ? '-' : '+';
3964 char sec_sign = (hour < 0 || min < 0 ||
3965 sec < 0 || fsec < 0) ? '-' : '+';
3967 sprintf(cp, "%c%d-%d %c%d %c%d:%02d:",
3968 year_sign, abs(year), abs(mon),
3969 day_sign, abs(mday),
3970 sec_sign, abs(hour), abs(min));
3971 cp += strlen(cp);
3972 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
3974 else if (has_year_month)
3976 sprintf(cp, "%d-%d", year, mon);
3978 else if (has_day)
3980 sprintf(cp, "%d %d:%02d:", mday, hour, min);
3981 cp += strlen(cp);
3982 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
3984 else
3986 sprintf(cp, "%d:%02d:", hour, min);
3987 cp += strlen(cp);
3988 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
3991 break;
3993 /* ISO 8601 "time-intervals by duration only" */
3994 case INTSTYLE_ISO_8601:
3995 /* special-case zero to avoid printing nothing */
3996 if (year == 0 && mon == 0 && mday == 0 &&
3997 hour == 0 && min == 0 && sec == 0 && fsec == 0)
3999 sprintf(cp, "PT0S");
4000 break;
4002 *cp++ = 'P';
4003 cp = AddISO8601IntPart(cp, year, 'Y');
4004 cp = AddISO8601IntPart(cp, mon, 'M');
4005 cp = AddISO8601IntPart(cp, mday, 'D');
4006 if (hour != 0 || min != 0 || sec != 0 || fsec != 0)
4007 *cp++ = 'T';
4008 cp = AddISO8601IntPart(cp, hour, 'H');
4009 cp = AddISO8601IntPart(cp, min, 'M');
4010 if (sec != 0 || fsec != 0)
4012 if (sec < 0 || fsec < 0)
4013 *cp++ = '-';
4014 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4015 cp += strlen(cp);
4016 *cp++ = 'S';
4017 *cp++ = '\0';
4019 break;
4021 /* Compatible with postgresql < 8.4 when DateStyle = 'iso' */
4022 case INTSTYLE_POSTGRES:
4023 cp = AddPostgresIntPart(cp, year, "year", &is_zero, &is_before);
4024 cp = AddPostgresIntPart(cp, mon, "mon", &is_zero, &is_before);
4025 cp = AddPostgresIntPart(cp, mday, "day", &is_zero, &is_before);
4026 if (is_zero || hour != 0 || min != 0 || sec != 0 || fsec != 0)
4028 bool minus = (hour < 0 || min < 0 || sec < 0 || fsec < 0);
4030 sprintf(cp, "%s%s%02d:%02d:",
4031 is_zero ? "" : " ",
4032 (minus ? "-" : (is_before ? "+" : "")),
4033 abs(hour), abs(min));
4034 cp += strlen(cp);
4035 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4037 break;
4039 /* Compatible with postgresql < 8.4 when DateStyle != 'iso' */
4040 case INTSTYLE_POSTGRES_VERBOSE:
4041 default:
4042 strcpy(cp, "@");
4043 cp++;
4044 cp = AddVerboseIntPart(cp, year, "year", &is_zero, &is_before);
4045 cp = AddVerboseIntPart(cp, mon, "mon", &is_zero, &is_before);
4046 cp = AddVerboseIntPart(cp, mday, "day", &is_zero, &is_before);
4047 cp = AddVerboseIntPart(cp, hour, "hour", &is_zero, &is_before);
4048 cp = AddVerboseIntPart(cp, min, "min", &is_zero, &is_before);
4049 if (sec != 0 || fsec != 0)
4051 *cp++ = ' ';
4052 if (sec < 0 || (sec == 0 && fsec < 0))
4054 if (is_zero)
4055 is_before = TRUE;
4056 else if (!is_before)
4057 *cp++ = '-';
4059 else if (is_before)
4060 *cp++ = '-';
4061 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4062 cp += strlen(cp);
4063 sprintf(cp, " sec%s",
4064 (abs(sec) != 1 || fsec != 0) ? "s" : "");
4065 is_zero = FALSE;
4067 /* identically zero? then put in a unitless zero... */
4068 if (is_zero)
4069 strcat(cp, " 0");
4070 if (is_before)
4071 strcat(cp, " ago");
4072 break;
4078 * We've been burnt by stupid errors in the ordering of the datetkn tables
4079 * once too often. Arrange to check them during postmaster start.
4081 static bool
4082 CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
4084 bool ok = true;
4085 int i;
4087 for (i = 1; i < nel; i++)
4089 if (strncmp(base[i - 1].token, base[i].token, TOKMAXLEN) >= 0)
4091 elog(LOG, "ordering error in %s table: \"%.*s\" >= \"%.*s\"",
4092 tablename,
4093 TOKMAXLEN, base[i - 1].token,
4094 TOKMAXLEN, base[i].token);
4095 ok = false;
4098 return ok;
4101 bool
4102 CheckDateTokenTables(void)
4104 bool ok = true;
4106 Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
4107 Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
4109 ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
4110 ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
4111 return ok;
4115 * This function gets called during timezone config file load or reload
4116 * to create the final array of timezone tokens. The argument array
4117 * is already sorted in name order. This data is in a temporary memory
4118 * context and must be copied to somewhere permanent.
4120 void
4121 InstallTimeZoneAbbrevs(tzEntry *abbrevs, int n)
4123 datetkn *newtbl;
4124 int i;
4127 * Copy the data into TopMemoryContext and convert to datetkn format.
4129 newtbl = (datetkn *) MemoryContextAlloc(TopMemoryContext,
4130 n * sizeof(datetkn));
4131 for (i = 0; i < n; i++)
4133 strncpy(newtbl[i].token, abbrevs[i].abbrev, TOKMAXLEN);
4134 newtbl[i].type = abbrevs[i].is_dst ? DTZ : TZ;
4135 TOVAL(&newtbl[i], abbrevs[i].offset / 60);
4138 /* Check the ordering, if testing */
4139 Assert(CheckDateTokenTable("timezone offset", newtbl, n));
4141 /* Now safe to replace existing table (if any) */
4142 if (timezonetktbl)
4143 pfree(timezonetktbl);
4144 timezonetktbl = newtbl;
4145 sztimezonetktbl = n;
4147 /* clear date cache in case it contains any stale timezone names */
4148 for (i = 0; i < MAXDATEFIELDS; i++)
4149 datecache[i] = NULL;
4153 * This set-returning function reads all the available time zone abbreviations
4154 * and returns a set of (abbrev, utc_offset, is_dst).
4156 Datum
4157 pg_timezone_abbrevs(PG_FUNCTION_ARGS)
4159 FuncCallContext *funcctx;
4160 int *pindex;
4161 Datum result;
4162 HeapTuple tuple;
4163 Datum values[3];
4164 bool nulls[3];
4165 char buffer[TOKMAXLEN + 1];
4166 unsigned char *p;
4167 struct pg_tm tm;
4168 Interval *resInterval;
4170 /* stuff done only on the first call of the function */
4171 if (SRF_IS_FIRSTCALL())
4173 TupleDesc tupdesc;
4174 MemoryContext oldcontext;
4176 /* create a function context for cross-call persistence */
4177 funcctx = SRF_FIRSTCALL_INIT();
4180 * switch to memory context appropriate for multiple function calls
4182 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4184 /* allocate memory for user context */
4185 pindex = (int *) palloc(sizeof(int));
4186 *pindex = 0;
4187 funcctx->user_fctx = (void *) pindex;
4190 * build tupdesc for result tuples. This must match this function's
4191 * pg_proc entry!
4193 tupdesc = CreateTemplateTupleDesc(3, false);
4194 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "abbrev",
4195 TEXTOID, -1, 0);
4196 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "utc_offset",
4197 INTERVALOID, -1, 0);
4198 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_dst",
4199 BOOLOID, -1, 0);
4201 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4202 MemoryContextSwitchTo(oldcontext);
4205 /* stuff done on every call of the function */
4206 funcctx = SRF_PERCALL_SETUP();
4207 pindex = (int *) funcctx->user_fctx;
4209 if (*pindex >= sztimezonetktbl)
4210 SRF_RETURN_DONE(funcctx);
4212 MemSet(nulls, 0, sizeof(nulls));
4215 * Convert name to text, using upcasing conversion that is the inverse of
4216 * what ParseDateTime() uses.
4218 strncpy(buffer, timezonetktbl[*pindex].token, TOKMAXLEN);
4219 buffer[TOKMAXLEN] = '\0'; /* may not be null-terminated */
4220 for (p = (unsigned char *) buffer; *p; p++)
4221 *p = pg_toupper(*p);
4223 values[0] = CStringGetTextDatum(buffer);
4225 MemSet(&tm, 0, sizeof(struct pg_tm));
4226 tm.tm_min = (-1) * FROMVAL(&timezonetktbl[*pindex]);
4227 resInterval = (Interval *) palloc(sizeof(Interval));
4228 tm2interval(&tm, 0, resInterval);
4229 values[1] = IntervalPGetDatum(resInterval);
4231 Assert(timezonetktbl[*pindex].type == DTZ ||
4232 timezonetktbl[*pindex].type == TZ);
4233 values[2] = BoolGetDatum(timezonetktbl[*pindex].type == DTZ);
4235 (*pindex)++;
4237 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4238 result = HeapTupleGetDatum(tuple);
4240 SRF_RETURN_NEXT(funcctx, result);
4244 * This set-returning function reads all the available full time zones
4245 * and returns a set of (name, abbrev, utc_offset, is_dst).
4247 Datum
4248 pg_timezone_names(PG_FUNCTION_ARGS)
4250 MemoryContext oldcontext;
4251 FuncCallContext *funcctx;
4252 pg_tzenum *tzenum;
4253 pg_tz *tz;
4254 Datum result;
4255 HeapTuple tuple;
4256 Datum values[4];
4257 bool nulls[4];
4258 int tzoff;
4259 struct pg_tm tm;
4260 fsec_t fsec;
4261 char *tzn;
4262 Interval *resInterval;
4263 struct pg_tm itm;
4265 /* stuff done only on the first call of the function */
4266 if (SRF_IS_FIRSTCALL())
4268 TupleDesc tupdesc;
4270 /* create a function context for cross-call persistence */
4271 funcctx = SRF_FIRSTCALL_INIT();
4274 * switch to memory context appropriate for multiple function calls
4276 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4278 /* initialize timezone scanning code */
4279 tzenum = pg_tzenumerate_start();
4280 funcctx->user_fctx = (void *) tzenum;
4283 * build tupdesc for result tuples. This must match this function's
4284 * pg_proc entry!
4286 tupdesc = CreateTemplateTupleDesc(4, false);
4287 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
4288 TEXTOID, -1, 0);
4289 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "abbrev",
4290 TEXTOID, -1, 0);
4291 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "utc_offset",
4292 INTERVALOID, -1, 0);
4293 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_dst",
4294 BOOLOID, -1, 0);
4296 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4297 MemoryContextSwitchTo(oldcontext);
4300 /* stuff done on every call of the function */
4301 funcctx = SRF_PERCALL_SETUP();
4302 tzenum = (pg_tzenum *) funcctx->user_fctx;
4304 /* search for another zone to display */
4305 for (;;)
4307 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4308 tz = pg_tzenumerate_next(tzenum);
4309 MemoryContextSwitchTo(oldcontext);
4311 if (!tz)
4313 pg_tzenumerate_end(tzenum);
4314 funcctx->user_fctx = NULL;
4315 SRF_RETURN_DONE(funcctx);
4318 /* Convert now() to local time in this zone */
4319 if (timestamp2tm(GetCurrentTransactionStartTimestamp(),
4320 &tzoff, &tm, &fsec, &tzn, tz) != 0)
4321 continue; /* ignore if conversion fails */
4323 /* Ignore zic's rather silly "Factory" time zone */
4324 if (tzn && strcmp(tzn, "Local time zone must be set--see zic manual page") == 0)
4325 continue;
4327 /* Found a displayable zone */
4328 break;
4331 MemSet(nulls, 0, sizeof(nulls));
4333 values[0] = CStringGetTextDatum(pg_get_timezone_name(tz));
4334 values[1] = CStringGetTextDatum(tzn ? tzn : "");
4336 MemSet(&itm, 0, sizeof(struct pg_tm));
4337 itm.tm_sec = -tzoff;
4338 resInterval = (Interval *) palloc(sizeof(Interval));
4339 tm2interval(&itm, 0, resInterval);
4340 values[2] = IntervalPGetDatum(resInterval);
4342 values[3] = BoolGetDatum(tm.tm_isdst > 0);
4344 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4345 result = HeapTupleGetDatum(tuple);
4347 SRF_RETURN_NEXT(funcctx, result);