1 /*-------------------------------------------------------------------------
4 * Support functions for date/time types.
6 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/utils/adt/datetime.c
13 *-------------------------------------------------------------------------
22 #include "access/xact.h"
23 #include "catalog/pg_type.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,
45 static int ValidateDate(int fmask, bool is2digits, bool bc,
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,
52 static void AdjustFractDays(double frac, struct pg_tm * tm, fsec_t *fsec,
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 /*****************************************************************************
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)
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 */
117 {"at", IGNORE_DTF, 0}, /* "at" (throwaway) */
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 */
124 {"december", MONTH, 12},
125 {"dow", RESERV, DTK_DOW}, /* day of week */
126 {"doy", RESERV, DTK_DOY}, /* day of year */
128 {EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
130 {"february", MONTH, 2},
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},
140 {"january", MONTH, 1},
141 {"jd", UNITS, DTK_JULIAN},
143 {"julian", UNITS, DTK_JULIAN},
147 {"m", UNITS, DTK_MONTH}, /* "month" for ISO input */
151 {"mm", UNITS, DTK_MINUTE}, /* "minute" for ISO input */
155 {"november", MONTH, 11},
156 {NOW, RESERV, DTK_NOW}, /* current transaction time */
158 {"october", MONTH, 10},
159 {"on", IGNORE_DTF, 0}, /* "on" (throwaway) */
161 {"s", UNITS, DTK_SECOND}, /* "seconds" for ISO input */
163 {"saturday", DOW, 6},
166 {"september", MONTH, 9},
169 {"t", ISOTIME, DTK_TIME}, /* Filler for ISO time fields */
173 {"thursday", DOW, 4},
174 {TODAY, RESERV, DTK_TODAY}, /* midnight */
175 {TOMORROW, RESERV, DTK_TOMORROW}, /* tomorrow midnight */
179 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
181 {"wednesday", 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
267 strtoi(const char *nptr, char **endptr, int base)
271 val = strtol(nptr, endptr, base);
272 #ifdef HAVE_LONG_INT_64
273 if (val != (long) ((int32) 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
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)
316 julian = y * 365 - 32167;
317 julian += y / 4 - century + century / 4;
318 julian += 7834 * m / 256 + d;
324 j2date(int jd, int *year, int *month, int *day)
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))
343 quad = julian * 2141 / 65536;
344 *day = julian - 7834 * quad / 256;
345 *month = (quad + 10) % 12 + 1;
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.
373 * GetCurrentDateTime()
375 * Get the transaction start time ("now()") broken down as a struct pg_tm.
378 GetCurrentDateTime(struct pg_tm * tm)
383 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, &fsec,
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.
395 GetCurrentTimeUsec(struct pg_tm * tm, fsec_t *fsec, int *tzp)
399 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, fsec,
401 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
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).
415 TrimTrailingZeros(char *str)
417 int len = strlen(str);
419 while (len > 1 && *(str + len - 1) == '0' && *(str + len - 2) != '.')
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.
433 AppendSeconds(char *cp, int sec, fsec_t fsec, int precision, bool fillzeros)
438 sprintf(cp, "%02d", abs(sec));
440 sprintf(cp, "%d", abs(sec));
444 #ifdef HAVE_INT64_TIMESTAMP
446 sprintf(cp, "%02d.%0*d", abs(sec), precision, (int) Abs(fsec));
448 sprintf(cp, "%d.%0*d", abs(sec), precision, (int) Abs(fsec));
451 sprintf(cp, "%0*.*f", precision + 3, precision, fabs(sec + fsec));
453 sprintf(cp, "%.*f", precision, fabs(sec + fsec));
455 TrimTrailingZeros(cp);
459 /* Variant of above that's specialized to timestamp case */
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)
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.
479 AdjustFractSeconds(double frac, struct pg_tm * tm, fsec_t *fsec, int scale)
489 #ifdef HAVE_INT64_TIMESTAMP
490 *fsec += rint(frac * 1000000);
496 /* As above, but initial scale produces days */
498 AdjustFractDays(double frac, struct pg_tm * tm, fsec_t *fsec, int scale)
505 extra_days = (int) frac;
506 tm->tm_mday += extra_days;
508 AdjustFractSeconds(frac, tm, fsec, SECS_PER_DAY);
511 /* Fetch a fractional-second value with suitable error checking */
513 ParseFractionalSecond(char *cp, fsec_t *fsec)
517 /* Caller should always pass the start of the fraction part */
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);
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)
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) \
582 if (((bufptr) + 1) >= (end)) \
583 return DTERR_BAD_FORMAT; \
584 *(bufptr)++ = newchar; \
587 /* outer loop through fields */
590 /* Ignore spaces between fields */
591 if (isspace((unsigned char) *cp))
597 /* Record start of current field */
599 return DTERR_BAD_FORMAT;
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++);
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 */
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
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++);
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...
657 ftype[nf] = DTK_NUMBER;
659 /* Leading decimal point? Then fractional seconds... */
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))
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.
690 if (*cp == '-' || *cp == '/' || *cp == '.')
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)
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))
718 /* numeric timezone? */
719 /* note that "DTK_TZ" could also be a signed float or yyyy-mm */
720 if (isdigit((unsigned char) *cp))
723 APPEND_CHAR(bufp, bufend, *cp++);
724 while (isdigit((unsigned char) *cp) ||
725 *cp == ':' || *cp == '.' || *cp == '-')
726 APPEND_CHAR(bufp, bufend, *cp++);
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... */
738 return DTERR_BAD_FORMAT;
740 /* ignore other punctuation but use as delimiter */
741 else if (ispunct((unsigned char) *cp))
746 /* otherwise, something is not right... */
748 return DTERR_BAD_FORMAT;
750 /* force in a delimiter after each field */
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:
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
786 DecodeDateTime(char **field, int *ftype, int nf,
787 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
792 int ptype = 0; /* "prefix type" for ISO y2001m02d04 format */
797 bool haveTextMonth = FALSE;
798 bool is2digits = 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...
811 /* don't know daylight savings time status apriori */
816 for (i = 0; i < nf; i++)
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.
826 if (ptype == DTK_JULIAN)
832 return DTERR_BAD_FORMAT;
835 val = strtoi(field[i], &cp, 10);
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);
845 tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
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.
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... */
865 return DTERR_BAD_FORMAT;
867 if (isdigit((unsigned char) *field[i]) || ptype != 0)
873 /* Sanity check; should not fail this test */
874 if (ptype != DTK_TIME)
875 return DTERR_BAD_FORMAT;
880 * Starts with a digit but we already have a time
881 * field? Then we are in trouble with a date and time
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);
897 * Then read the rest of the field as a concatenated
900 dterr = DecodeNumberField(strlen(field[i]), field[i],
908 * modify tmask after returning from
909 * DecodeNumberField()
915 namedTz = pg_tzset(field[i]);
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.
924 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
925 errmsg("time zone \"%s\" not recognized",
928 /* we'll apply the zone setting below */
934 dterr = DecodeDate(field[i], fmask,
935 &tmask, &is2digits, tm);
942 dterr = DecodeTime(field[i], fmask, INTERVAL_FULL_RANGE,
948 * Check upper limit on hours; other limits checked in
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;
963 return DTERR_BAD_FORMAT;
965 dterr = DecodeTimezone(field[i], &tz);
976 * Was this an "ISO date" with embedded field labels? An
977 * example is "y2001m02d04" - thomas 2001-02-04
985 val = strtoi(field[i], &cp, 10);
987 return DTERR_FIELD_OVERFLOW;
990 * only a few kinds are allowed to have an embedded
1001 return DTERR_BAD_FORMAT;
1004 else if (*cp != '\0')
1005 return DTERR_BAD_FORMAT;
1011 tmask = DTK_M(YEAR);
1017 * already have a month and hour? then assume
1020 if ((fmask & DTK_M(MONTH)) != 0 &&
1021 (fmask & DTK_M(HOUR)) != 0)
1024 tmask = DTK_M(MINUTE);
1029 tmask = DTK_M(MONTH);
1040 tmask = DTK_M(HOUR);
1045 tmask = DTK_M(MINUTE);
1050 tmask = DTK_M(SECOND);
1053 dterr = ParseFractionalSecond(cp, fsec);
1056 tmask = DTK_ALL_SECS_M;
1062 dterr = DecodeTimezone(field[i], tzp);
1069 * previous field was a label for "julian date"?
1072 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1073 /* fractional Julian Day? */
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;
1086 time *= SECS_PER_DAY;
1089 &tm->tm_hour, &tm->tm_min,
1091 tmask |= DTK_TIME_M;
1096 /* previous field was "t" for ISO time */
1097 dterr = DecodeNumberField(strlen(field[i]), field[i],
1098 (fmask | DTK_DATE_M),
1103 if (tmask != DTK_TIME_M)
1104 return DTERR_BAD_FORMAT;
1108 return DTERR_BAD_FORMAT;
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);
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,
1147 dterr = DecodeNumberField(flen, field[i], fmask,
1153 /* otherwise it is a single date/time field... */
1156 dterr = DecodeNumber(flen, field[i],
1157 haveTextMonth, fmask,
1168 type = DecodeSpecial(i, field[i], &val);
1169 if (type == IGNORE_DTF)
1172 tmask = DTK_M(type);
1180 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1181 errmsg("date/time value \"current\" is no longer supported")));
1183 return DTERR_BAD_FORMAT;
1187 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1189 GetCurrentTimeUsec(tm, fsec, tzp);
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);
1206 GetCurrentDateTime(tm);
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);
1224 tmask = (DTK_TIME_M | DTK_M(TZ));
1242 * already have a (numeric) month? then see if we can
1245 if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
1246 !(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 &&
1249 tm->tm_mday = tm->tm_mon;
1252 haveTextMonth = TRUE;
1259 * daylight savings time modifier (solves "MET DST"
1262 tmask |= DTK_M(DTZ);
1265 return DTERR_BAD_FORMAT;
1266 *tzp += val * MINS_PER_HOUR;
1272 * set mask for TZ here _or_ check for DTZ later when
1273 * getting default timezone
1278 return DTERR_BAD_FORMAT;
1279 *tzp = val * MINS_PER_HOUR;
1285 return DTERR_BAD_FORMAT;
1286 *tzp = val * MINS_PER_HOUR;
1312 * This is a filler field "t" indicating that the next
1313 * field is time. Try to verify that this is sensible.
1317 /* No preceding date? Then quit... */
1318 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1319 return DTERR_BAD_FORMAT;
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
1328 (ftype[i + 1] != DTK_NUMBER &&
1329 ftype[i + 1] != DTK_TIME &&
1330 ftype[i + 1] != DTK_DATE))
1331 return DTERR_BAD_FORMAT;
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]);
1344 return DTERR_BAD_FORMAT;
1345 /* we'll apply the zone setting below */
1350 return DTERR_BAD_FORMAT;
1355 return DTERR_BAD_FORMAT;
1359 return DTERR_BAD_FORMAT;
1361 } /* end loop over fields */
1363 /* do final checking/adjustment of Y/M/D fields */
1364 dterr = ValidateDate(fmask, is2digits, bc, tm);
1369 if (mer != HR24 && tm->tm_hour > 12)
1370 return DTERR_FIELD_OVERFLOW;
1371 if (mer == AM && tm->tm_hour == 12)
1373 else if (mer == PM && 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)
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
1406 if (fmask & DTK_M(DTZMOD))
1407 return DTERR_BAD_FORMAT;
1409 *tzp = DetermineTimeZoneOffset(tm, session_timezone);
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)
1439 long int before_gmtoff,
1445 if (tzp == session_timezone && HasCTZSet)
1447 tm->tm_isdst = 0; /* for lack of a better idea */
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))
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)
1464 sec = tm->tm_sec + (tm->tm_min + tm->tm_hour * MINS_PER_HOUR) * SECS_PER_MINUTE;
1466 /* since sec >= 0, overflow could only be from +day to -mytime */
1467 if (mytime < 0 && day > 0)
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)
1480 res = pg_next_dst_boundary(&prevtime,
1481 &before_gmtoff, &before_isdst,
1483 &after_gmtoff, &after_isdst,
1486 goto overflow; /* failure? */
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))
1504 aftertime = mytime - after_gmtoff;
1505 if ((after_gmtoff > 0 &&
1506 mytime < 0 && aftertime > 0) ||
1507 (after_gmtoff <= 0 &&
1508 mytime > 0 && aftertime < 0))
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;
1538 /* Given date is out of range, so assume UTC */
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)
1563 int ptype = 0; /* "prefix type" for ISO h04mm05s06 format */
1567 bool is2digits = FALSE;
1570 pg_tz *namedTz = NULL;
1577 /* don't know daylight savings time status apriori */
1583 for (i = 0; i < nf; i++)
1590 * Time zone not allowed? Then should not accept dates or time
1591 * zones no matter what else!
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);
1605 /* otherwise, this is a time and/or time zone */
1608 if (isdigit((unsigned char) *field[i]))
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);
1632 * Then read the rest of the field as a concatenated
1635 dterr = DecodeNumberField(strlen(field[i]), field[i],
1636 (fmask | DTK_DATE_M),
1647 namedTz = pg_tzset(field[i]);
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.
1656 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1657 errmsg("time zone \"%s\" not recognized",
1660 /* we'll apply the zone setting below */
1668 dterr = DecodeTime(field[i], (fmask | DTK_DATE_M),
1669 INTERVAL_FULL_RANGE,
1680 return DTERR_BAD_FORMAT;
1682 dterr = DecodeTimezone(field[i], &tz);
1693 * Was this an "ISO time" with embedded field labels? An
1694 * example is "h04m05s06" - thomas 2001-02-04
1701 /* Only accept a date under limited circumstances */
1709 return DTERR_BAD_FORMAT;
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
1731 return DTERR_BAD_FORMAT;
1734 else if (*cp != '\0')
1735 return DTERR_BAD_FORMAT;
1741 tmask = DTK_M(YEAR);
1747 * already have a month and hour? then assume
1750 if ((fmask & DTK_M(MONTH)) != 0 &&
1751 (fmask & DTK_M(HOUR)) != 0)
1754 tmask = DTK_M(MINUTE);
1759 tmask = DTK_M(MONTH);
1770 tmask = DTK_M(HOUR);
1775 tmask = DTK_M(MINUTE);
1780 tmask = DTK_M(SECOND);
1783 dterr = ParseFractionalSecond(cp, fsec);
1786 tmask = DTK_ALL_SECS_M;
1792 dterr = DecodeTimezone(field[i], tzp);
1799 * previous field was a label for "julian date"?
1802 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
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;
1815 time *= SECS_PER_DAY;
1818 &tm->tm_hour, &tm->tm_min,
1820 tmask |= DTK_TIME_M;
1825 /* previous field was "t" for ISO time */
1826 dterr = DecodeNumberField(strlen(field[i]), field[i],
1827 (fmask | DTK_DATE_M),
1834 if (tmask != DTK_TIME_M)
1835 return DTERR_BAD_FORMAT;
1839 return DTERR_BAD_FORMAT;
1851 flen = strlen(field[i]);
1852 cp = strchr(field[i], '.');
1854 /* Embedded decimal? */
1858 * Under limited circumstances, we will accept a
1861 if (i == 0 && nf >= 2 && ftype[nf - 1] == DTK_DATE)
1863 dterr = DecodeDate(field[i], fmask,
1864 &tmask, &is2digits, tm);
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),
1885 return DTERR_BAD_FORMAT;
1889 dterr = DecodeNumberField(flen, field[i],
1890 (fmask | DTK_DATE_M),
1897 /* otherwise it is a single date/time field... */
1900 dterr = DecodeNumber(flen, field[i],
1902 (fmask | DTK_DATE_M),
1913 type = DecodeSpecial(i, field[i], &val);
1914 if (type == IGNORE_DTF)
1917 tmask = DTK_M(type);
1925 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1926 errmsg("date/time value \"current\" is no longer supported")));
1927 return DTERR_BAD_FORMAT;
1933 GetCurrentTimeUsec(tm, fsec, NULL);
1937 tmask = (DTK_TIME_M | DTK_M(TZ));
1946 return DTERR_BAD_FORMAT;
1954 * daylight savings time modifier (solves "MET DST"
1957 tmask |= DTK_M(DTZ);
1960 return DTERR_BAD_FORMAT;
1961 *tzp += val * MINS_PER_HOUR;
1967 * set mask for TZ here _or_ check for DTZ later when
1968 * getting default timezone
1973 return DTERR_BAD_FORMAT;
1974 *tzp = val * MINS_PER_HOUR;
1981 return DTERR_BAD_FORMAT;
1982 *tzp = val * MINS_PER_HOUR;
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
2012 (ftype[i + 1] != DTK_NUMBER &&
2013 ftype[i + 1] != DTK_TIME &&
2014 ftype[i + 1] != DTK_DATE))
2015 return DTERR_BAD_FORMAT;
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]);
2028 return DTERR_BAD_FORMAT;
2029 /* we'll apply the zone setting below */
2034 return DTERR_BAD_FORMAT;
2039 return DTERR_BAD_FORMAT;
2043 return DTERR_BAD_FORMAT;
2045 } /* end loop over fields */
2047 /* do final checking/adjustment of Y/M/D fields */
2048 dterr = ValidateDate(fmask, is2digits, bc, tm);
2053 if (mer != HR24 && tm->tm_hour > 12)
2054 return DTERR_FIELD_OVERFLOW;
2055 if (mer == AM && tm->tm_hour == 12)
2057 else if (mer == PM && 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
2068 *fsec < 0 || *fsec > 1
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)
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;
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)))
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);
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;
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
2143 DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
2151 bool haveTextMonth = FALSE;
2155 char *field[MAXDATEFIELDS];
2159 /* parse this string... */
2160 while (*str != '\0' && nf < MAXDATEFIELDS)
2162 /* skip field separators */
2163 while (!isalnum((unsigned char) *str))
2167 if (isdigit((unsigned char) *str))
2169 while (isdigit((unsigned char) *str))
2172 else if (isalpha((unsigned char) *str))
2174 while (isalpha((unsigned char) *str))
2178 /* Just get rid of any non-digit, non-alpha characters... */
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)
2193 dmask = DTK_M(type);
2198 haveTextMonth = TRUE;
2202 return DTERR_BAD_FORMAT;
2205 return DTERR_BAD_FORMAT;
2210 /* mark this field as being completed */
2215 /* now pick up remaining numeric fields */
2216 for (i = 0; i < nf; i++)
2218 if (field[i] == NULL)
2221 if ((len = strlen(field[i])) <= 0)
2222 return DTERR_BAD_FORMAT;
2224 dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2231 return DTERR_BAD_FORMAT;
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() */
2246 * Check valid year/month/day values, handle BC and DOY cases
2247 * Return 0 if okay, a DTERR code if not.
2250 ValidateDate(int fmask, bool is2digits, bool bc, struct pg_tm * tm)
2252 if (fmask & DTK_M(YEAR))
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);
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;
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;
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.
2324 DecodeTime(char *str, int fmask, int range,
2325 int *tmask, struct pg_tm * tm, fsec_t *fsec)
2330 *tmask = DTK_TIME_M;
2333 tm->tm_hour = strtoi(str, &cp, 10);
2334 if (errno == ERANGE)
2335 return DTERR_FIELD_OVERFLOW;
2337 return DTERR_BAD_FORMAT;
2339 tm->tm_min = strtoi(cp + 1, &cp, 10);
2340 if (errno == ERANGE)
2341 return DTERR_FIELD_OVERFLOW;
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;
2354 else if (*cp == '.')
2356 /* always assume mm:ss.sss is MINUTE TO SECOND */
2357 dterr = ParseFractionalSecond(cp, fsec);
2360 tm->tm_sec = tm->tm_min;
2361 tm->tm_min = tm->tm_hour;
2364 else if (*cp == ':')
2367 tm->tm_sec = strtoi(cp + 1, &cp, 10);
2368 if (errno == ERANGE)
2369 return DTERR_FIELD_OVERFLOW;
2372 else if (*cp == '.')
2374 dterr = ParseFractionalSecond(cp, fsec);
2379 return DTERR_BAD_FORMAT;
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;
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;
2401 * Interpret plain numeric field as a date value in context.
2402 * Return 0 if okay, a DTERR code if not.
2405 DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask,
2406 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2415 val = strtoi(str, &cp, 10);
2416 if (errno == ERANGE)
2417 return DTERR_FIELD_OVERFLOW;
2419 return DTERR_BAD_FORMAT;
2424 * More than two digits before decimal point? Then could be a date or
2425 * a run-together time: 2001.360 20011225 040506.789
2429 dterr = DecodeNumberField(flen, str,
2430 (fmask | DTK_DATE_M),
2438 dterr = ParseFractionalSecond(cp, fsec);
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 &&
2449 *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2451 /* tm_mon and tm_mday can't actually be set yet ... */
2455 /* Switch based on what we have so far */
2456 switch (fmask & DTK_DATE_M)
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);
2472 else if (DateOrder == DATEORDER_DMY)
2474 *tmask = DTK_M(DAY);
2479 *tmask = DTK_M(MONTH);
2485 /* Must be at second field of YY-MM-DD */
2486 *tmask = DTK_M(MONTH);
2490 case (DTK_M(MONTH)):
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);
2507 *tmask = DTK_M(DAY);
2513 /* Must be at second field of MM-DD-YY */
2514 *tmask = DTK_M(DAY);
2519 case (DTK_M(YEAR) | DTK_M(MONTH)):
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;
2533 *tmask = DTK_M(DAY);
2539 /* Must be at third field of YY-MM-DD */
2540 *tmask = DTK_M(DAY);
2546 /* Must be at second field of DD-MM-YY */
2547 *tmask = DTK_M(MONTH);
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);
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,
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
2575 if (*tmask == DTK_M(YEAR))
2576 *is2digits = (flen <= 2);
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.
2590 DecodeNumberField(int len, char *str, int fmask,
2591 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2596 * Have a decimal point? Then this is a date or something with a seconds
2599 if ((cp = strchr(str, '.')) != NULL)
2602 * Can we use ParseFractionalSecond here? Not clear whether trailing
2603 * junk should be rejected ...
2608 frac = strtod(cp, NULL);
2610 return DTERR_BAD_FORMAT;
2611 #ifdef HAVE_INT64_TIMESTAMP
2612 *fsec = rint(frac * 1000000);
2616 /* Now truncate off the fraction for further processing */
2620 /* No decimal point and no complete date yet? */
2621 else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2626 *tmask = DTK_DATE_M;
2628 tm->tm_mday = atoi(str + 6);
2630 tm->tm_mon = atoi(str + 4);
2632 tm->tm_year = atoi(str + 0);
2639 *tmask = DTK_DATE_M;
2640 tm->tm_mday = atoi(str + 4);
2642 tm->tm_mon = atoi(str + 2);
2644 tm->tm_year = atoi(str + 0);
2651 /* not all time fields are specified? */
2652 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2657 *tmask = DTK_TIME_M;
2658 tm->tm_sec = atoi(str + 4);
2660 tm->tm_min = atoi(str + 2);
2662 tm->tm_hour = atoi(str + 0);
2669 *tmask = DTK_TIME_M;
2671 tm->tm_min = atoi(str + 2);
2673 tm->tm_hour = atoi(str + 0);
2679 return DTERR_BAD_FORMAT;
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.
2694 DecodeTimezone(char *str, int *tzp)
2702 /* leading character must be "+" or "-" */
2703 if (*str != '+' && *str != '-')
2704 return DTERR_BAD_FORMAT;
2707 hr = strtoi(str + 1, &cp, 10);
2708 if (errno == ERANGE)
2709 return DTERR_TZDISP_OVERFLOW;
2711 /* explicit delimiter? */
2715 min = strtoi(cp + 1, &cp, 10);
2716 if (errno == ERANGE)
2717 return DTERR_TZDISP_OVERFLOW;
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)
2731 /* we could, but don't, support a run-together hhmmss format */
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;
2750 return DTERR_BAD_FORMAT;
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)
2770 tp = datecache[field];
2771 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
2773 tp = datebsearch(lowtoken, timezonetktbl, sztimezonetktbl);
2775 tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
2779 type = UNKNOWN_FIELD;
2784 datecache[field] = tp;
2806 * Zero out a pg_tm and associated fsec_t
2809 ClearPgTm(struct pg_tm * tm, fsec_t *fsec)
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;
2848 ClearPgTm(tm, fsec);
2850 /* read through list backwards to pick up units before values */
2851 for (i = nf - 1; i >= 0; i--)
2856 dterr = DecodeTime(field[i], fmask, range,
2866 * Timezone is a token with a leading sign character and at
2867 * least one digit; there could be ':', '.', '-' embedded in
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;
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.
2903 if (type == IGNORE_DTF)
2905 /* use typmod to decide what rightmost field is */
2908 case INTERVAL_MASK(YEAR):
2911 case INTERVAL_MASK(MONTH):
2912 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
2915 case INTERVAL_MASK(DAY):
2918 case INTERVAL_MASK(HOUR):
2919 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
2922 case INTERVAL_MASK(MINUTE):
2923 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
2924 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
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):
2940 val = strtoi(field[i], &cp, 10);
2941 if (errno == ERANGE)
2942 return DTERR_FIELD_OVERFLOW;
2946 /* SQL "years-months" syntax */
2949 val2 = strtoi(cp + 1, &cp, 10);
2950 if (errno == ERANGE || val2 < 0 || val2 >= MONTHS_PER_YEAR)
2951 return DTERR_FIELD_OVERFLOW;
2953 return DTERR_BAD_FORMAT;
2955 if (*field[i] == '-')
2957 val = val * MONTHS_PER_YEAR + val2;
2960 else if (*cp == '.')
2963 fval = strtod(cp, &cp);
2964 if (*cp != '\0' || errno != 0)
2965 return DTERR_BAD_FORMAT;
2967 if (*field[i] == '-')
2970 else if (*cp == '\0')
2973 return DTERR_BAD_FORMAT;
2975 tmask = 0; /* DTK_M(type); */
2980 #ifdef HAVE_INT64_TIMESTAMP
2981 *fsec += rint(val + fval);
2983 *fsec += (val + fval) * 1e-6;
2985 tmask = DTK_M(MICROSECOND);
2989 /* avoid overflowing the fsec field */
2990 tm->tm_sec += val / 1000;
2991 val -= (val / 1000) * 1000;
2992 #ifdef HAVE_INT64_TIMESTAMP
2993 *fsec += rint((val + fval) * 1000);
2995 *fsec += (val + fval) * 1e-3;
2997 tmask = DTK_M(MILLISECOND);
3002 #ifdef HAVE_INT64_TIMESTAMP
3003 *fsec += rint(fval * 1000000);
3009 * If any subseconds were specified, consider this
3010 * microsecond and millisecond input as well.
3013 tmask = DTK_M(SECOND);
3015 tmask = DTK_ALL_SECS_M;
3020 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3021 tmask = DTK_M(MINUTE);
3026 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3027 tmask = DTK_M(HOUR);
3028 type = DTK_DAY; /* set for next field */
3033 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3038 tm->tm_mday += val * 7;
3039 AdjustFractDays(fval, tm, fsec, 7);
3040 tmask = DTK_M(WEEK);
3045 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3046 tmask = DTK_M(MONTH);
3052 tm->tm_mon += fval * MONTHS_PER_YEAR;
3053 tmask = DTK_M(YEAR);
3057 tm->tm_year += val * 10;
3059 tm->tm_mon += fval * MONTHS_PER_YEAR * 10;
3060 tmask = DTK_M(DECADE);
3064 tm->tm_year += val * 100;
3066 tm->tm_mon += fval * MONTHS_PER_YEAR * 100;
3067 tmask = DTK_M(CENTURY);
3070 case DTK_MILLENNIUM:
3071 tm->tm_year += val * 1000;
3073 tm->tm_mon += fval * MONTHS_PER_YEAR * 1000;
3074 tmask = DTK_M(MILLENNIUM);
3078 return DTERR_BAD_FORMAT;
3084 type = DecodeUnits(i, field[i], &val);
3085 if (type == IGNORE_DTF)
3088 tmask = 0; /* DTK_M(type); */
3101 tmask = (DTK_DATE_M | DTK_TIME_M);
3106 return DTERR_BAD_FORMAT;
3111 return DTERR_BAD_FORMAT;
3115 return DTERR_BAD_FORMAT;
3119 /* ensure that at least one time field has been found */
3121 return DTERR_BAD_FORMAT;
3123 /* ensure fractional seconds are fractional */
3128 #ifdef HAVE_INT64_TIMESTAMP
3129 sec = *fsec / USECS_PER_SEC;
3130 *fsec -= sec * USECS_PER_SEC;
3132 TMODULO(*fsec, sec, 1.0);
3138 * The SQL standard defines the interval literal
3140 * to mean "negative 1 days and negative 1 hours", while Postgres
3141 * traditionally treats this as meaning "negative 1 days and positive
3142 * 1 hours". In SQL_STANDARD intervalstyle, we apply the leading sign
3143 * to all fields if there are no other explicit signs.
3145 * We leave the signs alone if there are additional explicit signs.
3146 * This protects us against misinterpreting postgres-style dump output,
3147 * since the postgres-style output code has always put an explicit sign on
3148 * all fields following a negative field. But note that SQL-spec output
3149 * is ambiguous and can be misinterpreted on load! (So it's best practice
3150 * to dump in postgres style, not SQL style.)
3153 if (IntervalStyle == INTSTYLE_SQL_STANDARD && *field[0] == '-')
3155 /* Check for additional explicit signs */
3156 bool more_signs = false;
3158 for (i = 1; i < nf; i++)
3160 if (*field[i] == '-' || *field[i] == '+')
3170 * Rather than re-determining which field was field[0], just force
3176 tm->tm_sec = -tm->tm_sec;
3178 tm->tm_min = -tm->tm_min;
3179 if (tm->tm_hour > 0)
3180 tm->tm_hour = -tm->tm_hour;
3181 if (tm->tm_mday > 0)
3182 tm->tm_mday = -tm->tm_mday;
3184 tm->tm_mon = -tm->tm_mon;
3185 if (tm->tm_year > 0)
3186 tm->tm_year = -tm->tm_year;
3190 /* finally, AGO negates everything */
3194 tm->tm_sec = -tm->tm_sec;
3195 tm->tm_min = -tm->tm_min;
3196 tm->tm_hour = -tm->tm_hour;
3197 tm->tm_mday = -tm->tm_mday;
3198 tm->tm_mon = -tm->tm_mon;
3199 tm->tm_year = -tm->tm_year;
3207 * Helper functions to avoid duplicated code in DecodeISO8601Interval.
3209 * Parse a decimal value and break it into integer and fractional parts.
3210 * Returns 0 or DTERR code.
3213 ParseISO8601Number(char *str, char **endptr, int *ipart, double *fpart)
3217 if (!(isdigit((unsigned char) *str) || *str == '-' || *str == '.'))
3218 return DTERR_BAD_FORMAT;
3220 val = strtod(str, endptr);
3221 /* did we not see anything that looks like a double? */
3222 if (*endptr == str || errno != 0)
3223 return DTERR_BAD_FORMAT;
3224 /* watch out for overflow */
3225 if (val < INT_MIN || val > INT_MAX)
3226 return DTERR_FIELD_OVERFLOW;
3227 /* be very sure we truncate towards zero (cf dtrunc()) */
3229 *ipart = (int) floor(val);
3231 *ipart = (int) -floor(-val);
3232 *fpart = val - *ipart;
3237 * Determine number of integral digits in a valid ISO 8601 number field
3238 * (we should ignore sign and any fraction part)
3241 ISO8601IntegerWidth(char *fieldstart)
3243 /* We might have had a leading '-' */
3244 if (*fieldstart == '-')
3246 return strspn(fieldstart, "0123456789");
3250 /* DecodeISO8601Interval()
3251 * Decode an ISO 8601 time interval of the "format with designators"
3252 * (section 4.4.3.2) or "alternative format" (section 4.4.3.3)
3253 * Examples: P1D for 1 day
3255 * P2Y6M7DT1H30M for 2 years, 6 months, 7 days 1 hour 30 min
3256 * P0002-06-07T01:30:00 the same value in alternative format
3258 * Returns 0 if successful, DTERR code if bogus input detected.
3259 * Note: error code should be DTERR_BAD_FORMAT if input doesn't look like
3260 * ISO8601, otherwise this could cause unexpected error messages.
3261 * dtype, tm, fsec are output parameters.
3263 * A couple exceptions from the spec:
3264 * - a week field ('W') may coexist with other units
3265 * - allows decimals in fields other than the least significant unit.
3268 DecodeISO8601Interval(char *str,
3269 int *dtype, struct pg_tm * tm, fsec_t *fsec)
3271 bool datepart = true;
3272 bool havefield = false;
3275 ClearPgTm(tm, fsec);
3277 if (strlen(str) < 2 || str[0] != 'P')
3278 return DTERR_BAD_FORMAT;
3289 if (*str == 'T') /* T indicates the beginning of the time part */
3298 dterr = ParseISO8601Number(str, &str, &val, &fval);
3303 * Note: we could step off the end of the string here. Code below
3304 * *must* exit the loop if unit == '\0'.
3310 switch (unit) /* before T: Y M W D */
3314 tm->tm_mon += (fval * 12);
3318 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3321 tm->tm_mday += val * 7;
3322 AdjustFractDays(fval, tm, fsec, 7);
3326 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3328 case 'T': /* ISO 8601 4.4.3.3 Alternative Format / Basic */
3330 if (ISO8601IntegerWidth(fieldstart) == 8 && !havefield)
3332 tm->tm_year += val / 10000;
3333 tm->tm_mon += (val / 100) % 100;
3334 tm->tm_mday += val % 100;
3335 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3342 /* Else fall through to extended alternative format */
3343 case '-': /* ISO 8601 4.4.3.3 Alternative Format,
3346 return DTERR_BAD_FORMAT;
3349 tm->tm_mon += (fval * 12);
3359 dterr = ParseISO8601Number(str, &str, &val, &fval);
3363 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3373 return DTERR_BAD_FORMAT;
3376 dterr = ParseISO8601Number(str, &str, &val, &fval);
3380 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3389 return DTERR_BAD_FORMAT;
3391 /* not a valid date unit suffix */
3392 return DTERR_BAD_FORMAT;
3397 switch (unit) /* after T: H M S */
3401 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3405 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3409 AdjustFractSeconds(fval, tm, fsec, 1);
3411 case '\0': /* ISO 8601 4.4.3.3 Alternative Format */
3412 if (ISO8601IntegerWidth(fieldstart) == 6 && !havefield)
3414 tm->tm_hour += val / 10000;
3415 tm->tm_min += (val / 100) % 100;
3416 tm->tm_sec += val % 100;
3417 AdjustFractSeconds(fval, tm, fsec, 1);
3420 /* Else fall through to extended alternative format */
3421 case ':': /* ISO 8601 4.4.3.3 Alternative Format,
3424 return DTERR_BAD_FORMAT;
3427 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3431 dterr = ParseISO8601Number(str, &str, &val, &fval);
3435 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3439 return DTERR_BAD_FORMAT;
3442 dterr = ParseISO8601Number(str, &str, &val, &fval);
3446 AdjustFractSeconds(fval, tm, fsec, 1);
3449 return DTERR_BAD_FORMAT;
3452 /* not a valid time unit suffix */
3453 return DTERR_BAD_FORMAT;
3465 * Decode text string using lookup table.
3466 * This routine supports time interval decoding
3467 * (hence, it need not recognize timezone names).
3470 DecodeUnits(int field, char *lowtoken, int *val)
3475 tp = deltacache[field];
3476 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3478 tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
3482 type = UNKNOWN_FIELD;
3487 deltacache[field] = tp;
3489 if (type == TZ || type == DTZ)
3496 } /* DecodeUnits() */
3499 * Report an error detected by one of the datetime input processing routines.
3501 * dterr is the error code, str is the original input string, datatype is
3502 * the name of the datatype we were trying to accept.
3504 * Note: it might seem useless to distinguish DTERR_INTERVAL_OVERFLOW and
3505 * DTERR_TZDISP_OVERFLOW from DTERR_FIELD_OVERFLOW, but SQL99 mandates three
3506 * separate SQLSTATE codes, so ...
3509 DateTimeParseError(int dterr, const char *str, const char *datatype)
3513 case DTERR_FIELD_OVERFLOW:
3515 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3516 errmsg("date/time field value out of range: \"%s\"",
3519 case DTERR_MD_FIELD_OVERFLOW:
3520 /* <nanny>same as above, but add hint about DateStyle</nanny> */
3522 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3523 errmsg("date/time field value out of range: \"%s\"",
3525 errhint("Perhaps you need a different \"datestyle\" setting.")));
3527 case DTERR_INTERVAL_OVERFLOW:
3529 (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
3530 errmsg("interval field value out of range: \"%s\"",
3533 case DTERR_TZDISP_OVERFLOW:
3535 (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
3536 errmsg("time zone displacement out of range: \"%s\"",
3539 case DTERR_BAD_FORMAT:
3542 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
3543 errmsg("invalid input syntax for type %s: \"%s\"",
3550 * Binary search -- from Knuth (6.2.1) Algorithm B. Special case like this
3551 * is WAY faster than the generic bsearch().
3553 static const datetkn *
3554 datebsearch(const char *key, const datetkn *base, int nel)
3556 const datetkn *last = base + nel - 1,
3560 while (last >= base)
3562 position = base + ((last - base) >> 1);
3563 result = key[0] - position->token[0];
3566 result = strncmp(key, position->token, TOKMAXLEN);
3571 last = position - 1;
3573 base = position + 1;
3579 * Append representation of a numeric timezone offset to str.
3582 EncodeTimezone(char *str, int tz, int style)
3589 min = sec / SECS_PER_MINUTE;
3590 sec -= min * SECS_PER_MINUTE;
3591 hour = min / MINS_PER_HOUR;
3592 min -= hour * MINS_PER_HOUR;
3595 /* TZ is negated compared to sign we wish to display ... */
3596 *str++ = (tz <= 0 ? '+' : '-');
3599 sprintf(str, "%02d:%02d:%02d", hour, min, sec);
3600 else if (min != 0 || style == USE_XSD_DATES)
3601 sprintf(str, "%02d:%02d", hour, min);
3603 sprintf(str, "%02d", hour);
3607 * Encode date as local time.
3610 EncodeDateOnly(struct pg_tm * tm, int style, char *str)
3612 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3618 /* compatible with ISO date formats */
3619 if (tm->tm_year > 0)
3620 sprintf(str, "%04d-%02d-%02d",
3621 tm->tm_year, tm->tm_mon, tm->tm_mday);
3623 sprintf(str, "%04d-%02d-%02d %s",
3624 -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
3628 /* compatible with Oracle/Ingres date formats */
3629 if (DateOrder == DATEORDER_DMY)
3630 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3632 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3633 if (tm->tm_year > 0)
3634 sprintf(str + 5, "/%04d", tm->tm_year);
3636 sprintf(str + 5, "/%04d %s", -(tm->tm_year - 1), "BC");
3639 case USE_GERMAN_DATES:
3640 /* German-style date format */
3641 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3642 if (tm->tm_year > 0)
3643 sprintf(str + 5, ".%04d", tm->tm_year);
3645 sprintf(str + 5, ".%04d %s", -(tm->tm_year - 1), "BC");
3648 case USE_POSTGRES_DATES:
3650 /* traditional date-only style for Postgres */
3651 if (DateOrder == DATEORDER_DMY)
3652 sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
3654 sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
3655 if (tm->tm_year > 0)
3656 sprintf(str + 5, "-%04d", tm->tm_year);
3658 sprintf(str + 5, "-%04d %s", -(tm->tm_year - 1), "BC");
3665 * Encode time fields only.
3668 EncodeTimeOnly(struct pg_tm * tm, fsec_t fsec, int *tzp, int style, char *str)
3670 sprintf(str, "%02d:%02d:", tm->tm_hour, tm->tm_min);
3673 AppendSeconds(str, tm->tm_sec, fsec, MAX_TIME_PRECISION, true);
3676 EncodeTimezone(str, *tzp, style);
3681 * Encode date and time interpreted as local time.
3682 * Support several date styles:
3683 * Postgres - day mon hh:mm:ss yyyy tz
3684 * SQL - mm/dd/yyyy hh:mm:ss.ss tz
3685 * ISO - yyyy-mm-dd hh:mm:ss+/-tz
3686 * German - dd.mm.yyyy hh:mm:ss tz
3687 * XSD - yyyy-mm-ddThh:mm:ss.ss+/-tz
3688 * Variants (affects order of month and day for Postgres and SQL styles):
3690 * European - dd/mm/yyyy
3693 EncodeDateTime(struct pg_tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, char *str)
3697 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3703 /* Compatible with ISO-8601 date formats */
3705 if (style == USE_ISO_DATES)
3706 sprintf(str, "%04d-%02d-%02d %02d:%02d:",
3707 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3708 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3710 sprintf(str, "%04d-%02d-%02dT%02d:%02d:",
3711 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3712 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3714 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3717 * tzp == NULL indicates that we don't want *any* time zone info
3718 * in the output string. *tzn != NULL indicates that we have alpha
3719 * time zone info available. tm_isdst != -1 indicates that we have
3720 * a valid time zone translation.
3722 if (tzp != NULL && tm->tm_isdst >= 0)
3723 EncodeTimezone(str, *tzp, style);
3725 if (tm->tm_year <= 0)
3726 sprintf(str + strlen(str), " BC");
3730 /* Compatible with Oracle/Ingres date formats */
3732 if (DateOrder == DATEORDER_DMY)
3733 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3735 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3737 sprintf(str + 5, "/%04d %02d:%02d:",
3738 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3739 tm->tm_hour, tm->tm_min);
3741 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3744 * Note: the uses of %.*s in this function would be risky if the
3745 * timezone names ever contain non-ASCII characters. However, all
3746 * TZ abbreviations in the Olson database are plain ASCII.
3749 if (tzp != NULL && tm->tm_isdst >= 0)
3752 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3754 EncodeTimezone(str, *tzp, style);
3757 if (tm->tm_year <= 0)
3758 sprintf(str + strlen(str), " BC");
3761 case USE_GERMAN_DATES:
3762 /* German variant on European style */
3764 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3766 sprintf(str + 5, ".%04d %02d:%02d:",
3767 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3768 tm->tm_hour, tm->tm_min);
3770 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3772 if (tzp != NULL && tm->tm_isdst >= 0)
3775 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3777 EncodeTimezone(str, *tzp, style);
3780 if (tm->tm_year <= 0)
3781 sprintf(str + strlen(str), " BC");
3784 case USE_POSTGRES_DATES:
3786 /* Backward-compatible with traditional Postgres abstime dates */
3788 day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3789 tm->tm_wday = j2day(day);
3791 strncpy(str, days[tm->tm_wday], 3);
3792 strcpy(str + 3, " ");
3794 if (DateOrder == DATEORDER_DMY)
3795 sprintf(str + 4, "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
3797 sprintf(str + 4, "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);
3799 sprintf(str + 10, " %02d:%02d:", tm->tm_hour, tm->tm_min);
3801 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3803 sprintf(str + strlen(str), " %04d",
3804 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1));
3806 if (tzp != NULL && tm->tm_isdst >= 0)
3809 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3813 * We have a time zone, but no string version. Use the
3814 * numeric form, but be sure to include a leading space to
3815 * avoid formatting something which would be rejected by
3816 * the date/time parser later. - thomas 2001-10-19
3818 sprintf(str + strlen(str), " ");
3819 EncodeTimezone(str, *tzp, style);
3823 if (tm->tm_year <= 0)
3824 sprintf(str + strlen(str), " BC");
3831 * Helper functions to avoid duplicated code in EncodeInterval.
3834 /* Append an ISO-8601-style interval field, but only if value isn't zero */
3836 AddISO8601IntPart(char *cp, int value, char units)
3840 sprintf(cp, "%d%c", value, units);
3841 return cp + strlen(cp);
3844 /* Append a postgres-style interval field, but only if value isn't zero */
3846 AddPostgresIntPart(char *cp, int value, const char *units,
3847 bool *is_zero, bool *is_before)
3851 sprintf(cp, "%s%s%d %s%s",
3852 (!*is_zero) ? " " : "",
3853 (*is_before && value > 0) ? "+" : "",
3856 (value != 1) ? "s" : "");
3859 * Each nonzero field sets is_before for (only) the next one. This is a
3860 * tad bizarre but it's how it worked before...
3862 *is_before = (value < 0);
3864 return cp + strlen(cp);
3867 /* Append a verbose-style interval field, but only if value isn't zero */
3869 AddVerboseIntPart(char *cp, int value, const char *units,
3870 bool *is_zero, bool *is_before)
3874 /* first nonzero value sets is_before */
3877 *is_before = (value < 0);
3880 else if (*is_before)
3882 sprintf(cp, " %d %s%s", value, units, (value == 1) ? "" : "s");
3884 return cp + strlen(cp);
3889 * Interpret time structure as a delta time and convert to string.
3891 * Support "traditional Postgres" and ISO-8601 styles.
3892 * Actually, afaik ISO does not address time interval formatting,
3893 * but this looks similar to the spec for absolute date/time.
3894 * - thomas 1998-04-30
3896 * Actually, afaik, ISO 8601 does specify formats for "time
3897 * intervals...[of the]...format with time-unit designators", which
3898 * are pretty ugly. The format looks something like
3899 * P1Y1M1DT1H1M1.12345S
3900 * but useful for exchanging data with computers instead of humans.
3903 * And ISO's SQL 2008 standard specifies standards for
3904 * "year-month literal"s (that look like '2-3') and
3905 * "day-time literal"s (that look like ('4 5:6:7')
3908 EncodeInterval(struct pg_tm * tm, fsec_t fsec, int style, char *str)
3911 int year = tm->tm_year;
3912 int mon = tm->tm_mon;
3913 int mday = tm->tm_mday;
3914 int hour = tm->tm_hour;
3915 int min = tm->tm_min;
3916 int sec = tm->tm_sec;
3917 bool is_before = FALSE;
3918 bool is_zero = TRUE;
3921 * The sign of year and month are guaranteed to match, since they are
3922 * stored internally as "month". But we'll need to check for is_before and
3923 * is_zero when determining the signs of day and hour/minute/seconds
3928 /* SQL Standard interval format */
3929 case INTSTYLE_SQL_STANDARD:
3931 bool has_negative = year < 0 || mon < 0 ||
3932 mday < 0 || hour < 0 ||
3933 min < 0 || sec < 0 || fsec < 0;
3934 bool has_positive = year > 0 || mon > 0 ||
3935 mday > 0 || hour > 0 ||
3936 min > 0 || sec > 0 || fsec > 0;
3937 bool has_year_month = year != 0 || mon != 0;
3938 bool has_day_time = mday != 0 || hour != 0 ||
3939 min != 0 || sec != 0 || fsec != 0;
3940 bool has_day = mday != 0;
3941 bool sql_standard_value = !(has_negative && has_positive) &&
3942 !(has_year_month && has_day_time);
3945 * SQL Standard wants only 1 "<sign>" preceding the whole
3946 * interval ... but can't do that if mixed signs.
3948 if (has_negative && sql_standard_value)
3960 if (!has_negative && !has_positive)
3964 else if (!sql_standard_value)
3967 * For non sql-standard interval values, force outputting
3968 * the signs to avoid ambiguities with intervals with
3969 * mixed sign components.
3971 char year_sign = (year < 0 || mon < 0) ? '-' : '+';
3972 char day_sign = (mday < 0) ? '-' : '+';
3973 char sec_sign = (hour < 0 || min < 0 ||
3974 sec < 0 || fsec < 0) ? '-' : '+';
3976 sprintf(cp, "%c%d-%d %c%d %c%d:%02d:",
3977 year_sign, abs(year), abs(mon),
3978 day_sign, abs(mday),
3979 sec_sign, abs(hour), abs(min));
3981 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
3983 else if (has_year_month)
3985 sprintf(cp, "%d-%d", year, mon);
3989 sprintf(cp, "%d %d:%02d:", mday, hour, min);
3991 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
3995 sprintf(cp, "%d:%02d:", hour, min);
3997 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4002 /* ISO 8601 "time-intervals by duration only" */
4003 case INTSTYLE_ISO_8601:
4004 /* special-case zero to avoid printing nothing */
4005 if (year == 0 && mon == 0 && mday == 0 &&
4006 hour == 0 && min == 0 && sec == 0 && fsec == 0)
4008 sprintf(cp, "PT0S");
4012 cp = AddISO8601IntPart(cp, year, 'Y');
4013 cp = AddISO8601IntPart(cp, mon, 'M');
4014 cp = AddISO8601IntPart(cp, mday, 'D');
4015 if (hour != 0 || min != 0 || sec != 0 || fsec != 0)
4017 cp = AddISO8601IntPart(cp, hour, 'H');
4018 cp = AddISO8601IntPart(cp, min, 'M');
4019 if (sec != 0 || fsec != 0)
4021 if (sec < 0 || fsec < 0)
4023 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4030 /* Compatible with postgresql < 8.4 when DateStyle = 'iso' */
4031 case INTSTYLE_POSTGRES:
4032 cp = AddPostgresIntPart(cp, year, "year", &is_zero, &is_before);
4033 cp = AddPostgresIntPart(cp, mon, "mon", &is_zero, &is_before);
4034 cp = AddPostgresIntPart(cp, mday, "day", &is_zero, &is_before);
4035 if (is_zero || hour != 0 || min != 0 || sec != 0 || fsec != 0)
4037 bool minus = (hour < 0 || min < 0 || sec < 0 || fsec < 0);
4039 sprintf(cp, "%s%s%02d:%02d:",
4041 (minus ? "-" : (is_before ? "+" : "")),
4042 abs(hour), abs(min));
4044 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4048 /* Compatible with postgresql < 8.4 when DateStyle != 'iso' */
4049 case INTSTYLE_POSTGRES_VERBOSE:
4053 cp = AddVerboseIntPart(cp, year, "year", &is_zero, &is_before);
4054 cp = AddVerboseIntPart(cp, mon, "mon", &is_zero, &is_before);
4055 cp = AddVerboseIntPart(cp, mday, "day", &is_zero, &is_before);
4056 cp = AddVerboseIntPart(cp, hour, "hour", &is_zero, &is_before);
4057 cp = AddVerboseIntPart(cp, min, "min", &is_zero, &is_before);
4058 if (sec != 0 || fsec != 0)
4061 if (sec < 0 || (sec == 0 && fsec < 0))
4065 else if (!is_before)
4070 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4072 sprintf(cp, " sec%s",
4073 (abs(sec) != 1 || fsec != 0) ? "s" : "");
4076 /* identically zero? then put in a unitless zero... */
4087 * We've been burnt by stupid errors in the ordering of the datetkn tables
4088 * once too often. Arrange to check them during postmaster start.
4091 CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
4096 for (i = 1; i < nel; i++)
4098 if (strncmp(base[i - 1].token, base[i].token, TOKMAXLEN) >= 0)
4100 /* %.*s is safe since all our tokens are ASCII */
4101 elog(LOG, "ordering error in %s table: \"%.*s\" >= \"%.*s\"",
4103 TOKMAXLEN, base[i - 1].token,
4104 TOKMAXLEN, base[i].token);
4112 CheckDateTokenTables(void)
4116 Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
4117 Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
4119 ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
4120 ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
4125 * This function gets called during timezone config file load or reload
4126 * to create the final array of timezone tokens. The argument array
4127 * is already sorted in name order. This data is in a temporary memory
4128 * context and must be copied to somewhere permanent.
4131 InstallTimeZoneAbbrevs(tzEntry *abbrevs, int n)
4137 * Copy the data into TopMemoryContext and convert to datetkn format.
4139 newtbl = (datetkn *) MemoryContextAlloc(TopMemoryContext,
4140 n * sizeof(datetkn));
4141 for (i = 0; i < n; i++)
4143 strncpy(newtbl[i].token, abbrevs[i].abbrev, TOKMAXLEN);
4144 newtbl[i].type = abbrevs[i].is_dst ? DTZ : TZ;
4145 TOVAL(&newtbl[i], abbrevs[i].offset / 60);
4148 /* Check the ordering, if testing */
4149 Assert(CheckDateTokenTable("timezone offset", newtbl, n));
4151 /* Now safe to replace existing table (if any) */
4153 pfree(timezonetktbl);
4154 timezonetktbl = newtbl;
4155 sztimezonetktbl = n;
4157 /* clear date cache in case it contains any stale timezone names */
4158 for (i = 0; i < MAXDATEFIELDS; i++)
4159 datecache[i] = NULL;
4163 * This set-returning function reads all the available time zone abbreviations
4164 * and returns a set of (abbrev, utc_offset, is_dst).
4167 pg_timezone_abbrevs(PG_FUNCTION_ARGS)
4169 FuncCallContext *funcctx;
4175 char buffer[TOKMAXLEN + 1];
4178 Interval *resInterval;
4180 /* stuff done only on the first call of the function */
4181 if (SRF_IS_FIRSTCALL())
4184 MemoryContext oldcontext;
4186 /* create a function context for cross-call persistence */
4187 funcctx = SRF_FIRSTCALL_INIT();
4190 * switch to memory context appropriate for multiple function calls
4192 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4194 /* allocate memory for user context */
4195 pindex = (int *) palloc(sizeof(int));
4197 funcctx->user_fctx = (void *) pindex;
4200 * build tupdesc for result tuples. This must match this function's
4203 tupdesc = CreateTemplateTupleDesc(3, false);
4204 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "abbrev",
4206 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "utc_offset",
4207 INTERVALOID, -1, 0);
4208 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_dst",
4211 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4212 MemoryContextSwitchTo(oldcontext);
4215 /* stuff done on every call of the function */
4216 funcctx = SRF_PERCALL_SETUP();
4217 pindex = (int *) funcctx->user_fctx;
4219 if (*pindex >= sztimezonetktbl)
4220 SRF_RETURN_DONE(funcctx);
4222 MemSet(nulls, 0, sizeof(nulls));
4225 * Convert name to text, using upcasing conversion that is the inverse of
4226 * what ParseDateTime() uses.
4228 strncpy(buffer, timezonetktbl[*pindex].token, TOKMAXLEN);
4229 buffer[TOKMAXLEN] = '\0'; /* may not be null-terminated */
4230 for (p = (unsigned char *) buffer; *p; p++)
4231 *p = pg_toupper(*p);
4233 values[0] = CStringGetTextDatum(buffer);
4235 MemSet(&tm, 0, sizeof(struct pg_tm));
4236 tm.tm_min = (-1) * FROMVAL(&timezonetktbl[*pindex]);
4237 resInterval = (Interval *) palloc(sizeof(Interval));
4238 tm2interval(&tm, 0, resInterval);
4239 values[1] = IntervalPGetDatum(resInterval);
4241 Assert(timezonetktbl[*pindex].type == DTZ ||
4242 timezonetktbl[*pindex].type == TZ);
4243 values[2] = BoolGetDatum(timezonetktbl[*pindex].type == DTZ);
4247 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4248 result = HeapTupleGetDatum(tuple);
4250 SRF_RETURN_NEXT(funcctx, result);
4254 * This set-returning function reads all the available full time zones
4255 * and returns a set of (name, abbrev, utc_offset, is_dst).
4258 pg_timezone_names(PG_FUNCTION_ARGS)
4260 MemoryContext oldcontext;
4261 FuncCallContext *funcctx;
4272 Interval *resInterval;
4275 /* stuff done only on the first call of the function */
4276 if (SRF_IS_FIRSTCALL())
4280 /* create a function context for cross-call persistence */
4281 funcctx = SRF_FIRSTCALL_INIT();
4284 * switch to memory context appropriate for multiple function calls
4286 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4288 /* initialize timezone scanning code */
4289 tzenum = pg_tzenumerate_start();
4290 funcctx->user_fctx = (void *) tzenum;
4293 * build tupdesc for result tuples. This must match this function's
4296 tupdesc = CreateTemplateTupleDesc(4, false);
4297 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
4299 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "abbrev",
4301 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "utc_offset",
4302 INTERVALOID, -1, 0);
4303 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_dst",
4306 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4307 MemoryContextSwitchTo(oldcontext);
4310 /* stuff done on every call of the function */
4311 funcctx = SRF_PERCALL_SETUP();
4312 tzenum = (pg_tzenum *) funcctx->user_fctx;
4314 /* search for another zone to display */
4317 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4318 tz = pg_tzenumerate_next(tzenum);
4319 MemoryContextSwitchTo(oldcontext);
4323 pg_tzenumerate_end(tzenum);
4324 funcctx->user_fctx = NULL;
4325 SRF_RETURN_DONE(funcctx);
4328 /* Convert now() to local time in this zone */
4329 if (timestamp2tm(GetCurrentTransactionStartTimestamp(),
4330 &tzoff, &tm, &fsec, &tzn, tz) != 0)
4331 continue; /* ignore if conversion fails */
4333 /* Ignore zic's rather silly "Factory" time zone */
4334 if (tzn && strcmp(tzn, "Local time zone must be set--see zic manual page") == 0)
4337 /* Found a displayable zone */
4341 MemSet(nulls, 0, sizeof(nulls));
4343 values[0] = CStringGetTextDatum(pg_get_timezone_name(tz));
4344 values[1] = CStringGetTextDatum(tzn ? tzn : "");
4346 MemSet(&itm, 0, sizeof(struct pg_tm));
4347 itm.tm_sec = -tzoff;
4348 resInterval = (Interval *) palloc(sizeof(Interval));
4349 tm2interval(&itm, 0, resInterval);
4350 values[2] = IntervalPGetDatum(resInterval);
4352 values[3] = BoolGetDatum(tm.tm_isdst > 0);
4354 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4355 result = HeapTupleGetDatum(tuple);
4357 SRF_RETURN_NEXT(funcctx, result);