1 /*-------------------------------------------------------------------------
4 * Support functions for date/time types.
6 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/utils/adt/datetime.c
13 *-------------------------------------------------------------------------
22 #include "access/xact.h"
23 #include "catalog/pg_type.h"
25 #include "miscadmin.h"
26 #include "nodes/nodeFuncs.h"
27 #include "utils/builtins.h"
28 #include "utils/date.h"
29 #include "utils/datetime.h"
30 #include "utils/memutils.h"
31 #include "utils/tzparser.h"
34 static int DecodeNumber(int flen, char *field, bool haveTextMonth,
35 int fmask, int *tmask,
36 struct pg_tm * tm, fsec_t *fsec, bool *is2digits);
37 static int DecodeNumberField(int len, char *str,
38 int fmask, int *tmask,
39 struct pg_tm * tm, fsec_t *fsec, bool *is2digits);
40 static int DecodeTime(char *str, int fmask, int range,
41 int *tmask, struct pg_tm * tm, fsec_t *fsec);
42 static int DecodeTimezone(char *str, int *tzp);
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 int ValidateDate(int fmask, bool isjulian, bool is2digits, bool bc,
48 static void TrimTrailingZeros(char *str);
49 static void AppendSeconds(char *cp, int sec, fsec_t fsec,
50 int precision, bool fillzeros);
51 static void AdjustFractSeconds(double frac, struct pg_tm * tm, fsec_t *fsec,
53 static void AdjustFractDays(double frac, struct pg_tm * tm, fsec_t *fsec,
57 const int day_tab[2][13] =
59 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
60 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}
63 char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
64 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
66 char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
67 "Thursday", "Friday", "Saturday", NULL};
70 /*****************************************************************************
72 *****************************************************************************/
75 * Definitions for squeezing values into "value"
76 * We set aside a high bit for a sign, and scale the timezone offsets
77 * in minutes by a factor of 15 (so can represent quarter-hour increments).
79 #define ABS_SIGNBIT ((char) 0200)
80 #define VALMASK ((char) 0177)
82 #define NEG(n) ((n)|ABS_SIGNBIT)
83 #define SIGNEDCHAR(c) ((c)&ABS_SIGNBIT? -((c)&VALMASK): (c))
84 #define FROMVAL(tp) (-SIGNEDCHAR((tp)->value) * 15) /* uncompress */
85 #define TOVAL(tp, v) ((tp)->value = ((v) < 0? NEG((-(v))/15): POS(v)/15))
88 * datetktbl holds date/time keywords.
90 * Note that this table must be strictly alphabetically ordered to allow an
91 * O(ln(N)) search algorithm to be used.
93 * The text field is NOT guaranteed to be NULL-terminated.
95 * To keep this table reasonably small, we divide the lexval for TZ and DTZ
96 * entries by 15 (so they are on 15 minute boundaries) and truncate the text
97 * field at TOKMAXLEN characters.
98 * Formerly, we divided by 10 rather than 15 but there are a few time zones
99 * which are 30 or 45 minutes away from an even hour, most are on an hour
100 * boundary, and none on other boundaries.
102 * The static table contains no TZ or DTZ entries, rather those are loaded
103 * from configuration files and stored in timezonetktbl, which has the same
104 * format as the static datetktbl.
106 static datetkn *timezonetktbl = NULL;
108 static int sztimezonetktbl = 0;
110 static const datetkn datetktbl[] = {
111 /* text, token, lexval */
112 {EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
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 {"s", UNITS, DTK_SECOND},
234 {"sec", UNITS, DTK_SECOND},
235 {DSECOND, UNITS, DTK_SECOND},
236 {"seconds", UNITS, DTK_SECOND},
237 {"secs", UNITS, DTK_SECOND},
238 {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
239 {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
240 {"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */
241 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
242 {"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
243 {"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
244 {DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */
245 {"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
246 {"usecs", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
247 {"w", UNITS, DTK_WEEK}, /* "week" relative */
248 {DWEEK, UNITS, DTK_WEEK}, /* "week" relative */
249 {"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
250 {"y", UNITS, DTK_YEAR}, /* "year" relative */
251 {DYEAR, UNITS, DTK_YEAR}, /* "year" relative */
252 {"years", UNITS, DTK_YEAR}, /* "years" relative */
253 {"yr", UNITS, DTK_YEAR}, /* "year" relative */
254 {"yrs", UNITS, DTK_YEAR} /* "years" relative */
257 static int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];
259 static const datetkn *datecache[MAXDATEFIELDS] = {NULL};
261 static const datetkn *deltacache[MAXDATEFIELDS] = {NULL};
265 * strtoi --- just like strtol, but returns int not long
268 strtoi(const char *nptr, char **endptr, int base)
272 val = strtol(nptr, endptr, base);
273 #ifdef HAVE_LONG_INT_64
274 if (val != (long) ((int32) val))
282 * Calendar time to Julian date conversions.
283 * Julian date is commonly used in astronomical applications,
284 * since it is numerically accurate and computationally simple.
285 * The algorithms here will accurately convert between Julian day
286 * and calendar date for all non-negative Julian days
287 * (i.e. from Nov 24, -4713 on).
289 * These routines will be used by other date/time packages
292 * Rewritten to eliminate overflow problems. This now allows the
293 * routines to work correctly for all Julian day counts from
294 * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming
295 * a 32-bit integer. Longer types should also work to the limits
296 * of their precision.
300 date2j(int y, int m, int d)
317 julian = y * 365 - 32167;
318 julian += y / 4 - century + century / 4;
319 julian += 7834 * m / 256 + d;
325 j2date(int jd, int *year, int *month, int *day)
334 quad = julian / 146097;
335 extra = (julian - quad * 146097) * 4 + 3;
336 julian += 60 + quad * 3 + extra / 146097;
337 quad = julian / 1461;
338 julian -= quad * 1461;
339 y = julian * 4 / 1461;
340 julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
344 quad = julian * 2141 / 65536;
345 *day = julian - 7834 * quad / 256;
346 *month = (quad + 10) % MONTHS_PER_YEAR + 1;
353 * j2day - convert Julian date to day-of-week (0..6 == Sun..Sat)
355 * Note: various places use the locution j2day(date - 1) to produce a
356 * result according to the convention 0..6 = Mon..Sun. This is a bit of
357 * a crock, but will work as long as the computation here is just a modulo.
374 * GetCurrentDateTime()
376 * Get the transaction start time ("now()") broken down as a struct pg_tm.
379 GetCurrentDateTime(struct pg_tm * tm)
384 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, &fsec,
386 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
390 * GetCurrentTimeUsec()
392 * Get the transaction start time ("now()") broken down as a struct pg_tm,
393 * including fractional seconds and timezone offset.
396 GetCurrentTimeUsec(struct pg_tm * tm, fsec_t *fsec, int *tzp)
400 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, fsec,
402 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
408 /* TrimTrailingZeros()
409 * ... resulting from printing numbers with full precision.
411 * Before Postgres 8.4, this always left at least 2 fractional digits,
412 * but conversations on the lists suggest this isn't desired
413 * since showing '0.10' is misleading with values of precision(1).
416 TrimTrailingZeros(char *str)
418 int len = strlen(str);
420 while (len > 1 && *(str + len - 1) == '0' && *(str + len - 2) != '.')
428 * Append sections and fractional seconds (if any) at *cp.
429 * precision is the max number of fraction digits, fillzeros says to
430 * pad to two integral-seconds digits.
431 * Note that any sign is stripped from the input seconds values.
434 AppendSeconds(char *cp, int sec, fsec_t fsec, int precision, bool fillzeros)
439 sprintf(cp, "%02d", abs(sec));
441 sprintf(cp, "%d", abs(sec));
445 #ifdef HAVE_INT64_TIMESTAMP
447 sprintf(cp, "%02d.%0*d", abs(sec), precision, (int) Abs(fsec));
449 sprintf(cp, "%d.%0*d", abs(sec), precision, (int) Abs(fsec));
452 sprintf(cp, "%0*.*f", precision + 3, precision, fabs(sec + fsec));
454 sprintf(cp, "%.*f", precision, fabs(sec + fsec));
456 TrimTrailingZeros(cp);
460 /* Variant of above that's specialized to timestamp case */
462 AppendTimestampSeconds(char *cp, struct pg_tm * tm, fsec_t fsec)
465 * In float mode, don't print fractional seconds before 1 AD, since it's
466 * unlikely there's any precision left ...
468 #ifndef HAVE_INT64_TIMESTAMP
469 if (tm->tm_year <= 0)
472 AppendSeconds(cp, tm->tm_sec, fsec, MAX_TIMESTAMP_PRECISION, true);
476 * Multiply frac by scale (to produce seconds) and add to *tm & *fsec.
477 * We assume the input frac is less than 1 so overflow is not an issue.
480 AdjustFractSeconds(double frac, struct pg_tm * tm, fsec_t *fsec, int scale)
490 #ifdef HAVE_INT64_TIMESTAMP
491 *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 #ifdef HAVE_INT64_TIMESTAMP
526 *fsec = rint(frac * 1000000);
535 * Break string into tokens based on a date/time context.
536 * Returns 0 if successful, DTERR code if bogus input detected.
538 * timestr - the input string
539 * workbuf - workspace for field string storage. This must be
540 * larger than the largest legal input for this datetime type --
541 * some additional space will be needed to NUL terminate fields.
542 * buflen - the size of workbuf
543 * field[] - pointers to field strings are returned in this array
544 * ftype[] - field type indicators are returned in this array
545 * maxfields - dimensions of the above two arrays
546 * *numfields - set to the actual number of fields detected
548 * The fields extracted from the input are stored as separate,
549 * null-terminated strings in the workspace at workbuf. Any text is
550 * converted to lower case.
552 * Several field types are assigned:
553 * DTK_NUMBER - digits and (possibly) a decimal point
554 * DTK_DATE - digits and two delimiters, or digits and text
555 * DTK_TIME - digits, colon delimiters, and possibly a decimal point
556 * DTK_STRING - text (no digits or punctuation)
557 * DTK_SPECIAL - leading "+" or "-" followed by text
558 * DTK_TZ - leading "+" or "-" followed by digits (also eats ':', '.', '-')
560 * Note that some field types can hold unexpected items:
561 * DTK_NUMBER can hold date fields (yy.ddd)
562 * DTK_STRING can hold months (January) and time zones (PST)
563 * DTK_DATE can hold time zone names (America/New_York, GMT-8)
566 ParseDateTime(const char *timestr, char *workbuf, size_t buflen,
567 char **field, int *ftype, int maxfields, int *numfields)
570 const char *cp = timestr;
571 char *bufp = workbuf;
572 const char *bufend = workbuf + buflen;
575 * Set the character pointed-to by "bufptr" to "newchar", and increment
576 * "bufptr". "end" gives the end of the buffer -- we return an error if
577 * there is no space left to append a character to the buffer. Note that
578 * "bufptr" is evaluated twice.
580 #define APPEND_CHAR(bufptr, end, newchar) \
583 if (((bufptr) + 1) >= (end)) \
584 return DTERR_BAD_FORMAT; \
585 *(bufptr)++ = newchar; \
588 /* outer loop through fields */
591 /* Ignore spaces between fields */
592 if (isspace((unsigned char) *cp))
598 /* Record start of current field */
600 return DTERR_BAD_FORMAT;
603 /* leading digit? then date or time */
604 if (isdigit((unsigned char) *cp))
606 APPEND_CHAR(bufp, bufend, *cp++);
607 while (isdigit((unsigned char) *cp))
608 APPEND_CHAR(bufp, bufend, *cp++);
613 ftype[nf] = DTK_TIME;
614 APPEND_CHAR(bufp, bufend, *cp++);
615 while (isdigit((unsigned char) *cp) ||
616 (*cp == ':') || (*cp == '.'))
617 APPEND_CHAR(bufp, bufend, *cp++);
619 /* date field? allow embedded text month */
620 else if (*cp == '-' || *cp == '/' || *cp == '.')
622 /* save delimiting character to use later */
625 APPEND_CHAR(bufp, bufend, *cp++);
626 /* second field is all digits? then no embedded text month */
627 if (isdigit((unsigned char) *cp))
629 ftype[nf] = ((delim == '.') ? DTK_NUMBER : DTK_DATE);
630 while (isdigit((unsigned char) *cp))
631 APPEND_CHAR(bufp, bufend, *cp++);
634 * insist that the delimiters match to get a three-field
639 ftype[nf] = DTK_DATE;
640 APPEND_CHAR(bufp, bufend, *cp++);
641 while (isdigit((unsigned char) *cp) || *cp == delim)
642 APPEND_CHAR(bufp, bufend, *cp++);
647 ftype[nf] = DTK_DATE;
648 while (isalnum((unsigned char) *cp) || *cp == delim)
649 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
654 * otherwise, number only and will determine year, month, day, or
655 * concatenated fields later...
658 ftype[nf] = DTK_NUMBER;
660 /* Leading decimal point? Then fractional seconds... */
663 APPEND_CHAR(bufp, bufend, *cp++);
664 while (isdigit((unsigned char) *cp))
665 APPEND_CHAR(bufp, bufend, *cp++);
667 ftype[nf] = DTK_NUMBER;
671 * text? then date string, month, day of week, special, or timezone
673 else if (isalpha((unsigned char) *cp))
677 ftype[nf] = DTK_STRING;
678 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
679 while (isalpha((unsigned char) *cp))
680 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
683 * Dates can have embedded '-', '/', or '.' separators. It could
684 * also be a timezone name containing embedded '/', '+', '-', '_',
685 * or ':' (but '_' or ':' can't be the first punctuation). If the
686 * next character is a digit or '+', we need to check whether what
687 * we have so far is a recognized non-timezone keyword --- if so,
688 * don't believe that this is the start of a timezone.
691 if (*cp == '-' || *cp == '/' || *cp == '.')
693 else if (*cp == '+' || isdigit((unsigned char) *cp))
695 *bufp = '\0'; /* null-terminate current field value */
696 /* we need search only the core token table, not TZ names */
697 if (datebsearch(field[nf], datetktbl, szdatetktbl) == NULL)
702 ftype[nf] = DTK_DATE;
705 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
706 } while (*cp == '+' || *cp == '-' ||
707 *cp == '/' || *cp == '_' ||
708 *cp == '.' || *cp == ':' ||
709 isalnum((unsigned char) *cp));
712 /* sign? then special or numeric timezone */
713 else if (*cp == '+' || *cp == '-')
715 APPEND_CHAR(bufp, bufend, *cp++);
716 /* soak up leading whitespace */
717 while (isspace((unsigned char) *cp))
719 /* numeric timezone? */
720 /* note that "DTK_TZ" could also be a signed float or yyyy-mm */
721 if (isdigit((unsigned char) *cp))
724 APPEND_CHAR(bufp, bufend, *cp++);
725 while (isdigit((unsigned char) *cp) ||
726 *cp == ':' || *cp == '.' || *cp == '-')
727 APPEND_CHAR(bufp, bufend, *cp++);
730 else if (isalpha((unsigned char) *cp))
732 ftype[nf] = DTK_SPECIAL;
733 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
734 while (isalpha((unsigned char) *cp))
735 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
737 /* otherwise something wrong... */
739 return DTERR_BAD_FORMAT;
741 /* ignore other punctuation but use as delimiter */
742 else if (ispunct((unsigned char) *cp))
747 /* otherwise, something is not right... */
749 return DTERR_BAD_FORMAT;
751 /* force in a delimiter after each field */
763 * Interpret previously parsed fields for general date and time.
764 * Return 0 if full date, 1 if only time, and negative DTERR code if problems.
765 * (Currently, all callers treat 1 as an error return too.)
767 * External format(s):
768 * "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
769 * "Fri Feb-7-1997 15:23:27"
770 * "Feb-7-1997 15:23:27"
771 * "2-7-1997 15:23:27"
772 * "1997-2-7 15:23:27"
773 * "1997.038 15:23:27" (day of year 1-366)
774 * Also supports input in compact time:
777 * "20011225T040506.789-07"
779 * Use the system-provided functions to get the current time zone
780 * if not specified in the input string.
782 * If the date is outside the range of pg_time_t (in practice that could only
783 * happen if pg_time_t is just 32 bits), then assume UTC time zone - thomas
787 DecodeDateTime(char **field, int *ftype, int nf,
788 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
793 int ptype = 0; /* "prefix type" for ISO y2001m02d04 format */
798 bool haveTextMonth = FALSE;
799 bool isjulian = FALSE;
800 bool is2digits = FALSE;
802 pg_tz *namedTz = NULL;
806 * We'll insist on at least all of the date fields, but initialize the
807 * remaining fields in case they are not set later...
814 /* don't know daylight savings time status apriori */
819 for (i = 0; i < nf; i++)
825 * Integral julian day with attached time zone?
826 * All other forms with JD will be separated into
827 * distinct fields, so we handle just this case here.
829 if (ptype == DTK_JULIAN)
835 return DTERR_BAD_FORMAT;
838 val = strtoi(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);
855 * Already have a date? Then this might be a time zone name
856 * with embedded punctuation (e.g. "America/New_York") or a
857 * run-together time with trailing time zone (e.g. hhmmss-zz).
858 * - thomas 2001-12-25
860 * We consider it a time zone if we already have month & day.
861 * This is to allow the form "mmm dd hhmmss tz year", which
862 * we've historically accepted.
864 else if (ptype != 0 ||
865 ((fmask & (DTK_M(MONTH) | DTK_M(DAY))) ==
866 (DTK_M(MONTH) | DTK_M(DAY))))
868 /* No time zone accepted? Then quit... */
870 return DTERR_BAD_FORMAT;
872 if (isdigit((unsigned char) *field[i]) || ptype != 0)
878 /* Sanity check; should not fail this test */
879 if (ptype != DTK_TIME)
880 return DTERR_BAD_FORMAT;
885 * Starts with a digit but we already have a time
886 * field? Then we are in trouble with a date and time
889 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
890 return DTERR_BAD_FORMAT;
892 if ((cp = strchr(field[i], '-')) == NULL)
893 return DTERR_BAD_FORMAT;
895 /* Get the time zone from the end of the string */
896 dterr = DecodeTimezone(cp, tzp);
902 * Then read the rest of the field as a concatenated
905 dterr = DecodeNumberField(strlen(field[i]), field[i],
913 * modify tmask after returning from
914 * DecodeNumberField()
920 namedTz = pg_tzset(field[i]);
924 * We should return an error code instead of
925 * ereport'ing directly, but then there is no way
926 * to report the bad time zone name.
929 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
930 errmsg("time zone \"%s\" not recognized",
933 /* we'll apply the zone setting below */
939 dterr = DecodeDate(field[i], fmask,
940 &tmask, &is2digits, tm);
947 dterr = DecodeTime(field[i], fmask, INTERVAL_FULL_RANGE,
953 * Check upper limit on hours; other limits checked in
956 /* test for > 24:00:00 */
957 if (tm->tm_hour > HOURS_PER_DAY ||
958 (tm->tm_hour == HOURS_PER_DAY &&
959 (tm->tm_min > 0 || tm->tm_sec > 0 || *fsec > 0)))
960 return DTERR_FIELD_OVERFLOW;
968 return DTERR_BAD_FORMAT;
970 dterr = DecodeTimezone(field[i], &tz);
981 * Was this an "ISO date" with embedded field labels? An
982 * example is "y2001m02d04" - thomas 2001-02-04
990 val = strtoi(field[i], &cp, 10);
992 return DTERR_FIELD_OVERFLOW;
995 * only a few kinds are allowed to have an embedded
1006 return DTERR_BAD_FORMAT;
1009 else if (*cp != '\0')
1010 return DTERR_BAD_FORMAT;
1016 tmask = DTK_M(YEAR);
1022 * already have a month and hour? then assume
1025 if ((fmask & DTK_M(MONTH)) != 0 &&
1026 (fmask & DTK_M(HOUR)) != 0)
1029 tmask = DTK_M(MINUTE);
1034 tmask = DTK_M(MONTH);
1045 tmask = DTK_M(HOUR);
1050 tmask = DTK_M(MINUTE);
1055 tmask = DTK_M(SECOND);
1058 dterr = ParseFractionalSecond(cp, fsec);
1061 tmask = DTK_ALL_SECS_M;
1067 dterr = DecodeTimezone(field[i], tzp);
1073 /* previous field was a label for "julian date" */
1075 return DTERR_FIELD_OVERFLOW;
1077 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1080 /* fractional Julian Day? */
1086 time = strtod(cp, &cp);
1087 if (*cp != '\0' || errno != 0)
1088 return DTERR_BAD_FORMAT;
1090 #ifdef HAVE_INT64_TIMESTAMP
1091 time *= USECS_PER_DAY;
1093 time *= SECS_PER_DAY;
1096 &tm->tm_hour, &tm->tm_min,
1098 tmask |= DTK_TIME_M;
1103 /* previous field was "t" for ISO time */
1104 dterr = DecodeNumberField(strlen(field[i]), field[i],
1105 (fmask | DTK_DATE_M),
1110 if (tmask != DTK_TIME_M)
1111 return DTERR_BAD_FORMAT;
1115 return DTERR_BAD_FORMAT;
1127 flen = strlen(field[i]);
1128 cp = strchr(field[i], '.');
1130 /* Embedded decimal and no date yet? */
1131 if (cp != NULL && !(fmask & DTK_DATE_M))
1133 dterr = DecodeDate(field[i], fmask,
1134 &tmask, &is2digits, tm);
1138 /* embedded decimal and several digits before? */
1139 else if (cp != NULL && flen - strlen(cp) > 2)
1142 * Interpret as a concatenated date or time Set the
1143 * type field to allow decoding other fields later.
1144 * Example: 20011223 or 040506
1146 dterr = DecodeNumberField(flen, field[i], fmask,
1154 dterr = DecodeNumberField(flen, field[i], fmask,
1160 /* otherwise it is a single date/time field... */
1163 dterr = DecodeNumber(flen, field[i],
1164 haveTextMonth, fmask,
1175 type = DecodeSpecial(i, field[i], &val);
1176 if (type == IGNORE_DTF)
1179 tmask = DTK_M(type);
1187 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1188 errmsg("date/time value \"current\" is no longer supported")));
1190 return DTERR_BAD_FORMAT;
1194 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1196 GetCurrentTimeUsec(tm, fsec, tzp);
1202 GetCurrentDateTime(&cur_tm);
1203 j2date(date2j(cur_tm.tm_year, cur_tm.tm_mon, cur_tm.tm_mday) - 1,
1204 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1210 GetCurrentDateTime(&cur_tm);
1211 tm->tm_year = cur_tm.tm_year;
1212 tm->tm_mon = cur_tm.tm_mon;
1213 tm->tm_mday = cur_tm.tm_mday;
1219 GetCurrentDateTime(&cur_tm);
1220 j2date(date2j(cur_tm.tm_year, cur_tm.tm_mon, cur_tm.tm_mday) + 1,
1221 &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, isjulian, is2digits, bc, tm);
1370 if (mer != HR24 && tm->tm_hour > HOURS_PER_DAY / 2)
1371 return DTERR_FIELD_OVERFLOW;
1372 if (mer == AM && tm->tm_hour == HOURS_PER_DAY / 2)
1374 else if (mer == PM && tm->tm_hour != HOURS_PER_DAY / 2)
1375 tm->tm_hour += HOURS_PER_DAY / 2;
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 isjulian = FALSE;
1569 bool is2digits = FALSE;
1572 pg_tz *namedTz = NULL;
1579 /* don't know daylight savings time status apriori */
1585 for (i = 0; i < nf; i++)
1592 * Time zone not allowed? Then should not accept dates or time
1593 * zones no matter what else!
1596 return DTERR_BAD_FORMAT;
1598 /* Under limited circumstances, we will accept a date... */
1599 if (i == 0 && nf >= 2 &&
1600 (ftype[nf - 1] == DTK_DATE || ftype[1] == DTK_TIME))
1602 dterr = DecodeDate(field[i], fmask,
1603 &tmask, &is2digits, tm);
1607 /* otherwise, this is a time and/or time zone */
1610 if (isdigit((unsigned char) *field[i]))
1615 * Starts with a digit but we already have a time
1616 * field? Then we are in trouble with time already...
1618 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1619 return DTERR_BAD_FORMAT;
1622 * Should not get here and fail. Sanity check only...
1624 if ((cp = strchr(field[i], '-')) == NULL)
1625 return DTERR_BAD_FORMAT;
1627 /* Get the time zone from the end of the string */
1628 dterr = DecodeTimezone(cp, tzp);
1634 * Then read the rest of the field as a concatenated
1637 dterr = DecodeNumberField(strlen(field[i]), field[i],
1638 (fmask | DTK_DATE_M),
1649 namedTz = pg_tzset(field[i]);
1653 * We should return an error code instead of
1654 * ereport'ing directly, but then there is no way
1655 * to report the bad time zone name.
1658 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1659 errmsg("time zone \"%s\" not recognized",
1662 /* we'll apply the zone setting below */
1670 dterr = DecodeTime(field[i], (fmask | DTK_DATE_M),
1671 INTERVAL_FULL_RANGE,
1682 return DTERR_BAD_FORMAT;
1684 dterr = DecodeTimezone(field[i], &tz);
1695 * Was this an "ISO time" with embedded field labels? An
1696 * example is "h04m05s06" - thomas 2001-02-04
1703 /* Only accept a date under limited circumstances */
1711 return DTERR_BAD_FORMAT;
1717 val = strtoi(field[i], &cp, 10);
1718 if (errno == ERANGE)
1719 return DTERR_FIELD_OVERFLOW;
1722 * only a few kinds are allowed to have an embedded
1733 return DTERR_BAD_FORMAT;
1736 else if (*cp != '\0')
1737 return DTERR_BAD_FORMAT;
1743 tmask = DTK_M(YEAR);
1749 * already have a month and hour? then assume
1752 if ((fmask & DTK_M(MONTH)) != 0 &&
1753 (fmask & DTK_M(HOUR)) != 0)
1756 tmask = DTK_M(MINUTE);
1761 tmask = DTK_M(MONTH);
1772 tmask = DTK_M(HOUR);
1777 tmask = DTK_M(MINUTE);
1782 tmask = DTK_M(SECOND);
1785 dterr = ParseFractionalSecond(cp, fsec);
1788 tmask = DTK_ALL_SECS_M;
1794 dterr = DecodeTimezone(field[i], tzp);
1800 /* previous field was a label for "julian date" */
1802 return DTERR_FIELD_OVERFLOW;
1804 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1812 time = strtod(cp, &cp);
1813 if (*cp != '\0' || errno != 0)
1814 return DTERR_BAD_FORMAT;
1816 #ifdef HAVE_INT64_TIMESTAMP
1817 time *= USECS_PER_DAY;
1819 time *= SECS_PER_DAY;
1822 &tm->tm_hour, &tm->tm_min,
1824 tmask |= DTK_TIME_M;
1829 /* previous field was "t" for ISO time */
1830 dterr = DecodeNumberField(strlen(field[i]), field[i],
1831 (fmask | DTK_DATE_M),
1838 if (tmask != DTK_TIME_M)
1839 return DTERR_BAD_FORMAT;
1843 return DTERR_BAD_FORMAT;
1855 flen = strlen(field[i]);
1856 cp = strchr(field[i], '.');
1858 /* Embedded decimal? */
1862 * Under limited circumstances, we will accept a
1865 if (i == 0 && nf >= 2 && ftype[nf - 1] == DTK_DATE)
1867 dterr = DecodeDate(field[i], fmask,
1868 &tmask, &is2digits, tm);
1872 /* embedded decimal and several digits before? */
1873 else if (flen - strlen(cp) > 2)
1876 * Interpret as a concatenated date or time Set
1877 * the type field to allow decoding other fields
1878 * later. Example: 20011223 or 040506
1880 dterr = DecodeNumberField(flen, field[i],
1881 (fmask | DTK_DATE_M),
1889 return DTERR_BAD_FORMAT;
1893 dterr = DecodeNumberField(flen, field[i],
1894 (fmask | DTK_DATE_M),
1901 /* otherwise it is a single date/time field... */
1904 dterr = DecodeNumber(flen, field[i],
1906 (fmask | DTK_DATE_M),
1917 type = DecodeSpecial(i, field[i], &val);
1918 if (type == IGNORE_DTF)
1921 tmask = DTK_M(type);
1929 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1930 errmsg("date/time value \"current\" is no longer supported")));
1931 return DTERR_BAD_FORMAT;
1937 GetCurrentTimeUsec(tm, fsec, NULL);
1941 tmask = (DTK_TIME_M | DTK_M(TZ));
1950 return DTERR_BAD_FORMAT;
1958 * daylight savings time modifier (solves "MET DST"
1961 tmask |= DTK_M(DTZ);
1964 return DTERR_BAD_FORMAT;
1965 *tzp += val * MINS_PER_HOUR;
1971 * set mask for TZ here _or_ check for DTZ later when
1972 * getting default timezone
1977 return DTERR_BAD_FORMAT;
1978 *tzp = val * MINS_PER_HOUR;
1985 return DTERR_BAD_FORMAT;
1986 *tzp = val * MINS_PER_HOUR;
2010 * We will need one of the following fields:
2011 * DTK_NUMBER should be hhmmss.fff
2012 * DTK_TIME should be hh:mm:ss.fff
2013 * DTK_DATE should be hhmmss-zz
2016 (ftype[i + 1] != DTK_NUMBER &&
2017 ftype[i + 1] != DTK_TIME &&
2018 ftype[i + 1] != DTK_DATE))
2019 return DTERR_BAD_FORMAT;
2027 * Before giving up and declaring error, check to see
2028 * if it is an all-alpha timezone name.
2030 namedTz = pg_tzset(field[i]);
2032 return DTERR_BAD_FORMAT;
2033 /* we'll apply the zone setting below */
2038 return DTERR_BAD_FORMAT;
2043 return DTERR_BAD_FORMAT;
2047 return DTERR_BAD_FORMAT;
2049 } /* end loop over fields */
2051 /* do final checking/adjustment of Y/M/D fields */
2052 dterr = ValidateDate(fmask, isjulian, is2digits, bc, tm);
2057 if (mer != HR24 && tm->tm_hour > HOURS_PER_DAY / 2)
2058 return DTERR_FIELD_OVERFLOW;
2059 if (mer == AM && tm->tm_hour == HOURS_PER_DAY / 2)
2061 else if (mer == PM && tm->tm_hour != HOURS_PER_DAY / 2)
2062 tm->tm_hour += HOURS_PER_DAY / 2;
2064 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > MINS_PER_HOUR - 1 ||
2065 tm->tm_sec < 0 || tm->tm_sec > SECS_PER_MINUTE ||
2066 tm->tm_hour > HOURS_PER_DAY ||
2067 /* test for > 24:00:00 */
2068 (tm->tm_hour == HOURS_PER_DAY &&
2069 (tm->tm_min > 0 || tm->tm_sec > 0 || *fsec > 0)) ||
2070 #ifdef HAVE_INT64_TIMESTAMP
2071 *fsec < INT64CONST(0) || *fsec > USECS_PER_SEC
2073 *fsec < 0 || *fsec > 1
2076 return DTERR_FIELD_OVERFLOW;
2078 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2079 return DTERR_BAD_FORMAT;
2082 * If we had a full timezone spec, compute the offset (we could not do it
2083 * before, because we may need the date to resolve DST status).
2085 if (namedTz != NULL)
2089 /* daylight savings time modifier disallowed with full TZ */
2090 if (fmask & DTK_M(DTZMOD))
2091 return DTERR_BAD_FORMAT;
2093 /* if non-DST zone, we do not need to know the date */
2094 if (pg_get_timezone_offset(namedTz, &gmtoff))
2096 *tzp = -(int) gmtoff;
2100 /* a date has to be specified */
2101 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2102 return DTERR_BAD_FORMAT;
2103 *tzp = DetermineTimeZoneOffset(tm, namedTz);
2107 /* timezone not specified? then find local timezone if possible */
2108 if (tzp != NULL && !(fmask & DTK_M(TZ)))
2114 * daylight savings time modifier but no standard timezone? then error
2116 if (fmask & DTK_M(DTZMOD))
2117 return DTERR_BAD_FORMAT;
2119 if ((fmask & DTK_DATE_M) == 0)
2120 GetCurrentDateTime(tmp);
2123 tmp->tm_year = tm->tm_year;
2124 tmp->tm_mon = tm->tm_mon;
2125 tmp->tm_mday = tm->tm_mday;
2127 tmp->tm_hour = tm->tm_hour;
2128 tmp->tm_min = tm->tm_min;
2129 tmp->tm_sec = tm->tm_sec;
2130 *tzp = DetermineTimeZoneOffset(tmp, session_timezone);
2131 tm->tm_isdst = tmp->tm_isdst;
2138 * Decode date string which includes delimiters.
2139 * Return 0 if okay, a DTERR code if not.
2141 * str: field to be parsed
2142 * fmask: bitmask for field types already seen
2143 * *tmask: receives bitmask for fields found here
2144 * *is2digits: set to TRUE if we find 2-digit year
2145 * *tm: field values are stored into appropriate members of this struct
2148 DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
2156 bool haveTextMonth = FALSE;
2160 char *field[MAXDATEFIELDS];
2164 /* parse this string... */
2165 while (*str != '\0' && nf < MAXDATEFIELDS)
2167 /* skip field separators */
2168 while (!isalnum((unsigned char) *str))
2172 if (isdigit((unsigned char) *str))
2174 while (isdigit((unsigned char) *str))
2177 else if (isalpha((unsigned char) *str))
2179 while (isalpha((unsigned char) *str))
2183 /* Just get rid of any non-digit, non-alpha characters... */
2189 /* look first for text fields, since that will be unambiguous month */
2190 for (i = 0; i < nf; i++)
2192 if (isalpha((unsigned char) *field[i]))
2194 type = DecodeSpecial(i, field[i], &val);
2195 if (type == IGNORE_DTF)
2198 dmask = DTK_M(type);
2203 haveTextMonth = TRUE;
2207 return DTERR_BAD_FORMAT;
2210 return DTERR_BAD_FORMAT;
2215 /* mark this field as being completed */
2220 /* now pick up remaining numeric fields */
2221 for (i = 0; i < nf; i++)
2223 if (field[i] == NULL)
2226 if ((len = strlen(field[i])) <= 0)
2227 return DTERR_BAD_FORMAT;
2229 dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2236 return DTERR_BAD_FORMAT;
2242 if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
2243 return DTERR_BAD_FORMAT;
2245 /* validation of the field values must wait until ValidateDate() */
2251 * Check valid year/month/day values, handle BC and DOY cases
2252 * Return 0 if okay, a DTERR code if not.
2255 ValidateDate(int fmask, bool isjulian, bool is2digits, bool bc,
2258 if (fmask & DTK_M(YEAR))
2262 /* tm_year is correct and should not be touched */
2266 /* there is no year zero in AD/BC notation */
2267 if (tm->tm_year <= 0)
2268 return DTERR_FIELD_OVERFLOW;
2269 /* internally, we represent 1 BC as year zero, 2 BC as -1, etc */
2270 tm->tm_year = -(tm->tm_year - 1);
2274 /* process 1 or 2-digit input as 1970-2069 AD, allow '0' and '00' */
2275 if (tm->tm_year < 0) /* just paranoia */
2276 return DTERR_FIELD_OVERFLOW;
2277 if (tm->tm_year < 70)
2278 tm->tm_year += 2000;
2279 else if (tm->tm_year < 100)
2280 tm->tm_year += 1900;
2284 /* there is no year zero in AD/BC notation */
2285 if (tm->tm_year <= 0)
2286 return DTERR_FIELD_OVERFLOW;
2290 /* now that we have correct year, decode DOY */
2291 if (fmask & DTK_M(DOY))
2293 j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
2294 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2297 /* check for valid month */
2298 if (fmask & DTK_M(MONTH))
2300 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
2301 return DTERR_MD_FIELD_OVERFLOW;
2304 /* minimal check for valid day */
2305 if (fmask & DTK_M(DAY))
2307 if (tm->tm_mday < 1 || tm->tm_mday > 31)
2308 return DTERR_MD_FIELD_OVERFLOW;
2311 if ((fmask & DTK_DATE_M) == DTK_DATE_M)
2314 * Check for valid day of month, now that we know for sure the month
2315 * and year. Note we don't use MD_FIELD_OVERFLOW here, since it seems
2316 * unlikely that "Feb 29" is a YMD-order error.
2318 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2319 return DTERR_FIELD_OVERFLOW;
2327 * Decode time string which includes delimiters.
2328 * Return 0 if okay, a DTERR code if not.
2330 * Only check the lower limit on hours, since this same code can be
2331 * used to represent time spans.
2334 DecodeTime(char *str, int fmask, int range,
2335 int *tmask, struct pg_tm * tm, fsec_t *fsec)
2340 *tmask = DTK_TIME_M;
2343 tm->tm_hour = strtoi(str, &cp, 10);
2344 if (errno == ERANGE)
2345 return DTERR_FIELD_OVERFLOW;
2347 return DTERR_BAD_FORMAT;
2349 tm->tm_min = strtoi(cp + 1, &cp, 10);
2350 if (errno == ERANGE)
2351 return DTERR_FIELD_OVERFLOW;
2356 /* If it's a MINUTE TO SECOND interval, take 2 fields as being mm:ss */
2357 if (range == (INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND)))
2359 tm->tm_sec = tm->tm_min;
2360 tm->tm_min = tm->tm_hour;
2364 else if (*cp == '.')
2366 /* always assume mm:ss.sss is MINUTE TO SECOND */
2367 dterr = ParseFractionalSecond(cp, fsec);
2370 tm->tm_sec = tm->tm_min;
2371 tm->tm_min = tm->tm_hour;
2374 else if (*cp == ':')
2377 tm->tm_sec = strtoi(cp + 1, &cp, 10);
2378 if (errno == ERANGE)
2379 return DTERR_FIELD_OVERFLOW;
2382 else if (*cp == '.')
2384 dterr = ParseFractionalSecond(cp, fsec);
2389 return DTERR_BAD_FORMAT;
2392 return DTERR_BAD_FORMAT;
2394 /* do a sanity check */
2395 #ifdef HAVE_INT64_TIMESTAMP
2396 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > MINS_PER_HOUR - 1 ||
2397 tm->tm_sec < 0 || tm->tm_sec > SECS_PER_MINUTE ||
2398 *fsec < INT64CONST(0) ||
2399 *fsec > USECS_PER_SEC)
2400 return DTERR_FIELD_OVERFLOW;
2402 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > MINS_PER_HOUR - 1 ||
2403 tm->tm_sec < 0 || tm->tm_sec > SECS_PER_MINUTE ||
2404 *fsec < 0 || *fsec > 1)
2405 return DTERR_FIELD_OVERFLOW;
2413 * Interpret plain numeric field as a date value in context.
2414 * Return 0 if okay, a DTERR code if not.
2417 DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask,
2418 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2427 val = strtoi(str, &cp, 10);
2428 if (errno == ERANGE)
2429 return DTERR_FIELD_OVERFLOW;
2431 return DTERR_BAD_FORMAT;
2436 * More than two digits before decimal point? Then could be a date or
2437 * a run-together time: 2001.360 20011225 040506.789
2441 dterr = DecodeNumberField(flen, str,
2442 (fmask | DTK_DATE_M),
2450 dterr = ParseFractionalSecond(cp, fsec);
2454 else if (*cp != '\0')
2455 return DTERR_BAD_FORMAT;
2457 /* Special case for day of year */
2458 if (flen == 3 && (fmask & DTK_DATE_M) == DTK_M(YEAR) && val >= 1 &&
2461 *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2463 /* tm_mon and tm_mday can't actually be set yet ... */
2467 /* Switch based on what we have so far */
2468 switch (fmask & DTK_DATE_M)
2473 * Nothing so far; make a decision about what we think the input
2474 * is. There used to be lots of heuristics here, but the
2475 * consensus now is to be paranoid. It *must* be either
2476 * YYYY-MM-DD (with a more-than-two-digit year field), or the
2477 * field order defined by DateOrder.
2479 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2481 *tmask = DTK_M(YEAR);
2484 else if (DateOrder == DATEORDER_DMY)
2486 *tmask = DTK_M(DAY);
2491 *tmask = DTK_M(MONTH);
2497 /* Must be at second field of YY-MM-DD */
2498 *tmask = DTK_M(MONTH);
2502 case (DTK_M(MONTH)):
2506 * We are at the first numeric field of a date that included a
2507 * textual month name. We want to support the variants
2508 * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2509 * inputs. We will also accept MON-DD-YY or DD-MON-YY in
2510 * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2512 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2514 *tmask = DTK_M(YEAR);
2519 *tmask = DTK_M(DAY);
2525 /* Must be at second field of MM-DD-YY */
2526 *tmask = DTK_M(DAY);
2531 case (DTK_M(YEAR) | DTK_M(MONTH)):
2534 /* Need to accept DD-MON-YYYY even in YMD mode */
2535 if (flen >= 3 && *is2digits)
2537 /* Guess that first numeric field is day was wrong */
2538 *tmask = DTK_M(DAY); /* YEAR is already set */
2539 tm->tm_mday = tm->tm_year;
2545 *tmask = DTK_M(DAY);
2551 /* Must be at third field of YY-MM-DD */
2552 *tmask = DTK_M(DAY);
2558 /* Must be at second field of DD-MM-YY */
2559 *tmask = DTK_M(MONTH);
2563 case (DTK_M(MONTH) | DTK_M(DAY)):
2564 /* Must be at third field of DD-MM-YY or MM-DD-YY */
2565 *tmask = DTK_M(YEAR);
2569 case (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY)):
2570 /* we have all the date, so it must be a time field */
2571 dterr = DecodeNumberField(flen, str, fmask,
2579 /* Anything else is bogus input */
2580 return DTERR_BAD_FORMAT;
2584 * When processing a year field, mark it for adjustment if it's only one
2587 if (*tmask == DTK_M(YEAR))
2588 *is2digits = (flen <= 2);
2594 /* DecodeNumberField()
2595 * Interpret numeric string as a concatenated date or time field.
2596 * Return a DTK token (>= 0) if successful, a DTERR code (< 0) if not.
2598 * Use the context of previously decoded fields to help with
2599 * the interpretation.
2602 DecodeNumberField(int len, char *str, int fmask,
2603 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2608 * Have a decimal point? Then this is a date or something with a seconds
2611 if ((cp = strchr(str, '.')) != NULL)
2614 * Can we use ParseFractionalSecond here? Not clear whether trailing
2615 * junk should be rejected ...
2620 frac = strtod(cp, NULL);
2622 return DTERR_BAD_FORMAT;
2623 #ifdef HAVE_INT64_TIMESTAMP
2624 *fsec = rint(frac * 1000000);
2628 /* Now truncate off the fraction for further processing */
2632 /* No decimal point and no complete date yet? */
2633 else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2638 *tmask = DTK_DATE_M;
2640 tm->tm_mday = atoi(str + 6);
2642 tm->tm_mon = atoi(str + 4);
2644 tm->tm_year = atoi(str + 0);
2651 *tmask = DTK_DATE_M;
2652 tm->tm_mday = atoi(str + 4);
2654 tm->tm_mon = atoi(str + 2);
2656 tm->tm_year = atoi(str + 0);
2663 /* not all time fields are specified? */
2664 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2669 *tmask = DTK_TIME_M;
2670 tm->tm_sec = atoi(str + 4);
2672 tm->tm_min = atoi(str + 2);
2674 tm->tm_hour = atoi(str + 0);
2681 *tmask = DTK_TIME_M;
2683 tm->tm_min = atoi(str + 2);
2685 tm->tm_hour = atoi(str + 0);
2691 return DTERR_BAD_FORMAT;
2696 * Interpret string as a numeric timezone.
2698 * Return 0 if okay (and set *tzp), a DTERR code if not okay.
2700 * NB: this must *not* ereport on failure; see commands/variable.c.
2703 DecodeTimezone(char *str, int *tzp)
2711 /* leading character must be "+" or "-" */
2712 if (*str != '+' && *str != '-')
2713 return DTERR_BAD_FORMAT;
2716 hr = strtoi(str + 1, &cp, 10);
2717 if (errno == ERANGE)
2718 return DTERR_TZDISP_OVERFLOW;
2720 /* explicit delimiter? */
2724 min = strtoi(cp + 1, &cp, 10);
2725 if (errno == ERANGE)
2726 return DTERR_TZDISP_OVERFLOW;
2730 sec = strtoi(cp + 1, &cp, 10);
2731 if (errno == ERANGE)
2732 return DTERR_TZDISP_OVERFLOW;
2735 /* otherwise, might have run things together... */
2736 else if (*cp == '\0' && strlen(str) > 3)
2740 /* we could, but don't, support a run-together hhmmss format */
2745 /* Range-check the values; see notes in datatype/timestamp.h */
2746 if (hr < 0 || hr > MAX_TZDISP_HOUR)
2747 return DTERR_TZDISP_OVERFLOW;
2748 if (min < 0 || min >= MINS_PER_HOUR)
2749 return DTERR_TZDISP_OVERFLOW;
2750 if (sec < 0 || sec >= SECS_PER_MINUTE)
2751 return DTERR_TZDISP_OVERFLOW;
2753 tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
2760 return DTERR_BAD_FORMAT;
2766 * Decode text string using lookup table.
2768 * Implement a cache lookup since it is likely that dates
2769 * will be related in format.
2771 * NB: this must *not* ereport on failure;
2772 * see commands/variable.c.
2775 DecodeSpecial(int field, char *lowtoken, int *val)
2780 tp = datecache[field];
2781 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
2783 tp = datebsearch(lowtoken, timezonetktbl, sztimezonetktbl);
2785 tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
2789 type = UNKNOWN_FIELD;
2794 datecache[field] = tp;
2816 * Zero out a pg_tm and associated fsec_t
2819 ClearPgTm(struct pg_tm * tm, fsec_t *fsec)
2832 * Interpret previously parsed fields for general time interval.
2833 * Returns 0 if successful, DTERR code if bogus input detected.
2834 * dtype, tm, fsec are output parameters.
2836 * Allow "date" field DTK_DATE since this could be just
2837 * an unsigned floating point number. - thomas 1997-11-16
2839 * Allow ISO-style time span, with implicit units on number of days
2840 * preceding an hh:mm:ss field. - thomas 1998-04-30
2843 DecodeInterval(char **field, int *ftype, int nf, int range,
2844 int *dtype, struct pg_tm * tm, fsec_t *fsec)
2846 bool is_before = FALSE;
2858 ClearPgTm(tm, fsec);
2860 /* read through list backwards to pick up units before values */
2861 for (i = nf - 1; i >= 0; i--)
2866 dterr = DecodeTime(field[i], fmask, range,
2876 * Timezone is a token with a leading sign character and at
2877 * least one digit; there could be ':', '.', '-' embedded in
2880 Assert(*field[i] == '-' || *field[i] == '+');
2883 * Try for hh:mm or hh:mm:ss. If not, fall through to
2884 * DTK_NUMBER case, which can handle signed float numbers and
2885 * signed year-month values.
2887 if (strchr(field[i] + 1, ':') != NULL &&
2888 DecodeTime(field[i] + 1, fmask, INTERVAL_FULL_RANGE,
2889 &tmask, tm, fsec) == 0)
2891 if (*field[i] == '-')
2893 /* flip the sign on all fields */
2894 tm->tm_hour = -tm->tm_hour;
2895 tm->tm_min = -tm->tm_min;
2896 tm->tm_sec = -tm->tm_sec;
2901 * Set the next type to be a day, if units are not
2902 * specified. This handles the case of '1 +02:03' since we
2903 * are reading right to left.
2913 if (type == IGNORE_DTF)
2915 /* use typmod to decide what rightmost field is */
2918 case INTERVAL_MASK(YEAR):
2921 case INTERVAL_MASK(MONTH):
2922 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
2925 case INTERVAL_MASK(DAY):
2928 case INTERVAL_MASK(HOUR):
2929 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
2932 case INTERVAL_MASK(MINUTE):
2933 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
2934 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
2937 case INTERVAL_MASK(SECOND):
2938 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2939 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2940 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2950 val = strtoi(field[i], &cp, 10);
2951 if (errno == ERANGE)
2952 return DTERR_FIELD_OVERFLOW;
2956 /* SQL "years-months" syntax */
2959 val2 = strtoi(cp + 1, &cp, 10);
2960 if (errno == ERANGE || val2 < 0 || val2 >= MONTHS_PER_YEAR)
2961 return DTERR_FIELD_OVERFLOW;
2963 return DTERR_BAD_FORMAT;
2965 if (*field[i] == '-')
2967 val = val * MONTHS_PER_YEAR + val2;
2970 else if (*cp == '.')
2973 fval = strtod(cp, &cp);
2974 if (*cp != '\0' || errno != 0)
2975 return DTERR_BAD_FORMAT;
2977 if (*field[i] == '-')
2980 else if (*cp == '\0')
2983 return DTERR_BAD_FORMAT;
2985 tmask = 0; /* DTK_M(type); */
2990 #ifdef HAVE_INT64_TIMESTAMP
2991 *fsec += rint(val + fval);
2993 *fsec += (val + fval) * 1e-6;
2995 tmask = DTK_M(MICROSECOND);
2999 /* avoid overflowing the fsec field */
3000 tm->tm_sec += val / 1000;
3001 val -= (val / 1000) * 1000;
3002 #ifdef HAVE_INT64_TIMESTAMP
3003 *fsec += rint((val + fval) * 1000);
3005 *fsec += (val + fval) * 1e-3;
3007 tmask = DTK_M(MILLISECOND);
3012 #ifdef HAVE_INT64_TIMESTAMP
3013 *fsec += rint(fval * 1000000);
3019 * If any subseconds were specified, consider this
3020 * microsecond and millisecond input as well.
3023 tmask = DTK_M(SECOND);
3025 tmask = DTK_ALL_SECS_M;
3030 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3031 tmask = DTK_M(MINUTE);
3036 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3037 tmask = DTK_M(HOUR);
3038 type = DTK_DAY; /* set for next field */
3043 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3048 tm->tm_mday += val * 7;
3049 AdjustFractDays(fval, tm, fsec, 7);
3050 tmask = DTK_M(WEEK);
3055 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3056 tmask = DTK_M(MONTH);
3062 tm->tm_mon += fval * MONTHS_PER_YEAR;
3063 tmask = DTK_M(YEAR);
3067 tm->tm_year += val * 10;
3069 tm->tm_mon += fval * MONTHS_PER_YEAR * 10;
3070 tmask = DTK_M(DECADE);
3074 tm->tm_year += val * 100;
3076 tm->tm_mon += fval * MONTHS_PER_YEAR * 100;
3077 tmask = DTK_M(CENTURY);
3080 case DTK_MILLENNIUM:
3081 tm->tm_year += val * 1000;
3083 tm->tm_mon += fval * MONTHS_PER_YEAR * 1000;
3084 tmask = DTK_M(MILLENNIUM);
3088 return DTERR_BAD_FORMAT;
3094 type = DecodeUnits(i, field[i], &val);
3095 if (type == IGNORE_DTF)
3098 tmask = 0; /* DTK_M(type); */
3111 tmask = (DTK_DATE_M | DTK_TIME_M);
3116 return DTERR_BAD_FORMAT;
3121 return DTERR_BAD_FORMAT;
3125 return DTERR_BAD_FORMAT;
3129 /* ensure that at least one time field has been found */
3131 return DTERR_BAD_FORMAT;
3133 /* ensure fractional seconds are fractional */
3138 #ifdef HAVE_INT64_TIMESTAMP
3139 sec = *fsec / USECS_PER_SEC;
3140 *fsec -= sec * USECS_PER_SEC;
3142 TMODULO(*fsec, sec, 1.0);
3148 * The SQL standard defines the interval literal
3150 * to mean "negative 1 days and negative 1 hours", while Postgres
3151 * traditionally treats this as meaning "negative 1 days and positive
3152 * 1 hours". In SQL_STANDARD intervalstyle, we apply the leading sign
3153 * to all fields if there are no other explicit signs.
3155 * We leave the signs alone if there are additional explicit signs.
3156 * This protects us against misinterpreting postgres-style dump output,
3157 * since the postgres-style output code has always put an explicit sign on
3158 * all fields following a negative field. But note that SQL-spec output
3159 * is ambiguous and can be misinterpreted on load! (So it's best practice
3160 * to dump in postgres style, not SQL style.)
3163 if (IntervalStyle == INTSTYLE_SQL_STANDARD && *field[0] == '-')
3165 /* Check for additional explicit signs */
3166 bool more_signs = false;
3168 for (i = 1; i < nf; i++)
3170 if (*field[i] == '-' || *field[i] == '+')
3180 * Rather than re-determining which field was field[0], just force
3186 tm->tm_sec = -tm->tm_sec;
3188 tm->tm_min = -tm->tm_min;
3189 if (tm->tm_hour > 0)
3190 tm->tm_hour = -tm->tm_hour;
3191 if (tm->tm_mday > 0)
3192 tm->tm_mday = -tm->tm_mday;
3194 tm->tm_mon = -tm->tm_mon;
3195 if (tm->tm_year > 0)
3196 tm->tm_year = -tm->tm_year;
3200 /* finally, AGO negates everything */
3204 tm->tm_sec = -tm->tm_sec;
3205 tm->tm_min = -tm->tm_min;
3206 tm->tm_hour = -tm->tm_hour;
3207 tm->tm_mday = -tm->tm_mday;
3208 tm->tm_mon = -tm->tm_mon;
3209 tm->tm_year = -tm->tm_year;
3217 * Helper functions to avoid duplicated code in DecodeISO8601Interval.
3219 * Parse a decimal value and break it into integer and fractional parts.
3220 * Returns 0 or DTERR code.
3223 ParseISO8601Number(char *str, char **endptr, int *ipart, double *fpart)
3227 if (!(isdigit((unsigned char) *str) || *str == '-' || *str == '.'))
3228 return DTERR_BAD_FORMAT;
3230 val = strtod(str, endptr);
3231 /* did we not see anything that looks like a double? */
3232 if (*endptr == str || errno != 0)
3233 return DTERR_BAD_FORMAT;
3234 /* watch out for overflow */
3235 if (val < INT_MIN || val > INT_MAX)
3236 return DTERR_FIELD_OVERFLOW;
3237 /* be very sure we truncate towards zero (cf dtrunc()) */
3239 *ipart = (int) floor(val);
3241 *ipart = (int) -floor(-val);
3242 *fpart = val - *ipart;
3247 * Determine number of integral digits in a valid ISO 8601 number field
3248 * (we should ignore sign and any fraction part)
3251 ISO8601IntegerWidth(char *fieldstart)
3253 /* We might have had a leading '-' */
3254 if (*fieldstart == '-')
3256 return strspn(fieldstart, "0123456789");
3260 /* DecodeISO8601Interval()
3261 * Decode an ISO 8601 time interval of the "format with designators"
3262 * (section 4.4.3.2) or "alternative format" (section 4.4.3.3)
3263 * Examples: P1D for 1 day
3265 * P2Y6M7DT1H30M for 2 years, 6 months, 7 days 1 hour 30 min
3266 * P0002-06-07T01:30:00 the same value in alternative format
3268 * Returns 0 if successful, DTERR code if bogus input detected.
3269 * Note: error code should be DTERR_BAD_FORMAT if input doesn't look like
3270 * ISO8601, otherwise this could cause unexpected error messages.
3271 * dtype, tm, fsec are output parameters.
3273 * A couple exceptions from the spec:
3274 * - a week field ('W') may coexist with other units
3275 * - allows decimals in fields other than the least significant unit.
3278 DecodeISO8601Interval(char *str,
3279 int *dtype, struct pg_tm * tm, fsec_t *fsec)
3281 bool datepart = true;
3282 bool havefield = false;
3285 ClearPgTm(tm, fsec);
3287 if (strlen(str) < 2 || str[0] != 'P')
3288 return DTERR_BAD_FORMAT;
3299 if (*str == 'T') /* T indicates the beginning of the time part */
3308 dterr = ParseISO8601Number(str, &str, &val, &fval);
3313 * Note: we could step off the end of the string here. Code below
3314 * *must* exit the loop if unit == '\0'.
3320 switch (unit) /* before T: Y M W D */
3324 tm->tm_mon += (fval * MONTHS_PER_YEAR);
3328 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3331 tm->tm_mday += val * 7;
3332 AdjustFractDays(fval, tm, fsec, 7);
3336 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3338 case 'T': /* ISO 8601 4.4.3.3 Alternative Format / Basic */
3340 if (ISO8601IntegerWidth(fieldstart) == 8 && !havefield)
3342 tm->tm_year += val / 10000;
3343 tm->tm_mon += (val / 100) % 100;
3344 tm->tm_mday += val % 100;
3345 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3352 /* Else fall through to extended alternative format */
3353 case '-': /* ISO 8601 4.4.3.3 Alternative Format,
3356 return DTERR_BAD_FORMAT;
3359 tm->tm_mon += (fval * MONTHS_PER_YEAR);
3369 dterr = ParseISO8601Number(str, &str, &val, &fval);
3373 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3383 return DTERR_BAD_FORMAT;
3386 dterr = ParseISO8601Number(str, &str, &val, &fval);
3390 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3399 return DTERR_BAD_FORMAT;
3401 /* not a valid date unit suffix */
3402 return DTERR_BAD_FORMAT;
3407 switch (unit) /* after T: H M S */
3411 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3415 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3419 AdjustFractSeconds(fval, tm, fsec, 1);
3421 case '\0': /* ISO 8601 4.4.3.3 Alternative Format */
3422 if (ISO8601IntegerWidth(fieldstart) == 6 && !havefield)
3424 tm->tm_hour += val / 10000;
3425 tm->tm_min += (val / 100) % 100;
3426 tm->tm_sec += val % 100;
3427 AdjustFractSeconds(fval, tm, fsec, 1);
3430 /* Else fall through to extended alternative format */
3431 case ':': /* ISO 8601 4.4.3.3 Alternative Format,
3434 return DTERR_BAD_FORMAT;
3437 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3441 dterr = ParseISO8601Number(str, &str, &val, &fval);
3445 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3449 return DTERR_BAD_FORMAT;
3452 dterr = ParseISO8601Number(str, &str, &val, &fval);
3456 AdjustFractSeconds(fval, tm, fsec, 1);
3459 return DTERR_BAD_FORMAT;
3462 /* not a valid time unit suffix */
3463 return DTERR_BAD_FORMAT;
3475 * Decode text string using lookup table.
3476 * This routine supports time interval decoding
3477 * (hence, it need not recognize timezone names).
3480 DecodeUnits(int field, char *lowtoken, int *val)
3485 tp = deltacache[field];
3486 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3488 tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
3492 type = UNKNOWN_FIELD;
3497 deltacache[field] = tp;
3499 if (type == TZ || type == DTZ)
3506 } /* DecodeUnits() */
3509 * Report an error detected by one of the datetime input processing routines.
3511 * dterr is the error code, str is the original input string, datatype is
3512 * the name of the datatype we were trying to accept.
3514 * Note: it might seem useless to distinguish DTERR_INTERVAL_OVERFLOW and
3515 * DTERR_TZDISP_OVERFLOW from DTERR_FIELD_OVERFLOW, but SQL99 mandates three
3516 * separate SQLSTATE codes, so ...
3519 DateTimeParseError(int dterr, const char *str, const char *datatype)
3523 case DTERR_FIELD_OVERFLOW:
3525 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3526 errmsg("date/time field value out of range: \"%s\"",
3529 case DTERR_MD_FIELD_OVERFLOW:
3530 /* <nanny>same as above, but add hint about DateStyle</nanny> */
3532 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3533 errmsg("date/time field value out of range: \"%s\"",
3535 errhint("Perhaps you need a different \"datestyle\" setting.")));
3537 case DTERR_INTERVAL_OVERFLOW:
3539 (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
3540 errmsg("interval field value out of range: \"%s\"",
3543 case DTERR_TZDISP_OVERFLOW:
3545 (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
3546 errmsg("time zone displacement out of range: \"%s\"",
3549 case DTERR_BAD_FORMAT:
3552 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
3553 errmsg("invalid input syntax for type %s: \"%s\"",
3560 * Binary search -- from Knuth (6.2.1) Algorithm B. Special case like this
3561 * is WAY faster than the generic bsearch().
3563 static const datetkn *
3564 datebsearch(const char *key, const datetkn *base, int nel)
3568 const datetkn *last = base + nel - 1,
3572 while (last >= base)
3574 position = base + ((last - base) >> 1);
3575 result = key[0] - position->token[0];
3578 result = strncmp(key, position->token, TOKMAXLEN);
3583 last = position - 1;
3585 base = position + 1;
3592 * Append representation of a numeric timezone offset to str.
3595 EncodeTimezone(char *str, int tz, int style)
3602 min = sec / SECS_PER_MINUTE;
3603 sec -= min * SECS_PER_MINUTE;
3604 hour = min / MINS_PER_HOUR;
3605 min -= hour * MINS_PER_HOUR;
3608 /* TZ is negated compared to sign we wish to display ... */
3609 *str++ = (tz <= 0 ? '+' : '-');
3612 sprintf(str, "%02d:%02d:%02d", hour, min, sec);
3613 else if (min != 0 || style == USE_XSD_DATES)
3614 sprintf(str, "%02d:%02d", hour, min);
3616 sprintf(str, "%02d", hour);
3620 * Encode date as local time.
3623 EncodeDateOnly(struct pg_tm * tm, int style, char *str)
3625 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3631 /* compatible with ISO date formats */
3632 if (tm->tm_year > 0)
3633 sprintf(str, "%04d-%02d-%02d",
3634 tm->tm_year, tm->tm_mon, tm->tm_mday);
3636 sprintf(str, "%04d-%02d-%02d %s",
3637 -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
3641 /* compatible with Oracle/Ingres date formats */
3642 if (DateOrder == DATEORDER_DMY)
3643 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3645 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3646 if (tm->tm_year > 0)
3647 sprintf(str + 5, "/%04d", tm->tm_year);
3649 sprintf(str + 5, "/%04d %s", -(tm->tm_year - 1), "BC");
3652 case USE_GERMAN_DATES:
3653 /* German-style date format */
3654 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3655 if (tm->tm_year > 0)
3656 sprintf(str + 5, ".%04d", tm->tm_year);
3658 sprintf(str + 5, ".%04d %s", -(tm->tm_year - 1), "BC");
3661 case USE_POSTGRES_DATES:
3663 /* traditional date-only style for Postgres */
3664 if (DateOrder == DATEORDER_DMY)
3665 sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
3667 sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
3668 if (tm->tm_year > 0)
3669 sprintf(str + 5, "-%04d", tm->tm_year);
3671 sprintf(str + 5, "-%04d %s", -(tm->tm_year - 1), "BC");
3678 * Encode time fields only.
3680 * tm and fsec are the value to encode, print_tz determines whether to include
3681 * a time zone (the difference between time and timetz types), tz is the
3682 * numeric time zone offset, style is the date style, str is where to write the
3686 EncodeTimeOnly(struct pg_tm * tm, fsec_t fsec, bool print_tz, int tz, int style, char *str)
3688 sprintf(str, "%02d:%02d:", tm->tm_hour, tm->tm_min);
3691 AppendSeconds(str, tm->tm_sec, fsec, MAX_TIME_PRECISION, true);
3694 EncodeTimezone(str, tz, style);
3699 * Encode date and time interpreted as local time.
3701 * tm and fsec are the value to encode, print_tz determines whether to include
3702 * a time zone (the difference between timestamp and timestamptz types), tz is
3703 * the numeric time zone offset, tzn is the textual time zone, which if
3704 * specified will be used instead of tz by some styles, style is the date
3705 * style, str is where to write the output.
3707 * Supported date styles:
3708 * Postgres - day mon hh:mm:ss yyyy tz
3709 * SQL - mm/dd/yyyy hh:mm:ss.ss tz
3710 * ISO - yyyy-mm-dd hh:mm:ss+/-tz
3711 * German - dd.mm.yyyy hh:mm:ss tz
3712 * XSD - yyyy-mm-ddThh:mm:ss.ss+/-tz
3715 EncodeDateTime(struct pg_tm * tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str)
3719 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3722 * Negative tm_isdst means we have no valid time zone translation.
3724 if (tm->tm_isdst < 0)
3731 /* Compatible with ISO-8601 date formats */
3733 if (style == USE_ISO_DATES)
3734 sprintf(str, "%04d-%02d-%02d %02d:%02d:",
3735 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3736 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3738 sprintf(str, "%04d-%02d-%02dT%02d:%02d:",
3739 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3740 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3742 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3745 EncodeTimezone(str, tz, style);
3747 if (tm->tm_year <= 0)
3748 sprintf(str + strlen(str), " BC");
3752 /* Compatible with Oracle/Ingres date formats */
3754 if (DateOrder == DATEORDER_DMY)
3755 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3757 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3759 sprintf(str + 5, "/%04d %02d:%02d:",
3760 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3761 tm->tm_hour, tm->tm_min);
3763 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3766 * Note: the uses of %.*s in this function would be risky if the
3767 * timezone names ever contain non-ASCII characters. However, all
3768 * TZ abbreviations in the Olson database are plain ASCII.
3774 sprintf(str + strlen(str), " %.*s", MAXTZLEN, tzn);
3776 EncodeTimezone(str, tz, style);
3779 if (tm->tm_year <= 0)
3780 sprintf(str + strlen(str), " BC");
3783 case USE_GERMAN_DATES:
3784 /* German variant on European style */
3786 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3788 sprintf(str + 5, ".%04d %02d:%02d:",
3789 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3790 tm->tm_hour, tm->tm_min);
3792 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3797 sprintf(str + strlen(str), " %.*s", MAXTZLEN, tzn);
3799 EncodeTimezone(str, tz, style);
3802 if (tm->tm_year <= 0)
3803 sprintf(str + strlen(str), " BC");
3806 case USE_POSTGRES_DATES:
3808 /* Backward-compatible with traditional Postgres abstime dates */
3810 day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3811 tm->tm_wday = j2day(day);
3813 strncpy(str, days[tm->tm_wday], 3);
3814 strcpy(str + 3, " ");
3816 if (DateOrder == DATEORDER_DMY)
3817 sprintf(str + 4, "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
3819 sprintf(str + 4, "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);
3821 sprintf(str + 10, " %02d:%02d:", tm->tm_hour, tm->tm_min);
3823 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3825 sprintf(str + strlen(str), " %04d",
3826 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1));
3831 sprintf(str + strlen(str), " %.*s", MAXTZLEN, tzn);
3835 * We have a time zone, but no string version. Use the
3836 * numeric form, but be sure to include a leading space to
3837 * avoid formatting something which would be rejected by
3838 * the date/time parser later. - thomas 2001-10-19
3840 sprintf(str + strlen(str), " ");
3841 EncodeTimezone(str, tz, style);
3845 if (tm->tm_year <= 0)
3846 sprintf(str + strlen(str), " BC");
3853 * Helper functions to avoid duplicated code in EncodeInterval.
3856 /* Append an ISO-8601-style interval field, but only if value isn't zero */
3858 AddISO8601IntPart(char *cp, int value, char units)
3862 sprintf(cp, "%d%c", value, units);
3863 return cp + strlen(cp);
3866 /* Append a postgres-style interval field, but only if value isn't zero */
3868 AddPostgresIntPart(char *cp, int value, const char *units,
3869 bool *is_zero, bool *is_before)
3873 sprintf(cp, "%s%s%d %s%s",
3874 (!*is_zero) ? " " : "",
3875 (*is_before && value > 0) ? "+" : "",
3878 (value != 1) ? "s" : "");
3881 * Each nonzero field sets is_before for (only) the next one. This is a
3882 * tad bizarre but it's how it worked before...
3884 *is_before = (value < 0);
3886 return cp + strlen(cp);
3889 /* Append a verbose-style interval field, but only if value isn't zero */
3891 AddVerboseIntPart(char *cp, int value, const char *units,
3892 bool *is_zero, bool *is_before)
3896 /* first nonzero value sets is_before */
3899 *is_before = (value < 0);
3902 else if (*is_before)
3904 sprintf(cp, " %d %s%s", value, units, (value == 1) ? "" : "s");
3906 return cp + strlen(cp);
3911 * Interpret time structure as a delta time and convert to string.
3913 * Support "traditional Postgres" and ISO-8601 styles.
3914 * Actually, afaik ISO does not address time interval formatting,
3915 * but this looks similar to the spec for absolute date/time.
3916 * - thomas 1998-04-30
3918 * Actually, afaik, ISO 8601 does specify formats for "time
3919 * intervals...[of the]...format with time-unit designators", which
3920 * are pretty ugly. The format looks something like
3921 * P1Y1M1DT1H1M1.12345S
3922 * but useful for exchanging data with computers instead of humans.
3925 * And ISO's SQL 2008 standard specifies standards for
3926 * "year-month literal"s (that look like '2-3') and
3927 * "day-time literal"s (that look like ('4 5:6:7')
3930 EncodeInterval(struct pg_tm * tm, fsec_t fsec, int style, char *str)
3933 int year = tm->tm_year;
3934 int mon = tm->tm_mon;
3935 int mday = tm->tm_mday;
3936 int hour = tm->tm_hour;
3937 int min = tm->tm_min;
3938 int sec = tm->tm_sec;
3939 bool is_before = FALSE;
3940 bool is_zero = TRUE;
3943 * The sign of year and month are guaranteed to match, since they are
3944 * stored internally as "month". But we'll need to check for is_before and
3945 * is_zero when determining the signs of day and hour/minute/seconds
3950 /* SQL Standard interval format */
3951 case INTSTYLE_SQL_STANDARD:
3953 bool has_negative = year < 0 || mon < 0 ||
3954 mday < 0 || hour < 0 ||
3955 min < 0 || sec < 0 || fsec < 0;
3956 bool has_positive = year > 0 || mon > 0 ||
3957 mday > 0 || hour > 0 ||
3958 min > 0 || sec > 0 || fsec > 0;
3959 bool has_year_month = year != 0 || mon != 0;
3960 bool has_day_time = mday != 0 || hour != 0 ||
3961 min != 0 || sec != 0 || fsec != 0;
3962 bool has_day = mday != 0;
3963 bool sql_standard_value = !(has_negative && has_positive) &&
3964 !(has_year_month && has_day_time);
3967 * SQL Standard wants only 1 "<sign>" preceding the whole
3968 * interval ... but can't do that if mixed signs.
3970 if (has_negative && sql_standard_value)
3982 if (!has_negative && !has_positive)
3986 else if (!sql_standard_value)
3989 * For non sql-standard interval values, force outputting
3990 * the signs to avoid ambiguities with intervals with
3991 * mixed sign components.
3993 char year_sign = (year < 0 || mon < 0) ? '-' : '+';
3994 char day_sign = (mday < 0) ? '-' : '+';
3995 char sec_sign = (hour < 0 || min < 0 ||
3996 sec < 0 || fsec < 0) ? '-' : '+';
3998 sprintf(cp, "%c%d-%d %c%d %c%d:%02d:",
3999 year_sign, abs(year), abs(mon),
4000 day_sign, abs(mday),
4001 sec_sign, abs(hour), abs(min));
4003 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4005 else if (has_year_month)
4007 sprintf(cp, "%d-%d", year, mon);
4011 sprintf(cp, "%d %d:%02d:", mday, hour, min);
4013 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4017 sprintf(cp, "%d:%02d:", hour, min);
4019 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4024 /* ISO 8601 "time-intervals by duration only" */
4025 case INTSTYLE_ISO_8601:
4026 /* special-case zero to avoid printing nothing */
4027 if (year == 0 && mon == 0 && mday == 0 &&
4028 hour == 0 && min == 0 && sec == 0 && fsec == 0)
4030 sprintf(cp, "PT0S");
4034 cp = AddISO8601IntPart(cp, year, 'Y');
4035 cp = AddISO8601IntPart(cp, mon, 'M');
4036 cp = AddISO8601IntPart(cp, mday, 'D');
4037 if (hour != 0 || min != 0 || sec != 0 || fsec != 0)
4039 cp = AddISO8601IntPart(cp, hour, 'H');
4040 cp = AddISO8601IntPart(cp, min, 'M');
4041 if (sec != 0 || fsec != 0)
4043 if (sec < 0 || fsec < 0)
4045 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4052 /* Compatible with postgresql < 8.4 when DateStyle = 'iso' */
4053 case INTSTYLE_POSTGRES:
4054 cp = AddPostgresIntPart(cp, year, "year", &is_zero, &is_before);
4057 * Ideally we should spell out "month" like we do for "year" and
4058 * "day". However, for backward compatibility, we can't easily
4059 * fix this. bjm 2011-05-24
4061 cp = AddPostgresIntPart(cp, mon, "mon", &is_zero, &is_before);
4062 cp = AddPostgresIntPart(cp, mday, "day", &is_zero, &is_before);
4063 if (is_zero || hour != 0 || min != 0 || sec != 0 || fsec != 0)
4065 bool minus = (hour < 0 || min < 0 || sec < 0 || fsec < 0);
4067 sprintf(cp, "%s%s%02d:%02d:",
4069 (minus ? "-" : (is_before ? "+" : "")),
4070 abs(hour), abs(min));
4072 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4076 /* Compatible with postgresql < 8.4 when DateStyle != 'iso' */
4077 case INTSTYLE_POSTGRES_VERBOSE:
4081 cp = AddVerboseIntPart(cp, year, "year", &is_zero, &is_before);
4082 cp = AddVerboseIntPart(cp, mon, "mon", &is_zero, &is_before);
4083 cp = AddVerboseIntPart(cp, mday, "day", &is_zero, &is_before);
4084 cp = AddVerboseIntPart(cp, hour, "hour", &is_zero, &is_before);
4085 cp = AddVerboseIntPart(cp, min, "min", &is_zero, &is_before);
4086 if (sec != 0 || fsec != 0)
4089 if (sec < 0 || (sec == 0 && fsec < 0))
4093 else if (!is_before)
4098 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4100 sprintf(cp, " sec%s",
4101 (abs(sec) != 1 || fsec != 0) ? "s" : "");
4104 /* identically zero? then put in a unitless zero... */
4115 * We've been burnt by stupid errors in the ordering of the datetkn tables
4116 * once too often. Arrange to check them during postmaster start.
4119 CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
4124 for (i = 1; i < nel; i++)
4126 if (strncmp(base[i - 1].token, base[i].token, TOKMAXLEN) >= 0)
4128 /* %.*s is safe since all our tokens are ASCII */
4129 elog(LOG, "ordering error in %s table: \"%.*s\" >= \"%.*s\"",
4131 TOKMAXLEN, base[i - 1].token,
4132 TOKMAXLEN, base[i].token);
4140 CheckDateTokenTables(void)
4144 Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
4145 Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
4147 ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
4148 ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
4153 * Common code for temporal protransform functions. Types time, timetz,
4154 * timestamp and timestamptz each have a range of allowed precisions. An
4155 * unspecified precision is rigorously equivalent to the highest specifiable
4158 * Note: timestamp_scale throws an error when the typmod is out of range, but
4159 * we can't get there from a cast: our typmodin will have caught it already.
4162 TemporalTransform(int32 max_precis, Node *node)
4164 FuncExpr *expr = (FuncExpr *) node;
4168 Assert(IsA(expr, FuncExpr));
4169 Assert(list_length(expr->args) >= 2);
4171 typmod = (Node *) lsecond(expr->args);
4173 if (IsA(typmod, Const) &&!((Const *) typmod)->constisnull)
4175 Node *source = (Node *) linitial(expr->args);
4176 int32 old_precis = exprTypmod(source);
4177 int32 new_precis = DatumGetInt32(((Const *) typmod)->constvalue);
4179 if (new_precis < 0 || new_precis == max_precis ||
4180 (old_precis >= 0 && new_precis >= old_precis))
4181 ret = relabel_to_typmod(source, new_precis);
4188 * This function gets called during timezone config file load or reload
4189 * to create the final array of timezone tokens. The argument array
4190 * is already sorted in name order. The data is converted to datetkn
4191 * format and installed in *tbl, which must be allocated by the caller.
4194 ConvertTimeZoneAbbrevs(TimeZoneAbbrevTable *tbl,
4195 struct tzEntry *abbrevs, int n)
4197 datetkn *newtbl = tbl->abbrevs;
4200 tbl->numabbrevs = n;
4201 for (i = 0; i < n; i++)
4203 strncpy(newtbl[i].token, abbrevs[i].abbrev, TOKMAXLEN);
4204 newtbl[i].type = abbrevs[i].is_dst ? DTZ : TZ;
4205 TOVAL(&newtbl[i], abbrevs[i].offset / MINS_PER_HOUR);
4208 /* Check the ordering, if testing */
4209 Assert(CheckDateTokenTable("timezone offset", newtbl, n));
4213 * Install a TimeZoneAbbrevTable as the active table.
4215 * Caller is responsible that the passed table doesn't go away while in use.
4218 InstallTimeZoneAbbrevs(TimeZoneAbbrevTable *tbl)
4222 timezonetktbl = tbl->abbrevs;
4223 sztimezonetktbl = tbl->numabbrevs;
4225 /* clear date cache in case it contains any stale timezone names */
4226 for (i = 0; i < MAXDATEFIELDS; i++)
4227 datecache[i] = NULL;
4231 * This set-returning function reads all the available time zone abbreviations
4232 * and returns a set of (abbrev, utc_offset, is_dst).
4235 pg_timezone_abbrevs(PG_FUNCTION_ARGS)
4237 FuncCallContext *funcctx;
4243 char buffer[TOKMAXLEN + 1];
4246 Interval *resInterval;
4248 /* stuff done only on the first call of the function */
4249 if (SRF_IS_FIRSTCALL())
4252 MemoryContext oldcontext;
4254 /* create a function context for cross-call persistence */
4255 funcctx = SRF_FIRSTCALL_INIT();
4258 * switch to memory context appropriate for multiple function calls
4260 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4262 /* allocate memory for user context */
4263 pindex = (int *) palloc(sizeof(int));
4265 funcctx->user_fctx = (void *) pindex;
4268 * build tupdesc for result tuples. This must match this function's
4271 tupdesc = CreateTemplateTupleDesc(3, false);
4272 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "abbrev",
4274 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "utc_offset",
4275 INTERVALOID, -1, 0);
4276 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_dst",
4279 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4280 MemoryContextSwitchTo(oldcontext);
4283 /* stuff done on every call of the function */
4284 funcctx = SRF_PERCALL_SETUP();
4285 pindex = (int *) funcctx->user_fctx;
4287 if (*pindex >= sztimezonetktbl)
4288 SRF_RETURN_DONE(funcctx);
4290 MemSet(nulls, 0, sizeof(nulls));
4293 * Convert name to text, using upcasing conversion that is the inverse of
4294 * what ParseDateTime() uses.
4296 strncpy(buffer, timezonetktbl[*pindex].token, TOKMAXLEN);
4297 buffer[TOKMAXLEN] = '\0'; /* may not be null-terminated */
4298 for (p = (unsigned char *) buffer; *p; p++)
4299 *p = pg_toupper(*p);
4301 values[0] = CStringGetTextDatum(buffer);
4303 MemSet(&tm, 0, sizeof(struct pg_tm));
4304 tm.tm_min = (-1) * FROMVAL(&timezonetktbl[*pindex]);
4305 resInterval = (Interval *) palloc(sizeof(Interval));
4306 tm2interval(&tm, 0, resInterval);
4307 values[1] = IntervalPGetDatum(resInterval);
4309 Assert(timezonetktbl[*pindex].type == DTZ ||
4310 timezonetktbl[*pindex].type == TZ);
4311 values[2] = BoolGetDatum(timezonetktbl[*pindex].type == DTZ);
4315 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4316 result = HeapTupleGetDatum(tuple);
4318 SRF_RETURN_NEXT(funcctx, result);
4322 * This set-returning function reads all the available full time zones
4323 * and returns a set of (name, abbrev, utc_offset, is_dst).
4326 pg_timezone_names(PG_FUNCTION_ARGS)
4328 MemoryContext oldcontext;
4329 FuncCallContext *funcctx;
4340 Interval *resInterval;
4343 /* stuff done only on the first call of the function */
4344 if (SRF_IS_FIRSTCALL())
4348 /* create a function context for cross-call persistence */
4349 funcctx = SRF_FIRSTCALL_INIT();
4352 * switch to memory context appropriate for multiple function calls
4354 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4356 /* initialize timezone scanning code */
4357 tzenum = pg_tzenumerate_start();
4358 funcctx->user_fctx = (void *) tzenum;
4361 * build tupdesc for result tuples. This must match this function's
4364 tupdesc = CreateTemplateTupleDesc(4, false);
4365 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
4367 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "abbrev",
4369 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "utc_offset",
4370 INTERVALOID, -1, 0);
4371 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_dst",
4374 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4375 MemoryContextSwitchTo(oldcontext);
4378 /* stuff done on every call of the function */
4379 funcctx = SRF_PERCALL_SETUP();
4380 tzenum = (pg_tzenum *) funcctx->user_fctx;
4382 /* search for another zone to display */
4385 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4386 tz = pg_tzenumerate_next(tzenum);
4387 MemoryContextSwitchTo(oldcontext);
4391 pg_tzenumerate_end(tzenum);
4392 funcctx->user_fctx = NULL;
4393 SRF_RETURN_DONE(funcctx);
4396 /* Convert now() to local time in this zone */
4397 if (timestamp2tm(GetCurrentTransactionStartTimestamp(),
4398 &tzoff, &tm, &fsec, &tzn, tz) != 0)
4399 continue; /* ignore if conversion fails */
4401 /* Ignore zic's rather silly "Factory" time zone */
4402 if (tzn && strcmp(tzn, "Local time zone must be set--see zic manual page") == 0)
4405 /* Found a displayable zone */
4409 MemSet(nulls, 0, sizeof(nulls));
4411 values[0] = CStringGetTextDatum(pg_get_timezone_name(tz));
4412 values[1] = CStringGetTextDatum(tzn ? tzn : "");
4414 MemSet(&itm, 0, sizeof(struct pg_tm));
4415 itm.tm_sec = -tzoff;
4416 resInterval = (Interval *) palloc(sizeof(Interval));
4417 tm2interval(&itm, 0, resInterval);
4418 values[2] = IntervalPGetDatum(resInterval);
4420 values[3] = BoolGetDatum(tm.tm_isdst > 0);
4422 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4423 result = HeapTupleGetDatum(tuple);
4425 SRF_RETURN_NEXT(funcctx, result);