1 /*-------------------------------------------------------------------------
4 * Support functions for date/time types.
6 * Portions Copyright (c) 1996-2018, 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/htup_details.h"
23 #include "access/xact.h"
24 #include "catalog/pg_type.h"
26 #include "miscadmin.h"
27 #include "nodes/nodeFuncs.h"
28 #include "utils/builtins.h"
29 #include "utils/date.h"
30 #include "utils/datetime.h"
31 #include "utils/memutils.h"
32 #include "utils/tzparser.h"
35 static int DecodeNumber(int flen, char *field, bool haveTextMonth,
36 int fmask, int *tmask,
37 struct pg_tm *tm, fsec_t *fsec, bool *is2digits);
38 static int DecodeNumberField(int len, char *str,
39 int fmask, int *tmask,
40 struct pg_tm *tm, fsec_t *fsec, bool *is2digits);
41 static int DecodeTime(char *str, int fmask, int range,
42 int *tmask, struct pg_tm *tm, fsec_t *fsec);
43 static const datetkn *datebsearch(const char *key, const datetkn *base, int nel);
44 static int DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
46 static char *AppendSeconds(char *cp, int sec, fsec_t fsec,
47 int precision, bool fillzeros);
48 static void AdjustFractSeconds(double frac, struct pg_tm *tm, fsec_t *fsec,
50 static void AdjustFractDays(double frac, struct pg_tm *tm, fsec_t *fsec,
52 static int DetermineTimeZoneOffsetInternal(struct pg_tm *tm, pg_tz *tzp,
54 static bool DetermineTimeZoneAbbrevOffsetInternal(pg_time_t t,
55 const char *abbr, pg_tz *tzp,
56 int *offset, int *isdst);
57 static pg_tz *FetchDynamicTimeZone(TimeZoneAbbrevTable *tbl, const datetkn *tp);
60 const int day_tab[2][13] =
62 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
63 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}
66 const char *const months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
67 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
69 const char *const days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
70 "Thursday", "Friday", "Saturday", NULL};
73 /*****************************************************************************
75 *****************************************************************************/
78 * datetktbl holds date/time keywords.
80 * Note that this table must be strictly alphabetically ordered to allow an
81 * O(ln(N)) search algorithm to be used.
83 * The token field must be NUL-terminated; we truncate entries to TOKMAXLEN
86 * The static table contains no TZ, DTZ, or DYNTZ entries; rather those
87 * are loaded from configuration files and stored in zoneabbrevtbl, whose
88 * abbrevs[] field has the same format as the static datetktbl.
90 static const datetkn datetktbl[] = {
91 /* token, type, value */
92 {EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
93 {DA_D, ADBC, AD}, /* "ad" for years > 0 */
94 {"allballs", RESERV, DTK_ZULU}, /* 00:00:00 */
98 {"at", IGNORE_DTF, 0}, /* "at" (throwaway) */
100 {"august", MONTH, 8},
101 {DB_C, ADBC, BC}, /* "bc" for years <= 0 */
102 {DCURRENT, RESERV, DTK_CURRENT}, /* "current" is always now */
103 {"d", UNITS, DTK_DAY}, /* "day of month" for ISO input */
105 {"december", MONTH, 12},
106 {"dow", UNITS, DTK_DOW}, /* day of week */
107 {"doy", UNITS, DTK_DOY}, /* day of year */
108 {"dst", DTZMOD, SECS_PER_HOUR},
109 {EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
111 {"february", MONTH, 2},
114 {"h", UNITS, DTK_HOUR}, /* "hour" */
115 {LATE, RESERV, DTK_LATE}, /* "infinity" reserved for "late time" */
116 {INVALID, RESERV, DTK_INVALID}, /* "invalid" reserved for bad time */
117 {"isodow", UNITS, DTK_ISODOW}, /* ISO day of week, Sunday == 7 */
118 {"isoyear", UNITS, DTK_ISOYEAR}, /* year in terms of the ISO week date */
119 {"j", UNITS, DTK_JULIAN},
121 {"january", MONTH, 1},
122 {"jd", UNITS, DTK_JULIAN},
124 {"julian", UNITS, DTK_JULIAN},
128 {"m", UNITS, DTK_MONTH}, /* "month" for ISO input */
132 {"mm", UNITS, DTK_MINUTE}, /* "minute" for ISO input */
136 {"november", MONTH, 11},
137 {NOW, RESERV, DTK_NOW}, /* current transaction time */
139 {"october", MONTH, 10},
140 {"on", IGNORE_DTF, 0}, /* "on" (throwaway) */
142 {"s", UNITS, DTK_SECOND}, /* "seconds" for ISO input */
144 {"saturday", DOW, 6},
147 {"september", MONTH, 9},
150 {"t", ISOTIME, DTK_TIME}, /* Filler for ISO time fields */
154 {"thursday", DOW, 4},
155 {TODAY, RESERV, DTK_TODAY}, /* midnight */
156 {TOMORROW, RESERV, DTK_TOMORROW}, /* tomorrow midnight */
160 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
162 {"wednesday", DOW, 3},
164 {"y", UNITS, DTK_YEAR}, /* "year" for ISO input */
165 {YESTERDAY, RESERV, DTK_YESTERDAY} /* yesterday midnight */
168 static int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];
171 * deltatktbl: same format as datetktbl, but holds keywords used to represent
172 * time units (eg, for intervals, and for EXTRACT).
174 static const datetkn deltatktbl[] = {
175 /* token, type, value */
176 {"@", IGNORE_DTF, 0}, /* postgres relative prefix */
177 {DAGO, AGO, 0}, /* "ago" indicates negative time offset */
178 {"c", UNITS, DTK_CENTURY}, /* "century" relative */
179 {"cent", UNITS, DTK_CENTURY}, /* "century" relative */
180 {"centuries", UNITS, DTK_CENTURY}, /* "centuries" relative */
181 {DCENTURY, UNITS, DTK_CENTURY}, /* "century" relative */
182 {"d", UNITS, DTK_DAY}, /* "day" relative */
183 {DDAY, UNITS, DTK_DAY}, /* "day" relative */
184 {"days", UNITS, DTK_DAY}, /* "days" relative */
185 {"dec", UNITS, DTK_DECADE}, /* "decade" relative */
186 {DDECADE, UNITS, DTK_DECADE}, /* "decade" relative */
187 {"decades", UNITS, DTK_DECADE}, /* "decades" relative */
188 {"decs", UNITS, DTK_DECADE}, /* "decades" relative */
189 {"h", UNITS, DTK_HOUR}, /* "hour" relative */
190 {DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */
191 {"hours", UNITS, DTK_HOUR}, /* "hours" relative */
192 {"hr", UNITS, DTK_HOUR}, /* "hour" relative */
193 {"hrs", UNITS, DTK_HOUR}, /* "hours" relative */
194 {INVALID, RESERV, DTK_INVALID}, /* reserved for invalid time */
195 {"m", UNITS, DTK_MINUTE}, /* "minute" relative */
196 {"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
197 {"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
198 {"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
199 {DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
200 {"millisecon", UNITS, DTK_MILLISEC}, /* relative */
201 {"mils", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
202 {"min", UNITS, DTK_MINUTE}, /* "minute" relative */
203 {"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */
204 {DMINUTE, UNITS, DTK_MINUTE}, /* "minute" relative */
205 {"minutes", UNITS, DTK_MINUTE}, /* "minutes" relative */
206 {"mon", UNITS, DTK_MONTH}, /* "months" relative */
207 {"mons", UNITS, DTK_MONTH}, /* "months" relative */
208 {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
209 {"months", UNITS, DTK_MONTH},
210 {"ms", UNITS, DTK_MILLISEC},
211 {"msec", UNITS, DTK_MILLISEC},
212 {DMILLISEC, UNITS, DTK_MILLISEC},
213 {"mseconds", UNITS, DTK_MILLISEC},
214 {"msecs", UNITS, DTK_MILLISEC},
215 {"qtr", UNITS, DTK_QUARTER}, /* "quarter" relative */
216 {DQUARTER, UNITS, DTK_QUARTER}, /* "quarter" relative */
217 {"s", UNITS, DTK_SECOND},
218 {"sec", UNITS, DTK_SECOND},
219 {DSECOND, UNITS, DTK_SECOND},
220 {"seconds", UNITS, DTK_SECOND},
221 {"secs", UNITS, DTK_SECOND},
222 {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
223 {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
224 {"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */
225 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
226 {"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
227 {"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
228 {DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */
229 {"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
230 {"usecs", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
231 {"w", UNITS, DTK_WEEK}, /* "week" relative */
232 {DWEEK, UNITS, DTK_WEEK}, /* "week" relative */
233 {"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
234 {"y", UNITS, DTK_YEAR}, /* "year" relative */
235 {DYEAR, UNITS, DTK_YEAR}, /* "year" relative */
236 {"years", UNITS, DTK_YEAR}, /* "years" relative */
237 {"yr", UNITS, DTK_YEAR}, /* "year" relative */
238 {"yrs", UNITS, DTK_YEAR} /* "years" relative */
241 static int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];
243 static TimeZoneAbbrevTable *zoneabbrevtbl = NULL;
245 /* Caches of recent lookup results in the above tables */
247 static const datetkn *datecache[MAXDATEFIELDS] = {NULL};
249 static const datetkn *deltacache[MAXDATEFIELDS] = {NULL};
251 static const datetkn *abbrevcache[MAXDATEFIELDS] = {NULL};
255 * strtoint --- just like strtol, but returns int not long
258 strtoint(const char *nptr, char **endptr, int base)
262 val = strtol(nptr, endptr, base);
263 #ifdef HAVE_LONG_INT_64
264 if (val != (long) ((int32) val))
272 * Calendar time to Julian date conversions.
273 * Julian date is commonly used in astronomical applications,
274 * since it is numerically accurate and computationally simple.
275 * The algorithms here will accurately convert between Julian day
276 * and calendar date for all non-negative Julian days
277 * (i.e. from Nov 24, -4713 on).
279 * Rewritten to eliminate overflow problems. This now allows the
280 * routines to work correctly for all Julian day counts from
281 * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming
282 * a 32-bit integer. Longer types should also work to the limits
283 * of their precision.
285 * Actually, date2j() will work sanely, in the sense of producing
286 * valid negative Julian dates, significantly before Nov 24, -4713.
287 * We rely on it to do so back to Nov 1, -4713; see IS_VALID_JULIAN()
288 * and associated commentary in timestamp.h.
292 date2j(int y, int m, int d)
309 julian = y * 365 - 32167;
310 julian += y / 4 - century + century / 4;
311 julian += 7834 * m / 256 + d;
317 j2date(int jd, int *year, int *month, int *day)
326 quad = julian / 146097;
327 extra = (julian - quad * 146097) * 4 + 3;
328 julian += 60 + quad * 3 + extra / 146097;
329 quad = julian / 1461;
330 julian -= quad * 1461;
331 y = julian * 4 / 1461;
332 julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
336 quad = julian * 2141 / 65536;
337 *day = julian - 7834 * quad / 256;
338 *month = (quad + 10) % MONTHS_PER_YEAR + 1;
345 * j2day - convert Julian date to day-of-week (0..6 == Sun..Sat)
347 * Note: various places use the locution j2day(date - 1) to produce a
348 * result according to the convention 0..6 = Mon..Sun. This is a bit of
349 * a crock, but will work as long as the computation here is just a modulo.
356 /* Cope if division truncates towards zero, as it probably does */
365 * GetCurrentDateTime()
367 * Get the transaction start time ("now()") broken down as a struct pg_tm.
370 GetCurrentDateTime(struct pg_tm *tm)
375 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, &fsec,
377 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
381 * GetCurrentTimeUsec()
383 * Get the transaction start time ("now()") broken down as a struct pg_tm,
384 * including fractional seconds and timezone offset.
387 GetCurrentTimeUsec(struct pg_tm *tm, fsec_t *fsec, int *tzp)
391 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, fsec,
393 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
400 * Append seconds and fractional seconds (if any) at *cp.
402 * precision is the max number of fraction digits, fillzeros says to
403 * pad to two integral-seconds digits.
405 * Returns a pointer to the new end of string. No NUL terminator is put
406 * there; callers are responsible for NUL terminating str themselves.
408 * Note that any sign is stripped from the input seconds values.
411 AppendSeconds(char *cp, int sec, fsec_t fsec, int precision, bool fillzeros)
413 Assert(precision >= 0);
416 cp = pg_ltostr_zeropad(cp, Abs(sec), 2);
418 cp = pg_ltostr(cp, Abs(sec));
420 /* fsec_t is just an int32 */
423 int32 value = Abs(fsec);
424 char *end = &cp[precision + 1];
425 bool gotnonzero = false;
430 * Append the fractional seconds part. Note that we don't want any
431 * trailing zeros here, so since we're building the number in reverse
432 * we'll skip appending zeros until we've output a non-zero digit.
436 int32 oldval = value;
440 remainder = oldval - value * 10;
442 /* check if we got a non-zero */
447 cp[precision] = '0' + remainder;
449 end = &cp[precision];
453 * If we still have a non-zero value then precision must have not been
454 * enough to print the number. We punt the problem to pg_ltostr(),
455 * which will generate a correct answer in the minimum valid width.
458 return pg_ltostr(cp, Abs(fsec));
468 * Variant of above that's specialized to timestamp case.
470 * Returns a pointer to the new end of string. No NUL terminator is put
471 * there; callers are responsible for NUL terminating str themselves.
474 AppendTimestampSeconds(char *cp, struct pg_tm *tm, fsec_t fsec)
476 return AppendSeconds(cp, tm->tm_sec, fsec, MAX_TIMESTAMP_PRECISION, true);
480 * Multiply frac by scale (to produce seconds) and add to *tm & *fsec.
481 * We assume the input frac is less than 1 so overflow is not an issue.
484 AdjustFractSeconds(double frac, struct pg_tm *tm, fsec_t *fsec, int scale)
494 *fsec += rint(frac * 1000000);
497 /* As above, but initial scale produces days */
499 AdjustFractDays(double frac, struct pg_tm *tm, fsec_t *fsec, int scale)
506 extra_days = (int) frac;
507 tm->tm_mday += extra_days;
509 AdjustFractSeconds(frac, tm, fsec, SECS_PER_DAY);
512 /* Fetch a fractional-second value with suitable error checking */
514 ParseFractionalSecond(char *cp, fsec_t *fsec)
518 /* Caller should always pass the start of the fraction part */
521 frac = strtod(cp, &cp);
522 /* check for parse failure */
523 if (*cp != '\0' || errno != 0)
524 return DTERR_BAD_FORMAT;
525 *fsec = rint(frac * 1000000);
531 * Break string into tokens based on a date/time context.
532 * Returns 0 if successful, DTERR code if bogus input detected.
534 * timestr - the input string
535 * workbuf - workspace for field string storage. This must be
536 * larger than the largest legal input for this datetime type --
537 * some additional space will be needed to NUL terminate fields.
538 * buflen - the size of workbuf
539 * field[] - pointers to field strings are returned in this array
540 * ftype[] - field type indicators are returned in this array
541 * maxfields - dimensions of the above two arrays
542 * *numfields - set to the actual number of fields detected
544 * The fields extracted from the input are stored as separate,
545 * null-terminated strings in the workspace at workbuf. Any text is
546 * converted to lower case.
548 * Several field types are assigned:
549 * DTK_NUMBER - digits and (possibly) a decimal point
550 * DTK_DATE - digits and two delimiters, or digits and text
551 * DTK_TIME - digits, colon delimiters, and possibly a decimal point
552 * DTK_STRING - text (no digits or punctuation)
553 * DTK_SPECIAL - leading "+" or "-" followed by text
554 * DTK_TZ - leading "+" or "-" followed by digits (also eats ':', '.', '-')
556 * Note that some field types can hold unexpected items:
557 * DTK_NUMBER can hold date fields (yy.ddd)
558 * DTK_STRING can hold months (January) and time zones (PST)
559 * DTK_DATE can hold time zone names (America/New_York, GMT-8)
562 ParseDateTime(const char *timestr, char *workbuf, size_t buflen,
563 char **field, int *ftype, int maxfields, int *numfields)
566 const char *cp = timestr;
567 char *bufp = workbuf;
568 const char *bufend = workbuf + buflen;
571 * Set the character pointed-to by "bufptr" to "newchar", and increment
572 * "bufptr". "end" gives the end of the buffer -- we return an error if
573 * there is no space left to append a character to the buffer. Note that
574 * "bufptr" is evaluated twice.
576 #define APPEND_CHAR(bufptr, end, newchar) \
579 if (((bufptr) + 1) >= (end)) \
580 return DTERR_BAD_FORMAT; \
581 *(bufptr)++ = newchar; \
584 /* outer loop through fields */
587 /* Ignore spaces between fields */
588 if (isspace((unsigned char) *cp))
594 /* Record start of current field */
596 return DTERR_BAD_FORMAT;
599 /* leading digit? then date or time */
600 if (isdigit((unsigned char) *cp))
602 APPEND_CHAR(bufp, bufend, *cp++);
603 while (isdigit((unsigned char) *cp))
604 APPEND_CHAR(bufp, bufend, *cp++);
609 ftype[nf] = DTK_TIME;
610 APPEND_CHAR(bufp, bufend, *cp++);
611 while (isdigit((unsigned char) *cp) ||
612 (*cp == ':') || (*cp == '.'))
613 APPEND_CHAR(bufp, bufend, *cp++);
615 /* date field? allow embedded text month */
616 else if (*cp == '-' || *cp == '/' || *cp == '.')
618 /* save delimiting character to use later */
621 APPEND_CHAR(bufp, bufend, *cp++);
622 /* second field is all digits? then no embedded text month */
623 if (isdigit((unsigned char) *cp))
625 ftype[nf] = ((delim == '.') ? DTK_NUMBER : DTK_DATE);
626 while (isdigit((unsigned char) *cp))
627 APPEND_CHAR(bufp, bufend, *cp++);
630 * insist that the delimiters match to get a three-field
635 ftype[nf] = DTK_DATE;
636 APPEND_CHAR(bufp, bufend, *cp++);
637 while (isdigit((unsigned char) *cp) || *cp == delim)
638 APPEND_CHAR(bufp, bufend, *cp++);
643 ftype[nf] = DTK_DATE;
644 while (isalnum((unsigned char) *cp) || *cp == delim)
645 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
650 * otherwise, number only and will determine year, month, day, or
651 * concatenated fields later...
654 ftype[nf] = DTK_NUMBER;
656 /* Leading decimal point? Then fractional seconds... */
659 APPEND_CHAR(bufp, bufend, *cp++);
660 while (isdigit((unsigned char) *cp))
661 APPEND_CHAR(bufp, bufend, *cp++);
663 ftype[nf] = DTK_NUMBER;
667 * text? then date string, month, day of week, special, or timezone
669 else if (isalpha((unsigned char) *cp))
673 ftype[nf] = DTK_STRING;
674 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
675 while (isalpha((unsigned char) *cp))
676 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
679 * Dates can have embedded '-', '/', or '.' separators. It could
680 * also be a timezone name containing embedded '/', '+', '-', '_',
681 * or ':' (but '_' or ':' can't be the first punctuation). If the
682 * next character is a digit or '+', we need to check whether what
683 * we have so far is a recognized non-timezone keyword --- if so,
684 * don't believe that this is the start of a timezone.
687 if (*cp == '-' || *cp == '/' || *cp == '.')
689 else if (*cp == '+' || isdigit((unsigned char) *cp))
691 *bufp = '\0'; /* null-terminate current field value */
692 /* we need search only the core token table, not TZ names */
693 if (datebsearch(field[nf], datetktbl, szdatetktbl) == NULL)
698 ftype[nf] = DTK_DATE;
701 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
702 } while (*cp == '+' || *cp == '-' ||
703 *cp == '/' || *cp == '_' ||
704 *cp == '.' || *cp == ':' ||
705 isalnum((unsigned char) *cp));
708 /* sign? then special or numeric timezone */
709 else if (*cp == '+' || *cp == '-')
711 APPEND_CHAR(bufp, bufend, *cp++);
712 /* soak up leading whitespace */
713 while (isspace((unsigned char) *cp))
715 /* numeric timezone? */
716 /* note that "DTK_TZ" could also be a signed float or yyyy-mm */
717 if (isdigit((unsigned char) *cp))
720 APPEND_CHAR(bufp, bufend, *cp++);
721 while (isdigit((unsigned char) *cp) ||
722 *cp == ':' || *cp == '.' || *cp == '-')
723 APPEND_CHAR(bufp, bufend, *cp++);
726 else if (isalpha((unsigned char) *cp))
728 ftype[nf] = DTK_SPECIAL;
729 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
730 while (isalpha((unsigned char) *cp))
731 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
733 /* otherwise something wrong... */
735 return DTERR_BAD_FORMAT;
737 /* ignore other punctuation but use as delimiter */
738 else if (ispunct((unsigned char) *cp))
743 /* otherwise, something is not right... */
745 return DTERR_BAD_FORMAT;
747 /* force in a delimiter after each field */
759 * Interpret previously parsed fields for general date and time.
760 * Return 0 if full date, 1 if only time, and negative DTERR code if problems.
761 * (Currently, all callers treat 1 as an error return too.)
763 * External format(s):
764 * "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
765 * "Fri Feb-7-1997 15:23:27"
766 * "Feb-7-1997 15:23:27"
767 * "2-7-1997 15:23:27"
768 * "1997-2-7 15:23:27"
769 * "1997.038 15:23:27" (day of year 1-366)
770 * Also supports input in compact time:
773 * "20011225T040506.789-07"
775 * Use the system-provided functions to get the current time zone
776 * if not specified in the input string.
778 * If the date is outside the range of pg_time_t (in practice that could only
779 * happen if pg_time_t is just 32 bits), then assume UTC time zone - thomas
783 DecodeDateTime(char **field, int *ftype, int nf,
784 int *dtype, struct pg_tm *tm, fsec_t *fsec, int *tzp)
789 int ptype = 0; /* "prefix type" for ISO y2001m02d04 format */
794 bool haveTextMonth = false;
795 bool isjulian = false;
796 bool is2digits = false;
798 pg_tz *namedTz = NULL;
799 pg_tz *abbrevTz = NULL;
805 * We'll insist on at least all of the date fields, but initialize the
806 * remaining fields in case they are not set later...
813 /* don't know daylight savings time status apriori */
818 for (i = 0; i < nf; i++)
825 * Integral julian day with attached time zone? All other
826 * forms with JD will be separated into distinct fields, so we
827 * handle just this case here.
829 if (ptype == DTK_JULIAN)
835 return DTERR_BAD_FORMAT;
838 val = strtoint(field[i], &cp, 10);
839 if (errno == ERANGE || val < 0)
840 return DTERR_FIELD_OVERFLOW;
842 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
845 /* Get the time zone from the end of the string */
846 dterr = DecodeTimezone(cp, tzp);
850 tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
856 * Already have a date? Then this might be a time zone name
857 * with embedded punctuation (e.g. "America/New_York") or a
858 * run-together time with trailing time zone (e.g. hhmmss-zz).
859 * - thomas 2001-12-25
861 * We consider it a time zone if we already have month & day.
862 * This is to allow the form "mmm dd hhmmss tz year", which
863 * we've historically accepted.
865 else if (ptype != 0 ||
866 ((fmask & (DTK_M(MONTH) | DTK_M(DAY))) ==
867 (DTK_M(MONTH) | DTK_M(DAY))))
869 /* No time zone accepted? Then quit... */
871 return DTERR_BAD_FORMAT;
873 if (isdigit((unsigned char) *field[i]) || ptype != 0)
879 /* Sanity check; should not fail this test */
880 if (ptype != DTK_TIME)
881 return DTERR_BAD_FORMAT;
886 * Starts with a digit but we already have a time
887 * field? Then we are in trouble with a date and time
890 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
891 return DTERR_BAD_FORMAT;
893 if ((cp = strchr(field[i], '-')) == NULL)
894 return DTERR_BAD_FORMAT;
896 /* Get the time zone from the end of the string */
897 dterr = DecodeTimezone(cp, tzp);
903 * Then read the rest of the field as a concatenated
906 dterr = DecodeNumberField(strlen(field[i]), field[i],
914 * modify tmask after returning from
915 * DecodeNumberField()
921 namedTz = pg_tzset(field[i]);
925 * We should return an error code instead of
926 * ereport'ing directly, but then there is no way
927 * to report the bad time zone name.
930 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
931 errmsg("time zone \"%s\" not recognized",
934 /* we'll apply the zone setting below */
940 dterr = DecodeDate(field[i], fmask,
941 &tmask, &is2digits, tm);
950 * This might be an ISO time following a "t" field.
954 /* Sanity check; should not fail this test */
955 if (ptype != DTK_TIME)
956 return DTERR_BAD_FORMAT;
959 dterr = DecodeTime(field[i], fmask, INTERVAL_FULL_RANGE,
965 * Check upper limit on hours; other limits checked in
968 /* test for > 24:00:00 */
969 if (tm->tm_hour > HOURS_PER_DAY ||
970 (tm->tm_hour == HOURS_PER_DAY &&
971 (tm->tm_min > 0 || tm->tm_sec > 0 || *fsec > 0)))
972 return DTERR_FIELD_OVERFLOW;
980 return DTERR_BAD_FORMAT;
982 dterr = DecodeTimezone(field[i], &tz);
993 * Was this an "ISO date" with embedded field labels? An
994 * example is "y2001m02d04" - thomas 2001-02-04
1002 val = strtoint(field[i], &cp, 10);
1003 if (errno == ERANGE)
1004 return DTERR_FIELD_OVERFLOW;
1007 * only a few kinds are allowed to have an embedded
1018 return DTERR_BAD_FORMAT;
1021 else if (*cp != '\0')
1022 return DTERR_BAD_FORMAT;
1028 tmask = DTK_M(YEAR);
1034 * already have a month and hour? then assume
1037 if ((fmask & DTK_M(MONTH)) != 0 &&
1038 (fmask & DTK_M(HOUR)) != 0)
1041 tmask = DTK_M(MINUTE);
1046 tmask = DTK_M(MONTH);
1057 tmask = DTK_M(HOUR);
1062 tmask = DTK_M(MINUTE);
1067 tmask = DTK_M(SECOND);
1070 dterr = ParseFractionalSecond(cp, fsec);
1073 tmask = DTK_ALL_SECS_M;
1079 dterr = DecodeTimezone(field[i], tzp);
1085 /* previous field was a label for "julian date" */
1087 return DTERR_FIELD_OVERFLOW;
1089 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1092 /* fractional Julian Day? */
1098 time = strtod(cp, &cp);
1099 if (*cp != '\0' || errno != 0)
1100 return DTERR_BAD_FORMAT;
1101 time *= USECS_PER_DAY;
1103 &tm->tm_hour, &tm->tm_min,
1105 tmask |= DTK_TIME_M;
1110 /* previous field was "t" for ISO time */
1111 dterr = DecodeNumberField(strlen(field[i]), field[i],
1112 (fmask | DTK_DATE_M),
1117 if (tmask != DTK_TIME_M)
1118 return DTERR_BAD_FORMAT;
1122 return DTERR_BAD_FORMAT;
1134 flen = strlen(field[i]);
1135 cp = strchr(field[i], '.');
1137 /* Embedded decimal and no date yet? */
1138 if (cp != NULL && !(fmask & DTK_DATE_M))
1140 dterr = DecodeDate(field[i], fmask,
1141 &tmask, &is2digits, tm);
1145 /* embedded decimal and several digits before? */
1146 else if (cp != NULL && flen - strlen(cp) > 2)
1149 * Interpret as a concatenated date or time Set the
1150 * type field to allow decoding other fields later.
1151 * Example: 20011223 or 040506
1153 dterr = DecodeNumberField(flen, field[i], fmask,
1161 * Is this a YMD or HMS specification, or a year number?
1162 * YMD and HMS are required to be six digits or more, so
1163 * if it is 5 digits, it is a year. If it is six or more
1164 * more digits, we assume it is YMD or HMS unless no date
1165 * and no time values have been specified. This forces 6+
1166 * digit years to be at the end of the string, or to use
1167 * the ISO date specification.
1169 else if (flen >= 6 && (!(fmask & DTK_DATE_M) ||
1170 !(fmask & DTK_TIME_M)))
1172 dterr = DecodeNumberField(flen, field[i], fmask,
1178 /* otherwise it is a single date/time field... */
1181 dterr = DecodeNumber(flen, field[i],
1182 haveTextMonth, fmask,
1193 /* timezone abbrevs take precedence over built-in tokens */
1194 type = DecodeTimezoneAbbrev(i, field[i], &val, &valtz);
1195 if (type == UNKNOWN_FIELD)
1196 type = DecodeSpecial(i, field[i], &val);
1197 if (type == IGNORE_DTF)
1200 tmask = DTK_M(type);
1208 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1209 errmsg("date/time value \"current\" is no longer supported")));
1211 return DTERR_BAD_FORMAT;
1215 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1217 GetCurrentTimeUsec(tm, fsec, tzp);
1223 GetCurrentDateTime(&cur_tm);
1224 j2date(date2j(cur_tm.tm_year, cur_tm.tm_mon, cur_tm.tm_mday) - 1,
1225 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1231 GetCurrentDateTime(&cur_tm);
1232 tm->tm_year = cur_tm.tm_year;
1233 tm->tm_mon = cur_tm.tm_mon;
1234 tm->tm_mday = cur_tm.tm_mday;
1240 GetCurrentDateTime(&cur_tm);
1241 j2date(date2j(cur_tm.tm_year, cur_tm.tm_mon, cur_tm.tm_mday) + 1,
1242 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1246 tmask = (DTK_TIME_M | DTK_M(TZ));
1264 * already have a (numeric) month? then see if we can
1267 if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
1268 !(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 &&
1271 tm->tm_mday = tm->tm_mon;
1274 haveTextMonth = true;
1281 * daylight savings time modifier (solves "MET DST"
1284 tmask |= DTK_M(DTZ);
1287 return DTERR_BAD_FORMAT;
1294 * set mask for TZ here _or_ check for DTZ later when
1295 * getting default timezone
1300 return DTERR_BAD_FORMAT;
1307 return DTERR_BAD_FORMAT;
1314 return DTERR_BAD_FORMAT;
1315 /* we'll determine the actual offset later */
1340 * This is a filler field "t" indicating that the next
1341 * field is time. Try to verify that this is sensible.
1345 /* No preceding date? Then quit... */
1346 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1347 return DTERR_BAD_FORMAT;
1350 * We will need one of the following fields:
1351 * DTK_NUMBER should be hhmmss.fff
1352 * DTK_TIME should be hh:mm:ss.fff
1353 * DTK_DATE should be hhmmss-zz
1356 (ftype[i + 1] != DTK_NUMBER &&
1357 ftype[i + 1] != DTK_TIME &&
1358 ftype[i + 1] != DTK_DATE))
1359 return DTERR_BAD_FORMAT;
1367 * Before giving up and declaring error, check to see
1368 * if it is an all-alpha timezone name.
1370 namedTz = pg_tzset(field[i]);
1372 return DTERR_BAD_FORMAT;
1373 /* we'll apply the zone setting below */
1378 return DTERR_BAD_FORMAT;
1383 return DTERR_BAD_FORMAT;
1387 return DTERR_BAD_FORMAT;
1389 } /* end loop over fields */
1391 /* do final checking/adjustment of Y/M/D fields */
1392 dterr = ValidateDate(fmask, isjulian, is2digits, bc, tm);
1397 if (mer != HR24 && tm->tm_hour > HOURS_PER_DAY / 2)
1398 return DTERR_FIELD_OVERFLOW;
1399 if (mer == AM && tm->tm_hour == HOURS_PER_DAY / 2)
1401 else if (mer == PM && tm->tm_hour != HOURS_PER_DAY / 2)
1402 tm->tm_hour += HOURS_PER_DAY / 2;
1404 /* do additional checking for full date specs... */
1405 if (*dtype == DTK_DATE)
1407 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1409 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1411 return DTERR_BAD_FORMAT;
1415 * If we had a full timezone spec, compute the offset (we could not do
1416 * it before, because we need the date to resolve DST status).
1418 if (namedTz != NULL)
1420 /* daylight savings time modifier disallowed with full TZ */
1421 if (fmask & DTK_M(DTZMOD))
1422 return DTERR_BAD_FORMAT;
1424 *tzp = DetermineTimeZoneOffset(tm, namedTz);
1428 * Likewise, if we had a dynamic timezone abbreviation, resolve it
1431 if (abbrevTz != NULL)
1433 /* daylight savings time modifier disallowed with dynamic TZ */
1434 if (fmask & DTK_M(DTZMOD))
1435 return DTERR_BAD_FORMAT;
1437 *tzp = DetermineTimeZoneAbbrevOffset(tm, abbrev, abbrevTz);
1440 /* timezone not specified? then use session timezone */
1441 if (tzp != NULL && !(fmask & DTK_M(TZ)))
1444 * daylight savings time modifier but no standard timezone? then
1447 if (fmask & DTK_M(DTZMOD))
1448 return DTERR_BAD_FORMAT;
1450 *tzp = DetermineTimeZoneOffset(tm, session_timezone);
1458 /* DetermineTimeZoneOffset()
1460 * Given a struct pg_tm in which tm_year, tm_mon, tm_mday, tm_hour, tm_min,
1461 * and tm_sec fields are set, and a zic-style time zone definition, determine
1462 * the applicable GMT offset and daylight-savings status at that time.
1463 * Set the struct pg_tm's tm_isdst field accordingly, and return the GMT
1464 * offset as the function result.
1466 * Note: if the date is out of the range we can deal with, we return zero
1467 * as the GMT offset and set tm_isdst = 0. We don't throw an error here,
1468 * though probably some higher-level code will.
1471 DetermineTimeZoneOffset(struct pg_tm *tm, pg_tz *tzp)
1475 return DetermineTimeZoneOffsetInternal(tm, tzp, &t);
1479 /* DetermineTimeZoneOffsetInternal()
1481 * As above, but also return the actual UTC time imputed to the date/time
1484 * In event of an out-of-range date, we punt by returning zero into *tp.
1485 * This is okay for the immediate callers but is a good reason for not
1486 * exposing this worker function globally.
1488 * Note: it might seem that we should use mktime() for this, but bitter
1489 * experience teaches otherwise. This code is much faster than most versions
1490 * of mktime(), anyway.
1493 DetermineTimeZoneOffsetInternal(struct pg_tm *tm, pg_tz *tzp, pg_time_t *tp)
1503 long int before_gmtoff,
1510 * First, generate the pg_time_t value corresponding to the given
1511 * y/m/d/h/m/s taken as GMT time. If this overflows, punt and decide the
1512 * timezone is GMT. (For a valid Julian date, integer overflow should be
1513 * impossible with 64-bit pg_time_t, but let's check for safety.)
1515 if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
1517 date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - UNIX_EPOCH_JDATE;
1519 day = ((pg_time_t) date) * SECS_PER_DAY;
1520 if (day / SECS_PER_DAY != date)
1522 sec = tm->tm_sec + (tm->tm_min + tm->tm_hour * MINS_PER_HOUR) * SECS_PER_MINUTE;
1524 /* since sec >= 0, overflow could only be from +day to -mytime */
1525 if (mytime < 0 && day > 0)
1529 * Find the DST time boundary just before or following the target time. We
1530 * assume that all zones have GMT offsets less than 24 hours, and that DST
1531 * boundaries can't be closer together than 48 hours, so backing up 24
1532 * hours and finding the "next" boundary will work.
1534 prevtime = mytime - SECS_PER_DAY;
1535 if (mytime < 0 && prevtime > 0)
1538 res = pg_next_dst_boundary(&prevtime,
1539 &before_gmtoff, &before_isdst,
1541 &after_gmtoff, &after_isdst,
1544 goto overflow; /* failure? */
1548 /* Non-DST zone, life is simple */
1549 tm->tm_isdst = before_isdst;
1550 *tp = mytime - before_gmtoff;
1551 return -(int) before_gmtoff;
1555 * Form the candidate pg_time_t values with local-time adjustment
1557 beforetime = mytime - before_gmtoff;
1558 if ((before_gmtoff > 0 &&
1559 mytime < 0 && beforetime > 0) ||
1560 (before_gmtoff <= 0 &&
1561 mytime > 0 && beforetime < 0))
1563 aftertime = mytime - after_gmtoff;
1564 if ((after_gmtoff > 0 &&
1565 mytime < 0 && aftertime > 0) ||
1566 (after_gmtoff <= 0 &&
1567 mytime > 0 && aftertime < 0))
1571 * If both before or both after the boundary time, we know what to do. The
1572 * boundary time itself is considered to be after the transition, which
1573 * means we can accept aftertime == boundary in the second case.
1575 if (beforetime < boundary && aftertime < boundary)
1577 tm->tm_isdst = before_isdst;
1579 return -(int) before_gmtoff;
1581 if (beforetime > boundary && aftertime >= boundary)
1583 tm->tm_isdst = after_isdst;
1585 return -(int) after_gmtoff;
1589 * It's an invalid or ambiguous time due to timezone transition. In a
1590 * spring-forward transition, prefer the "before" interpretation; in a
1591 * fall-back transition, prefer "after". (We used to define and implement
1592 * this test as "prefer the standard-time interpretation", but that rule
1593 * does not help to resolve the behavior when both times are reported as
1594 * standard time; which does happen, eg Europe/Moscow in Oct 2014.)
1596 if (beforetime > aftertime)
1598 tm->tm_isdst = before_isdst;
1600 return -(int) before_gmtoff;
1602 tm->tm_isdst = after_isdst;
1604 return -(int) after_gmtoff;
1607 /* Given date is out of range, so assume UTC */
1614 /* DetermineTimeZoneAbbrevOffset()
1616 * Determine the GMT offset and DST flag to be attributed to a dynamic
1617 * time zone abbreviation, that is one whose meaning has changed over time.
1618 * *tm contains the local time at which the meaning should be determined,
1619 * and tm->tm_isdst receives the DST flag.
1621 * This differs from the behavior of DetermineTimeZoneOffset() in that a
1622 * standard-time or daylight-time abbreviation forces use of the corresponding
1623 * GMT offset even when the zone was then in DS or standard time respectively.
1624 * (However, that happens only if we can match the given abbreviation to some
1625 * abbreviation that appears in the IANA timezone data. Otherwise, we fall
1626 * back to doing DetermineTimeZoneOffset().)
1629 DetermineTimeZoneAbbrevOffset(struct pg_tm *tm, const char *abbr, pg_tz *tzp)
1637 * Compute the UTC time we want to probe at. (In event of overflow, we'll
1638 * probe at the epoch, which is a bit random but probably doesn't matter.)
1640 zone_offset = DetermineTimeZoneOffsetInternal(tm, tzp, &t);
1643 * Try to match the abbreviation to something in the zone definition.
1645 if (DetermineTimeZoneAbbrevOffsetInternal(t, abbr, tzp,
1646 &abbr_offset, &abbr_isdst))
1648 /* Success, so use the abbrev-specific answers. */
1649 tm->tm_isdst = abbr_isdst;
1654 * No match, so use the answers we already got from
1655 * DetermineTimeZoneOffsetInternal.
1661 /* DetermineTimeZoneAbbrevOffsetTS()
1663 * As above but the probe time is specified as a TimestampTz (hence, UTC time),
1664 * and DST status is returned into *isdst rather than into tm->tm_isdst.
1667 DetermineTimeZoneAbbrevOffsetTS(TimestampTz ts, const char *abbr,
1668 pg_tz *tzp, int *isdst)
1670 pg_time_t t = timestamptz_to_time_t(ts);
1678 * If the abbrev matches anything in the zone data, this is pretty easy.
1680 if (DetermineTimeZoneAbbrevOffsetInternal(t, abbr, tzp,
1681 &abbr_offset, isdst))
1685 * Else, break down the timestamp so we can use DetermineTimeZoneOffset.
1687 if (timestamp2tm(ts, &tz, &tm, &fsec, NULL, tzp) != 0)
1689 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1690 errmsg("timestamp out of range")));
1692 zone_offset = DetermineTimeZoneOffset(&tm, tzp);
1693 *isdst = tm.tm_isdst;
1698 /* DetermineTimeZoneAbbrevOffsetInternal()
1700 * Workhorse for above two functions: work from a pg_time_t probe instant.
1701 * On success, return GMT offset and DST status into *offset and *isdst.
1704 DetermineTimeZoneAbbrevOffsetInternal(pg_time_t t, const char *abbr, pg_tz *tzp,
1705 int *offset, int *isdst)
1707 char upabbr[TZ_STRLEN_MAX + 1];
1711 /* We need to force the abbrev to upper case */
1712 strlcpy(upabbr, abbr, sizeof(upabbr));
1713 for (p = (unsigned char *) upabbr; *p; p++)
1714 *p = pg_toupper(*p);
1716 /* Look up the abbrev's meaning at this time in this zone */
1717 if (pg_interpret_timezone_abbrev(upabbr,
1723 /* Change sign to agree with DetermineTimeZoneOffset() */
1724 *offset = (int) -gmtoff;
1732 * Interpret parsed string as time fields only.
1733 * Returns 0 if successful, DTERR code if bogus input detected.
1735 * Note that support for time zone is here for
1736 * SQL TIME WITH TIME ZONE, but it reveals
1737 * bogosity with SQL date/time standards, since
1738 * we must infer a time zone from current time.
1739 * - thomas 2000-03-10
1740 * Allow specifying date to get a better time zone,
1741 * if time zones are allowed. - thomas 2001-12-26
1744 DecodeTimeOnly(char **field, int *ftype, int nf,
1745 int *dtype, struct pg_tm *tm, fsec_t *fsec, int *tzp)
1750 int ptype = 0; /* "prefix type" for ISO h04mm05s06 format */
1754 bool isjulian = false;
1755 bool is2digits = false;
1758 pg_tz *namedTz = NULL;
1759 pg_tz *abbrevTz = NULL;
1760 char *abbrev = NULL;
1768 /* don't know daylight savings time status apriori */
1774 for (i = 0; i < nf; i++)
1781 * Time zone not allowed? Then should not accept dates or time
1782 * zones no matter what else!
1785 return DTERR_BAD_FORMAT;
1787 /* Under limited circumstances, we will accept a date... */
1788 if (i == 0 && nf >= 2 &&
1789 (ftype[nf - 1] == DTK_DATE || ftype[1] == DTK_TIME))
1791 dterr = DecodeDate(field[i], fmask,
1792 &tmask, &is2digits, tm);
1796 /* otherwise, this is a time and/or time zone */
1799 if (isdigit((unsigned char) *field[i]))
1804 * Starts with a digit but we already have a time
1805 * field? Then we are in trouble with time already...
1807 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1808 return DTERR_BAD_FORMAT;
1811 * Should not get here and fail. Sanity check only...
1813 if ((cp = strchr(field[i], '-')) == NULL)
1814 return DTERR_BAD_FORMAT;
1816 /* Get the time zone from the end of the string */
1817 dterr = DecodeTimezone(cp, tzp);
1823 * Then read the rest of the field as a concatenated
1826 dterr = DecodeNumberField(strlen(field[i]), field[i],
1827 (fmask | DTK_DATE_M),
1838 namedTz = pg_tzset(field[i]);
1842 * We should return an error code instead of
1843 * ereport'ing directly, but then there is no way
1844 * to report the bad time zone name.
1847 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1848 errmsg("time zone \"%s\" not recognized",
1851 /* we'll apply the zone setting below */
1859 dterr = DecodeTime(field[i], (fmask | DTK_DATE_M),
1860 INTERVAL_FULL_RANGE,
1871 return DTERR_BAD_FORMAT;
1873 dterr = DecodeTimezone(field[i], &tz);
1884 * Was this an "ISO time" with embedded field labels? An
1885 * example is "h04m05s06" - thomas 2001-02-04
1892 /* Only accept a date under limited circumstances */
1900 return DTERR_BAD_FORMAT;
1906 val = strtoint(field[i], &cp, 10);
1907 if (errno == ERANGE)
1908 return DTERR_FIELD_OVERFLOW;
1911 * only a few kinds are allowed to have an embedded
1922 return DTERR_BAD_FORMAT;
1925 else if (*cp != '\0')
1926 return DTERR_BAD_FORMAT;
1932 tmask = DTK_M(YEAR);
1938 * already have a month and hour? then assume
1941 if ((fmask & DTK_M(MONTH)) != 0 &&
1942 (fmask & DTK_M(HOUR)) != 0)
1945 tmask = DTK_M(MINUTE);
1950 tmask = DTK_M(MONTH);
1961 tmask = DTK_M(HOUR);
1966 tmask = DTK_M(MINUTE);
1971 tmask = DTK_M(SECOND);
1974 dterr = ParseFractionalSecond(cp, fsec);
1977 tmask = DTK_ALL_SECS_M;
1983 dterr = DecodeTimezone(field[i], tzp);
1989 /* previous field was a label for "julian date" */
1991 return DTERR_FIELD_OVERFLOW;
1993 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2001 time = strtod(cp, &cp);
2002 if (*cp != '\0' || errno != 0)
2003 return DTERR_BAD_FORMAT;
2004 time *= USECS_PER_DAY;
2006 &tm->tm_hour, &tm->tm_min,
2008 tmask |= DTK_TIME_M;
2013 /* previous field was "t" for ISO time */
2014 dterr = DecodeNumberField(strlen(field[i]), field[i],
2015 (fmask | DTK_DATE_M),
2022 if (tmask != DTK_TIME_M)
2023 return DTERR_BAD_FORMAT;
2027 return DTERR_BAD_FORMAT;
2039 flen = strlen(field[i]);
2040 cp = strchr(field[i], '.');
2042 /* Embedded decimal? */
2046 * Under limited circumstances, we will accept a
2049 if (i == 0 && nf >= 2 && ftype[nf - 1] == DTK_DATE)
2051 dterr = DecodeDate(field[i], fmask,
2052 &tmask, &is2digits, tm);
2056 /* embedded decimal and several digits before? */
2057 else if (flen - strlen(cp) > 2)
2060 * Interpret as a concatenated date or time Set
2061 * the type field to allow decoding other fields
2062 * later. Example: 20011223 or 040506
2064 dterr = DecodeNumberField(flen, field[i],
2065 (fmask | DTK_DATE_M),
2073 return DTERR_BAD_FORMAT;
2077 dterr = DecodeNumberField(flen, field[i],
2078 (fmask | DTK_DATE_M),
2085 /* otherwise it is a single date/time field... */
2088 dterr = DecodeNumber(flen, field[i],
2090 (fmask | DTK_DATE_M),
2101 /* timezone abbrevs take precedence over built-in tokens */
2102 type = DecodeTimezoneAbbrev(i, field[i], &val, &valtz);
2103 if (type == UNKNOWN_FIELD)
2104 type = DecodeSpecial(i, field[i], &val);
2105 if (type == IGNORE_DTF)
2108 tmask = DTK_M(type);
2116 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2117 errmsg("date/time value \"current\" is no longer supported")));
2118 return DTERR_BAD_FORMAT;
2124 GetCurrentTimeUsec(tm, fsec, NULL);
2128 tmask = (DTK_TIME_M | DTK_M(TZ));
2137 return DTERR_BAD_FORMAT;
2145 * daylight savings time modifier (solves "MET DST"
2148 tmask |= DTK_M(DTZ);
2151 return DTERR_BAD_FORMAT;
2158 * set mask for TZ here _or_ check for DTZ later when
2159 * getting default timezone
2164 return DTERR_BAD_FORMAT;
2172 return DTERR_BAD_FORMAT;
2180 return DTERR_BAD_FORMAT;
2181 /* we'll determine the actual offset later */
2204 * We will need one of the following fields:
2205 * DTK_NUMBER should be hhmmss.fff
2206 * DTK_TIME should be hh:mm:ss.fff
2207 * DTK_DATE should be hhmmss-zz
2210 (ftype[i + 1] != DTK_NUMBER &&
2211 ftype[i + 1] != DTK_TIME &&
2212 ftype[i + 1] != DTK_DATE))
2213 return DTERR_BAD_FORMAT;
2221 * Before giving up and declaring error, check to see
2222 * if it is an all-alpha timezone name.
2224 namedTz = pg_tzset(field[i]);
2226 return DTERR_BAD_FORMAT;
2227 /* we'll apply the zone setting below */
2232 return DTERR_BAD_FORMAT;
2237 return DTERR_BAD_FORMAT;
2241 return DTERR_BAD_FORMAT;
2243 } /* end loop over fields */
2245 /* do final checking/adjustment of Y/M/D fields */
2246 dterr = ValidateDate(fmask, isjulian, is2digits, bc, tm);
2251 if (mer != HR24 && tm->tm_hour > HOURS_PER_DAY / 2)
2252 return DTERR_FIELD_OVERFLOW;
2253 if (mer == AM && tm->tm_hour == HOURS_PER_DAY / 2)
2255 else if (mer == PM && tm->tm_hour != HOURS_PER_DAY / 2)
2256 tm->tm_hour += HOURS_PER_DAY / 2;
2259 * This should match the checks in make_timestamp_internal
2261 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > MINS_PER_HOUR - 1 ||
2262 tm->tm_sec < 0 || tm->tm_sec > SECS_PER_MINUTE ||
2263 tm->tm_hour > HOURS_PER_DAY ||
2264 /* test for > 24:00:00 */
2265 (tm->tm_hour == HOURS_PER_DAY &&
2266 (tm->tm_min > 0 || tm->tm_sec > 0 || *fsec > 0)) ||
2267 *fsec < INT64CONST(0) || *fsec > USECS_PER_SEC)
2268 return DTERR_FIELD_OVERFLOW;
2270 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2271 return DTERR_BAD_FORMAT;
2274 * If we had a full timezone spec, compute the offset (we could not do it
2275 * before, because we may need the date to resolve DST status).
2277 if (namedTz != NULL)
2281 /* daylight savings time modifier disallowed with full TZ */
2282 if (fmask & DTK_M(DTZMOD))
2283 return DTERR_BAD_FORMAT;
2285 /* if non-DST zone, we do not need to know the date */
2286 if (pg_get_timezone_offset(namedTz, &gmtoff))
2288 *tzp = -(int) gmtoff;
2292 /* a date has to be specified */
2293 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2294 return DTERR_BAD_FORMAT;
2295 *tzp = DetermineTimeZoneOffset(tm, namedTz);
2300 * Likewise, if we had a dynamic timezone abbreviation, resolve it now.
2302 if (abbrevTz != NULL)
2308 * daylight savings time modifier but no standard timezone? then error
2310 if (fmask & DTK_M(DTZMOD))
2311 return DTERR_BAD_FORMAT;
2313 if ((fmask & DTK_DATE_M) == 0)
2314 GetCurrentDateTime(tmp);
2317 tmp->tm_year = tm->tm_year;
2318 tmp->tm_mon = tm->tm_mon;
2319 tmp->tm_mday = tm->tm_mday;
2321 tmp->tm_hour = tm->tm_hour;
2322 tmp->tm_min = tm->tm_min;
2323 tmp->tm_sec = tm->tm_sec;
2324 *tzp = DetermineTimeZoneAbbrevOffset(tmp, abbrev, abbrevTz);
2325 tm->tm_isdst = tmp->tm_isdst;
2328 /* timezone not specified? then use session timezone */
2329 if (tzp != NULL && !(fmask & DTK_M(TZ)))
2335 * daylight savings time modifier but no standard timezone? then error
2337 if (fmask & DTK_M(DTZMOD))
2338 return DTERR_BAD_FORMAT;
2340 if ((fmask & DTK_DATE_M) == 0)
2341 GetCurrentDateTime(tmp);
2344 tmp->tm_year = tm->tm_year;
2345 tmp->tm_mon = tm->tm_mon;
2346 tmp->tm_mday = tm->tm_mday;
2348 tmp->tm_hour = tm->tm_hour;
2349 tmp->tm_min = tm->tm_min;
2350 tmp->tm_sec = tm->tm_sec;
2351 *tzp = DetermineTimeZoneOffset(tmp, session_timezone);
2352 tm->tm_isdst = tmp->tm_isdst;
2359 * Decode date string which includes delimiters.
2360 * Return 0 if okay, a DTERR code if not.
2362 * str: field to be parsed
2363 * fmask: bitmask for field types already seen
2364 * *tmask: receives bitmask for fields found here
2365 * *is2digits: set to true if we find 2-digit year
2366 * *tm: field values are stored into appropriate members of this struct
2369 DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
2377 bool haveTextMonth = false;
2381 char *field[MAXDATEFIELDS];
2385 /* parse this string... */
2386 while (*str != '\0' && nf < MAXDATEFIELDS)
2388 /* skip field separators */
2389 while (*str != '\0' && !isalnum((unsigned char) *str))
2393 return DTERR_BAD_FORMAT; /* end of string after separator */
2396 if (isdigit((unsigned char) *str))
2398 while (isdigit((unsigned char) *str))
2401 else if (isalpha((unsigned char) *str))
2403 while (isalpha((unsigned char) *str))
2407 /* Just get rid of any non-digit, non-alpha characters... */
2413 /* look first for text fields, since that will be unambiguous month */
2414 for (i = 0; i < nf; i++)
2416 if (isalpha((unsigned char) *field[i]))
2418 type = DecodeSpecial(i, field[i], &val);
2419 if (type == IGNORE_DTF)
2422 dmask = DTK_M(type);
2427 haveTextMonth = true;
2431 return DTERR_BAD_FORMAT;
2434 return DTERR_BAD_FORMAT;
2439 /* mark this field as being completed */
2444 /* now pick up remaining numeric fields */
2445 for (i = 0; i < nf; i++)
2447 if (field[i] == NULL)
2450 if ((len = strlen(field[i])) <= 0)
2451 return DTERR_BAD_FORMAT;
2453 dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2460 return DTERR_BAD_FORMAT;
2466 if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
2467 return DTERR_BAD_FORMAT;
2469 /* validation of the field values must wait until ValidateDate() */
2475 * Check valid year/month/day values, handle BC and DOY cases
2476 * Return 0 if okay, a DTERR code if not.
2479 ValidateDate(int fmask, bool isjulian, bool is2digits, bool bc,
2482 if (fmask & DTK_M(YEAR))
2486 /* tm_year is correct and should not be touched */
2490 /* there is no year zero in AD/BC notation */
2491 if (tm->tm_year <= 0)
2492 return DTERR_FIELD_OVERFLOW;
2493 /* internally, we represent 1 BC as year zero, 2 BC as -1, etc */
2494 tm->tm_year = -(tm->tm_year - 1);
2498 /* process 1 or 2-digit input as 1970-2069 AD, allow '0' and '00' */
2499 if (tm->tm_year < 0) /* just paranoia */
2500 return DTERR_FIELD_OVERFLOW;
2501 if (tm->tm_year < 70)
2502 tm->tm_year += 2000;
2503 else if (tm->tm_year < 100)
2504 tm->tm_year += 1900;
2508 /* there is no year zero in AD/BC notation */
2509 if (tm->tm_year <= 0)
2510 return DTERR_FIELD_OVERFLOW;
2514 /* now that we have correct year, decode DOY */
2515 if (fmask & DTK_M(DOY))
2517 j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
2518 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2521 /* check for valid month */
2522 if (fmask & DTK_M(MONTH))
2524 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
2525 return DTERR_MD_FIELD_OVERFLOW;
2528 /* minimal check for valid day */
2529 if (fmask & DTK_M(DAY))
2531 if (tm->tm_mday < 1 || tm->tm_mday > 31)
2532 return DTERR_MD_FIELD_OVERFLOW;
2535 if ((fmask & DTK_DATE_M) == DTK_DATE_M)
2538 * Check for valid day of month, now that we know for sure the month
2539 * and year. Note we don't use MD_FIELD_OVERFLOW here, since it seems
2540 * unlikely that "Feb 29" is a YMD-order error.
2542 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2543 return DTERR_FIELD_OVERFLOW;
2551 * Decode time string which includes delimiters.
2552 * Return 0 if okay, a DTERR code if not.
2554 * Only check the lower limit on hours, since this same code can be
2555 * used to represent time spans.
2558 DecodeTime(char *str, int fmask, int range,
2559 int *tmask, struct pg_tm *tm, fsec_t *fsec)
2564 *tmask = DTK_TIME_M;
2567 tm->tm_hour = strtoint(str, &cp, 10);
2568 if (errno == ERANGE)
2569 return DTERR_FIELD_OVERFLOW;
2571 return DTERR_BAD_FORMAT;
2573 tm->tm_min = strtoint(cp + 1, &cp, 10);
2574 if (errno == ERANGE)
2575 return DTERR_FIELD_OVERFLOW;
2580 /* If it's a MINUTE TO SECOND interval, take 2 fields as being mm:ss */
2581 if (range == (INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND)))
2583 tm->tm_sec = tm->tm_min;
2584 tm->tm_min = tm->tm_hour;
2588 else if (*cp == '.')
2590 /* always assume mm:ss.sss is MINUTE TO SECOND */
2591 dterr = ParseFractionalSecond(cp, fsec);
2594 tm->tm_sec = tm->tm_min;
2595 tm->tm_min = tm->tm_hour;
2598 else if (*cp == ':')
2601 tm->tm_sec = strtoint(cp + 1, &cp, 10);
2602 if (errno == ERANGE)
2603 return DTERR_FIELD_OVERFLOW;
2606 else if (*cp == '.')
2608 dterr = ParseFractionalSecond(cp, fsec);
2613 return DTERR_BAD_FORMAT;
2616 return DTERR_BAD_FORMAT;
2618 /* do a sanity check */
2619 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > MINS_PER_HOUR - 1 ||
2620 tm->tm_sec < 0 || tm->tm_sec > SECS_PER_MINUTE ||
2621 *fsec < INT64CONST(0) ||
2622 *fsec > USECS_PER_SEC)
2623 return DTERR_FIELD_OVERFLOW;
2630 * Interpret plain numeric field as a date value in context.
2631 * Return 0 if okay, a DTERR code if not.
2634 DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask,
2635 int *tmask, struct pg_tm *tm, fsec_t *fsec, bool *is2digits)
2644 val = strtoint(str, &cp, 10);
2645 if (errno == ERANGE)
2646 return DTERR_FIELD_OVERFLOW;
2648 return DTERR_BAD_FORMAT;
2653 * More than two digits before decimal point? Then could be a date or
2654 * a run-together time: 2001.360 20011225 040506.789
2658 dterr = DecodeNumberField(flen, str,
2659 (fmask | DTK_DATE_M),
2667 dterr = ParseFractionalSecond(cp, fsec);
2671 else if (*cp != '\0')
2672 return DTERR_BAD_FORMAT;
2674 /* Special case for day of year */
2675 if (flen == 3 && (fmask & DTK_DATE_M) == DTK_M(YEAR) && val >= 1 &&
2678 *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2680 /* tm_mon and tm_mday can't actually be set yet ... */
2684 /* Switch based on what we have so far */
2685 switch (fmask & DTK_DATE_M)
2690 * Nothing so far; make a decision about what we think the input
2691 * is. There used to be lots of heuristics here, but the
2692 * consensus now is to be paranoid. It *must* be either
2693 * YYYY-MM-DD (with a more-than-two-digit year field), or the
2694 * field order defined by DateOrder.
2696 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2698 *tmask = DTK_M(YEAR);
2701 else if (DateOrder == DATEORDER_DMY)
2703 *tmask = DTK_M(DAY);
2708 *tmask = DTK_M(MONTH);
2714 /* Must be at second field of YY-MM-DD */
2715 *tmask = DTK_M(MONTH);
2719 case (DTK_M(MONTH)):
2723 * We are at the first numeric field of a date that included a
2724 * textual month name. We want to support the variants
2725 * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2726 * inputs. We will also accept MON-DD-YY or DD-MON-YY in
2727 * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2729 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2731 *tmask = DTK_M(YEAR);
2736 *tmask = DTK_M(DAY);
2742 /* Must be at second field of MM-DD-YY */
2743 *tmask = DTK_M(DAY);
2748 case (DTK_M(YEAR) | DTK_M(MONTH)):
2751 /* Need to accept DD-MON-YYYY even in YMD mode */
2752 if (flen >= 3 && *is2digits)
2754 /* Guess that first numeric field is day was wrong */
2755 *tmask = DTK_M(DAY); /* YEAR is already set */
2756 tm->tm_mday = tm->tm_year;
2762 *tmask = DTK_M(DAY);
2768 /* Must be at third field of YY-MM-DD */
2769 *tmask = DTK_M(DAY);
2775 /* Must be at second field of DD-MM-YY */
2776 *tmask = DTK_M(MONTH);
2780 case (DTK_M(MONTH) | DTK_M(DAY)):
2781 /* Must be at third field of DD-MM-YY or MM-DD-YY */
2782 *tmask = DTK_M(YEAR);
2786 case (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY)):
2787 /* we have all the date, so it must be a time field */
2788 dterr = DecodeNumberField(flen, str, fmask,
2796 /* Anything else is bogus input */
2797 return DTERR_BAD_FORMAT;
2801 * When processing a year field, mark it for adjustment if it's only one
2804 if (*tmask == DTK_M(YEAR))
2805 *is2digits = (flen <= 2);
2811 /* DecodeNumberField()
2812 * Interpret numeric string as a concatenated date or time field.
2813 * Return a DTK token (>= 0) if successful, a DTERR code (< 0) if not.
2815 * Use the context of previously decoded fields to help with
2816 * the interpretation.
2819 DecodeNumberField(int len, char *str, int fmask,
2820 int *tmask, struct pg_tm *tm, fsec_t *fsec, bool *is2digits)
2825 * Have a decimal point? Then this is a date or something with a seconds
2828 if ((cp = strchr(str, '.')) != NULL)
2831 * Can we use ParseFractionalSecond here? Not clear whether trailing
2832 * junk should be rejected ...
2837 frac = strtod(cp, NULL);
2839 return DTERR_BAD_FORMAT;
2840 *fsec = rint(frac * 1000000);
2841 /* Now truncate off the fraction for further processing */
2845 /* No decimal point and no complete date yet? */
2846 else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2850 *tmask = DTK_DATE_M;
2853 * Start from end and consider first 2 as Day, next 2 as Month,
2854 * and the rest as Year.
2856 tm->tm_mday = atoi(str + (len - 2));
2857 *(str + (len - 2)) = '\0';
2858 tm->tm_mon = atoi(str + (len - 4));
2859 *(str + (len - 4)) = '\0';
2860 tm->tm_year = atoi(str);
2868 /* not all time fields are specified? */
2869 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2874 *tmask = DTK_TIME_M;
2875 tm->tm_sec = atoi(str + 4);
2877 tm->tm_min = atoi(str + 2);
2879 tm->tm_hour = atoi(str);
2886 *tmask = DTK_TIME_M;
2888 tm->tm_min = atoi(str + 2);
2890 tm->tm_hour = atoi(str);
2896 return DTERR_BAD_FORMAT;
2901 * Interpret string as a numeric timezone.
2903 * Return 0 if okay (and set *tzp), a DTERR code if not okay.
2906 DecodeTimezone(char *str, int *tzp)
2914 /* leading character must be "+" or "-" */
2915 if (*str != '+' && *str != '-')
2916 return DTERR_BAD_FORMAT;
2919 hr = strtoint(str + 1, &cp, 10);
2920 if (errno == ERANGE)
2921 return DTERR_TZDISP_OVERFLOW;
2923 /* explicit delimiter? */
2927 min = strtoint(cp + 1, &cp, 10);
2928 if (errno == ERANGE)
2929 return DTERR_TZDISP_OVERFLOW;
2933 sec = strtoint(cp + 1, &cp, 10);
2934 if (errno == ERANGE)
2935 return DTERR_TZDISP_OVERFLOW;
2938 /* otherwise, might have run things together... */
2939 else if (*cp == '\0' && strlen(str) > 3)
2943 /* we could, but don't, support a run-together hhmmss format */
2948 /* Range-check the values; see notes in datatype/timestamp.h */
2949 if (hr < 0 || hr > MAX_TZDISP_HOUR)
2950 return DTERR_TZDISP_OVERFLOW;
2951 if (min < 0 || min >= MINS_PER_HOUR)
2952 return DTERR_TZDISP_OVERFLOW;
2953 if (sec < 0 || sec >= SECS_PER_MINUTE)
2954 return DTERR_TZDISP_OVERFLOW;
2956 tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
2963 return DTERR_BAD_FORMAT;
2969 /* DecodeTimezoneAbbrev()
2970 * Interpret string as a timezone abbreviation, if possible.
2972 * Returns an abbreviation type (TZ, DTZ, or DYNTZ), or UNKNOWN_FIELD if
2973 * string is not any known abbreviation. On success, set *offset and *tz to
2974 * represent the UTC offset (for TZ or DTZ) or underlying zone (for DYNTZ).
2975 * Note that full timezone names (such as America/New_York) are not handled
2976 * here, mostly for historical reasons.
2978 * Given string must be lowercased already.
2980 * Implement a cache lookup since it is likely that dates
2981 * will be related in format.
2984 DecodeTimezoneAbbrev(int field, char *lowtoken,
2985 int *offset, pg_tz **tz)
2990 tp = abbrevcache[field];
2991 /* use strncmp so that we match truncated tokens */
2992 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
2995 tp = datebsearch(lowtoken, zoneabbrevtbl->abbrevs,
2996 zoneabbrevtbl->numabbrevs);
3002 type = UNKNOWN_FIELD;
3008 abbrevcache[field] = tp;
3013 *tz = FetchDynamicTimeZone(zoneabbrevtbl, tp);
3017 *offset = tp->value;
3027 * Decode text string using lookup table.
3029 * Recognizes the keywords listed in datetktbl.
3030 * Note: at one time this would also recognize timezone abbreviations,
3031 * but no more; use DecodeTimezoneAbbrev for that.
3033 * Given string must be lowercased already.
3035 * Implement a cache lookup since it is likely that dates
3036 * will be related in format.
3039 DecodeSpecial(int field, char *lowtoken, int *val)
3044 tp = datecache[field];
3045 /* use strncmp so that we match truncated tokens */
3046 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3048 tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
3052 type = UNKNOWN_FIELD;
3057 datecache[field] = tp;
3068 * Zero out a pg_tm and associated fsec_t
3071 ClearPgTm(struct pg_tm *tm, fsec_t *fsec)
3084 * Interpret previously parsed fields for general time interval.
3085 * Returns 0 if successful, DTERR code if bogus input detected.
3086 * dtype, tm, fsec are output parameters.
3088 * Allow "date" field DTK_DATE since this could be just
3089 * an unsigned floating point number. - thomas 1997-11-16
3091 * Allow ISO-style time span, with implicit units on number of days
3092 * preceding an hh:mm:ss field. - thomas 1998-04-30
3095 DecodeInterval(char **field, int *ftype, int nf, int range,
3096 int *dtype, struct pg_tm *tm, fsec_t *fsec)
3098 bool is_before = false;
3110 ClearPgTm(tm, fsec);
3112 /* read through list backwards to pick up units before values */
3113 for (i = nf - 1; i >= 0; i--)
3118 dterr = DecodeTime(field[i], fmask, range,
3128 * Timezone means a token with a leading sign character and at
3129 * least one digit; there could be ':', '.', '-' embedded in
3132 Assert(*field[i] == '-' || *field[i] == '+');
3135 * Check for signed hh:mm or hh:mm:ss. If so, process exactly
3136 * like DTK_TIME case above, plus handling the sign.
3138 if (strchr(field[i] + 1, ':') != NULL &&
3139 DecodeTime(field[i] + 1, fmask, range,
3140 &tmask, tm, fsec) == 0)
3142 if (*field[i] == '-')
3144 /* flip the sign on all fields */
3145 tm->tm_hour = -tm->tm_hour;
3146 tm->tm_min = -tm->tm_min;
3147 tm->tm_sec = -tm->tm_sec;
3152 * Set the next type to be a day, if units are not
3153 * specified. This handles the case of '1 +02:03' since we
3154 * are reading right to left.
3161 * Otherwise, fall through to DTK_NUMBER case, which can
3162 * handle signed float numbers and signed year-month values.
3169 if (type == IGNORE_DTF)
3171 /* use typmod to decide what rightmost field is */
3174 case INTERVAL_MASK(YEAR):
3177 case INTERVAL_MASK(MONTH):
3178 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
3181 case INTERVAL_MASK(DAY):
3184 case INTERVAL_MASK(HOUR):
3185 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
3188 case INTERVAL_MASK(MINUTE):
3189 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
3190 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
3193 case INTERVAL_MASK(SECOND):
3194 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
3195 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
3196 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
3206 val = strtoint(field[i], &cp, 10);
3207 if (errno == ERANGE)
3208 return DTERR_FIELD_OVERFLOW;
3212 /* SQL "years-months" syntax */
3215 val2 = strtoint(cp + 1, &cp, 10);
3216 if (errno == ERANGE || val2 < 0 || val2 >= MONTHS_PER_YEAR)
3217 return DTERR_FIELD_OVERFLOW;
3219 return DTERR_BAD_FORMAT;
3221 if (*field[i] == '-')
3223 if (((double) val * MONTHS_PER_YEAR + val2) > INT_MAX ||
3224 ((double) val * MONTHS_PER_YEAR + val2) < INT_MIN)
3225 return DTERR_FIELD_OVERFLOW;
3226 val = val * MONTHS_PER_YEAR + val2;
3229 else if (*cp == '.')
3232 fval = strtod(cp, &cp);
3233 if (*cp != '\0' || errno != 0)
3234 return DTERR_BAD_FORMAT;
3236 if (*field[i] == '-')
3239 else if (*cp == '\0')
3242 return DTERR_BAD_FORMAT;
3244 tmask = 0; /* DTK_M(type); */
3249 *fsec += rint(val + fval);
3250 tmask = DTK_M(MICROSECOND);
3254 /* avoid overflowing the fsec field */
3255 tm->tm_sec += val / 1000;
3256 val -= (val / 1000) * 1000;
3257 *fsec += rint((val + fval) * 1000);
3258 tmask = DTK_M(MILLISECOND);
3263 *fsec += rint(fval * 1000000);
3266 * If any subseconds were specified, consider this
3267 * microsecond and millisecond input as well.
3270 tmask = DTK_M(SECOND);
3272 tmask = DTK_ALL_SECS_M;
3277 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3278 tmask = DTK_M(MINUTE);
3283 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3284 tmask = DTK_M(HOUR);
3285 type = DTK_DAY; /* set for next field */
3290 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3295 tm->tm_mday += val * 7;
3296 AdjustFractDays(fval, tm, fsec, 7);
3297 tmask = DTK_M(WEEK);
3302 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3303 tmask = DTK_M(MONTH);
3309 tm->tm_mon += fval * MONTHS_PER_YEAR;
3310 tmask = DTK_M(YEAR);
3314 tm->tm_year += val * 10;
3316 tm->tm_mon += fval * MONTHS_PER_YEAR * 10;
3317 tmask = DTK_M(DECADE);
3321 tm->tm_year += val * 100;
3323 tm->tm_mon += fval * MONTHS_PER_YEAR * 100;
3324 tmask = DTK_M(CENTURY);
3327 case DTK_MILLENNIUM:
3328 tm->tm_year += val * 1000;
3330 tm->tm_mon += fval * MONTHS_PER_YEAR * 1000;
3331 tmask = DTK_M(MILLENNIUM);
3335 return DTERR_BAD_FORMAT;
3341 type = DecodeUnits(i, field[i], &val);
3342 if (type == IGNORE_DTF)
3345 tmask = 0; /* DTK_M(type); */
3358 tmask = (DTK_DATE_M | DTK_TIME_M);
3363 return DTERR_BAD_FORMAT;
3368 return DTERR_BAD_FORMAT;
3372 return DTERR_BAD_FORMAT;
3376 /* ensure that at least one time field has been found */
3378 return DTERR_BAD_FORMAT;
3380 /* ensure fractional seconds are fractional */
3385 sec = *fsec / USECS_PER_SEC;
3386 *fsec -= sec * USECS_PER_SEC;
3391 * The SQL standard defines the interval literal
3393 * to mean "negative 1 days and negative 1 hours", while Postgres
3394 * traditionally treats this as meaning "negative 1 days and positive
3395 * 1 hours". In SQL_STANDARD intervalstyle, we apply the leading sign
3396 * to all fields if there are no other explicit signs.
3398 * We leave the signs alone if there are additional explicit signs.
3399 * This protects us against misinterpreting postgres-style dump output,
3400 * since the postgres-style output code has always put an explicit sign on
3401 * all fields following a negative field. But note that SQL-spec output
3402 * is ambiguous and can be misinterpreted on load! (So it's best practice
3403 * to dump in postgres style, not SQL style.)
3406 if (IntervalStyle == INTSTYLE_SQL_STANDARD && *field[0] == '-')
3408 /* Check for additional explicit signs */
3409 bool more_signs = false;
3411 for (i = 1; i < nf; i++)
3413 if (*field[i] == '-' || *field[i] == '+')
3423 * Rather than re-determining which field was field[0], just force
3429 tm->tm_sec = -tm->tm_sec;
3431 tm->tm_min = -tm->tm_min;
3432 if (tm->tm_hour > 0)
3433 tm->tm_hour = -tm->tm_hour;
3434 if (tm->tm_mday > 0)
3435 tm->tm_mday = -tm->tm_mday;
3437 tm->tm_mon = -tm->tm_mon;
3438 if (tm->tm_year > 0)
3439 tm->tm_year = -tm->tm_year;
3443 /* finally, AGO negates everything */
3447 tm->tm_sec = -tm->tm_sec;
3448 tm->tm_min = -tm->tm_min;
3449 tm->tm_hour = -tm->tm_hour;
3450 tm->tm_mday = -tm->tm_mday;
3451 tm->tm_mon = -tm->tm_mon;
3452 tm->tm_year = -tm->tm_year;
3460 * Helper functions to avoid duplicated code in DecodeISO8601Interval.
3462 * Parse a decimal value and break it into integer and fractional parts.
3463 * Returns 0 or DTERR code.
3466 ParseISO8601Number(char *str, char **endptr, int *ipart, double *fpart)
3470 if (!(isdigit((unsigned char) *str) || *str == '-' || *str == '.'))
3471 return DTERR_BAD_FORMAT;
3473 val = strtod(str, endptr);
3474 /* did we not see anything that looks like a double? */
3475 if (*endptr == str || errno != 0)
3476 return DTERR_BAD_FORMAT;
3477 /* watch out for overflow */
3478 if (val < INT_MIN || val > INT_MAX)
3479 return DTERR_FIELD_OVERFLOW;
3480 /* be very sure we truncate towards zero (cf dtrunc()) */
3482 *ipart = (int) floor(val);
3484 *ipart = (int) -floor(-val);
3485 *fpart = val - *ipart;
3490 * Determine number of integral digits in a valid ISO 8601 number field
3491 * (we should ignore sign and any fraction part)
3494 ISO8601IntegerWidth(char *fieldstart)
3496 /* We might have had a leading '-' */
3497 if (*fieldstart == '-')
3499 return strspn(fieldstart, "0123456789");
3503 /* DecodeISO8601Interval()
3504 * Decode an ISO 8601 time interval of the "format with designators"
3505 * (section 4.4.3.2) or "alternative format" (section 4.4.3.3)
3506 * Examples: P1D for 1 day
3508 * P2Y6M7DT1H30M for 2 years, 6 months, 7 days 1 hour 30 min
3509 * P0002-06-07T01:30:00 the same value in alternative format
3511 * Returns 0 if successful, DTERR code if bogus input detected.
3512 * Note: error code should be DTERR_BAD_FORMAT if input doesn't look like
3513 * ISO8601, otherwise this could cause unexpected error messages.
3514 * dtype, tm, fsec are output parameters.
3516 * A couple exceptions from the spec:
3517 * - a week field ('W') may coexist with other units
3518 * - allows decimals in fields other than the least significant unit.
3521 DecodeISO8601Interval(char *str,
3522 int *dtype, struct pg_tm *tm, fsec_t *fsec)
3524 bool datepart = true;
3525 bool havefield = false;
3528 ClearPgTm(tm, fsec);
3530 if (strlen(str) < 2 || str[0] != 'P')
3531 return DTERR_BAD_FORMAT;
3542 if (*str == 'T') /* T indicates the beginning of the time part */
3551 dterr = ParseISO8601Number(str, &str, &val, &fval);
3556 * Note: we could step off the end of the string here. Code below
3557 * *must* exit the loop if unit == '\0'.
3563 switch (unit) /* before T: Y M W D */
3567 tm->tm_mon += (fval * MONTHS_PER_YEAR);
3571 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3574 tm->tm_mday += val * 7;
3575 AdjustFractDays(fval, tm, fsec, 7);
3579 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3581 case 'T': /* ISO 8601 4.4.3.3 Alternative Format / Basic */
3583 if (ISO8601IntegerWidth(fieldstart) == 8 && !havefield)
3585 tm->tm_year += val / 10000;
3586 tm->tm_mon += (val / 100) % 100;
3587 tm->tm_mday += val % 100;
3588 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3595 /* Else fall through to extended alternative format */
3596 case '-': /* ISO 8601 4.4.3.3 Alternative Format,
3599 return DTERR_BAD_FORMAT;
3602 tm->tm_mon += (fval * MONTHS_PER_YEAR);
3612 dterr = ParseISO8601Number(str, &str, &val, &fval);
3616 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3626 return DTERR_BAD_FORMAT;
3629 dterr = ParseISO8601Number(str, &str, &val, &fval);
3633 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3642 return DTERR_BAD_FORMAT;
3644 /* not a valid date unit suffix */
3645 return DTERR_BAD_FORMAT;
3650 switch (unit) /* after T: H M S */
3654 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3658 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3662 AdjustFractSeconds(fval, tm, fsec, 1);
3664 case '\0': /* ISO 8601 4.4.3.3 Alternative Format */
3665 if (ISO8601IntegerWidth(fieldstart) == 6 && !havefield)
3667 tm->tm_hour += val / 10000;
3668 tm->tm_min += (val / 100) % 100;
3669 tm->tm_sec += val % 100;
3670 AdjustFractSeconds(fval, tm, fsec, 1);
3673 /* Else fall through to extended alternative format */
3674 case ':': /* ISO 8601 4.4.3.3 Alternative Format,
3677 return DTERR_BAD_FORMAT;
3680 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3684 dterr = ParseISO8601Number(str, &str, &val, &fval);
3688 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3692 return DTERR_BAD_FORMAT;
3695 dterr = ParseISO8601Number(str, &str, &val, &fval);
3699 AdjustFractSeconds(fval, tm, fsec, 1);
3702 return DTERR_BAD_FORMAT;
3705 /* not a valid time unit suffix */
3706 return DTERR_BAD_FORMAT;
3718 * Decode text string using lookup table.
3720 * This routine recognizes keywords associated with time interval units.
3722 * Given string must be lowercased already.
3724 * Implement a cache lookup since it is likely that dates
3725 * will be related in format.
3728 DecodeUnits(int field, char *lowtoken, int *val)
3733 tp = deltacache[field];
3734 /* use strncmp so that we match truncated tokens */
3735 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3737 tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
3741 type = UNKNOWN_FIELD;
3746 deltacache[field] = tp;
3752 } /* DecodeUnits() */
3755 * Report an error detected by one of the datetime input processing routines.
3757 * dterr is the error code, str is the original input string, datatype is
3758 * the name of the datatype we were trying to accept.
3760 * Note: it might seem useless to distinguish DTERR_INTERVAL_OVERFLOW and
3761 * DTERR_TZDISP_OVERFLOW from DTERR_FIELD_OVERFLOW, but SQL99 mandates three
3762 * separate SQLSTATE codes, so ...
3765 DateTimeParseError(int dterr, const char *str, const char *datatype)
3769 case DTERR_FIELD_OVERFLOW:
3771 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3772 errmsg("date/time field value out of range: \"%s\"",
3775 case DTERR_MD_FIELD_OVERFLOW:
3776 /* <nanny>same as above, but add hint about DateStyle</nanny> */
3778 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3779 errmsg("date/time field value out of range: \"%s\"",
3781 errhint("Perhaps you need a different \"datestyle\" setting.")));
3783 case DTERR_INTERVAL_OVERFLOW:
3785 (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
3786 errmsg("interval field value out of range: \"%s\"",
3789 case DTERR_TZDISP_OVERFLOW:
3791 (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
3792 errmsg("time zone displacement out of range: \"%s\"",
3795 case DTERR_BAD_FORMAT:
3798 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
3799 errmsg("invalid input syntax for type %s: \"%s\"",
3806 * Binary search -- from Knuth (6.2.1) Algorithm B. Special case like this
3807 * is WAY faster than the generic bsearch().
3809 static const datetkn *
3810 datebsearch(const char *key, const datetkn *base, int nel)
3814 const datetkn *last = base + nel - 1,
3818 while (last >= base)
3820 position = base + ((last - base) >> 1);
3821 /* precheck the first character for a bit of extra speed */
3822 result = (int) key[0] - (int) position->token[0];
3825 /* use strncmp so that we match truncated tokens */
3826 result = strncmp(key, position->token, TOKMAXLEN);
3831 last = position - 1;
3833 base = position + 1;
3840 * Copies representation of a numeric timezone offset to str.
3842 * Returns a pointer to the new end of string. No NUL terminator is put
3843 * there; callers are responsible for NUL terminating str themselves.
3846 EncodeTimezone(char *str, int tz, int style)
3853 min = sec / SECS_PER_MINUTE;
3854 sec -= min * SECS_PER_MINUTE;
3855 hour = min / MINS_PER_HOUR;
3856 min -= hour * MINS_PER_HOUR;
3858 /* TZ is negated compared to sign we wish to display ... */
3859 *str++ = (tz <= 0 ? '+' : '-');
3863 str = pg_ltostr_zeropad(str, hour, 2);
3865 str = pg_ltostr_zeropad(str, min, 2);
3867 str = pg_ltostr_zeropad(str, sec, 2);
3869 else if (min != 0 || style == USE_XSD_DATES)
3871 str = pg_ltostr_zeropad(str, hour, 2);
3873 str = pg_ltostr_zeropad(str, min, 2);
3876 str = pg_ltostr_zeropad(str, hour, 2);
3881 * Encode date as local time.
3884 EncodeDateOnly(struct pg_tm *tm, int style, char *str)
3886 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3892 /* compatible with ISO date formats */
3893 str = pg_ltostr_zeropad(str,
3894 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
3896 str = pg_ltostr_zeropad(str, tm->tm_mon, 2);
3898 str = pg_ltostr_zeropad(str, tm->tm_mday, 2);
3902 /* compatible with Oracle/Ingres date formats */
3903 if (DateOrder == DATEORDER_DMY)
3905 str = pg_ltostr_zeropad(str, tm->tm_mday, 2);
3907 str = pg_ltostr_zeropad(str, tm->tm_mon, 2);
3911 str = pg_ltostr_zeropad(str, tm->tm_mon, 2);
3913 str = pg_ltostr_zeropad(str, tm->tm_mday, 2);
3916 str = pg_ltostr_zeropad(str,
3917 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
3920 case USE_GERMAN_DATES:
3921 /* German-style date format */
3922 str = pg_ltostr_zeropad(str, tm->tm_mday, 2);
3924 str = pg_ltostr_zeropad(str, tm->tm_mon, 2);
3926 str = pg_ltostr_zeropad(str,
3927 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
3930 case USE_POSTGRES_DATES:
3932 /* traditional date-only style for Postgres */
3933 if (DateOrder == DATEORDER_DMY)
3935 str = pg_ltostr_zeropad(str, tm->tm_mday, 2);
3937 str = pg_ltostr_zeropad(str, tm->tm_mon, 2);
3941 str = pg_ltostr_zeropad(str, tm->tm_mon, 2);
3943 str = pg_ltostr_zeropad(str, tm->tm_mday, 2);
3946 str = pg_ltostr_zeropad(str,
3947 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
3951 if (tm->tm_year <= 0)
3953 memcpy(str, " BC", 3); /* Don't copy NUL */
3961 * Encode time fields only.
3963 * tm and fsec are the value to encode, print_tz determines whether to include
3964 * a time zone (the difference between time and timetz types), tz is the
3965 * numeric time zone offset, style is the date style, str is where to write the
3969 EncodeTimeOnly(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, int style, char *str)
3971 str = pg_ltostr_zeropad(str, tm->tm_hour, 2);
3973 str = pg_ltostr_zeropad(str, tm->tm_min, 2);
3975 str = AppendSeconds(str, tm->tm_sec, fsec, MAX_TIME_PRECISION, true);
3977 str = EncodeTimezone(str, tz, style);
3983 * Encode date and time interpreted as local time.
3985 * tm and fsec are the value to encode, print_tz determines whether to include
3986 * a time zone (the difference between timestamp and timestamptz types), tz is
3987 * the numeric time zone offset, tzn is the textual time zone, which if
3988 * specified will be used instead of tz by some styles, style is the date
3989 * style, str is where to write the output.
3991 * Supported date styles:
3992 * Postgres - day mon hh:mm:ss yyyy tz
3993 * SQL - mm/dd/yyyy hh:mm:ss.ss tz
3994 * ISO - yyyy-mm-dd hh:mm:ss+/-tz
3995 * German - dd.mm.yyyy hh:mm:ss tz
3996 * XSD - yyyy-mm-ddThh:mm:ss.ss+/-tz
3999 EncodeDateTime(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str)
4003 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
4006 * Negative tm_isdst means we have no valid time zone translation.
4008 if (tm->tm_isdst < 0)
4015 /* Compatible with ISO-8601 date formats */
4016 str = pg_ltostr_zeropad(str,
4017 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4019 str = pg_ltostr_zeropad(str, tm->tm_mon, 2);
4021 str = pg_ltostr_zeropad(str, tm->tm_mday, 2);
4022 *str++ = (style == USE_ISO_DATES) ? ' ' : 'T';
4023 str = pg_ltostr_zeropad(str, tm->tm_hour, 2);
4025 str = pg_ltostr_zeropad(str, tm->tm_min, 2);
4027 str = AppendTimestampSeconds(str, tm, fsec);
4029 str = EncodeTimezone(str, tz, style);
4033 /* Compatible with Oracle/Ingres date formats */
4034 if (DateOrder == DATEORDER_DMY)
4036 str = pg_ltostr_zeropad(str, tm->tm_mday, 2);
4038 str = pg_ltostr_zeropad(str, tm->tm_mon, 2);
4042 str = pg_ltostr_zeropad(str, tm->tm_mon, 2);
4044 str = pg_ltostr_zeropad(str, tm->tm_mday, 2);
4047 str = pg_ltostr_zeropad(str,
4048 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4050 str = pg_ltostr_zeropad(str, tm->tm_hour, 2);
4052 str = pg_ltostr_zeropad(str, tm->tm_min, 2);
4054 str = AppendTimestampSeconds(str, tm, fsec);
4057 * Note: the uses of %.*s in this function would be risky if the
4058 * timezone names ever contain non-ASCII characters. However, all
4059 * TZ abbreviations in the IANA database are plain ASCII.
4065 sprintf(str, " %.*s", MAXTZLEN, tzn);
4069 str = EncodeTimezone(str, tz, style);
4073 case USE_GERMAN_DATES:
4074 /* German variant on European style */
4075 str = pg_ltostr_zeropad(str, tm->tm_mday, 2);
4077 str = pg_ltostr_zeropad(str, tm->tm_mon, 2);
4079 str = pg_ltostr_zeropad(str,
4080 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4082 str = pg_ltostr_zeropad(str, tm->tm_hour, 2);
4084 str = pg_ltostr_zeropad(str, tm->tm_min, 2);
4086 str = AppendTimestampSeconds(str, tm, fsec);
4092 sprintf(str, " %.*s", MAXTZLEN, tzn);
4096 str = EncodeTimezone(str, tz, style);
4100 case USE_POSTGRES_DATES:
4102 /* Backward-compatible with traditional Postgres abstime dates */
4103 day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
4104 tm->tm_wday = j2day(day);
4105 memcpy(str, days[tm->tm_wday], 3);
4108 if (DateOrder == DATEORDER_DMY)
4110 str = pg_ltostr_zeropad(str, tm->tm_mday, 2);
4112 memcpy(str, months[tm->tm_mon - 1], 3);
4117 memcpy(str, months[tm->tm_mon - 1], 3);
4120 str = pg_ltostr_zeropad(str, tm->tm_mday, 2);
4123 str = pg_ltostr_zeropad(str, tm->tm_hour, 2);
4125 str = pg_ltostr_zeropad(str, tm->tm_min, 2);
4127 str = AppendTimestampSeconds(str, tm, fsec);
4129 str = pg_ltostr_zeropad(str,
4130 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4136 sprintf(str, " %.*s", MAXTZLEN, tzn);
4142 * We have a time zone, but no string version. Use the
4143 * numeric form, but be sure to include a leading space to
4144 * avoid formatting something which would be rejected by
4145 * the date/time parser later. - thomas 2001-10-19
4148 str = EncodeTimezone(str, tz, style);
4154 if (tm->tm_year <= 0)
4156 memcpy(str, " BC", 3); /* Don't copy NUL */
4164 * Helper functions to avoid duplicated code in EncodeInterval.
4167 /* Append an ISO-8601-style interval field, but only if value isn't zero */
4169 AddISO8601IntPart(char *cp, int value, char units)
4173 sprintf(cp, "%d%c", value, units);
4174 return cp + strlen(cp);
4177 /* Append a postgres-style interval field, but only if value isn't zero */
4179 AddPostgresIntPart(char *cp, int value, const char *units,
4180 bool *is_zero, bool *is_before)
4184 sprintf(cp, "%s%s%d %s%s",
4185 (!*is_zero) ? " " : "",
4186 (*is_before && value > 0) ? "+" : "",
4189 (value != 1) ? "s" : "");
4192 * Each nonzero field sets is_before for (only) the next one. This is a
4193 * tad bizarre but it's how it worked before...
4195 *is_before = (value < 0);
4197 return cp + strlen(cp);
4200 /* Append a verbose-style interval field, but only if value isn't zero */
4202 AddVerboseIntPart(char *cp, int value, const char *units,
4203 bool *is_zero, bool *is_before)
4207 /* first nonzero value sets is_before */
4210 *is_before = (value < 0);
4213 else if (*is_before)
4215 sprintf(cp, " %d %s%s", value, units, (value == 1) ? "" : "s");
4217 return cp + strlen(cp);
4222 * Interpret time structure as a delta time and convert to string.
4224 * Support "traditional Postgres" and ISO-8601 styles.
4225 * Actually, afaik ISO does not address time interval formatting,
4226 * but this looks similar to the spec for absolute date/time.
4227 * - thomas 1998-04-30
4229 * Actually, afaik, ISO 8601 does specify formats for "time
4230 * intervals...[of the]...format with time-unit designators", which
4231 * are pretty ugly. The format looks something like
4232 * P1Y1M1DT1H1M1.12345S
4233 * but useful for exchanging data with computers instead of humans.
4236 * And ISO's SQL 2008 standard specifies standards for
4237 * "year-month literal"s (that look like '2-3') and
4238 * "day-time literal"s (that look like ('4 5:6:7')
4241 EncodeInterval(struct pg_tm *tm, fsec_t fsec, int style, char *str)
4244 int year = tm->tm_year;
4245 int mon = tm->tm_mon;
4246 int mday = tm->tm_mday;
4247 int hour = tm->tm_hour;
4248 int min = tm->tm_min;
4249 int sec = tm->tm_sec;
4250 bool is_before = false;
4251 bool is_zero = true;
4254 * The sign of year and month are guaranteed to match, since they are
4255 * stored internally as "month". But we'll need to check for is_before and
4256 * is_zero when determining the signs of day and hour/minute/seconds
4261 /* SQL Standard interval format */
4262 case INTSTYLE_SQL_STANDARD:
4264 bool has_negative = year < 0 || mon < 0 ||
4265 mday < 0 || hour < 0 ||
4266 min < 0 || sec < 0 || fsec < 0;
4267 bool has_positive = year > 0 || mon > 0 ||
4268 mday > 0 || hour > 0 ||
4269 min > 0 || sec > 0 || fsec > 0;
4270 bool has_year_month = year != 0 || mon != 0;
4271 bool has_day_time = mday != 0 || hour != 0 ||
4272 min != 0 || sec != 0 || fsec != 0;
4273 bool has_day = mday != 0;
4274 bool sql_standard_value = !(has_negative && has_positive) &&
4275 !(has_year_month && has_day_time);
4278 * SQL Standard wants only 1 "<sign>" preceding the whole
4279 * interval ... but can't do that if mixed signs.
4281 if (has_negative && sql_standard_value)
4293 if (!has_negative && !has_positive)
4297 else if (!sql_standard_value)
4300 * For non sql-standard interval values, force outputting
4301 * the signs to avoid ambiguities with intervals with
4302 * mixed sign components.
4304 char year_sign = (year < 0 || mon < 0) ? '-' : '+';
4305 char day_sign = (mday < 0) ? '-' : '+';
4306 char sec_sign = (hour < 0 || min < 0 ||
4307 sec < 0 || fsec < 0) ? '-' : '+';
4309 sprintf(cp, "%c%d-%d %c%d %c%d:%02d:",
4310 year_sign, abs(year), abs(mon),
4311 day_sign, abs(mday),
4312 sec_sign, abs(hour), abs(min));
4314 cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4317 else if (has_year_month)
4319 sprintf(cp, "%d-%d", year, mon);
4323 sprintf(cp, "%d %d:%02d:", mday, hour, min);
4325 cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4330 sprintf(cp, "%d:%02d:", hour, min);
4332 cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4338 /* ISO 8601 "time-intervals by duration only" */
4339 case INTSTYLE_ISO_8601:
4340 /* special-case zero to avoid printing nothing */
4341 if (year == 0 && mon == 0 && mday == 0 &&
4342 hour == 0 && min == 0 && sec == 0 && fsec == 0)
4344 sprintf(cp, "PT0S");
4348 cp = AddISO8601IntPart(cp, year, 'Y');
4349 cp = AddISO8601IntPart(cp, mon, 'M');
4350 cp = AddISO8601IntPart(cp, mday, 'D');
4351 if (hour != 0 || min != 0 || sec != 0 || fsec != 0)
4353 cp = AddISO8601IntPart(cp, hour, 'H');
4354 cp = AddISO8601IntPart(cp, min, 'M');
4355 if (sec != 0 || fsec != 0)
4357 if (sec < 0 || fsec < 0)
4359 cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4365 /* Compatible with postgresql < 8.4 when DateStyle = 'iso' */
4366 case INTSTYLE_POSTGRES:
4367 cp = AddPostgresIntPart(cp, year, "year", &is_zero, &is_before);
4370 * Ideally we should spell out "month" like we do for "year" and
4371 * "day". However, for backward compatibility, we can't easily
4372 * fix this. bjm 2011-05-24
4374 cp = AddPostgresIntPart(cp, mon, "mon", &is_zero, &is_before);
4375 cp = AddPostgresIntPart(cp, mday, "day", &is_zero, &is_before);
4376 if (is_zero || hour != 0 || min != 0 || sec != 0 || fsec != 0)
4378 bool minus = (hour < 0 || min < 0 || sec < 0 || fsec < 0);
4380 sprintf(cp, "%s%s%02d:%02d:",
4382 (minus ? "-" : (is_before ? "+" : "")),
4383 abs(hour), abs(min));
4385 cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4390 /* Compatible with postgresql < 8.4 when DateStyle != 'iso' */
4391 case INTSTYLE_POSTGRES_VERBOSE:
4395 cp = AddVerboseIntPart(cp, year, "year", &is_zero, &is_before);
4396 cp = AddVerboseIntPart(cp, mon, "mon", &is_zero, &is_before);
4397 cp = AddVerboseIntPart(cp, mday, "day", &is_zero, &is_before);
4398 cp = AddVerboseIntPart(cp, hour, "hour", &is_zero, &is_before);
4399 cp = AddVerboseIntPart(cp, min, "min", &is_zero, &is_before);
4400 if (sec != 0 || fsec != 0)
4403 if (sec < 0 || (sec == 0 && fsec < 0))
4407 else if (!is_before)
4412 cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4413 sprintf(cp, " sec%s",
4414 (abs(sec) != 1 || fsec != 0) ? "s" : "");
4417 /* identically zero? then put in a unitless zero... */
4428 * We've been burnt by stupid errors in the ordering of the datetkn tables
4429 * once too often. Arrange to check them during postmaster start.
4432 CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
4437 for (i = 0; i < nel; i++)
4439 /* check for token strings that don't fit */
4440 if (strlen(base[i].token) > TOKMAXLEN)
4442 /* %.*s is safe since all our tokens are ASCII */
4443 elog(LOG, "token too long in %s table: \"%.*s\"",
4445 TOKMAXLEN + 1, base[i].token);
4447 break; /* don't risk applying strcmp */
4449 /* check for out of order */
4451 strcmp(base[i - 1].token, base[i].token) >= 0)
4453 elog(LOG, "ordering error in %s table: \"%s\" >= \"%s\"",
4464 CheckDateTokenTables(void)
4468 Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
4469 Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
4471 ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
4472 ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
4477 * Common code for temporal protransform functions. Types time, timetz,
4478 * timestamp and timestamptz each have a range of allowed precisions. An
4479 * unspecified precision is rigorously equivalent to the highest specifiable
4482 * Note: timestamp_scale throws an error when the typmod is out of range, but
4483 * we can't get there from a cast: our typmodin will have caught it already.
4486 TemporalTransform(int32 max_precis, Node *node)
4488 FuncExpr *expr = castNode(FuncExpr, node);
4492 Assert(list_length(expr->args) >= 2);
4494 typmod = (Node *) lsecond(expr->args);
4496 if (IsA(typmod, Const) &&!((Const *) typmod)->constisnull)
4498 Node *source = (Node *) linitial(expr->args);
4499 int32 old_precis = exprTypmod(source);
4500 int32 new_precis = DatumGetInt32(((Const *) typmod)->constvalue);
4502 if (new_precis < 0 || new_precis == max_precis ||
4503 (old_precis >= 0 && new_precis >= old_precis))
4504 ret = relabel_to_typmod(source, new_precis);
4511 * This function gets called during timezone config file load or reload
4512 * to create the final array of timezone tokens. The argument array
4513 * is already sorted in name order.
4515 * The result is a TimeZoneAbbrevTable (which must be a single malloc'd chunk)
4516 * or NULL on malloc failure. No other error conditions are defined.
4518 TimeZoneAbbrevTable *
4519 ConvertTimeZoneAbbrevs(struct tzEntry *abbrevs, int n)
4521 TimeZoneAbbrevTable *tbl;
4525 /* Space for fixed fields and datetkn array */
4526 tbl_size = offsetof(TimeZoneAbbrevTable, abbrevs) +
4527 n * sizeof(datetkn);
4528 tbl_size = MAXALIGN(tbl_size);
4529 /* Count up space for dynamic abbreviations */
4530 for (i = 0; i < n; i++)
4532 struct tzEntry *abbr = abbrevs + i;
4534 if (abbr->zone != NULL)
4538 dsize = offsetof(DynamicZoneAbbrev, zone) +
4539 strlen(abbr->zone) + 1;
4540 tbl_size += MAXALIGN(dsize);
4544 /* Alloc the result ... */
4545 tbl = malloc(tbl_size);
4549 /* ... and fill it in */
4550 tbl->tblsize = tbl_size;
4551 tbl->numabbrevs = n;
4552 /* in this loop, tbl_size reprises the space calculation above */
4553 tbl_size = offsetof(TimeZoneAbbrevTable, abbrevs) +
4554 n * sizeof(datetkn);
4555 tbl_size = MAXALIGN(tbl_size);
4556 for (i = 0; i < n; i++)
4558 struct tzEntry *abbr = abbrevs + i;
4559 datetkn *dtoken = tbl->abbrevs + i;
4561 /* use strlcpy to truncate name if necessary */
4562 strlcpy(dtoken->token, abbr->abbrev, TOKMAXLEN + 1);
4563 if (abbr->zone != NULL)
4565 /* Allocate a DynamicZoneAbbrev for this abbreviation */
4566 DynamicZoneAbbrev *dtza;
4569 dtza = (DynamicZoneAbbrev *) ((char *) tbl + tbl_size);
4571 strcpy(dtza->zone, abbr->zone);
4573 dtoken->type = DYNTZ;
4574 /* value is offset from table start to DynamicZoneAbbrev */
4575 dtoken->value = (int32) tbl_size;
4577 dsize = offsetof(DynamicZoneAbbrev, zone) +
4578 strlen(abbr->zone) + 1;
4579 tbl_size += MAXALIGN(dsize);
4583 dtoken->type = abbr->is_dst ? DTZ : TZ;
4584 dtoken->value = abbr->offset;
4588 /* Assert the two loops above agreed on size calculations */
4589 Assert(tbl->tblsize == tbl_size);
4591 /* Check the ordering, if testing */
4592 Assert(CheckDateTokenTable("timezone abbreviations", tbl->abbrevs, n));
4598 * Install a TimeZoneAbbrevTable as the active table.
4600 * Caller is responsible that the passed table doesn't go away while in use.
4603 InstallTimeZoneAbbrevs(TimeZoneAbbrevTable *tbl)
4605 zoneabbrevtbl = tbl;
4606 /* reset abbrevcache, which may contain pointers into old table */
4607 memset(abbrevcache, 0, sizeof(abbrevcache));
4611 * Helper subroutine to locate pg_tz timezone for a dynamic abbreviation.
4614 FetchDynamicTimeZone(TimeZoneAbbrevTable *tbl, const datetkn *tp)
4616 DynamicZoneAbbrev *dtza;
4618 /* Just some sanity checks to prevent indexing off into nowhere */
4619 Assert(tp->type == DYNTZ);
4620 Assert(tp->value > 0 && tp->value < tbl->tblsize);
4622 dtza = (DynamicZoneAbbrev *) ((char *) tbl + tp->value);
4624 /* Look up the underlying zone if we haven't already */
4625 if (dtza->tz == NULL)
4627 dtza->tz = pg_tzset(dtza->zone);
4630 * Ideally we'd let the caller ereport instead of doing it here, but
4631 * then there is no way to report the bad time zone name.
4633 if (dtza->tz == NULL)
4635 (errcode(ERRCODE_CONFIG_FILE_ERROR),
4636 errmsg("time zone \"%s\" not recognized",
4638 errdetail("This time zone name appears in the configuration file for time zone abbreviation \"%s\".",
4646 * This set-returning function reads all the available time zone abbreviations
4647 * and returns a set of (abbrev, utc_offset, is_dst).
4650 pg_timezone_abbrevs(PG_FUNCTION_ARGS)
4652 FuncCallContext *funcctx;
4659 char buffer[TOKMAXLEN + 1];
4664 Interval *resInterval;
4666 /* stuff done only on the first call of the function */
4667 if (SRF_IS_FIRSTCALL())
4670 MemoryContext oldcontext;
4672 /* create a function context for cross-call persistence */
4673 funcctx = SRF_FIRSTCALL_INIT();
4676 * switch to memory context appropriate for multiple function calls
4678 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4680 /* allocate memory for user context */
4681 pindex = (int *) palloc(sizeof(int));
4683 funcctx->user_fctx = (void *) pindex;
4686 * build tupdesc for result tuples. This must match this function's
4689 tupdesc = CreateTemplateTupleDesc(3, false);
4690 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "abbrev",
4692 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "utc_offset",
4693 INTERVALOID, -1, 0);
4694 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_dst",
4697 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4698 MemoryContextSwitchTo(oldcontext);
4701 /* stuff done on every call of the function */
4702 funcctx = SRF_PERCALL_SETUP();
4703 pindex = (int *) funcctx->user_fctx;
4705 if (zoneabbrevtbl == NULL ||
4706 *pindex >= zoneabbrevtbl->numabbrevs)
4707 SRF_RETURN_DONE(funcctx);
4709 tp = zoneabbrevtbl->abbrevs + *pindex;
4714 gmtoffset = tp->value;
4718 gmtoffset = tp->value;
4723 /* Determine the current meaning of the abbrev */
4728 tzp = FetchDynamicTimeZone(zoneabbrevtbl, tp);
4729 now = GetCurrentTransactionStartTimestamp();
4730 gmtoffset = -DetermineTimeZoneAbbrevOffsetTS(now,
4734 is_dst = (bool) isdst;
4738 elog(ERROR, "unrecognized timezone type %d", (int) tp->type);
4739 gmtoffset = 0; /* keep compiler quiet */
4744 MemSet(nulls, 0, sizeof(nulls));
4747 * Convert name to text, using upcasing conversion that is the inverse of
4748 * what ParseDateTime() uses.
4750 strlcpy(buffer, tp->token, sizeof(buffer));
4751 for (p = (unsigned char *) buffer; *p; p++)
4752 *p = pg_toupper(*p);
4754 values[0] = CStringGetTextDatum(buffer);
4756 /* Convert offset (in seconds) to an interval */
4757 MemSet(&tm, 0, sizeof(struct pg_tm));
4758 tm.tm_sec = gmtoffset;
4759 resInterval = (Interval *) palloc(sizeof(Interval));
4760 tm2interval(&tm, 0, resInterval);
4761 values[1] = IntervalPGetDatum(resInterval);
4763 values[2] = BoolGetDatum(is_dst);
4767 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4768 result = HeapTupleGetDatum(tuple);
4770 SRF_RETURN_NEXT(funcctx, result);
4774 * This set-returning function reads all the available full time zones
4775 * and returns a set of (name, abbrev, utc_offset, is_dst).
4778 pg_timezone_names(PG_FUNCTION_ARGS)
4780 MemoryContext oldcontext;
4781 FuncCallContext *funcctx;
4792 Interval *resInterval;
4795 /* stuff done only on the first call of the function */
4796 if (SRF_IS_FIRSTCALL())
4800 /* create a function context for cross-call persistence */
4801 funcctx = SRF_FIRSTCALL_INIT();
4804 * switch to memory context appropriate for multiple function calls
4806 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4808 /* initialize timezone scanning code */
4809 tzenum = pg_tzenumerate_start();
4810 funcctx->user_fctx = (void *) tzenum;
4813 * build tupdesc for result tuples. This must match this function's
4816 tupdesc = CreateTemplateTupleDesc(4, false);
4817 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
4819 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "abbrev",
4821 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "utc_offset",
4822 INTERVALOID, -1, 0);
4823 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_dst",
4826 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4827 MemoryContextSwitchTo(oldcontext);
4830 /* stuff done on every call of the function */
4831 funcctx = SRF_PERCALL_SETUP();
4832 tzenum = (pg_tzenum *) funcctx->user_fctx;
4834 /* search for another zone to display */
4837 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4838 tz = pg_tzenumerate_next(tzenum);
4839 MemoryContextSwitchTo(oldcontext);
4843 pg_tzenumerate_end(tzenum);
4844 funcctx->user_fctx = NULL;
4845 SRF_RETURN_DONE(funcctx);
4848 /* Convert now() to local time in this zone */
4849 if (timestamp2tm(GetCurrentTransactionStartTimestamp(),
4850 &tzoff, &tm, &fsec, &tzn, tz) != 0)
4851 continue; /* ignore if conversion fails */
4854 * Ignore zic's rather silly "Factory" time zone. The long string
4855 * about "see zic manual page" is used in tzdata versions before
4856 * 2016g; we can drop it someday when we're pretty sure no such data
4857 * exists in the wild on platforms using --with-system-tzdata. In
4858 * 2016g and later, the time zone abbreviation "-00" is used for
4859 * "Factory" as well as some invalid cases, all of which we can
4860 * reasonably omit from the pg_timezone_names view.
4862 if (tzn && (strcmp(tzn, "-00") == 0 ||
4863 strcmp(tzn, "Local time zone must be set--see zic manual page") == 0))
4866 /* Found a displayable zone */
4870 MemSet(nulls, 0, sizeof(nulls));
4872 values[0] = CStringGetTextDatum(pg_get_timezone_name(tz));
4873 values[1] = CStringGetTextDatum(tzn ? tzn : "");
4875 MemSet(&itm, 0, sizeof(struct pg_tm));
4876 itm.tm_sec = -tzoff;
4877 resInterval = (Interval *) palloc(sizeof(Interval));
4878 tm2interval(&itm, 0, resInterval);
4879 values[2] = IntervalPGetDatum(resInterval);
4881 values[3] = BoolGetDatum(tm.tm_isdst > 0);
4883 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4884 result = HeapTupleGetDatum(tuple);
4886 SRF_RETURN_NEXT(funcctx, result);