1 /*-------------------------------------------------------------------------
4 * Support functions for date/time types.
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/utils/adt/datetime.c,v 1.202 2009/03/17 18:39:39 momjian Exp $
13 *-------------------------------------------------------------------------
22 #include "access/xact.h"
23 #include "catalog/pg_type.h"
25 #include "miscadmin.h"
26 #include "utils/builtins.h"
27 #include "utils/date.h"
28 #include "utils/datetime.h"
29 #include "utils/memutils.h"
30 #include "utils/tzparser.h"
33 static int DecodeNumber(int flen, char *field, bool haveTextMonth,
34 int fmask, int *tmask,
35 struct pg_tm * tm, fsec_t *fsec, bool *is2digits);
36 static int DecodeNumberField(int len, char *str,
37 int fmask, int *tmask,
38 struct pg_tm * tm, fsec_t *fsec, bool *is2digits);
39 static int DecodeTime(char *str, int fmask, int range,
40 int *tmask, struct pg_tm * tm, fsec_t *fsec);
41 static int DecodeTimezone(char *str, int *tzp);
42 static const datetkn *datebsearch(const char *key, const datetkn *base, int nel);
43 static int DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
45 static int ValidateDate(int fmask, bool is2digits, bool bc,
47 static void TrimTrailingZeros(char *str);
48 static void AppendSeconds(char *cp, int sec, fsec_t fsec,
49 int precision, bool fillzeros);
50 static void AdjustFractSeconds(double frac, struct pg_tm * tm, fsec_t *fsec,
52 static void AdjustFractDays(double frac, struct pg_tm * tm, fsec_t *fsec,
56 const int day_tab[2][13] =
58 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
59 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}
62 char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
63 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
65 char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
66 "Thursday", "Friday", "Saturday", NULL};
69 /*****************************************************************************
71 *****************************************************************************/
74 * Definitions for squeezing values into "value"
75 * We set aside a high bit for a sign, and scale the timezone offsets
76 * in minutes by a factor of 15 (so can represent quarter-hour increments).
78 #define ABS_SIGNBIT ((char) 0200)
79 #define VALMASK ((char) 0177)
81 #define NEG(n) ((n)|ABS_SIGNBIT)
82 #define SIGNEDCHAR(c) ((c)&ABS_SIGNBIT? -((c)&VALMASK): (c))
83 #define FROMVAL(tp) (-SIGNEDCHAR((tp)->value) * 15) /* uncompress */
84 #define TOVAL(tp, v) ((tp)->value = ((v) < 0? NEG((-(v))/15): POS(v)/15))
87 * datetktbl holds date/time keywords.
89 * Note that this table must be strictly alphabetically ordered to allow an
90 * O(ln(N)) search algorithm to be used.
92 * The text field is NOT guaranteed to be NULL-terminated.
94 * To keep this table reasonably small, we divide the lexval for TZ and DTZ
95 * entries by 15 (so they are on 15 minute boundaries) and truncate the text
96 * field at TOKMAXLEN characters.
97 * Formerly, we divided by 10 rather than 15 but there are a few time zones
98 * which are 30 or 45 minutes away from an even hour, most are on an hour
99 * boundary, and none on other boundaries.
101 * The static table contains no TZ or DTZ entries, rather those are loaded
102 * from configuration files and stored in timezonetktbl, which has the same
103 * format as the static datetktbl.
105 static datetkn *timezonetktbl = NULL;
107 static int sztimezonetktbl = 0;
109 static const datetkn datetktbl[] = {
110 /* text, token, lexval */
111 {EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
112 {"abstime", IGNORE_DTF, 0}, /* for pre-v6.1 "Invalid Abstime" */
113 {DA_D, ADBC, AD}, /* "ad" for years > 0 */
114 {"allballs", RESERV, DTK_ZULU}, /* 00:00:00 */
118 {"at", IGNORE_DTF, 0}, /* "at" (throwaway) */
120 {"august", MONTH, 8},
121 {DB_C, ADBC, BC}, /* "bc" for years <= 0 */
122 {DCURRENT, RESERV, DTK_CURRENT}, /* "current" is always now */
123 {"d", UNITS, DTK_DAY}, /* "day of month" for ISO input */
125 {"december", MONTH, 12},
126 {"dow", RESERV, DTK_DOW}, /* day of week */
127 {"doy", RESERV, DTK_DOY}, /* day of year */
129 {EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
131 {"february", MONTH, 2},
134 {"h", UNITS, DTK_HOUR}, /* "hour" */
135 {LATE, RESERV, DTK_LATE}, /* "infinity" reserved for "late time" */
136 {INVALID, RESERV, DTK_INVALID}, /* "invalid" reserved for bad time */
137 {"isodow", RESERV, DTK_ISODOW}, /* ISO day of week, Sunday == 7 */
138 {"isoyear", UNITS, DTK_ISOYEAR}, /* year in terms of the ISO week date */
139 {"j", UNITS, DTK_JULIAN},
141 {"january", MONTH, 1},
142 {"jd", UNITS, DTK_JULIAN},
144 {"julian", UNITS, DTK_JULIAN},
148 {"m", UNITS, DTK_MONTH}, /* "month" for ISO input */
152 {"mm", UNITS, DTK_MINUTE}, /* "minute" for ISO input */
156 {"november", MONTH, 11},
157 {NOW, RESERV, DTK_NOW}, /* current transaction time */
159 {"october", MONTH, 10},
160 {"on", IGNORE_DTF, 0}, /* "on" (throwaway) */
162 {"s", UNITS, DTK_SECOND}, /* "seconds" for ISO input */
164 {"saturday", DOW, 6},
167 {"september", MONTH, 9},
170 {"t", ISOTIME, DTK_TIME}, /* Filler for ISO time fields */
174 {"thursday", DOW, 4},
175 {TODAY, RESERV, DTK_TODAY}, /* midnight */
176 {TOMORROW, RESERV, DTK_TOMORROW}, /* tomorrow midnight */
180 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
182 {"wednesday", DOW, 3},
184 {"y", UNITS, DTK_YEAR}, /* "year" for ISO input */
185 {YESTERDAY, RESERV, DTK_YESTERDAY} /* yesterday midnight */
188 static int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];
190 static datetkn deltatktbl[] = {
191 /* text, token, lexval */
192 {"@", IGNORE_DTF, 0}, /* postgres relative prefix */
193 {DAGO, AGO, 0}, /* "ago" indicates negative time offset */
194 {"c", UNITS, DTK_CENTURY}, /* "century" relative */
195 {"cent", UNITS, DTK_CENTURY}, /* "century" relative */
196 {"centuries", UNITS, DTK_CENTURY}, /* "centuries" relative */
197 {DCENTURY, UNITS, DTK_CENTURY}, /* "century" relative */
198 {"d", UNITS, DTK_DAY}, /* "day" relative */
199 {DDAY, UNITS, DTK_DAY}, /* "day" relative */
200 {"days", UNITS, DTK_DAY}, /* "days" relative */
201 {"dec", UNITS, DTK_DECADE}, /* "decade" relative */
202 {DDECADE, UNITS, DTK_DECADE}, /* "decade" relative */
203 {"decades", UNITS, DTK_DECADE}, /* "decades" relative */
204 {"decs", UNITS, DTK_DECADE}, /* "decades" relative */
205 {"h", UNITS, DTK_HOUR}, /* "hour" relative */
206 {DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */
207 {"hours", UNITS, DTK_HOUR}, /* "hours" relative */
208 {"hr", UNITS, DTK_HOUR}, /* "hour" relative */
209 {"hrs", UNITS, DTK_HOUR}, /* "hours" relative */
210 {INVALID, RESERV, DTK_INVALID}, /* reserved for invalid time */
211 {"m", UNITS, DTK_MINUTE}, /* "minute" relative */
212 {"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
213 {"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
214 {"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
215 {DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
216 {"millisecon", UNITS, DTK_MILLISEC}, /* relative */
217 {"mils", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
218 {"min", UNITS, DTK_MINUTE}, /* "minute" relative */
219 {"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */
220 {DMINUTE, UNITS, DTK_MINUTE}, /* "minute" relative */
221 {"minutes", UNITS, DTK_MINUTE}, /* "minutes" relative */
222 {"mon", UNITS, DTK_MONTH}, /* "months" relative */
223 {"mons", UNITS, DTK_MONTH}, /* "months" relative */
224 {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
225 {"months", UNITS, DTK_MONTH},
226 {"ms", UNITS, DTK_MILLISEC},
227 {"msec", UNITS, DTK_MILLISEC},
228 {DMILLISEC, UNITS, DTK_MILLISEC},
229 {"mseconds", UNITS, DTK_MILLISEC},
230 {"msecs", UNITS, DTK_MILLISEC},
231 {"qtr", UNITS, DTK_QUARTER}, /* "quarter" relative */
232 {DQUARTER, UNITS, DTK_QUARTER}, /* "quarter" relative */
233 {"reltime", IGNORE_DTF, 0}, /* pre-v6.1 "Undefined Reltime" */
234 {"s", UNITS, DTK_SECOND},
235 {"sec", UNITS, DTK_SECOND},
236 {DSECOND, UNITS, DTK_SECOND},
237 {"seconds", UNITS, DTK_SECOND},
238 {"secs", UNITS, DTK_SECOND},
239 {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
240 {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
241 {"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */
242 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
243 {"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
244 {"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
245 {DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */
246 {"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
247 {"usecs", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
248 {"w", UNITS, DTK_WEEK}, /* "week" relative */
249 {DWEEK, UNITS, DTK_WEEK}, /* "week" relative */
250 {"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
251 {"y", UNITS, DTK_YEAR}, /* "year" relative */
252 {DYEAR, UNITS, DTK_YEAR}, /* "year" relative */
253 {"years", UNITS, DTK_YEAR}, /* "years" relative */
254 {"yr", UNITS, DTK_YEAR}, /* "year" relative */
255 {"yrs", UNITS, DTK_YEAR} /* "years" relative */
258 static int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];
260 static const datetkn *datecache[MAXDATEFIELDS] = {NULL};
262 static const datetkn *deltacache[MAXDATEFIELDS] = {NULL};
266 * strtoi --- just like strtol, but returns int not long
269 strtoi(const char *nptr, char **endptr, int base)
273 val = strtol(nptr, endptr, base);
274 #ifdef HAVE_LONG_INT_64
275 if (val != (long) ((int32) val))
283 * Calendar time to Julian date conversions.
284 * Julian date is commonly used in astronomical applications,
285 * since it is numerically accurate and computationally simple.
286 * The algorithms here will accurately convert between Julian day
287 * and calendar date for all non-negative Julian days
288 * (i.e. from Nov 24, -4713 on).
290 * These routines will be used by other date/time packages
293 * Rewritten to eliminate overflow problems. This now allows the
294 * routines to work correctly for all Julian day counts from
295 * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming
296 * a 32-bit integer. Longer types should also work to the limits
297 * of their precision.
301 date2j(int y, int m, int d)
318 julian = y * 365 - 32167;
319 julian += y / 4 - century + century / 4;
320 julian += 7834 * m / 256 + d;
326 j2date(int jd, int *year, int *month, int *day)
335 quad = julian / 146097;
336 extra = (julian - quad * 146097) * 4 + 3;
337 julian += 60 + quad * 3 + extra / 146097;
338 quad = julian / 1461;
339 julian -= quad * 1461;
340 y = julian * 4 / 1461;
341 julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
345 quad = julian * 2141 / 65536;
346 *day = julian - 7834 * quad / 256;
347 *month = (quad + 10) % 12 + 1;
354 * j2day - convert Julian date to day-of-week (0..6 == Sun..Sat)
356 * Note: various places use the locution j2day(date - 1) to produce a
357 * result according to the convention 0..6 = Mon..Sun. This is a bit of
358 * a crock, but will work as long as the computation here is just a modulo.
375 * GetCurrentDateTime()
377 * Get the transaction start time ("now()") broken down as a struct pg_tm.
380 GetCurrentDateTime(struct pg_tm * tm)
385 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, &fsec,
387 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
391 * GetCurrentTimeUsec()
393 * Get the transaction start time ("now()") broken down as a struct pg_tm,
394 * including fractional seconds and timezone offset.
397 GetCurrentTimeUsec(struct pg_tm * tm, fsec_t *fsec, int *tzp)
401 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, fsec,
403 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
409 /* TrimTrailingZeros()
410 * ... resulting from printing numbers with full precision.
412 * Before Postgres 8.4, this always left at least 2 fractional digits,
413 * but conversations on the lists suggest this isn't desired
414 * since showing '0.10' is misleading with values of precision(1).
417 TrimTrailingZeros(char *str)
419 int len = strlen(str);
421 while (len > 1 && *(str + len - 1) == '0' && *(str + len - 2) != '.')
429 * Append sections and fractional seconds (if any) at *cp.
430 * precision is the max number of fraction digits, fillzeros says to
431 * pad to two integral-seconds digits.
432 * Note that any sign is stripped from the input seconds values.
435 AppendSeconds(char *cp, int sec, fsec_t fsec, int precision, bool fillzeros)
440 sprintf(cp, "%02d", abs(sec));
442 sprintf(cp, "%d", abs(sec));
446 #ifdef HAVE_INT64_TIMESTAMP
448 sprintf(cp, "%02d.%0*d", abs(sec), precision, (int) Abs(fsec));
450 sprintf(cp, "%d.%0*d", abs(sec), precision, (int) Abs(fsec));
453 sprintf(cp, "%0*.*f", precision + 3, precision, fabs(sec + fsec));
455 sprintf(cp, "%.*f", precision, fabs(sec + fsec));
457 TrimTrailingZeros(cp);
461 /* Variant of above that's specialized to timestamp case */
463 AppendTimestampSeconds(char *cp, struct pg_tm * tm, fsec_t fsec)
466 * In float mode, don't print fractional seconds before 1 AD,
467 * since it's unlikely there's any precision left ...
469 #ifndef HAVE_INT64_TIMESTAMP
470 if (tm->tm_year <= 0)
473 AppendSeconds(cp, tm->tm_sec, fsec, MAX_TIMESTAMP_PRECISION, true);
477 * Multiply frac by scale (to produce seconds) and add to *tm & *fsec.
478 * We assume the input frac is less than 1 so overflow is not an issue.
481 AdjustFractSeconds(double frac, struct pg_tm * tm, fsec_t *fsec, int scale)
491 #ifdef HAVE_INT64_TIMESTAMP
492 *fsec += rint(frac * 1000000);
498 /* As above, but initial scale produces days */
500 AdjustFractDays(double frac, struct pg_tm * tm, fsec_t *fsec, int scale)
507 extra_days = (int) frac;
508 tm->tm_mday += extra_days;
510 AdjustFractSeconds(frac, tm, fsec, SECS_PER_DAY);
513 /* Fetch a fractional-second value with suitable error checking */
515 ParseFractionalSecond(char *cp, fsec_t *fsec)
519 /* Caller should always pass the start of the fraction part */
522 frac = strtod(cp, &cp);
523 /* check for parse failure */
524 if (*cp != '\0' || errno != 0)
525 return DTERR_BAD_FORMAT;
526 #ifdef HAVE_INT64_TIMESTAMP
527 *fsec = rint(frac * 1000000);
536 * Break string into tokens based on a date/time context.
537 * Returns 0 if successful, DTERR code if bogus input detected.
539 * timestr - the input string
540 * workbuf - workspace for field string storage. This must be
541 * larger than the largest legal input for this datetime type --
542 * some additional space will be needed to NUL terminate fields.
543 * buflen - the size of workbuf
544 * field[] - pointers to field strings are returned in this array
545 * ftype[] - field type indicators are returned in this array
546 * maxfields - dimensions of the above two arrays
547 * *numfields - set to the actual number of fields detected
549 * The fields extracted from the input are stored as separate,
550 * null-terminated strings in the workspace at workbuf. Any text is
551 * converted to lower case.
553 * Several field types are assigned:
554 * DTK_NUMBER - digits and (possibly) a decimal point
555 * DTK_DATE - digits and two delimiters, or digits and text
556 * DTK_TIME - digits, colon delimiters, and possibly a decimal point
557 * DTK_STRING - text (no digits or punctuation)
558 * DTK_SPECIAL - leading "+" or "-" followed by text
559 * DTK_TZ - leading "+" or "-" followed by digits (also eats ':', '.', '-')
561 * Note that some field types can hold unexpected items:
562 * DTK_NUMBER can hold date fields (yy.ddd)
563 * DTK_STRING can hold months (January) and time zones (PST)
564 * DTK_DATE can hold time zone names (America/New_York, GMT-8)
567 ParseDateTime(const char *timestr, char *workbuf, size_t buflen,
568 char **field, int *ftype, int maxfields, int *numfields)
571 const char *cp = timestr;
572 char *bufp = workbuf;
573 const char *bufend = workbuf + buflen;
576 * Set the character pointed-to by "bufptr" to "newchar", and increment
577 * "bufptr". "end" gives the end of the buffer -- we return an error if
578 * there is no space left to append a character to the buffer. Note that
579 * "bufptr" is evaluated twice.
581 #define APPEND_CHAR(bufptr, end, newchar) \
584 if (((bufptr) + 1) >= (end)) \
585 return DTERR_BAD_FORMAT; \
586 *(bufptr)++ = newchar; \
589 /* outer loop through fields */
592 /* Ignore spaces between fields */
593 if (isspace((unsigned char) *cp))
599 /* Record start of current field */
601 return DTERR_BAD_FORMAT;
604 /* leading digit? then date or time */
605 if (isdigit((unsigned char) *cp))
607 APPEND_CHAR(bufp, bufend, *cp++);
608 while (isdigit((unsigned char) *cp))
609 APPEND_CHAR(bufp, bufend, *cp++);
614 ftype[nf] = DTK_TIME;
615 APPEND_CHAR(bufp, bufend, *cp++);
616 while (isdigit((unsigned char) *cp) ||
617 (*cp == ':') || (*cp == '.'))
618 APPEND_CHAR(bufp, bufend, *cp++);
620 /* date field? allow embedded text month */
621 else if (*cp == '-' || *cp == '/' || *cp == '.')
623 /* save delimiting character to use later */
626 APPEND_CHAR(bufp, bufend, *cp++);
627 /* second field is all digits? then no embedded text month */
628 if (isdigit((unsigned char) *cp))
630 ftype[nf] = ((delim == '.') ? DTK_NUMBER : DTK_DATE);
631 while (isdigit((unsigned char) *cp))
632 APPEND_CHAR(bufp, bufend, *cp++);
635 * insist that the delimiters match to get a three-field
640 ftype[nf] = DTK_DATE;
641 APPEND_CHAR(bufp, bufend, *cp++);
642 while (isdigit((unsigned char) *cp) || *cp == delim)
643 APPEND_CHAR(bufp, bufend, *cp++);
648 ftype[nf] = DTK_DATE;
649 while (isalnum((unsigned char) *cp) || *cp == delim)
650 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
655 * otherwise, number only and will determine year, month, day, or
656 * concatenated fields later...
659 ftype[nf] = DTK_NUMBER;
661 /* Leading decimal point? Then fractional seconds... */
664 APPEND_CHAR(bufp, bufend, *cp++);
665 while (isdigit((unsigned char) *cp))
666 APPEND_CHAR(bufp, bufend, *cp++);
668 ftype[nf] = DTK_NUMBER;
672 * text? then date string, month, day of week, special, or timezone
674 else if (isalpha((unsigned char) *cp))
678 ftype[nf] = DTK_STRING;
679 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
680 while (isalpha((unsigned char) *cp))
681 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
684 * Dates can have embedded '-', '/', or '.' separators. It could
685 * also be a timezone name containing embedded '/', '+', '-', '_',
686 * or ':' (but '_' or ':' can't be the first punctuation). If the
687 * next character is a digit or '+', we need to check whether what
688 * we have so far is a recognized non-timezone keyword --- if so,
689 * don't believe that this is the start of a timezone.
692 if (*cp == '-' || *cp == '/' || *cp == '.')
694 else if (*cp == '+' || isdigit((unsigned char) *cp))
696 *bufp = '\0'; /* null-terminate current field value */
697 /* we need search only the core token table, not TZ names */
698 if (datebsearch(field[nf], datetktbl, szdatetktbl) == NULL)
703 ftype[nf] = DTK_DATE;
706 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
707 } while (*cp == '+' || *cp == '-' ||
708 *cp == '/' || *cp == '_' ||
709 *cp == '.' || *cp == ':' ||
710 isalnum((unsigned char) *cp));
713 /* sign? then special or numeric timezone */
714 else if (*cp == '+' || *cp == '-')
716 APPEND_CHAR(bufp, bufend, *cp++);
717 /* soak up leading whitespace */
718 while (isspace((unsigned char) *cp))
720 /* numeric timezone? */
721 /* note that "DTK_TZ" could also be a signed float or yyyy-mm */
722 if (isdigit((unsigned char) *cp))
725 APPEND_CHAR(bufp, bufend, *cp++);
726 while (isdigit((unsigned char) *cp) ||
727 *cp == ':' || *cp == '.' || *cp == '-')
728 APPEND_CHAR(bufp, bufend, *cp++);
731 else if (isalpha((unsigned char) *cp))
733 ftype[nf] = DTK_SPECIAL;
734 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
735 while (isalpha((unsigned char) *cp))
736 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
738 /* otherwise something wrong... */
740 return DTERR_BAD_FORMAT;
742 /* ignore other punctuation but use as delimiter */
743 else if (ispunct((unsigned char) *cp))
748 /* otherwise, something is not right... */
750 return DTERR_BAD_FORMAT;
752 /* force in a delimiter after each field */
764 * Interpret previously parsed fields for general date and time.
765 * Return 0 if full date, 1 if only time, and negative DTERR code if problems.
766 * (Currently, all callers treat 1 as an error return too.)
768 * External format(s):
769 * "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
770 * "Fri Feb-7-1997 15:23:27"
771 * "Feb-7-1997 15:23:27"
772 * "2-7-1997 15:23:27"
773 * "1997-2-7 15:23:27"
774 * "1997.038 15:23:27" (day of year 1-366)
775 * Also supports input in compact time:
778 * "20011225T040506.789-07"
780 * Use the system-provided functions to get the current time zone
781 * if not specified in the input string.
783 * If the date is outside the range of pg_time_t (in practice that could only
784 * happen if pg_time_t is just 32 bits), then assume UTC time zone - thomas
788 DecodeDateTime(char **field, int *ftype, int nf,
789 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
794 int ptype = 0; /* "prefix type" for ISO y2001m02d04 format */
799 bool haveTextMonth = FALSE;
800 bool is2digits = FALSE;
802 pg_tz *namedTz = 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++)
824 * Integral julian day with attached time zone?
825 * All other forms with JD will be separated into
826 * distinct fields, so we handle just this case here.
828 if (ptype == DTK_JULIAN)
834 return DTERR_BAD_FORMAT;
837 val = strtoi(field[i], &cp, 10);
839 return DTERR_FIELD_OVERFLOW;
841 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
842 /* Get the time zone from the end of the string */
843 dterr = DecodeTimezone(cp, tzp);
847 tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
852 * Already have a date? Then this might be a time zone name
853 * with embedded punctuation (e.g. "America/New_York") or a
854 * run-together time with trailing time zone (e.g. hhmmss-zz).
855 * - thomas 2001-12-25
857 * We consider it a time zone if we already have month & day.
858 * This is to allow the form "mmm dd hhmmss tz year", which
859 * we've historically accepted.
861 else if (ptype != 0 ||
862 ((fmask & (DTK_M(MONTH) | DTK_M(DAY))) ==
863 (DTK_M(MONTH) | DTK_M(DAY))))
865 /* No time zone accepted? Then quit... */
867 return DTERR_BAD_FORMAT;
869 if (isdigit((unsigned char) *field[i]) || ptype != 0)
875 /* Sanity check; should not fail this test */
876 if (ptype != DTK_TIME)
877 return DTERR_BAD_FORMAT;
882 * Starts with a digit but we already have a time
883 * field? Then we are in trouble with a date and time
886 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
887 return DTERR_BAD_FORMAT;
889 if ((cp = strchr(field[i], '-')) == NULL)
890 return DTERR_BAD_FORMAT;
892 /* Get the time zone from the end of the string */
893 dterr = DecodeTimezone(cp, tzp);
899 * Then read the rest of the field as a concatenated
902 dterr = DecodeNumberField(strlen(field[i]), field[i],
910 * modify tmask after returning from
911 * DecodeNumberField()
917 namedTz = pg_tzset(field[i]);
921 * We should return an error code instead of
922 * ereport'ing directly, but then there is no way
923 * to report the bad time zone name.
926 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
927 errmsg("time zone \"%s\" not recognized",
930 /* we'll apply the zone setting below */
936 dterr = DecodeDate(field[i], fmask,
937 &tmask, &is2digits, tm);
944 dterr = DecodeTime(field[i], fmask, INTERVAL_FULL_RANGE,
950 * Check upper limit on hours; other limits checked in
953 /* test for > 24:00:00 */
954 if (tm->tm_hour > 24 ||
955 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0)))
956 return DTERR_FIELD_OVERFLOW;
964 return DTERR_BAD_FORMAT;
966 dterr = DecodeTimezone(field[i], &tz);
977 * Was this an "ISO date" with embedded field labels? An
978 * example is "y2001m02d04" - thomas 2001-02-04
986 val = strtoi(field[i], &cp, 10);
988 return DTERR_FIELD_OVERFLOW;
991 * only a few kinds are allowed to have an embedded
1002 return DTERR_BAD_FORMAT;
1005 else if (*cp != '\0')
1006 return DTERR_BAD_FORMAT;
1012 tmask = DTK_M(YEAR);
1018 * already have a month and hour? then assume
1021 if ((fmask & DTK_M(MONTH)) != 0 &&
1022 (fmask & DTK_M(HOUR)) != 0)
1025 tmask = DTK_M(MINUTE);
1030 tmask = DTK_M(MONTH);
1041 tmask = DTK_M(HOUR);
1046 tmask = DTK_M(MINUTE);
1051 tmask = DTK_M(SECOND);
1054 dterr = ParseFractionalSecond(cp, fsec);
1057 tmask = DTK_ALL_SECS_M;
1063 dterr = DecodeTimezone(field[i], tzp);
1070 * previous field was a label for "julian date"?
1073 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1074 /* fractional Julian Day? */
1080 time = strtod(cp, &cp);
1081 if (*cp != '\0' || errno != 0)
1082 return DTERR_BAD_FORMAT;
1084 #ifdef HAVE_INT64_TIMESTAMP
1085 time *= USECS_PER_DAY;
1087 time *= SECS_PER_DAY;
1090 &tm->tm_hour, &tm->tm_min,
1092 tmask |= DTK_TIME_M;
1097 /* previous field was "t" for ISO time */
1098 dterr = DecodeNumberField(strlen(field[i]), field[i],
1099 (fmask | DTK_DATE_M),
1104 if (tmask != DTK_TIME_M)
1105 return DTERR_BAD_FORMAT;
1109 return DTERR_BAD_FORMAT;
1121 flen = strlen(field[i]);
1122 cp = strchr(field[i], '.');
1124 /* Embedded decimal and no date yet? */
1125 if (cp != NULL && !(fmask & DTK_DATE_M))
1127 dterr = DecodeDate(field[i], fmask,
1128 &tmask, &is2digits, tm);
1132 /* embedded decimal and several digits before? */
1133 else if (cp != NULL && flen - strlen(cp) > 2)
1136 * Interpret as a concatenated date or time Set the
1137 * type field to allow decoding other fields later.
1138 * Example: 20011223 or 040506
1140 dterr = DecodeNumberField(flen, field[i], fmask,
1148 dterr = DecodeNumberField(flen, field[i], fmask,
1154 /* otherwise it is a single date/time field... */
1157 dterr = DecodeNumber(flen, field[i],
1158 haveTextMonth, fmask,
1169 type = DecodeSpecial(i, field[i], &val);
1170 if (type == IGNORE_DTF)
1173 tmask = DTK_M(type);
1181 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1182 errmsg("date/time value \"current\" is no longer supported")));
1184 return DTERR_BAD_FORMAT;
1188 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1190 GetCurrentTimeUsec(tm, fsec, tzp);
1196 GetCurrentDateTime(tm);
1197 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - 1,
1198 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1207 GetCurrentDateTime(tm);
1216 GetCurrentDateTime(tm);
1217 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1,
1218 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1225 tmask = (DTK_TIME_M | DTK_M(TZ));
1243 * already have a (numeric) month? then see if we can
1246 if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
1247 !(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 &&
1250 tm->tm_mday = tm->tm_mon;
1253 haveTextMonth = TRUE;
1260 * daylight savings time modifier (solves "MET DST"
1263 tmask |= DTK_M(DTZ);
1266 return DTERR_BAD_FORMAT;
1267 *tzp += val * MINS_PER_HOUR;
1273 * set mask for TZ here _or_ check for DTZ later when
1274 * getting default timezone
1279 return DTERR_BAD_FORMAT;
1280 *tzp = val * MINS_PER_HOUR;
1286 return DTERR_BAD_FORMAT;
1287 *tzp = val * MINS_PER_HOUR;
1313 * This is a filler field "t" indicating that the next
1314 * field is time. Try to verify that this is sensible.
1318 /* No preceding date? Then quit... */
1319 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1320 return DTERR_BAD_FORMAT;
1323 * We will need one of the following fields:
1324 * DTK_NUMBER should be hhmmss.fff
1325 * DTK_TIME should be hh:mm:ss.fff
1326 * DTK_DATE should be hhmmss-zz
1329 (ftype[i + 1] != DTK_NUMBER &&
1330 ftype[i + 1] != DTK_TIME &&
1331 ftype[i + 1] != DTK_DATE))
1332 return DTERR_BAD_FORMAT;
1340 * Before giving up and declaring error, check to see
1341 * if it is an all-alpha timezone name.
1343 namedTz = pg_tzset(field[i]);
1345 return DTERR_BAD_FORMAT;
1346 /* we'll apply the zone setting below */
1351 return DTERR_BAD_FORMAT;
1356 return DTERR_BAD_FORMAT;
1360 return DTERR_BAD_FORMAT;
1362 } /* end loop over fields */
1364 /* do final checking/adjustment of Y/M/D fields */
1365 dterr = ValidateDate(fmask, is2digits, bc, tm);
1370 if (mer != HR24 && tm->tm_hour > 12)
1371 return DTERR_FIELD_OVERFLOW;
1372 if (mer == AM && tm->tm_hour == 12)
1374 else if (mer == PM && tm->tm_hour != 12)
1377 /* do additional checking for full date specs... */
1378 if (*dtype == DTK_DATE)
1380 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1382 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1384 return DTERR_BAD_FORMAT;
1388 * If we had a full timezone spec, compute the offset (we could not do
1389 * it before, because we need the date to resolve DST status).
1391 if (namedTz != NULL)
1393 /* daylight savings time modifier disallowed with full TZ */
1394 if (fmask & DTK_M(DTZMOD))
1395 return DTERR_BAD_FORMAT;
1397 *tzp = DetermineTimeZoneOffset(tm, namedTz);
1400 /* timezone not specified? then find local timezone if possible */
1401 if (tzp != NULL && !(fmask & DTK_M(TZ)))
1404 * daylight savings time modifier but no standard timezone? then
1407 if (fmask & DTK_M(DTZMOD))
1408 return DTERR_BAD_FORMAT;
1410 *tzp = DetermineTimeZoneOffset(tm, session_timezone);
1418 /* DetermineTimeZoneOffset()
1420 * Given a struct pg_tm in which tm_year, tm_mon, tm_mday, tm_hour, tm_min, and
1421 * tm_sec fields are set, attempt to determine the applicable time zone
1422 * (ie, regular or daylight-savings time) at that time. Set the struct pg_tm's
1423 * tm_isdst field accordingly, and return the actual timezone offset.
1425 * Note: it might seem that we should use mktime() for this, but bitter
1426 * experience teaches otherwise. This code is much faster than most versions
1427 * of mktime(), anyway.
1430 DetermineTimeZoneOffset(struct pg_tm * tm, pg_tz *tzp)
1440 long int before_gmtoff,
1446 if (tzp == session_timezone && HasCTZSet)
1448 tm->tm_isdst = 0; /* for lack of a better idea */
1453 * First, generate the pg_time_t value corresponding to the given
1454 * y/m/d/h/m/s taken as GMT time. If this overflows, punt and decide the
1455 * timezone is GMT. (We only need to worry about overflow on machines
1456 * where pg_time_t is 32 bits.)
1458 if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
1460 date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - UNIX_EPOCH_JDATE;
1462 day = ((pg_time_t) date) * SECS_PER_DAY;
1463 if (day / SECS_PER_DAY != date)
1465 sec = tm->tm_sec + (tm->tm_min + tm->tm_hour * MINS_PER_HOUR) * SECS_PER_MINUTE;
1467 /* since sec >= 0, overflow could only be from +day to -mytime */
1468 if (mytime < 0 && day > 0)
1472 * Find the DST time boundary just before or following the target time. We
1473 * assume that all zones have GMT offsets less than 24 hours, and that DST
1474 * boundaries can't be closer together than 48 hours, so backing up 24
1475 * hours and finding the "next" boundary will work.
1477 prevtime = mytime - SECS_PER_DAY;
1478 if (mytime < 0 && prevtime > 0)
1481 res = pg_next_dst_boundary(&prevtime,
1482 &before_gmtoff, &before_isdst,
1484 &after_gmtoff, &after_isdst,
1487 goto overflow; /* failure? */
1491 /* Non-DST zone, life is simple */
1492 tm->tm_isdst = before_isdst;
1493 return -(int) before_gmtoff;
1497 * Form the candidate pg_time_t values with local-time adjustment
1499 beforetime = mytime - before_gmtoff;
1500 if ((before_gmtoff > 0 &&
1501 mytime < 0 && beforetime > 0) ||
1502 (before_gmtoff <= 0 &&
1503 mytime > 0 && beforetime < 0))
1505 aftertime = mytime - after_gmtoff;
1506 if ((after_gmtoff > 0 &&
1507 mytime < 0 && aftertime > 0) ||
1508 (after_gmtoff <= 0 &&
1509 mytime > 0 && aftertime < 0))
1513 * If both before or both after the boundary time, we know what to do
1515 if (beforetime <= boundary && aftertime < boundary)
1517 tm->tm_isdst = before_isdst;
1518 return -(int) before_gmtoff;
1520 if (beforetime > boundary && aftertime >= boundary)
1522 tm->tm_isdst = after_isdst;
1523 return -(int) after_gmtoff;
1527 * It's an invalid or ambiguous time due to timezone transition. Prefer
1528 * the standard-time interpretation.
1530 if (after_isdst == 0)
1532 tm->tm_isdst = after_isdst;
1533 return -(int) after_gmtoff;
1535 tm->tm_isdst = before_isdst;
1536 return -(int) before_gmtoff;
1539 /* Given date is out of range, so assume UTC */
1546 * Interpret parsed string as time fields only.
1547 * Returns 0 if successful, DTERR code if bogus input detected.
1549 * Note that support for time zone is here for
1550 * SQL92 TIME WITH TIME ZONE, but it reveals
1551 * bogosity with SQL92 date/time standards, since
1552 * we must infer a time zone from current time.
1553 * - thomas 2000-03-10
1554 * Allow specifying date to get a better time zone,
1555 * if time zones are allowed. - thomas 2001-12-26
1558 DecodeTimeOnly(char **field, int *ftype, int nf,
1559 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
1564 int ptype = 0; /* "prefix type" for ISO h04mm05s06 format */
1568 bool is2digits = FALSE;
1571 pg_tz *namedTz = NULL;
1578 /* don't know daylight savings time status apriori */
1584 for (i = 0; i < nf; i++)
1591 * Time zone not allowed? Then should not accept dates or time
1592 * zones no matter what else!
1595 return DTERR_BAD_FORMAT;
1597 /* Under limited circumstances, we will accept a date... */
1598 if (i == 0 && nf >= 2 &&
1599 (ftype[nf - 1] == DTK_DATE || ftype[1] == DTK_TIME))
1601 dterr = DecodeDate(field[i], fmask,
1602 &tmask, &is2digits, tm);
1606 /* otherwise, this is a time and/or time zone */
1609 if (isdigit((unsigned char) *field[i]))
1614 * Starts with a digit but we already have a time
1615 * field? Then we are in trouble with time already...
1617 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1618 return DTERR_BAD_FORMAT;
1621 * Should not get here and fail. Sanity check only...
1623 if ((cp = strchr(field[i], '-')) == NULL)
1624 return DTERR_BAD_FORMAT;
1626 /* Get the time zone from the end of the string */
1627 dterr = DecodeTimezone(cp, tzp);
1633 * Then read the rest of the field as a concatenated
1636 dterr = DecodeNumberField(strlen(field[i]), field[i],
1637 (fmask | DTK_DATE_M),
1648 namedTz = pg_tzset(field[i]);
1652 * We should return an error code instead of
1653 * ereport'ing directly, but then there is no way
1654 * to report the bad time zone name.
1657 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1658 errmsg("time zone \"%s\" not recognized",
1661 /* we'll apply the zone setting below */
1669 dterr = DecodeTime(field[i], (fmask | DTK_DATE_M),
1670 INTERVAL_FULL_RANGE,
1681 return DTERR_BAD_FORMAT;
1683 dterr = DecodeTimezone(field[i], &tz);
1694 * Was this an "ISO time" with embedded field labels? An
1695 * example is "h04m05s06" - thomas 2001-02-04
1702 /* Only accept a date under limited circumstances */
1710 return DTERR_BAD_FORMAT;
1716 val = strtoi(field[i], &cp, 10);
1717 if (errno == ERANGE)
1718 return DTERR_FIELD_OVERFLOW;
1721 * only a few kinds are allowed to have an embedded
1732 return DTERR_BAD_FORMAT;
1735 else if (*cp != '\0')
1736 return DTERR_BAD_FORMAT;
1742 tmask = DTK_M(YEAR);
1748 * already have a month and hour? then assume
1751 if ((fmask & DTK_M(MONTH)) != 0 &&
1752 (fmask & DTK_M(HOUR)) != 0)
1755 tmask = DTK_M(MINUTE);
1760 tmask = DTK_M(MONTH);
1771 tmask = DTK_M(HOUR);
1776 tmask = DTK_M(MINUTE);
1781 tmask = DTK_M(SECOND);
1784 dterr = ParseFractionalSecond(cp, fsec);
1787 tmask = DTK_ALL_SECS_M;
1793 dterr = DecodeTimezone(field[i], tzp);
1800 * previous field was a label for "julian date"?
1803 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1809 time = strtod(cp, &cp);
1810 if (*cp != '\0' || errno != 0)
1811 return DTERR_BAD_FORMAT;
1813 #ifdef HAVE_INT64_TIMESTAMP
1814 time *= USECS_PER_DAY;
1816 time *= SECS_PER_DAY;
1819 &tm->tm_hour, &tm->tm_min,
1821 tmask |= DTK_TIME_M;
1826 /* previous field was "t" for ISO time */
1827 dterr = DecodeNumberField(strlen(field[i]), field[i],
1828 (fmask | DTK_DATE_M),
1835 if (tmask != DTK_TIME_M)
1836 return DTERR_BAD_FORMAT;
1840 return DTERR_BAD_FORMAT;
1852 flen = strlen(field[i]);
1853 cp = strchr(field[i], '.');
1855 /* Embedded decimal? */
1859 * Under limited circumstances, we will accept a
1862 if (i == 0 && nf >= 2 && ftype[nf - 1] == DTK_DATE)
1864 dterr = DecodeDate(field[i], fmask,
1865 &tmask, &is2digits, tm);
1869 /* embedded decimal and several digits before? */
1870 else if (flen - strlen(cp) > 2)
1873 * Interpret as a concatenated date or time Set
1874 * the type field to allow decoding other fields
1875 * later. Example: 20011223 or 040506
1877 dterr = DecodeNumberField(flen, field[i],
1878 (fmask | DTK_DATE_M),
1886 return DTERR_BAD_FORMAT;
1890 dterr = DecodeNumberField(flen, field[i],
1891 (fmask | DTK_DATE_M),
1898 /* otherwise it is a single date/time field... */
1901 dterr = DecodeNumber(flen, field[i],
1903 (fmask | DTK_DATE_M),
1914 type = DecodeSpecial(i, field[i], &val);
1915 if (type == IGNORE_DTF)
1918 tmask = DTK_M(type);
1926 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1927 errmsg("date/time value \"current\" is no longer supported")));
1928 return DTERR_BAD_FORMAT;
1934 GetCurrentTimeUsec(tm, fsec, NULL);
1938 tmask = (DTK_TIME_M | DTK_M(TZ));
1947 return DTERR_BAD_FORMAT;
1955 * daylight savings time modifier (solves "MET DST"
1958 tmask |= DTK_M(DTZ);
1961 return DTERR_BAD_FORMAT;
1962 *tzp += val * MINS_PER_HOUR;
1968 * set mask for TZ here _or_ check for DTZ later when
1969 * getting default timezone
1974 return DTERR_BAD_FORMAT;
1975 *tzp = val * MINS_PER_HOUR;
1982 return DTERR_BAD_FORMAT;
1983 *tzp = val * MINS_PER_HOUR;
2007 * We will need one of the following fields:
2008 * DTK_NUMBER should be hhmmss.fff
2009 * DTK_TIME should be hh:mm:ss.fff
2010 * DTK_DATE should be hhmmss-zz
2013 (ftype[i + 1] != DTK_NUMBER &&
2014 ftype[i + 1] != DTK_TIME &&
2015 ftype[i + 1] != DTK_DATE))
2016 return DTERR_BAD_FORMAT;
2024 * Before giving up and declaring error, check to see
2025 * if it is an all-alpha timezone name.
2027 namedTz = pg_tzset(field[i]);
2029 return DTERR_BAD_FORMAT;
2030 /* we'll apply the zone setting below */
2035 return DTERR_BAD_FORMAT;
2040 return DTERR_BAD_FORMAT;
2044 return DTERR_BAD_FORMAT;
2046 } /* end loop over fields */
2048 /* do final checking/adjustment of Y/M/D fields */
2049 dterr = ValidateDate(fmask, is2digits, bc, tm);
2054 if (mer != HR24 && tm->tm_hour > 12)
2055 return DTERR_FIELD_OVERFLOW;
2056 if (mer == AM && tm->tm_hour == 12)
2058 else if (mer == PM && tm->tm_hour != 12)
2061 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2062 tm->tm_sec < 0 || tm->tm_sec > 60 || tm->tm_hour > 24 ||
2063 /* test for > 24:00:00 */
2064 #ifdef HAVE_INT64_TIMESTAMP
2065 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0 ||
2066 *fsec > INT64CONST(0))) ||
2067 *fsec < INT64CONST(0) || *fsec >= USECS_PER_SEC
2069 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0 ||
2071 *fsec < 0 || *fsec >= 1
2074 return DTERR_FIELD_OVERFLOW;
2076 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2077 return DTERR_BAD_FORMAT;
2080 * If we had a full timezone spec, compute the offset (we could not do it
2081 * before, because we may need the date to resolve DST status).
2083 if (namedTz != NULL)
2087 /* daylight savings time modifier disallowed with full TZ */
2088 if (fmask & DTK_M(DTZMOD))
2089 return DTERR_BAD_FORMAT;
2091 /* if non-DST zone, we do not need to know the date */
2092 if (pg_get_timezone_offset(namedTz, &gmtoff))
2094 *tzp = -(int) gmtoff;
2098 /* a date has to be specified */
2099 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2100 return DTERR_BAD_FORMAT;
2101 *tzp = DetermineTimeZoneOffset(tm, namedTz);
2105 /* timezone not specified? then find local timezone if possible */
2106 if (tzp != NULL && !(fmask & DTK_M(TZ)))
2112 * daylight savings time modifier but no standard timezone? then error
2114 if (fmask & DTK_M(DTZMOD))
2115 return DTERR_BAD_FORMAT;
2117 if ((fmask & DTK_DATE_M) == 0)
2118 GetCurrentDateTime(tmp);
2121 tmp->tm_year = tm->tm_year;
2122 tmp->tm_mon = tm->tm_mon;
2123 tmp->tm_mday = tm->tm_mday;
2125 tmp->tm_hour = tm->tm_hour;
2126 tmp->tm_min = tm->tm_min;
2127 tmp->tm_sec = tm->tm_sec;
2128 *tzp = DetermineTimeZoneOffset(tmp, session_timezone);
2129 tm->tm_isdst = tmp->tm_isdst;
2136 * Decode date string which includes delimiters.
2137 * Return 0 if okay, a DTERR code if not.
2139 * str: field to be parsed
2140 * fmask: bitmask for field types already seen
2141 * *tmask: receives bitmask for fields found here
2142 * *is2digits: set to TRUE if we find 2-digit year
2143 * *tm: field values are stored into appropriate members of this struct
2146 DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
2154 bool haveTextMonth = FALSE;
2158 char *field[MAXDATEFIELDS];
2162 /* parse this string... */
2163 while (*str != '\0' && nf < MAXDATEFIELDS)
2165 /* skip field separators */
2166 while (!isalnum((unsigned char) *str))
2170 if (isdigit((unsigned char) *str))
2172 while (isdigit((unsigned char) *str))
2175 else if (isalpha((unsigned char) *str))
2177 while (isalpha((unsigned char) *str))
2181 /* Just get rid of any non-digit, non-alpha characters... */
2187 /* look first for text fields, since that will be unambiguous month */
2188 for (i = 0; i < nf; i++)
2190 if (isalpha((unsigned char) *field[i]))
2192 type = DecodeSpecial(i, field[i], &val);
2193 if (type == IGNORE_DTF)
2196 dmask = DTK_M(type);
2201 haveTextMonth = TRUE;
2205 return DTERR_BAD_FORMAT;
2208 return DTERR_BAD_FORMAT;
2213 /* mark this field as being completed */
2218 /* now pick up remaining numeric fields */
2219 for (i = 0; i < nf; i++)
2221 if (field[i] == NULL)
2224 if ((len = strlen(field[i])) <= 0)
2225 return DTERR_BAD_FORMAT;
2227 dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2234 return DTERR_BAD_FORMAT;
2240 if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
2241 return DTERR_BAD_FORMAT;
2243 /* validation of the field values must wait until ValidateDate() */
2249 * Check valid year/month/day values, handle BC and DOY cases
2250 * Return 0 if okay, a DTERR code if not.
2253 ValidateDate(int fmask, bool is2digits, bool bc, struct pg_tm * tm)
2255 if (fmask & DTK_M(YEAR))
2259 /* there is no year zero in AD/BC notation */
2260 if (tm->tm_year <= 0)
2261 return DTERR_FIELD_OVERFLOW;
2262 /* internally, we represent 1 BC as year zero, 2 BC as -1, etc */
2263 tm->tm_year = -(tm->tm_year - 1);
2267 /* process 1 or 2-digit input as 1970-2069 AD, allow '0' and '00' */
2268 if (tm->tm_year < 0) /* just paranoia */
2269 return DTERR_FIELD_OVERFLOW;
2270 if (tm->tm_year < 70)
2271 tm->tm_year += 2000;
2272 else if (tm->tm_year < 100)
2273 tm->tm_year += 1900;
2277 /* there is no year zero in AD/BC notation */
2278 if (tm->tm_year <= 0)
2279 return DTERR_FIELD_OVERFLOW;
2283 /* now that we have correct year, decode DOY */
2284 if (fmask & DTK_M(DOY))
2286 j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
2287 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2290 /* check for valid month */
2291 if (fmask & DTK_M(MONTH))
2293 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
2294 return DTERR_MD_FIELD_OVERFLOW;
2297 /* minimal check for valid day */
2298 if (fmask & DTK_M(DAY))
2300 if (tm->tm_mday < 1 || tm->tm_mday > 31)
2301 return DTERR_MD_FIELD_OVERFLOW;
2304 if ((fmask & DTK_DATE_M) == DTK_DATE_M)
2307 * Check for valid day of month, now that we know for sure the month
2308 * and year. Note we don't use MD_FIELD_OVERFLOW here, since it seems
2309 * unlikely that "Feb 29" is a YMD-order error.
2311 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2312 return DTERR_FIELD_OVERFLOW;
2320 * Decode time string which includes delimiters.
2321 * Return 0 if okay, a DTERR code if not.
2323 * Only check the lower limit on hours, since this same code can be
2324 * used to represent time spans.
2327 DecodeTime(char *str, int fmask, int range,
2328 int *tmask, struct pg_tm * tm, fsec_t *fsec)
2333 *tmask = DTK_TIME_M;
2336 tm->tm_hour = strtoi(str, &cp, 10);
2337 if (errno == ERANGE)
2338 return DTERR_FIELD_OVERFLOW;
2340 return DTERR_BAD_FORMAT;
2342 tm->tm_min = strtoi(cp + 1, &cp, 10);
2343 if (errno == ERANGE)
2344 return DTERR_FIELD_OVERFLOW;
2349 /* If it's a MINUTE TO SECOND interval, take 2 fields as being mm:ss */
2350 if (range == (INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND)))
2352 tm->tm_sec = tm->tm_min;
2353 tm->tm_min = tm->tm_hour;
2357 else if (*cp == '.')
2359 /* always assume mm:ss.sss is MINUTE TO SECOND */
2360 dterr = ParseFractionalSecond(cp, fsec);
2363 tm->tm_sec = tm->tm_min;
2364 tm->tm_min = tm->tm_hour;
2367 else if (*cp == ':')
2370 tm->tm_sec = strtoi(cp + 1, &cp, 10);
2371 if (errno == ERANGE)
2372 return DTERR_FIELD_OVERFLOW;
2375 else if (*cp == '.')
2377 dterr = ParseFractionalSecond(cp, fsec);
2382 return DTERR_BAD_FORMAT;
2385 return DTERR_BAD_FORMAT;
2387 /* do a sanity check */
2388 #ifdef HAVE_INT64_TIMESTAMP
2389 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2390 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < INT64CONST(0) ||
2391 *fsec >= USECS_PER_SEC)
2392 return DTERR_FIELD_OVERFLOW;
2394 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2395 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < 0 || *fsec >= 1)
2396 return DTERR_FIELD_OVERFLOW;
2404 * Interpret plain numeric field as a date value in context.
2405 * Return 0 if okay, a DTERR code if not.
2408 DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask,
2409 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2418 val = strtoi(str, &cp, 10);
2419 if (errno == ERANGE)
2420 return DTERR_FIELD_OVERFLOW;
2422 return DTERR_BAD_FORMAT;
2427 * More than two digits before decimal point? Then could be a date or
2428 * a run-together time: 2001.360 20011225 040506.789
2432 dterr = DecodeNumberField(flen, str,
2433 (fmask | DTK_DATE_M),
2441 dterr = ParseFractionalSecond(cp, fsec);
2445 else if (*cp != '\0')
2446 return DTERR_BAD_FORMAT;
2448 /* Special case for day of year */
2449 if (flen == 3 && (fmask & DTK_DATE_M) == DTK_M(YEAR) && val >= 1 &&
2452 *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2454 /* tm_mon and tm_mday can't actually be set yet ... */
2458 /* Switch based on what we have so far */
2459 switch (fmask & DTK_DATE_M)
2464 * Nothing so far; make a decision about what we think the input
2465 * is. There used to be lots of heuristics here, but the
2466 * consensus now is to be paranoid. It *must* be either
2467 * YYYY-MM-DD (with a more-than-two-digit year field), or the
2468 * field order defined by DateOrder.
2470 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2472 *tmask = DTK_M(YEAR);
2475 else if (DateOrder == DATEORDER_DMY)
2477 *tmask = DTK_M(DAY);
2482 *tmask = DTK_M(MONTH);
2488 /* Must be at second field of YY-MM-DD */
2489 *tmask = DTK_M(MONTH);
2493 case (DTK_M(MONTH)):
2497 * We are at the first numeric field of a date that included a
2498 * textual month name. We want to support the variants
2499 * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2500 * inputs. We will also accept MON-DD-YY or DD-MON-YY in
2501 * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2503 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2505 *tmask = DTK_M(YEAR);
2510 *tmask = DTK_M(DAY);
2516 /* Must be at second field of MM-DD-YY */
2517 *tmask = DTK_M(DAY);
2522 case (DTK_M(YEAR) | DTK_M(MONTH)):
2525 /* Need to accept DD-MON-YYYY even in YMD mode */
2526 if (flen >= 3 && *is2digits)
2528 /* Guess that first numeric field is day was wrong */
2529 *tmask = DTK_M(DAY); /* YEAR is already set */
2530 tm->tm_mday = tm->tm_year;
2536 *tmask = DTK_M(DAY);
2542 /* Must be at third field of YY-MM-DD */
2543 *tmask = DTK_M(DAY);
2549 /* Must be at second field of DD-MM-YY */
2550 *tmask = DTK_M(MONTH);
2554 case (DTK_M(MONTH) | DTK_M(DAY)):
2555 /* Must be at third field of DD-MM-YY or MM-DD-YY */
2556 *tmask = DTK_M(YEAR);
2560 case (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY)):
2561 /* we have all the date, so it must be a time field */
2562 dterr = DecodeNumberField(flen, str, fmask,
2570 /* Anything else is bogus input */
2571 return DTERR_BAD_FORMAT;
2575 * When processing a year field, mark it for adjustment if it's only one
2578 if (*tmask == DTK_M(YEAR))
2579 *is2digits = (flen <= 2);
2585 /* DecodeNumberField()
2586 * Interpret numeric string as a concatenated date or time field.
2587 * Return a DTK token (>= 0) if successful, a DTERR code (< 0) if not.
2589 * Use the context of previously decoded fields to help with
2590 * the interpretation.
2593 DecodeNumberField(int len, char *str, int fmask,
2594 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2599 * Have a decimal point? Then this is a date or something with a seconds
2602 if ((cp = strchr(str, '.')) != NULL)
2605 * Can we use ParseFractionalSecond here? Not clear whether
2606 * trailing junk should be rejected ...
2611 frac = strtod(cp, NULL);
2613 return DTERR_BAD_FORMAT;
2614 #ifdef HAVE_INT64_TIMESTAMP
2615 *fsec = rint(frac * 1000000);
2619 /* Now truncate off the fraction for further processing */
2623 /* No decimal point and no complete date yet? */
2624 else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2629 *tmask = DTK_DATE_M;
2631 tm->tm_mday = atoi(str + 6);
2633 tm->tm_mon = atoi(str + 4);
2635 tm->tm_year = atoi(str + 0);
2642 *tmask = DTK_DATE_M;
2643 tm->tm_mday = atoi(str + 4);
2645 tm->tm_mon = atoi(str + 2);
2647 tm->tm_year = atoi(str + 0);
2654 /* not all time fields are specified? */
2655 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2660 *tmask = DTK_TIME_M;
2661 tm->tm_sec = atoi(str + 4);
2663 tm->tm_min = atoi(str + 2);
2665 tm->tm_hour = atoi(str + 0);
2672 *tmask = DTK_TIME_M;
2674 tm->tm_min = atoi(str + 2);
2676 tm->tm_hour = atoi(str + 0);
2682 return DTERR_BAD_FORMAT;
2687 * Interpret string as a numeric timezone.
2689 * Return 0 if okay (and set *tzp), a DTERR code if not okay.
2691 * NB: this must *not* ereport on failure; see commands/variable.c.
2693 * Note: we allow timezone offsets up to 13:59. There are places that
2694 * use +1300 summer time.
2697 DecodeTimezone(char *str, int *tzp)
2705 /* leading character must be "+" or "-" */
2706 if (*str != '+' && *str != '-')
2707 return DTERR_BAD_FORMAT;
2710 hr = strtoi(str + 1, &cp, 10);
2711 if (errno == ERANGE)
2712 return DTERR_TZDISP_OVERFLOW;
2714 /* explicit delimiter? */
2718 min = strtoi(cp + 1, &cp, 10);
2719 if (errno == ERANGE)
2720 return DTERR_TZDISP_OVERFLOW;
2724 sec = strtoi(cp + 1, &cp, 10);
2725 if (errno == ERANGE)
2726 return DTERR_TZDISP_OVERFLOW;
2729 /* otherwise, might have run things together... */
2730 else if (*cp == '\0' && strlen(str) > 3)
2734 /* we could, but don't, support a run-together hhmmss format */
2739 if (hr < 0 || hr > 14)
2740 return DTERR_TZDISP_OVERFLOW;
2741 if (min < 0 || min >= 60)
2742 return DTERR_TZDISP_OVERFLOW;
2743 if (sec < 0 || sec >= 60)
2744 return DTERR_TZDISP_OVERFLOW;
2746 tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
2753 return DTERR_BAD_FORMAT;
2759 * Decode text string using lookup table.
2761 * Implement a cache lookup since it is likely that dates
2762 * will be related in format.
2764 * NB: this must *not* ereport on failure;
2765 * see commands/variable.c.
2768 DecodeSpecial(int field, char *lowtoken, int *val)
2773 tp = datecache[field];
2774 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
2776 tp = datebsearch(lowtoken, timezonetktbl, sztimezonetktbl);
2778 tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
2782 type = UNKNOWN_FIELD;
2787 datecache[field] = tp;
2809 * Zero out a pg_tm and associated fsec_t
2812 ClearPgTm(struct pg_tm *tm, fsec_t *fsec)
2825 * Interpret previously parsed fields for general time interval.
2826 * Returns 0 if successful, DTERR code if bogus input detected.
2827 * dtype, tm, fsec are output parameters.
2829 * Allow "date" field DTK_DATE since this could be just
2830 * an unsigned floating point number. - thomas 1997-11-16
2832 * Allow ISO-style time span, with implicit units on number of days
2833 * preceding an hh:mm:ss field. - thomas 1998-04-30
2836 DecodeInterval(char **field, int *ftype, int nf, int range,
2837 int *dtype, struct pg_tm * tm, fsec_t *fsec)
2839 bool is_before = FALSE;
2853 /* read through list backwards to pick up units before values */
2854 for (i = nf - 1; i >= 0; i--)
2859 dterr = DecodeTime(field[i], fmask, range,
2869 * Timezone is a token with a leading sign character and
2870 * at least one digit; there could be ':', '.', '-'
2871 * embedded in it as well.
2873 Assert(*field[i] == '-' || *field[i] == '+');
2876 * Try for hh:mm or hh:mm:ss. If not, fall through to
2877 * DTK_NUMBER case, which can handle signed float numbers
2878 * and signed year-month values.
2880 if (strchr(field[i] + 1, ':') != NULL &&
2881 DecodeTime(field[i] + 1, fmask, INTERVAL_FULL_RANGE,
2882 &tmask, tm, fsec) == 0)
2884 if (*field[i] == '-')
2886 /* flip the sign on all fields */
2887 tm->tm_hour = -tm->tm_hour;
2888 tm->tm_min = -tm->tm_min;
2889 tm->tm_sec = -tm->tm_sec;
2894 * Set the next type to be a day, if units are not
2895 * specified. This handles the case of '1 +02:03' since we
2896 * are reading right to left.
2906 if (type == IGNORE_DTF)
2908 /* use typmod to decide what rightmost field is */
2911 case INTERVAL_MASK(YEAR):
2914 case INTERVAL_MASK(MONTH):
2915 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
2918 case INTERVAL_MASK(DAY):
2921 case INTERVAL_MASK(HOUR):
2922 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
2923 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
2924 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2927 case INTERVAL_MASK(MINUTE):
2928 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
2931 case INTERVAL_MASK(SECOND):
2932 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2933 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2943 val = strtoi(field[i], &cp, 10);
2944 if (errno == ERANGE)
2945 return DTERR_FIELD_OVERFLOW;
2949 /* SQL "years-months" syntax */
2952 val2 = strtoi(cp + 1, &cp, 10);
2953 if (errno == ERANGE || val2 < 0 || val2 >= MONTHS_PER_YEAR)
2954 return DTERR_FIELD_OVERFLOW;
2956 return DTERR_BAD_FORMAT;
2958 if (*field[i] == '-')
2960 val = val * MONTHS_PER_YEAR + val2;
2963 else if (*cp == '.')
2966 fval = strtod(cp, &cp);
2967 if (*cp != '\0' || errno != 0)
2968 return DTERR_BAD_FORMAT;
2970 if (*field[i] == '-')
2973 else if (*cp == '\0')
2976 return DTERR_BAD_FORMAT;
2978 tmask = 0; /* DTK_M(type); */
2983 #ifdef HAVE_INT64_TIMESTAMP
2984 *fsec += rint(val + fval);
2986 *fsec += (val + fval) * 1e-6;
2988 tmask = DTK_M(MICROSECOND);
2992 #ifdef HAVE_INT64_TIMESTAMP
2993 *fsec += rint((val + fval) * 1000);
2995 *fsec += (val + fval) * 1e-3;
2997 tmask = DTK_M(MILLISECOND);
3002 #ifdef HAVE_INT64_TIMESTAMP
3003 *fsec += rint(fval * 1000000);
3009 * If any subseconds were specified, consider this
3010 * microsecond and millisecond input as well.
3013 tmask = DTK_M(SECOND);
3015 tmask = DTK_ALL_SECS_M;
3020 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3021 tmask = DTK_M(MINUTE);
3026 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3027 tmask = DTK_M(HOUR);
3033 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3034 tmask = (fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY);
3038 tm->tm_mday += val * 7;
3039 AdjustFractDays(fval, tm, fsec, 7);
3040 tmask = (fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY);
3045 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3046 tmask = DTK_M(MONTH);
3052 tm->tm_mon += fval * MONTHS_PER_YEAR;
3053 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
3057 tm->tm_year += val * 10;
3059 tm->tm_mon += fval * MONTHS_PER_YEAR * 10;
3060 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
3064 tm->tm_year += val * 100;
3066 tm->tm_mon += fval * MONTHS_PER_YEAR * 100;
3067 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
3070 case DTK_MILLENNIUM:
3071 tm->tm_year += val * 1000;
3073 tm->tm_mon += fval * MONTHS_PER_YEAR * 1000;
3074 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
3078 return DTERR_BAD_FORMAT;
3084 type = DecodeUnits(i, field[i], &val);
3085 if (type == IGNORE_DTF)
3088 tmask = 0; /* DTK_M(type); */
3101 tmask = (DTK_DATE_M || DTK_TIME_M);
3106 return DTERR_BAD_FORMAT;
3111 return DTERR_BAD_FORMAT;
3115 return DTERR_BAD_FORMAT;
3119 /* ensure that at least one time field has been found */
3121 return DTERR_BAD_FORMAT;
3123 /* ensure fractional seconds are fractional */
3128 #ifdef HAVE_INT64_TIMESTAMP
3129 sec = *fsec / USECS_PER_SEC;
3130 *fsec -= sec * USECS_PER_SEC;
3132 TMODULO(*fsec, sec, 1.0);
3138 * The SQL standard defines the interval literal
3140 * to mean "negative 1 days and negative 1 hours", while Postgres
3141 * traditionally treats this as meaning "negative 1 days and positive
3142 * 1 hours". In SQL_STANDARD intervalstyle, we apply the leading sign
3143 * to all fields if there are no other explicit signs.
3145 * We leave the signs alone if there are additional explicit signs.
3146 * This protects us against misinterpreting postgres-style dump output,
3147 * since the postgres-style output code has always put an explicit sign on
3148 * all fields following a negative field. But note that SQL-spec output
3149 * is ambiguous and can be misinterpreted on load! (So it's best practice
3150 * to dump in postgres style, not SQL style.)
3153 if (IntervalStyle == INTSTYLE_SQL_STANDARD && *field[0] == '-')
3155 /* Check for additional explicit signs */
3156 bool more_signs = false;
3158 for (i = 1; i < nf; i++)
3160 if (*field[i] == '-' || *field[i] == '+')
3170 * Rather than re-determining which field was field[0], just
3171 * force 'em all negative.
3176 tm->tm_sec = -tm->tm_sec;
3178 tm->tm_min = -tm->tm_min;
3179 if (tm->tm_hour > 0)
3180 tm->tm_hour = -tm->tm_hour;
3181 if (tm->tm_mday > 0)
3182 tm->tm_mday = -tm->tm_mday;
3184 tm->tm_mon = -tm->tm_mon;
3185 if (tm->tm_year > 0)
3186 tm->tm_year = -tm->tm_year;
3190 /* finally, AGO negates everything */
3194 tm->tm_sec = -tm->tm_sec;
3195 tm->tm_min = -tm->tm_min;
3196 tm->tm_hour = -tm->tm_hour;
3197 tm->tm_mday = -tm->tm_mday;
3198 tm->tm_mon = -tm->tm_mon;
3199 tm->tm_year = -tm->tm_year;
3207 * Helper functions to avoid duplicated code in DecodeISO8601Interval.
3209 * Parse a decimal value and break it into integer and fractional parts.
3210 * Returns 0 or DTERR code.
3213 ParseISO8601Number(char *str, char **endptr, int *ipart, double *fpart)
3217 if (!(isdigit((unsigned char) *str) || *str == '-' || *str == '.'))
3218 return DTERR_BAD_FORMAT;
3220 val = strtod(str, endptr);
3221 /* did we not see anything that looks like a double? */
3222 if (*endptr == str || errno != 0)
3223 return DTERR_BAD_FORMAT;
3224 /* watch out for overflow */
3225 if (val < INT_MIN || val > INT_MAX)
3226 return DTERR_FIELD_OVERFLOW;
3227 /* be very sure we truncate towards zero (cf dtrunc()) */
3229 *ipart = (int) floor(val);
3231 *ipart = (int) -floor(-val);
3232 *fpart = val - *ipart;
3237 * Determine number of integral digits in a valid ISO 8601 number field
3238 * (we should ignore sign and any fraction part)
3241 ISO8601IntegerWidth(char *fieldstart)
3243 /* We might have had a leading '-' */
3244 if (*fieldstart == '-')
3246 return strspn(fieldstart, "0123456789");
3250 /* DecodeISO8601Interval()
3251 * Decode an ISO 8601 time interval of the "format with designators"
3252 * (section 4.4.3.2) or "alternative format" (section 4.4.3.3)
3253 * Examples: P1D for 1 day
3255 * P2Y6M7DT1H30M for 2 years, 6 months, 7 days 1 hour 30 min
3256 * P0002-06-07T01:30:00 the same value in alternative format
3258 * Returns 0 if successful, DTERR code if bogus input detected.
3259 * Note: error code should be DTERR_BAD_FORMAT if input doesn't look like
3260 * ISO8601, otherwise this could cause unexpected error messages.
3261 * dtype, tm, fsec are output parameters.
3263 * A couple exceptions from the spec:
3264 * - a week field ('W') may coexist with other units
3265 * - allows decimals in fields other than the least significant unit.
3268 DecodeISO8601Interval(char *str,
3269 int *dtype, struct pg_tm * tm, fsec_t *fsec)
3271 bool datepart = true;
3272 bool havefield = false;
3275 ClearPgTm(tm, fsec);
3277 if (strlen(str) < 2 || str[0] != 'P')
3278 return DTERR_BAD_FORMAT;
3289 if (*str == 'T') /* T indicates the beginning of the time part */
3298 dterr = ParseISO8601Number(str, &str, &val, &fval);
3303 * Note: we could step off the end of the string here. Code below
3304 * *must* exit the loop if unit == '\0'.
3310 switch (unit) /* before T: Y M W D */
3314 tm->tm_mon += (fval * 12);
3318 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3321 tm->tm_mday += val * 7;
3322 AdjustFractDays(fval, tm, fsec, 7);
3326 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3328 case 'T': /* ISO 8601 4.4.3.3 Alternative Format / Basic */
3330 if (ISO8601IntegerWidth(fieldstart) == 8 && !havefield)
3332 tm->tm_year += val / 10000;
3333 tm->tm_mon += (val / 100) % 100;
3334 tm->tm_mday += val % 100;
3335 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3342 /* Else fall through to extended alternative format */
3343 case '-': /* ISO 8601 4.4.3.3 Alternative Format, Extended */
3345 return DTERR_BAD_FORMAT;
3348 tm->tm_mon += (fval * 12);
3358 dterr = ParseISO8601Number(str, &str, &val, &fval);
3362 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3372 return DTERR_BAD_FORMAT;
3375 dterr = ParseISO8601Number(str, &str, &val, &fval);
3379 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3388 return DTERR_BAD_FORMAT;
3390 /* not a valid date unit suffix */
3391 return DTERR_BAD_FORMAT;
3396 switch (unit) /* after T: H M S */
3400 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3404 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3408 AdjustFractSeconds(fval, tm, fsec, 1);
3410 case '\0': /* ISO 8601 4.4.3.3 Alternative Format */
3411 if (ISO8601IntegerWidth(fieldstart) == 6 && !havefield)
3413 tm->tm_hour += val / 10000;
3414 tm->tm_min += (val / 100) % 100;
3415 tm->tm_sec += val % 100;
3416 AdjustFractSeconds(fval, tm, fsec, 1);
3419 /* Else fall through to extended alternative format */
3420 case ':': /* ISO 8601 4.4.3.3 Alternative Format, Extended */
3422 return DTERR_BAD_FORMAT;
3425 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3429 dterr = ParseISO8601Number(str, &str, &val, &fval);
3433 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3437 return DTERR_BAD_FORMAT;
3440 dterr = ParseISO8601Number(str, &str, &val, &fval);
3444 AdjustFractSeconds(fval, tm, fsec, 1);
3447 return DTERR_BAD_FORMAT;
3450 /* not a valid time unit suffix */
3451 return DTERR_BAD_FORMAT;
3463 * Decode text string using lookup table.
3464 * This routine supports time interval decoding
3465 * (hence, it need not recognize timezone names).
3468 DecodeUnits(int field, char *lowtoken, int *val)
3473 tp = deltacache[field];
3474 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3476 tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
3480 type = UNKNOWN_FIELD;
3485 deltacache[field] = tp;
3487 if (type == TZ || type == DTZ)
3494 } /* DecodeUnits() */
3497 * Report an error detected by one of the datetime input processing routines.
3499 * dterr is the error code, str is the original input string, datatype is
3500 * the name of the datatype we were trying to accept.
3502 * Note: it might seem useless to distinguish DTERR_INTERVAL_OVERFLOW and
3503 * DTERR_TZDISP_OVERFLOW from DTERR_FIELD_OVERFLOW, but SQL99 mandates three
3504 * separate SQLSTATE codes, so ...
3507 DateTimeParseError(int dterr, const char *str, const char *datatype)
3511 case DTERR_FIELD_OVERFLOW:
3513 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3514 errmsg("date/time field value out of range: \"%s\"",
3517 case DTERR_MD_FIELD_OVERFLOW:
3518 /* <nanny>same as above, but add hint about DateStyle</nanny> */
3520 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3521 errmsg("date/time field value out of range: \"%s\"",
3523 errhint("Perhaps you need a different \"datestyle\" setting.")));
3525 case DTERR_INTERVAL_OVERFLOW:
3527 (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
3528 errmsg("interval field value out of range: \"%s\"",
3531 case DTERR_TZDISP_OVERFLOW:
3533 (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
3534 errmsg("time zone displacement out of range: \"%s\"",
3537 case DTERR_BAD_FORMAT:
3540 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
3541 errmsg("invalid input syntax for type %s: \"%s\"",
3548 * Binary search -- from Knuth (6.2.1) Algorithm B. Special case like this
3549 * is WAY faster than the generic bsearch().
3551 static const datetkn *
3552 datebsearch(const char *key, const datetkn *base, int nel)
3554 const datetkn *last = base + nel - 1,
3558 while (last >= base)
3560 position = base + ((last - base) >> 1);
3561 result = key[0] - position->token[0];
3564 result = strncmp(key, position->token, TOKMAXLEN);
3569 last = position - 1;
3571 base = position + 1;
3577 * Append representation of a numeric timezone offset to str.
3580 EncodeTimezone(char *str, int tz, int style)
3587 min = sec / SECS_PER_MINUTE;
3588 sec -= min * SECS_PER_MINUTE;
3589 hour = min / MINS_PER_HOUR;
3590 min -= hour * MINS_PER_HOUR;
3593 /* TZ is negated compared to sign we wish to display ... */
3594 *str++ = (tz <= 0 ? '+' : '-');
3597 sprintf(str, "%02d:%02d:%02d", hour, min, sec);
3598 else if (min != 0 || style == USE_XSD_DATES)
3599 sprintf(str, "%02d:%02d", hour, min);
3601 sprintf(str, "%02d", hour);
3605 * Encode date as local time.
3608 EncodeDateOnly(struct pg_tm * tm, int style, char *str)
3610 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
3617 /* compatible with ISO date formats */
3618 if (tm->tm_year > 0)
3619 sprintf(str, "%04d-%02d-%02d",
3620 tm->tm_year, tm->tm_mon, tm->tm_mday);
3622 sprintf(str, "%04d-%02d-%02d %s",
3623 -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
3627 /* compatible with Oracle/Ingres date formats */
3628 if (DateOrder == DATEORDER_DMY)
3629 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3631 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3632 if (tm->tm_year > 0)
3633 sprintf(str + 5, "/%04d", tm->tm_year);
3635 sprintf(str + 5, "/%04d %s", -(tm->tm_year - 1), "BC");
3638 case USE_GERMAN_DATES:
3639 /* German-style date format */
3640 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3641 if (tm->tm_year > 0)
3642 sprintf(str + 5, ".%04d", tm->tm_year);
3644 sprintf(str + 5, ".%04d %s", -(tm->tm_year - 1), "BC");
3647 case USE_POSTGRES_DATES:
3649 /* traditional date-only style for Postgres */
3650 if (DateOrder == DATEORDER_DMY)
3651 sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
3653 sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
3654 if (tm->tm_year > 0)
3655 sprintf(str + 5, "-%04d", tm->tm_year);
3657 sprintf(str + 5, "-%04d %s", -(tm->tm_year - 1), "BC");
3662 } /* EncodeDateOnly() */
3666 * Encode time fields only.
3669 EncodeTimeOnly(struct pg_tm * tm, fsec_t fsec, int *tzp, int style, char *str)
3671 if (tm->tm_hour < 0 || tm->tm_hour > HOURS_PER_DAY)
3674 sprintf(str, "%02d:%02d:", tm->tm_hour, tm->tm_min);
3677 AppendSeconds(str, tm->tm_sec, fsec, MAX_TIME_PRECISION, true);
3680 EncodeTimezone(str, *tzp, style);
3683 } /* EncodeTimeOnly() */
3687 * Encode date and time interpreted as local time.
3688 * Support several date styles:
3689 * Postgres - day mon hh:mm:ss yyyy tz
3690 * SQL - mm/dd/yyyy hh:mm:ss.ss tz
3691 * ISO - yyyy-mm-dd hh:mm:ss+/-tz
3692 * German - dd.mm.yyyy hh:mm:ss tz
3693 * XSD - yyyy-mm-ddThh:mm:ss.ss+/-tz
3694 * Variants (affects order of month and day for Postgres and SQL styles):
3696 * European - dd/mm/yyyy
3699 EncodeDateTime(struct pg_tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, char *str)
3704 * Why are we checking only the month field? Change this to an assert...
3705 * if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR) return -1;
3707 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3713 /* Compatible with ISO-8601 date formats */
3715 if (style == USE_ISO_DATES)
3716 sprintf(str, "%04d-%02d-%02d %02d:%02d:",
3717 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3718 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3720 sprintf(str, "%04d-%02d-%02dT%02d:%02d:",
3721 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3722 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3724 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3727 * tzp == NULL indicates that we don't want *any* time zone info
3728 * in the output string. *tzn != NULL indicates that we have alpha
3729 * time zone info available. tm_isdst != -1 indicates that we have
3730 * a valid time zone translation.
3732 if (tzp != NULL && tm->tm_isdst >= 0)
3733 EncodeTimezone(str, *tzp, style);
3735 if (tm->tm_year <= 0)
3736 sprintf(str + strlen(str), " BC");
3740 /* Compatible with Oracle/Ingres date formats */
3742 if (DateOrder == DATEORDER_DMY)
3743 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3745 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3747 sprintf(str + 5, "/%04d %02d:%02d:",
3748 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3749 tm->tm_hour, tm->tm_min);
3751 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3753 if (tzp != NULL && tm->tm_isdst >= 0)
3756 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3758 EncodeTimezone(str, *tzp, style);
3761 if (tm->tm_year <= 0)
3762 sprintf(str + strlen(str), " BC");
3765 case USE_GERMAN_DATES:
3766 /* German variant on European style */
3768 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3770 sprintf(str + 5, ".%04d %02d:%02d:",
3771 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3772 tm->tm_hour, tm->tm_min);
3774 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3776 if (tzp != NULL && tm->tm_isdst >= 0)
3779 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3781 EncodeTimezone(str, *tzp, style);
3784 if (tm->tm_year <= 0)
3785 sprintf(str + strlen(str), " BC");
3788 case USE_POSTGRES_DATES:
3790 /* Backward-compatible with traditional Postgres abstime dates */
3792 day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3793 tm->tm_wday = j2day(day);
3795 strncpy(str, days[tm->tm_wday], 3);
3796 strcpy(str + 3, " ");
3798 if (DateOrder == DATEORDER_DMY)
3799 sprintf(str + 4, "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
3801 sprintf(str + 4, "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);
3803 sprintf(str + 10, " %02d:%02d:", tm->tm_hour, tm->tm_min);
3805 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3807 sprintf(str + strlen(str), " %04d",
3808 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1));
3810 if (tzp != NULL && tm->tm_isdst >= 0)
3813 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3817 * We have a time zone, but no string version. Use the
3818 * numeric form, but be sure to include a leading space to
3819 * avoid formatting something which would be rejected by
3820 * the date/time parser later. - thomas 2001-10-19
3822 sprintf(str + strlen(str), " ");
3823 EncodeTimezone(str, *tzp, style);
3827 if (tm->tm_year <= 0)
3828 sprintf(str + strlen(str), " BC");
3837 * Helper functions to avoid duplicated code in EncodeInterval.
3840 /* Append an ISO-8601-style interval field, but only if value isn't zero */
3842 AddISO8601IntPart(char *cp, int value, char units)
3846 sprintf(cp, "%d%c", value, units);
3847 return cp + strlen(cp);
3850 /* Append a postgres-style interval field, but only if value isn't zero */
3852 AddPostgresIntPart(char *cp, int value, const char *units,
3853 bool *is_zero, bool *is_before)
3857 sprintf(cp, "%s%s%d %s%s",
3858 (!*is_zero) ? " " : "",
3859 (*is_before && value > 0) ? "+" : "",
3862 (value != 1) ? "s" : "");
3864 * Each nonzero field sets is_before for (only) the next one. This is
3865 * a tad bizarre but it's how it worked before...
3867 *is_before = (value < 0);
3869 return cp + strlen(cp);
3872 /* Append a verbose-style interval field, but only if value isn't zero */
3874 AddVerboseIntPart(char *cp, int value, const char *units,
3875 bool *is_zero, bool *is_before)
3879 /* first nonzero value sets is_before */
3882 *is_before = (value < 0);
3885 else if (*is_before)
3887 sprintf(cp, " %d %s%s", value, units, (value == 1) ? "" : "s");
3889 return cp + strlen(cp);
3894 * Interpret time structure as a delta time and convert to string.
3896 * Support "traditional Postgres" and ISO-8601 styles.
3897 * Actually, afaik ISO does not address time interval formatting,
3898 * but this looks similar to the spec for absolute date/time.
3899 * - thomas 1998-04-30
3901 * Actually, afaik, ISO 8601 does specify formats for "time
3902 * intervals...[of the]...format with time-unit designators", which
3903 * are pretty ugly. The format looks something like
3904 * P1Y1M1DT1H1M1.12345S
3905 * but useful for exchanging data with computers instead of humans.
3908 * And ISO's SQL 2008 standard specifies standards for
3909 * "year-month literal"s (that look like '2-3') and
3910 * "day-time literal"s (that look like ('4 5:6:7')
3913 EncodeInterval(struct pg_tm * tm, fsec_t fsec, int style, char *str)
3916 int year = tm->tm_year;
3917 int mon = tm->tm_mon;
3918 int mday = tm->tm_mday;
3919 int hour = tm->tm_hour;
3920 int min = tm->tm_min;
3921 int sec = tm->tm_sec;
3922 bool is_before = FALSE;
3923 bool is_zero = TRUE;
3926 * The sign of year and month are guaranteed to match, since they are
3927 * stored internally as "month". But we'll need to check for is_before and
3928 * is_zero when determining the signs of day and hour/minute/seconds
3933 /* SQL Standard interval format */
3934 case INTSTYLE_SQL_STANDARD:
3936 bool has_negative = year < 0 || mon < 0 ||
3937 mday < 0 || hour < 0 ||
3938 min < 0 || sec < 0 || fsec < 0;
3939 bool has_positive = year > 0 || mon > 0 ||
3940 mday > 0 || hour > 0 ||
3941 min > 0 || sec > 0 || fsec > 0;
3942 bool has_year_month = year != 0 || mon != 0;
3943 bool has_day_time = mday != 0 || hour != 0 ||
3944 min != 0 || sec != 0 || fsec != 0;
3945 bool has_day = mday != 0;
3946 bool sql_standard_value = !(has_negative && has_positive) &&
3947 !(has_year_month && has_day_time);
3950 * SQL Standard wants only 1 "<sign>" preceding the whole
3951 * interval ... but can't do that if mixed signs.
3953 if (has_negative && sql_standard_value)
3965 if (!has_negative && !has_positive)
3969 else if (!sql_standard_value)
3972 * For non sql-standard interval values,
3973 * force outputting the signs to avoid
3974 * ambiguities with intervals with mixed
3977 char year_sign = (year < 0 || mon < 0) ? '-' : '+';
3978 char day_sign = (mday < 0) ? '-' : '+';
3979 char sec_sign = (hour < 0 || min < 0 ||
3980 sec < 0 || fsec < 0) ? '-' : '+';
3982 sprintf(cp, "%c%d-%d %c%d %c%d:%02d:",
3983 year_sign, abs(year), abs(mon),
3984 day_sign, abs(mday),
3985 sec_sign, abs(hour), abs(min));
3987 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
3989 else if (has_year_month)
3991 sprintf(cp, "%d-%d", year, mon);
3995 sprintf(cp, "%d %d:%02d:", mday, hour, min);
3997 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4001 sprintf(cp, "%d:%02d:", hour, min);
4003 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4008 /* ISO 8601 "time-intervals by duration only" */
4009 case INTSTYLE_ISO_8601:
4010 /* special-case zero to avoid printing nothing */
4011 if (year == 0 && mon == 0 && mday == 0 &&
4012 hour == 0 && min == 0 && sec == 0 && fsec == 0)
4014 sprintf(cp, "PT0S");
4018 cp = AddISO8601IntPart(cp, year, 'Y');
4019 cp = AddISO8601IntPart(cp, mon , 'M');
4020 cp = AddISO8601IntPart(cp, mday, 'D');
4021 if (hour != 0 || min != 0 || sec != 0 || fsec != 0)
4023 cp = AddISO8601IntPart(cp, hour, 'H');
4024 cp = AddISO8601IntPart(cp, min , 'M');
4025 if (sec != 0 || fsec != 0)
4027 if (sec < 0 || fsec < 0)
4029 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4036 /* Compatible with postgresql < 8.4 when DateStyle = 'iso' */
4037 case INTSTYLE_POSTGRES:
4038 cp = AddPostgresIntPart(cp, year, "year", &is_zero, &is_before);
4039 cp = AddPostgresIntPart(cp, mon, "mon", &is_zero, &is_before);
4040 cp = AddPostgresIntPart(cp, mday, "day", &is_zero, &is_before);
4041 if (is_zero || hour != 0 || min != 0 || sec != 0 || fsec != 0)
4043 bool minus = (hour < 0 || min < 0 || sec < 0 || fsec < 0);
4045 sprintf(cp, "%s%s%02d:%02d:",
4047 (minus ? "-" : (is_before ? "+" : "")),
4048 abs(hour), abs(min));
4050 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4054 /* Compatible with postgresql < 8.4 when DateStyle != 'iso' */
4055 case INTSTYLE_POSTGRES_VERBOSE:
4059 cp = AddVerboseIntPart(cp, year, "year", &is_zero, &is_before);
4060 cp = AddVerboseIntPart(cp, mon, "mon", &is_zero, &is_before);
4061 cp = AddVerboseIntPart(cp, mday, "day", &is_zero, &is_before);
4062 cp = AddVerboseIntPart(cp, hour, "hour", &is_zero, &is_before);
4063 cp = AddVerboseIntPart(cp, min, "min", &is_zero, &is_before);
4064 if (sec != 0 || fsec != 0)
4067 if (sec < 0 || (sec == 0 && fsec < 0))
4071 else if (!is_before)
4076 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4078 sprintf(cp, " sec%s",
4079 (abs(sec) != 1 || fsec != 0) ? "s" : "");
4082 /* identically zero? then put in a unitless zero... */
4091 } /* EncodeInterval() */
4095 * We've been burnt by stupid errors in the ordering of the datetkn tables
4096 * once too often. Arrange to check them during postmaster start.
4099 CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
4104 for (i = 1; i < nel; i++)
4106 if (strncmp(base[i - 1].token, base[i].token, TOKMAXLEN) >= 0)
4108 elog(LOG, "ordering error in %s table: \"%.*s\" >= \"%.*s\"",
4110 TOKMAXLEN, base[i - 1].token,
4111 TOKMAXLEN, base[i].token);
4119 CheckDateTokenTables(void)
4123 Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
4124 Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
4126 ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
4127 ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
4132 * This function gets called during timezone config file load or reload
4133 * to create the final array of timezone tokens. The argument array
4134 * is already sorted in name order. This data is in a temporary memory
4135 * context and must be copied to somewhere permanent.
4138 InstallTimeZoneAbbrevs(tzEntry *abbrevs, int n)
4144 * Copy the data into TopMemoryContext and convert to datetkn format.
4146 newtbl = (datetkn *) MemoryContextAlloc(TopMemoryContext,
4147 n * sizeof(datetkn));
4148 for (i = 0; i < n; i++)
4150 strncpy(newtbl[i].token, abbrevs[i].abbrev, TOKMAXLEN);
4151 newtbl[i].type = abbrevs[i].is_dst ? DTZ : TZ;
4152 TOVAL(&newtbl[i], abbrevs[i].offset / 60);
4155 /* Check the ordering, if testing */
4156 Assert(CheckDateTokenTable("timezone offset", newtbl, n));
4158 /* Now safe to replace existing table (if any) */
4160 pfree(timezonetktbl);
4161 timezonetktbl = newtbl;
4162 sztimezonetktbl = n;
4164 /* clear date cache in case it contains any stale timezone names */
4165 for (i = 0; i < MAXDATEFIELDS; i++)
4166 datecache[i] = NULL;
4170 * This set-returning function reads all the available time zone abbreviations
4171 * and returns a set of (abbrev, utc_offset, is_dst).
4174 pg_timezone_abbrevs(PG_FUNCTION_ARGS)
4176 FuncCallContext *funcctx;
4182 char buffer[TOKMAXLEN + 1];
4185 Interval *resInterval;
4187 /* stuff done only on the first call of the function */
4188 if (SRF_IS_FIRSTCALL())
4191 MemoryContext oldcontext;
4193 /* create a function context for cross-call persistence */
4194 funcctx = SRF_FIRSTCALL_INIT();
4197 * switch to memory context appropriate for multiple function calls
4199 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4201 /* allocate memory for user context */
4202 pindex = (int *) palloc(sizeof(int));
4204 funcctx->user_fctx = (void *) pindex;
4207 * build tupdesc for result tuples. This must match this function's
4210 tupdesc = CreateTemplateTupleDesc(3, false);
4211 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "abbrev",
4213 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "utc_offset",
4214 INTERVALOID, -1, 0);
4215 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_dst",
4218 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4219 MemoryContextSwitchTo(oldcontext);
4222 /* stuff done on every call of the function */
4223 funcctx = SRF_PERCALL_SETUP();
4224 pindex = (int *) funcctx->user_fctx;
4226 if (*pindex >= sztimezonetktbl)
4227 SRF_RETURN_DONE(funcctx);
4229 MemSet(nulls, 0, sizeof(nulls));
4232 * Convert name to text, using upcasing conversion that is the inverse of
4233 * what ParseDateTime() uses.
4235 strncpy(buffer, timezonetktbl[*pindex].token, TOKMAXLEN);
4236 buffer[TOKMAXLEN] = '\0'; /* may not be null-terminated */
4237 for (p = (unsigned char *) buffer; *p; p++)
4238 *p = pg_toupper(*p);
4240 values[0] = CStringGetTextDatum(buffer);
4242 MemSet(&tm, 0, sizeof(struct pg_tm));
4243 tm.tm_min = (-1) * FROMVAL(&timezonetktbl[*pindex]);
4244 resInterval = (Interval *) palloc(sizeof(Interval));
4245 tm2interval(&tm, 0, resInterval);
4246 values[1] = IntervalPGetDatum(resInterval);
4248 Assert(timezonetktbl[*pindex].type == DTZ ||
4249 timezonetktbl[*pindex].type == TZ);
4250 values[2] = BoolGetDatum(timezonetktbl[*pindex].type == DTZ);
4254 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4255 result = HeapTupleGetDatum(tuple);
4257 SRF_RETURN_NEXT(funcctx, result);
4261 * This set-returning function reads all the available full time zones
4262 * and returns a set of (name, abbrev, utc_offset, is_dst).
4265 pg_timezone_names(PG_FUNCTION_ARGS)
4267 MemoryContext oldcontext;
4268 FuncCallContext *funcctx;
4279 Interval *resInterval;
4282 /* stuff done only on the first call of the function */
4283 if (SRF_IS_FIRSTCALL())
4287 /* create a function context for cross-call persistence */
4288 funcctx = SRF_FIRSTCALL_INIT();
4291 * switch to memory context appropriate for multiple function calls
4293 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4295 /* initialize timezone scanning code */
4296 tzenum = pg_tzenumerate_start();
4297 funcctx->user_fctx = (void *) tzenum;
4300 * build tupdesc for result tuples. This must match this function's
4303 tupdesc = CreateTemplateTupleDesc(4, false);
4304 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
4306 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "abbrev",
4308 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "utc_offset",
4309 INTERVALOID, -1, 0);
4310 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_dst",
4313 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4314 MemoryContextSwitchTo(oldcontext);
4317 /* stuff done on every call of the function */
4318 funcctx = SRF_PERCALL_SETUP();
4319 tzenum = (pg_tzenum *) funcctx->user_fctx;
4321 /* search for another zone to display */
4324 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4325 tz = pg_tzenumerate_next(tzenum);
4326 MemoryContextSwitchTo(oldcontext);
4330 pg_tzenumerate_end(tzenum);
4331 funcctx->user_fctx = NULL;
4332 SRF_RETURN_DONE(funcctx);
4335 /* Convert now() to local time in this zone */
4336 if (timestamp2tm(GetCurrentTransactionStartTimestamp(),
4337 &tzoff, &tm, &fsec, &tzn, tz) != 0)
4338 continue; /* ignore if conversion fails */
4340 /* Ignore zic's rather silly "Factory" time zone */
4341 if (tzn && strcmp(tzn, "Local time zone must be set--see zic manual page") == 0)
4344 /* Found a displayable zone */
4348 MemSet(nulls, 0, sizeof(nulls));
4350 values[0] = CStringGetTextDatum(pg_get_timezone_name(tz));
4351 values[1] = CStringGetTextDatum(tzn ? tzn : "");
4353 MemSet(&itm, 0, sizeof(struct pg_tm));
4354 itm.tm_sec = -tzoff;
4355 resInterval = (Interval *) palloc(sizeof(Interval));
4356 tm2interval(&itm, 0, resInterval);
4357 values[2] = IntervalPGetDatum(resInterval);
4359 values[3] = BoolGetDatum(tm.tm_isdst > 0);
4361 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4362 result = HeapTupleGetDatum(tuple);
4364 SRF_RETURN_NEXT(funcctx, result);