1 /*-------------------------------------------------------------------------
4 * Support functions for date/time types.
6 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/utils/adt/datetime.c
13 *-------------------------------------------------------------------------
22 #include "access/htup_details.h"
23 #include "access/xact.h"
24 #include "catalog/pg_type.h"
26 #include "miscadmin.h"
27 #include "nodes/nodeFuncs.h"
28 #include "utils/builtins.h"
29 #include "utils/date.h"
30 #include "utils/datetime.h"
31 #include "utils/memutils.h"
32 #include "utils/tzparser.h"
35 static int DecodeNumber(int flen, char *field, bool haveTextMonth,
36 int fmask, int *tmask,
37 struct pg_tm * tm, fsec_t *fsec, bool *is2digits);
38 static int DecodeNumberField(int len, char *str,
39 int fmask, int *tmask,
40 struct pg_tm * tm, fsec_t *fsec, bool *is2digits);
41 static int DecodeTime(char *str, int fmask, int range,
42 int *tmask, struct pg_tm * tm, fsec_t *fsec);
43 static int DecodeTimezone(char *str, int *tzp);
44 static const datetkn *datebsearch(const char *key, const datetkn *base, int nel);
45 static int DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
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 const char *const months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
63 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
65 const char *const 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 token field is NOT guaranteed to be NULL-terminated.
94 * To keep this table reasonably small, we divide the value for TZ and DTZ
95 * entries by 15 (so they are on 15 minute boundaries) and truncate the token
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 /* token, type, value */
111 {EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
112 {DA_D, ADBC, AD}, /* "ad" for years > 0 */
113 {"allballs", RESERV, DTK_ZULU}, /* 00:00:00 */
117 {"at", IGNORE_DTF, 0}, /* "at" (throwaway) */
119 {"august", MONTH, 8},
120 {DB_C, ADBC, BC}, /* "bc" for years <= 0 */
121 {DCURRENT, RESERV, DTK_CURRENT}, /* "current" is always now */
122 {"d", UNITS, DTK_DAY}, /* "day of month" for ISO input */
124 {"december", MONTH, 12},
125 {"dow", RESERV, DTK_DOW}, /* day of week */
126 {"doy", RESERV, DTK_DOY}, /* day of year */
128 {EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
130 {"february", MONTH, 2},
133 {"h", UNITS, DTK_HOUR}, /* "hour" */
134 {LATE, RESERV, DTK_LATE}, /* "infinity" reserved for "late time" */
135 {INVALID, RESERV, DTK_INVALID}, /* "invalid" reserved for bad time */
136 {"isodow", RESERV, DTK_ISODOW}, /* ISO day of week, Sunday == 7 */
137 {"isoyear", UNITS, DTK_ISOYEAR}, /* year in terms of the ISO week date */
138 {"j", UNITS, DTK_JULIAN},
140 {"january", MONTH, 1},
141 {"jd", UNITS, DTK_JULIAN},
143 {"julian", UNITS, DTK_JULIAN},
147 {"m", UNITS, DTK_MONTH}, /* "month" for ISO input */
151 {"mm", UNITS, DTK_MINUTE}, /* "minute" for ISO input */
155 {"november", MONTH, 11},
156 {NOW, RESERV, DTK_NOW}, /* current transaction time */
158 {"october", MONTH, 10},
159 {"on", IGNORE_DTF, 0}, /* "on" (throwaway) */
161 {"s", UNITS, DTK_SECOND}, /* "seconds" for ISO input */
163 {"saturday", DOW, 6},
166 {"september", MONTH, 9},
169 {"t", ISOTIME, DTK_TIME}, /* Filler for ISO time fields */
173 {"thursday", DOW, 4},
174 {TODAY, RESERV, DTK_TODAY}, /* midnight */
175 {TOMORROW, RESERV, DTK_TOMORROW}, /* tomorrow midnight */
179 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
181 {"wednesday", DOW, 3},
183 {"y", UNITS, DTK_YEAR}, /* "year" for ISO input */
184 {YESTERDAY, RESERV, DTK_YESTERDAY} /* yesterday midnight */
187 static int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];
189 static const datetkn deltatktbl[] = {
190 /* token, type, value */
191 {"@", IGNORE_DTF, 0}, /* postgres relative prefix */
192 {DAGO, AGO, 0}, /* "ago" indicates negative time offset */
193 {"c", UNITS, DTK_CENTURY}, /* "century" relative */
194 {"cent", UNITS, DTK_CENTURY}, /* "century" relative */
195 {"centuries", UNITS, DTK_CENTURY}, /* "centuries" relative */
196 {DCENTURY, UNITS, DTK_CENTURY}, /* "century" relative */
197 {"d", UNITS, DTK_DAY}, /* "day" relative */
198 {DDAY, UNITS, DTK_DAY}, /* "day" relative */
199 {"days", UNITS, DTK_DAY}, /* "days" relative */
200 {"dec", UNITS, DTK_DECADE}, /* "decade" relative */
201 {DDECADE, UNITS, DTK_DECADE}, /* "decade" relative */
202 {"decades", UNITS, DTK_DECADE}, /* "decades" relative */
203 {"decs", UNITS, DTK_DECADE}, /* "decades" relative */
204 {"h", UNITS, DTK_HOUR}, /* "hour" relative */
205 {DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */
206 {"hours", UNITS, DTK_HOUR}, /* "hours" relative */
207 {"hr", UNITS, DTK_HOUR}, /* "hour" relative */
208 {"hrs", UNITS, DTK_HOUR}, /* "hours" relative */
209 {INVALID, RESERV, DTK_INVALID}, /* reserved for invalid time */
210 {"m", UNITS, DTK_MINUTE}, /* "minute" relative */
211 {"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
212 {"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
213 {"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
214 {DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
215 {"millisecon", UNITS, DTK_MILLISEC}, /* relative */
216 {"mils", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
217 {"min", UNITS, DTK_MINUTE}, /* "minute" relative */
218 {"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */
219 {DMINUTE, UNITS, DTK_MINUTE}, /* "minute" relative */
220 {"minutes", UNITS, DTK_MINUTE}, /* "minutes" relative */
221 {"mon", UNITS, DTK_MONTH}, /* "months" relative */
222 {"mons", UNITS, DTK_MONTH}, /* "months" relative */
223 {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
224 {"months", UNITS, DTK_MONTH},
225 {"ms", UNITS, DTK_MILLISEC},
226 {"msec", UNITS, DTK_MILLISEC},
227 {DMILLISEC, UNITS, DTK_MILLISEC},
228 {"mseconds", UNITS, DTK_MILLISEC},
229 {"msecs", UNITS, DTK_MILLISEC},
230 {"qtr", UNITS, DTK_QUARTER}, /* "quarter" relative */
231 {DQUARTER, UNITS, DTK_QUARTER}, /* "quarter" relative */
232 {"s", UNITS, DTK_SECOND},
233 {"sec", UNITS, DTK_SECOND},
234 {DSECOND, UNITS, DTK_SECOND},
235 {"seconds", UNITS, DTK_SECOND},
236 {"secs", UNITS, DTK_SECOND},
237 {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
238 {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
239 {"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */
240 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
241 {"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
242 {"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
243 {DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */
244 {"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
245 {"usecs", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
246 {"w", UNITS, DTK_WEEK}, /* "week" relative */
247 {DWEEK, UNITS, DTK_WEEK}, /* "week" relative */
248 {"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
249 {"y", UNITS, DTK_YEAR}, /* "year" relative */
250 {DYEAR, UNITS, DTK_YEAR}, /* "year" relative */
251 {"years", UNITS, DTK_YEAR}, /* "years" relative */
252 {"yr", UNITS, DTK_YEAR}, /* "year" relative */
253 {"yrs", UNITS, DTK_YEAR} /* "years" relative */
256 static int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];
258 static const datetkn *datecache[MAXDATEFIELDS] = {NULL};
260 static const datetkn *deltacache[MAXDATEFIELDS] = {NULL};
264 * strtoi --- just like strtol, but returns int not long
267 strtoi(const char *nptr, char **endptr, int base)
271 val = strtol(nptr, endptr, base);
272 #ifdef HAVE_LONG_INT_64
273 if (val != (long) ((int32) val))
281 * Calendar time to Julian date conversions.
282 * Julian date is commonly used in astronomical applications,
283 * since it is numerically accurate and computationally simple.
284 * The algorithms here will accurately convert between Julian day
285 * and calendar date for all non-negative Julian days
286 * (i.e. from Nov 24, -4713 on).
288 * These routines will be used by other date/time packages
291 * Rewritten to eliminate overflow problems. This now allows the
292 * routines to work correctly for all Julian day counts from
293 * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming
294 * a 32-bit integer. Longer types should also work to the limits
295 * of their precision.
299 date2j(int y, int m, int d)
316 julian = y * 365 - 32167;
317 julian += y / 4 - century + century / 4;
318 julian += 7834 * m / 256 + d;
324 j2date(int jd, int *year, int *month, int *day)
333 quad = julian / 146097;
334 extra = (julian - quad * 146097) * 4 + 3;
335 julian += 60 + quad * 3 + extra / 146097;
336 quad = julian / 1461;
337 julian -= quad * 1461;
338 y = julian * 4 / 1461;
339 julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
343 quad = julian * 2141 / 65536;
344 *day = julian - 7834 * quad / 256;
345 *month = (quad + 10) % MONTHS_PER_YEAR + 1;
352 * j2day - convert Julian date to day-of-week (0..6 == Sun..Sat)
354 * Note: various places use the locution j2day(date - 1) to produce a
355 * result according to the convention 0..6 = Mon..Sun. This is a bit of
356 * a crock, but will work as long as the computation here is just a modulo.
373 * GetCurrentDateTime()
375 * Get the transaction start time ("now()") broken down as a struct pg_tm.
378 GetCurrentDateTime(struct pg_tm * tm)
383 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, &fsec,
385 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
389 * GetCurrentTimeUsec()
391 * Get the transaction start time ("now()") broken down as a struct pg_tm,
392 * including fractional seconds and timezone offset.
395 GetCurrentTimeUsec(struct pg_tm * tm, fsec_t *fsec, int *tzp)
399 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, fsec,
401 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
407 /* TrimTrailingZeros()
408 * ... resulting from printing numbers with full precision.
410 * Before Postgres 8.4, this always left at least 2 fractional digits,
411 * but conversations on the lists suggest this isn't desired
412 * since showing '0.10' is misleading with values of precision(1).
415 TrimTrailingZeros(char *str)
417 int len = strlen(str);
419 while (len > 1 && *(str + len - 1) == '0' && *(str + len - 2) != '.')
427 * Append sections and fractional seconds (if any) at *cp.
428 * precision is the max number of fraction digits, fillzeros says to
429 * pad to two integral-seconds digits.
430 * Note that any sign is stripped from the input seconds values.
433 AppendSeconds(char *cp, int sec, fsec_t fsec, int precision, bool fillzeros)
438 sprintf(cp, "%02d", abs(sec));
440 sprintf(cp, "%d", abs(sec));
444 #ifdef HAVE_INT64_TIMESTAMP
446 sprintf(cp, "%02d.%0*d", abs(sec), precision, (int) Abs(fsec));
448 sprintf(cp, "%d.%0*d", abs(sec), precision, (int) Abs(fsec));
451 sprintf(cp, "%0*.*f", precision + 3, precision, fabs(sec + fsec));
453 sprintf(cp, "%.*f", precision, fabs(sec + fsec));
455 TrimTrailingZeros(cp);
459 /* Variant of above that's specialized to timestamp case */
461 AppendTimestampSeconds(char *cp, struct pg_tm * tm, fsec_t fsec)
464 * In float mode, don't print fractional seconds before 1 AD, since it's
465 * unlikely there's any precision left ...
467 #ifndef HAVE_INT64_TIMESTAMP
468 if (tm->tm_year <= 0)
471 AppendSeconds(cp, tm->tm_sec, fsec, MAX_TIMESTAMP_PRECISION, true);
475 * Multiply frac by scale (to produce seconds) and add to *tm & *fsec.
476 * We assume the input frac is less than 1 so overflow is not an issue.
479 AdjustFractSeconds(double frac, struct pg_tm * tm, fsec_t *fsec, int scale)
489 #ifdef HAVE_INT64_TIMESTAMP
490 *fsec += rint(frac * 1000000);
496 /* As above, but initial scale produces days */
498 AdjustFractDays(double frac, struct pg_tm * tm, fsec_t *fsec, int scale)
505 extra_days = (int) frac;
506 tm->tm_mday += extra_days;
508 AdjustFractSeconds(frac, tm, fsec, SECS_PER_DAY);
511 /* Fetch a fractional-second value with suitable error checking */
513 ParseFractionalSecond(char *cp, fsec_t *fsec)
517 /* Caller should always pass the start of the fraction part */
520 frac = strtod(cp, &cp);
521 /* check for parse failure */
522 if (*cp != '\0' || errno != 0)
523 return DTERR_BAD_FORMAT;
524 #ifdef HAVE_INT64_TIMESTAMP
525 *fsec = rint(frac * 1000000);
534 * Break string into tokens based on a date/time context.
535 * Returns 0 if successful, DTERR code if bogus input detected.
537 * timestr - the input string
538 * workbuf - workspace for field string storage. This must be
539 * larger than the largest legal input for this datetime type --
540 * some additional space will be needed to NUL terminate fields.
541 * buflen - the size of workbuf
542 * field[] - pointers to field strings are returned in this array
543 * ftype[] - field type indicators are returned in this array
544 * maxfields - dimensions of the above two arrays
545 * *numfields - set to the actual number of fields detected
547 * The fields extracted from the input are stored as separate,
548 * null-terminated strings in the workspace at workbuf. Any text is
549 * converted to lower case.
551 * Several field types are assigned:
552 * DTK_NUMBER - digits and (possibly) a decimal point
553 * DTK_DATE - digits and two delimiters, or digits and text
554 * DTK_TIME - digits, colon delimiters, and possibly a decimal point
555 * DTK_STRING - text (no digits or punctuation)
556 * DTK_SPECIAL - leading "+" or "-" followed by text
557 * DTK_TZ - leading "+" or "-" followed by digits (also eats ':', '.', '-')
559 * Note that some field types can hold unexpected items:
560 * DTK_NUMBER can hold date fields (yy.ddd)
561 * DTK_STRING can hold months (January) and time zones (PST)
562 * DTK_DATE can hold time zone names (America/New_York, GMT-8)
565 ParseDateTime(const char *timestr, char *workbuf, size_t buflen,
566 char **field, int *ftype, int maxfields, int *numfields)
569 const char *cp = timestr;
570 char *bufp = workbuf;
571 const char *bufend = workbuf + buflen;
574 * Set the character pointed-to by "bufptr" to "newchar", and increment
575 * "bufptr". "end" gives the end of the buffer -- we return an error if
576 * there is no space left to append a character to the buffer. Note that
577 * "bufptr" is evaluated twice.
579 #define APPEND_CHAR(bufptr, end, newchar) \
582 if (((bufptr) + 1) >= (end)) \
583 return DTERR_BAD_FORMAT; \
584 *(bufptr)++ = newchar; \
587 /* outer loop through fields */
590 /* Ignore spaces between fields */
591 if (isspace((unsigned char) *cp))
597 /* Record start of current field */
599 return DTERR_BAD_FORMAT;
602 /* leading digit? then date or time */
603 if (isdigit((unsigned char) *cp))
605 APPEND_CHAR(bufp, bufend, *cp++);
606 while (isdigit((unsigned char) *cp))
607 APPEND_CHAR(bufp, bufend, *cp++);
612 ftype[nf] = DTK_TIME;
613 APPEND_CHAR(bufp, bufend, *cp++);
614 while (isdigit((unsigned char) *cp) ||
615 (*cp == ':') || (*cp == '.'))
616 APPEND_CHAR(bufp, bufend, *cp++);
618 /* date field? allow embedded text month */
619 else if (*cp == '-' || *cp == '/' || *cp == '.')
621 /* save delimiting character to use later */
624 APPEND_CHAR(bufp, bufend, *cp++);
625 /* second field is all digits? then no embedded text month */
626 if (isdigit((unsigned char) *cp))
628 ftype[nf] = ((delim == '.') ? DTK_NUMBER : DTK_DATE);
629 while (isdigit((unsigned char) *cp))
630 APPEND_CHAR(bufp, bufend, *cp++);
633 * insist that the delimiters match to get a three-field
638 ftype[nf] = DTK_DATE;
639 APPEND_CHAR(bufp, bufend, *cp++);
640 while (isdigit((unsigned char) *cp) || *cp == delim)
641 APPEND_CHAR(bufp, bufend, *cp++);
646 ftype[nf] = DTK_DATE;
647 while (isalnum((unsigned char) *cp) || *cp == delim)
648 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
653 * otherwise, number only and will determine year, month, day, or
654 * concatenated fields later...
657 ftype[nf] = DTK_NUMBER;
659 /* Leading decimal point? Then fractional seconds... */
662 APPEND_CHAR(bufp, bufend, *cp++);
663 while (isdigit((unsigned char) *cp))
664 APPEND_CHAR(bufp, bufend, *cp++);
666 ftype[nf] = DTK_NUMBER;
670 * text? then date string, month, day of week, special, or timezone
672 else if (isalpha((unsigned char) *cp))
676 ftype[nf] = DTK_STRING;
677 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
678 while (isalpha((unsigned char) *cp))
679 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
682 * Dates can have embedded '-', '/', or '.' separators. It could
683 * also be a timezone name containing embedded '/', '+', '-', '_',
684 * or ':' (but '_' or ':' can't be the first punctuation). If the
685 * next character is a digit or '+', we need to check whether what
686 * we have so far is a recognized non-timezone keyword --- if so,
687 * don't believe that this is the start of a timezone.
690 if (*cp == '-' || *cp == '/' || *cp == '.')
692 else if (*cp == '+' || isdigit((unsigned char) *cp))
694 *bufp = '\0'; /* null-terminate current field value */
695 /* we need search only the core token table, not TZ names */
696 if (datebsearch(field[nf], datetktbl, szdatetktbl) == NULL)
701 ftype[nf] = DTK_DATE;
704 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
705 } while (*cp == '+' || *cp == '-' ||
706 *cp == '/' || *cp == '_' ||
707 *cp == '.' || *cp == ':' ||
708 isalnum((unsigned char) *cp));
711 /* sign? then special or numeric timezone */
712 else if (*cp == '+' || *cp == '-')
714 APPEND_CHAR(bufp, bufend, *cp++);
715 /* soak up leading whitespace */
716 while (isspace((unsigned char) *cp))
718 /* numeric timezone? */
719 /* note that "DTK_TZ" could also be a signed float or yyyy-mm */
720 if (isdigit((unsigned char) *cp))
723 APPEND_CHAR(bufp, bufend, *cp++);
724 while (isdigit((unsigned char) *cp) ||
725 *cp == ':' || *cp == '.' || *cp == '-')
726 APPEND_CHAR(bufp, bufend, *cp++);
729 else if (isalpha((unsigned char) *cp))
731 ftype[nf] = DTK_SPECIAL;
732 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
733 while (isalpha((unsigned char) *cp))
734 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
736 /* otherwise something wrong... */
738 return DTERR_BAD_FORMAT;
740 /* ignore other punctuation but use as delimiter */
741 else if (ispunct((unsigned char) *cp))
746 /* otherwise, something is not right... */
748 return DTERR_BAD_FORMAT;
750 /* force in a delimiter after each field */
762 * Interpret previously parsed fields for general date and time.
763 * Return 0 if full date, 1 if only time, and negative DTERR code if problems.
764 * (Currently, all callers treat 1 as an error return too.)
766 * External format(s):
767 * "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
768 * "Fri Feb-7-1997 15:23:27"
769 * "Feb-7-1997 15:23:27"
770 * "2-7-1997 15:23:27"
771 * "1997-2-7 15:23:27"
772 * "1997.038 15:23:27" (day of year 1-366)
773 * Also supports input in compact time:
776 * "20011225T040506.789-07"
778 * Use the system-provided functions to get the current time zone
779 * if not specified in the input string.
781 * If the date is outside the range of pg_time_t (in practice that could only
782 * happen if pg_time_t is just 32 bits), then assume UTC time zone - thomas
786 DecodeDateTime(char **field, int *ftype, int nf,
787 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
792 int ptype = 0; /* "prefix type" for ISO y2001m02d04 format */
797 bool haveTextMonth = FALSE;
798 bool isjulian = FALSE;
799 bool is2digits = FALSE;
801 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);
838 if (errno == ERANGE || val < 0)
839 return DTERR_FIELD_OVERFLOW;
841 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
844 /* Get the time zone from the end of the string */
845 dterr = DecodeTimezone(cp, tzp);
849 tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
854 * Already have a date? Then this might be a time zone name
855 * with embedded punctuation (e.g. "America/New_York") or a
856 * run-together time with trailing time zone (e.g. hhmmss-zz).
857 * - thomas 2001-12-25
859 * We consider it a time zone if we already have month & day.
860 * This is to allow the form "mmm dd hhmmss tz year", which
861 * we've historically accepted.
863 else if (ptype != 0 ||
864 ((fmask & (DTK_M(MONTH) | DTK_M(DAY))) ==
865 (DTK_M(MONTH) | DTK_M(DAY))))
867 /* No time zone accepted? Then quit... */
869 return DTERR_BAD_FORMAT;
871 if (isdigit((unsigned char) *field[i]) || ptype != 0)
877 /* Sanity check; should not fail this test */
878 if (ptype != DTK_TIME)
879 return DTERR_BAD_FORMAT;
884 * Starts with a digit but we already have a time
885 * field? Then we are in trouble with a date and time
888 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
889 return DTERR_BAD_FORMAT;
891 if ((cp = strchr(field[i], '-')) == NULL)
892 return DTERR_BAD_FORMAT;
894 /* Get the time zone from the end of the string */
895 dterr = DecodeTimezone(cp, tzp);
901 * Then read the rest of the field as a concatenated
904 dterr = DecodeNumberField(strlen(field[i]), field[i],
912 * modify tmask after returning from
913 * DecodeNumberField()
919 namedTz = pg_tzset(field[i]);
923 * We should return an error code instead of
924 * ereport'ing directly, but then there is no way
925 * to report the bad time zone name.
928 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
929 errmsg("time zone \"%s\" not recognized",
932 /* we'll apply the zone setting below */
938 dterr = DecodeDate(field[i], fmask,
939 &tmask, &is2digits, tm);
948 * This might be an ISO time following a "t" field.
952 /* Sanity check; should not fail this test */
953 if (ptype != DTK_TIME)
954 return DTERR_BAD_FORMAT;
957 dterr = DecodeTime(field[i], fmask, INTERVAL_FULL_RANGE,
963 * Check upper limit on hours; other limits checked in
966 /* test for > 24:00:00 */
967 if (tm->tm_hour > HOURS_PER_DAY ||
968 (tm->tm_hour == HOURS_PER_DAY &&
969 (tm->tm_min > 0 || tm->tm_sec > 0 || *fsec > 0)))
970 return DTERR_FIELD_OVERFLOW;
978 return DTERR_BAD_FORMAT;
980 dterr = DecodeTimezone(field[i], &tz);
991 * Was this an "ISO date" with embedded field labels? An
992 * example is "y2001m02d04" - thomas 2001-02-04
1000 val = strtoi(field[i], &cp, 10);
1001 if (errno == ERANGE)
1002 return DTERR_FIELD_OVERFLOW;
1005 * only a few kinds are allowed to have an embedded
1016 return DTERR_BAD_FORMAT;
1019 else if (*cp != '\0')
1020 return DTERR_BAD_FORMAT;
1026 tmask = DTK_M(YEAR);
1032 * already have a month and hour? then assume
1035 if ((fmask & DTK_M(MONTH)) != 0 &&
1036 (fmask & DTK_M(HOUR)) != 0)
1039 tmask = DTK_M(MINUTE);
1044 tmask = DTK_M(MONTH);
1055 tmask = DTK_M(HOUR);
1060 tmask = DTK_M(MINUTE);
1065 tmask = DTK_M(SECOND);
1068 dterr = ParseFractionalSecond(cp, fsec);
1071 tmask = DTK_ALL_SECS_M;
1077 dterr = DecodeTimezone(field[i], tzp);
1083 /* previous field was a label for "julian date" */
1085 return DTERR_FIELD_OVERFLOW;
1087 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1090 /* fractional Julian Day? */
1096 time = strtod(cp, &cp);
1097 if (*cp != '\0' || errno != 0)
1098 return DTERR_BAD_FORMAT;
1100 #ifdef HAVE_INT64_TIMESTAMP
1101 time *= USECS_PER_DAY;
1103 time *= SECS_PER_DAY;
1106 &tm->tm_hour, &tm->tm_min,
1108 tmask |= DTK_TIME_M;
1113 /* previous field was "t" for ISO time */
1114 dterr = DecodeNumberField(strlen(field[i]), field[i],
1115 (fmask | DTK_DATE_M),
1120 if (tmask != DTK_TIME_M)
1121 return DTERR_BAD_FORMAT;
1125 return DTERR_BAD_FORMAT;
1137 flen = strlen(field[i]);
1138 cp = strchr(field[i], '.');
1140 /* Embedded decimal and no date yet? */
1141 if (cp != NULL && !(fmask & DTK_DATE_M))
1143 dterr = DecodeDate(field[i], fmask,
1144 &tmask, &is2digits, tm);
1148 /* embedded decimal and several digits before? */
1149 else if (cp != NULL && flen - strlen(cp) > 2)
1152 * Interpret as a concatenated date or time Set the
1153 * type field to allow decoding other fields later.
1154 * Example: 20011223 or 040506
1156 dterr = DecodeNumberField(flen, field[i], fmask,
1163 * Is this a YMD or HMS specification, or a year number?
1164 * YMD and HMS are required to be six digits or more, so
1165 * if it is 5 digits, it is a year. If it is six or more
1166 * more digits, we assume it is YMD or HMS unless no date
1167 * and no time values have been specified. This forces
1168 * 6+ digit years to be at the end of the string, or to use
1169 * the ISO date specification.
1171 else if (flen >= 6 && (!(fmask & DTK_DATE_M) ||
1172 !(fmask & DTK_TIME_M)))
1174 dterr = DecodeNumberField(flen, field[i], fmask,
1180 /* otherwise it is a single date/time field... */
1183 dterr = DecodeNumber(flen, field[i],
1184 haveTextMonth, fmask,
1195 type = DecodeSpecial(i, field[i], &val);
1196 if (type == IGNORE_DTF)
1199 tmask = DTK_M(type);
1207 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1208 errmsg("date/time value \"current\" is no longer supported")));
1210 return DTERR_BAD_FORMAT;
1214 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1216 GetCurrentTimeUsec(tm, fsec, tzp);
1222 GetCurrentDateTime(&cur_tm);
1223 j2date(date2j(cur_tm.tm_year, cur_tm.tm_mon, cur_tm.tm_mday) - 1,
1224 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1230 GetCurrentDateTime(&cur_tm);
1231 tm->tm_year = cur_tm.tm_year;
1232 tm->tm_mon = cur_tm.tm_mon;
1233 tm->tm_mday = cur_tm.tm_mday;
1239 GetCurrentDateTime(&cur_tm);
1240 j2date(date2j(cur_tm.tm_year, cur_tm.tm_mon, cur_tm.tm_mday) + 1,
1241 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1245 tmask = (DTK_TIME_M | DTK_M(TZ));
1263 * already have a (numeric) month? then see if we can
1266 if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
1267 !(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 &&
1270 tm->tm_mday = tm->tm_mon;
1273 haveTextMonth = TRUE;
1280 * daylight savings time modifier (solves "MET DST"
1283 tmask |= DTK_M(DTZ);
1286 return DTERR_BAD_FORMAT;
1287 *tzp += val * MINS_PER_HOUR;
1293 * set mask for TZ here _or_ check for DTZ later when
1294 * getting default timezone
1299 return DTERR_BAD_FORMAT;
1300 *tzp = val * MINS_PER_HOUR;
1306 return DTERR_BAD_FORMAT;
1307 *tzp = val * MINS_PER_HOUR;
1333 * This is a filler field "t" indicating that the next
1334 * field is time. Try to verify that this is sensible.
1338 /* No preceding date? Then quit... */
1339 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1340 return DTERR_BAD_FORMAT;
1343 * We will need one of the following fields:
1344 * DTK_NUMBER should be hhmmss.fff
1345 * DTK_TIME should be hh:mm:ss.fff
1346 * DTK_DATE should be hhmmss-zz
1349 (ftype[i + 1] != DTK_NUMBER &&
1350 ftype[i + 1] != DTK_TIME &&
1351 ftype[i + 1] != DTK_DATE))
1352 return DTERR_BAD_FORMAT;
1360 * Before giving up and declaring error, check to see
1361 * if it is an all-alpha timezone name.
1363 namedTz = pg_tzset(field[i]);
1365 return DTERR_BAD_FORMAT;
1366 /* we'll apply the zone setting below */
1371 return DTERR_BAD_FORMAT;
1376 return DTERR_BAD_FORMAT;
1380 return DTERR_BAD_FORMAT;
1382 } /* end loop over fields */
1384 /* do final checking/adjustment of Y/M/D fields */
1385 dterr = ValidateDate(fmask, isjulian, is2digits, bc, tm);
1390 if (mer != HR24 && tm->tm_hour > HOURS_PER_DAY / 2)
1391 return DTERR_FIELD_OVERFLOW;
1392 if (mer == AM && tm->tm_hour == HOURS_PER_DAY / 2)
1394 else if (mer == PM && tm->tm_hour != HOURS_PER_DAY / 2)
1395 tm->tm_hour += HOURS_PER_DAY / 2;
1397 /* do additional checking for full date specs... */
1398 if (*dtype == DTK_DATE)
1400 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1402 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1404 return DTERR_BAD_FORMAT;
1408 * If we had a full timezone spec, compute the offset (we could not do
1409 * it before, because we need the date to resolve DST status).
1411 if (namedTz != NULL)
1413 /* daylight savings time modifier disallowed with full TZ */
1414 if (fmask & DTK_M(DTZMOD))
1415 return DTERR_BAD_FORMAT;
1417 *tzp = DetermineTimeZoneOffset(tm, namedTz);
1420 /* timezone not specified? then find local timezone if possible */
1421 if (tzp != NULL && !(fmask & DTK_M(TZ)))
1424 * daylight savings time modifier but no standard timezone? then
1427 if (fmask & DTK_M(DTZMOD))
1428 return DTERR_BAD_FORMAT;
1430 *tzp = DetermineTimeZoneOffset(tm, session_timezone);
1438 /* DetermineTimeZoneOffset()
1440 * Given a struct pg_tm in which tm_year, tm_mon, tm_mday, tm_hour, tm_min, and
1441 * tm_sec fields are set, attempt to determine the applicable time zone
1442 * (ie, regular or daylight-savings time) at that time. Set the struct pg_tm's
1443 * tm_isdst field accordingly, and return the actual timezone offset.
1445 * Note: it might seem that we should use mktime() for this, but bitter
1446 * experience teaches otherwise. This code is much faster than most versions
1447 * of mktime(), anyway.
1450 DetermineTimeZoneOffset(struct pg_tm * tm, pg_tz *tzp)
1460 long int before_gmtoff,
1467 * First, generate the pg_time_t value corresponding to the given
1468 * y/m/d/h/m/s taken as GMT time. If this overflows, punt and decide the
1469 * timezone is GMT. (We only need to worry about overflow on machines
1470 * where pg_time_t is 32 bits.)
1472 if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
1474 date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - UNIX_EPOCH_JDATE;
1476 day = ((pg_time_t) date) * SECS_PER_DAY;
1477 if (day / SECS_PER_DAY != date)
1479 sec = tm->tm_sec + (tm->tm_min + tm->tm_hour * MINS_PER_HOUR) * SECS_PER_MINUTE;
1481 /* since sec >= 0, overflow could only be from +day to -mytime */
1482 if (mytime < 0 && day > 0)
1486 * Find the DST time boundary just before or following the target time. We
1487 * assume that all zones have GMT offsets less than 24 hours, and that DST
1488 * boundaries can't be closer together than 48 hours, so backing up 24
1489 * hours and finding the "next" boundary will work.
1491 prevtime = mytime - SECS_PER_DAY;
1492 if (mytime < 0 && prevtime > 0)
1495 res = pg_next_dst_boundary(&prevtime,
1496 &before_gmtoff, &before_isdst,
1498 &after_gmtoff, &after_isdst,
1501 goto overflow; /* failure? */
1505 /* Non-DST zone, life is simple */
1506 tm->tm_isdst = before_isdst;
1507 return -(int) before_gmtoff;
1511 * Form the candidate pg_time_t values with local-time adjustment
1513 beforetime = mytime - before_gmtoff;
1514 if ((before_gmtoff > 0 &&
1515 mytime < 0 && beforetime > 0) ||
1516 (before_gmtoff <= 0 &&
1517 mytime > 0 && beforetime < 0))
1519 aftertime = mytime - after_gmtoff;
1520 if ((after_gmtoff > 0 &&
1521 mytime < 0 && aftertime > 0) ||
1522 (after_gmtoff <= 0 &&
1523 mytime > 0 && aftertime < 0))
1527 * If both before or both after the boundary time, we know what to do
1529 if (beforetime <= boundary && aftertime < boundary)
1531 tm->tm_isdst = before_isdst;
1532 return -(int) before_gmtoff;
1534 if (beforetime > boundary && aftertime >= boundary)
1536 tm->tm_isdst = after_isdst;
1537 return -(int) after_gmtoff;
1541 * It's an invalid or ambiguous time due to timezone transition. Prefer
1542 * the standard-time interpretation.
1544 if (after_isdst == 0)
1546 tm->tm_isdst = after_isdst;
1547 return -(int) after_gmtoff;
1549 tm->tm_isdst = before_isdst;
1550 return -(int) before_gmtoff;
1553 /* Given date is out of range, so assume UTC */
1560 * Interpret parsed string as time fields only.
1561 * Returns 0 if successful, DTERR code if bogus input detected.
1563 * Note that support for time zone is here for
1564 * SQL TIME WITH TIME ZONE, but it reveals
1565 * bogosity with SQL date/time standards, since
1566 * we must infer a time zone from current time.
1567 * - thomas 2000-03-10
1568 * Allow specifying date to get a better time zone,
1569 * if time zones are allowed. - thomas 2001-12-26
1572 DecodeTimeOnly(char **field, int *ftype, int nf,
1573 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
1578 int ptype = 0; /* "prefix type" for ISO h04mm05s06 format */
1582 bool isjulian = FALSE;
1583 bool is2digits = FALSE;
1586 pg_tz *namedTz = NULL;
1593 /* don't know daylight savings time status apriori */
1599 for (i = 0; i < nf; i++)
1606 * Time zone not allowed? Then should not accept dates or time
1607 * zones no matter what else!
1610 return DTERR_BAD_FORMAT;
1612 /* Under limited circumstances, we will accept a date... */
1613 if (i == 0 && nf >= 2 &&
1614 (ftype[nf - 1] == DTK_DATE || ftype[1] == DTK_TIME))
1616 dterr = DecodeDate(field[i], fmask,
1617 &tmask, &is2digits, tm);
1621 /* otherwise, this is a time and/or time zone */
1624 if (isdigit((unsigned char) *field[i]))
1629 * Starts with a digit but we already have a time
1630 * field? Then we are in trouble with time already...
1632 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1633 return DTERR_BAD_FORMAT;
1636 * Should not get here and fail. Sanity check only...
1638 if ((cp = strchr(field[i], '-')) == NULL)
1639 return DTERR_BAD_FORMAT;
1641 /* Get the time zone from the end of the string */
1642 dterr = DecodeTimezone(cp, tzp);
1648 * Then read the rest of the field as a concatenated
1651 dterr = DecodeNumberField(strlen(field[i]), field[i],
1652 (fmask | DTK_DATE_M),
1663 namedTz = pg_tzset(field[i]);
1667 * We should return an error code instead of
1668 * ereport'ing directly, but then there is no way
1669 * to report the bad time zone name.
1672 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1673 errmsg("time zone \"%s\" not recognized",
1676 /* we'll apply the zone setting below */
1684 dterr = DecodeTime(field[i], (fmask | DTK_DATE_M),
1685 INTERVAL_FULL_RANGE,
1696 return DTERR_BAD_FORMAT;
1698 dterr = DecodeTimezone(field[i], &tz);
1709 * Was this an "ISO time" with embedded field labels? An
1710 * example is "h04m05s06" - thomas 2001-02-04
1717 /* Only accept a date under limited circumstances */
1725 return DTERR_BAD_FORMAT;
1731 val = strtoi(field[i], &cp, 10);
1732 if (errno == ERANGE)
1733 return DTERR_FIELD_OVERFLOW;
1736 * only a few kinds are allowed to have an embedded
1747 return DTERR_BAD_FORMAT;
1750 else if (*cp != '\0')
1751 return DTERR_BAD_FORMAT;
1757 tmask = DTK_M(YEAR);
1763 * already have a month and hour? then assume
1766 if ((fmask & DTK_M(MONTH)) != 0 &&
1767 (fmask & DTK_M(HOUR)) != 0)
1770 tmask = DTK_M(MINUTE);
1775 tmask = DTK_M(MONTH);
1786 tmask = DTK_M(HOUR);
1791 tmask = DTK_M(MINUTE);
1796 tmask = DTK_M(SECOND);
1799 dterr = ParseFractionalSecond(cp, fsec);
1802 tmask = DTK_ALL_SECS_M;
1808 dterr = DecodeTimezone(field[i], tzp);
1814 /* previous field was a label for "julian date" */
1816 return DTERR_FIELD_OVERFLOW;
1818 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1826 time = strtod(cp, &cp);
1827 if (*cp != '\0' || errno != 0)
1828 return DTERR_BAD_FORMAT;
1830 #ifdef HAVE_INT64_TIMESTAMP
1831 time *= USECS_PER_DAY;
1833 time *= SECS_PER_DAY;
1836 &tm->tm_hour, &tm->tm_min,
1838 tmask |= DTK_TIME_M;
1843 /* previous field was "t" for ISO time */
1844 dterr = DecodeNumberField(strlen(field[i]), field[i],
1845 (fmask | DTK_DATE_M),
1852 if (tmask != DTK_TIME_M)
1853 return DTERR_BAD_FORMAT;
1857 return DTERR_BAD_FORMAT;
1869 flen = strlen(field[i]);
1870 cp = strchr(field[i], '.');
1872 /* Embedded decimal? */
1876 * Under limited circumstances, we will accept a
1879 if (i == 0 && nf >= 2 && ftype[nf - 1] == DTK_DATE)
1881 dterr = DecodeDate(field[i], fmask,
1882 &tmask, &is2digits, tm);
1886 /* embedded decimal and several digits before? */
1887 else if (flen - strlen(cp) > 2)
1890 * Interpret as a concatenated date or time Set
1891 * the type field to allow decoding other fields
1892 * later. Example: 20011223 or 040506
1894 dterr = DecodeNumberField(flen, field[i],
1895 (fmask | DTK_DATE_M),
1903 return DTERR_BAD_FORMAT;
1907 dterr = DecodeNumberField(flen, field[i],
1908 (fmask | DTK_DATE_M),
1915 /* otherwise it is a single date/time field... */
1918 dterr = DecodeNumber(flen, field[i],
1920 (fmask | DTK_DATE_M),
1931 type = DecodeSpecial(i, field[i], &val);
1932 if (type == IGNORE_DTF)
1935 tmask = DTK_M(type);
1943 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1944 errmsg("date/time value \"current\" is no longer supported")));
1945 return DTERR_BAD_FORMAT;
1951 GetCurrentTimeUsec(tm, fsec, NULL);
1955 tmask = (DTK_TIME_M | DTK_M(TZ));
1964 return DTERR_BAD_FORMAT;
1972 * daylight savings time modifier (solves "MET DST"
1975 tmask |= DTK_M(DTZ);
1978 return DTERR_BAD_FORMAT;
1979 *tzp += val * MINS_PER_HOUR;
1985 * set mask for TZ here _or_ check for DTZ later when
1986 * getting default timezone
1991 return DTERR_BAD_FORMAT;
1992 *tzp = val * MINS_PER_HOUR;
1999 return DTERR_BAD_FORMAT;
2000 *tzp = val * MINS_PER_HOUR;
2024 * We will need one of the following fields:
2025 * DTK_NUMBER should be hhmmss.fff
2026 * DTK_TIME should be hh:mm:ss.fff
2027 * DTK_DATE should be hhmmss-zz
2030 (ftype[i + 1] != DTK_NUMBER &&
2031 ftype[i + 1] != DTK_TIME &&
2032 ftype[i + 1] != DTK_DATE))
2033 return DTERR_BAD_FORMAT;
2041 * Before giving up and declaring error, check to see
2042 * if it is an all-alpha timezone name.
2044 namedTz = pg_tzset(field[i]);
2046 return DTERR_BAD_FORMAT;
2047 /* we'll apply the zone setting below */
2052 return DTERR_BAD_FORMAT;
2057 return DTERR_BAD_FORMAT;
2061 return DTERR_BAD_FORMAT;
2063 } /* end loop over fields */
2065 /* do final checking/adjustment of Y/M/D fields */
2066 dterr = ValidateDate(fmask, isjulian, is2digits, bc, tm);
2071 if (mer != HR24 && tm->tm_hour > HOURS_PER_DAY / 2)
2072 return DTERR_FIELD_OVERFLOW;
2073 if (mer == AM && tm->tm_hour == HOURS_PER_DAY / 2)
2075 else if (mer == PM && tm->tm_hour != HOURS_PER_DAY / 2)
2076 tm->tm_hour += HOURS_PER_DAY / 2;
2078 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > MINS_PER_HOUR - 1 ||
2079 tm->tm_sec < 0 || tm->tm_sec > SECS_PER_MINUTE ||
2080 tm->tm_hour > HOURS_PER_DAY ||
2081 /* test for > 24:00:00 */
2082 (tm->tm_hour == HOURS_PER_DAY &&
2083 (tm->tm_min > 0 || tm->tm_sec > 0 || *fsec > 0)) ||
2084 #ifdef HAVE_INT64_TIMESTAMP
2085 *fsec < INT64CONST(0) || *fsec > USECS_PER_SEC
2087 *fsec < 0 || *fsec > 1
2090 return DTERR_FIELD_OVERFLOW;
2092 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2093 return DTERR_BAD_FORMAT;
2096 * If we had a full timezone spec, compute the offset (we could not do it
2097 * before, because we may need the date to resolve DST status).
2099 if (namedTz != NULL)
2103 /* daylight savings time modifier disallowed with full TZ */
2104 if (fmask & DTK_M(DTZMOD))
2105 return DTERR_BAD_FORMAT;
2107 /* if non-DST zone, we do not need to know the date */
2108 if (pg_get_timezone_offset(namedTz, &gmtoff))
2110 *tzp = -(int) gmtoff;
2114 /* a date has to be specified */
2115 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2116 return DTERR_BAD_FORMAT;
2117 *tzp = DetermineTimeZoneOffset(tm, namedTz);
2121 /* timezone not specified? then find local timezone if possible */
2122 if (tzp != NULL && !(fmask & DTK_M(TZ)))
2128 * daylight savings time modifier but no standard timezone? then error
2130 if (fmask & DTK_M(DTZMOD))
2131 return DTERR_BAD_FORMAT;
2133 if ((fmask & DTK_DATE_M) == 0)
2134 GetCurrentDateTime(tmp);
2137 tmp->tm_year = tm->tm_year;
2138 tmp->tm_mon = tm->tm_mon;
2139 tmp->tm_mday = tm->tm_mday;
2141 tmp->tm_hour = tm->tm_hour;
2142 tmp->tm_min = tm->tm_min;
2143 tmp->tm_sec = tm->tm_sec;
2144 *tzp = DetermineTimeZoneOffset(tmp, session_timezone);
2145 tm->tm_isdst = tmp->tm_isdst;
2152 * Decode date string which includes delimiters.
2153 * Return 0 if okay, a DTERR code if not.
2155 * str: field to be parsed
2156 * fmask: bitmask for field types already seen
2157 * *tmask: receives bitmask for fields found here
2158 * *is2digits: set to TRUE if we find 2-digit year
2159 * *tm: field values are stored into appropriate members of this struct
2162 DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
2170 bool haveTextMonth = FALSE;
2174 char *field[MAXDATEFIELDS];
2178 /* parse this string... */
2179 while (*str != '\0' && nf < MAXDATEFIELDS)
2181 /* skip field separators */
2182 while (*str != '\0' && !isalnum((unsigned char) *str))
2186 return DTERR_BAD_FORMAT; /* end of string after separator */
2189 if (isdigit((unsigned char) *str))
2191 while (isdigit((unsigned char) *str))
2194 else if (isalpha((unsigned char) *str))
2196 while (isalpha((unsigned char) *str))
2200 /* Just get rid of any non-digit, non-alpha characters... */
2206 /* look first for text fields, since that will be unambiguous month */
2207 for (i = 0; i < nf; i++)
2209 if (isalpha((unsigned char) *field[i]))
2211 type = DecodeSpecial(i, field[i], &val);
2212 if (type == IGNORE_DTF)
2215 dmask = DTK_M(type);
2220 haveTextMonth = TRUE;
2224 return DTERR_BAD_FORMAT;
2227 return DTERR_BAD_FORMAT;
2232 /* mark this field as being completed */
2237 /* now pick up remaining numeric fields */
2238 for (i = 0; i < nf; i++)
2240 if (field[i] == NULL)
2243 if ((len = strlen(field[i])) <= 0)
2244 return DTERR_BAD_FORMAT;
2246 dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2253 return DTERR_BAD_FORMAT;
2259 if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
2260 return DTERR_BAD_FORMAT;
2262 /* validation of the field values must wait until ValidateDate() */
2268 * Check valid year/month/day values, handle BC and DOY cases
2269 * Return 0 if okay, a DTERR code if not.
2272 ValidateDate(int fmask, bool isjulian, bool is2digits, bool bc,
2275 if (fmask & DTK_M(YEAR))
2279 /* tm_year is correct and should not be touched */
2283 /* there is no year zero in AD/BC notation */
2284 if (tm->tm_year <= 0)
2285 return DTERR_FIELD_OVERFLOW;
2286 /* internally, we represent 1 BC as year zero, 2 BC as -1, etc */
2287 tm->tm_year = -(tm->tm_year - 1);
2291 /* process 1 or 2-digit input as 1970-2069 AD, allow '0' and '00' */
2292 if (tm->tm_year < 0) /* just paranoia */
2293 return DTERR_FIELD_OVERFLOW;
2294 if (tm->tm_year < 70)
2295 tm->tm_year += 2000;
2296 else if (tm->tm_year < 100)
2297 tm->tm_year += 1900;
2301 /* there is no year zero in AD/BC notation */
2302 if (tm->tm_year <= 0)
2303 return DTERR_FIELD_OVERFLOW;
2307 /* now that we have correct year, decode DOY */
2308 if (fmask & DTK_M(DOY))
2310 j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
2311 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2314 /* check for valid month */
2315 if (fmask & DTK_M(MONTH))
2317 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
2318 return DTERR_MD_FIELD_OVERFLOW;
2321 /* minimal check for valid day */
2322 if (fmask & DTK_M(DAY))
2324 if (tm->tm_mday < 1 || tm->tm_mday > 31)
2325 return DTERR_MD_FIELD_OVERFLOW;
2328 if ((fmask & DTK_DATE_M) == DTK_DATE_M)
2331 * Check for valid day of month, now that we know for sure the month
2332 * and year. Note we don't use MD_FIELD_OVERFLOW here, since it seems
2333 * unlikely that "Feb 29" is a YMD-order error.
2335 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2336 return DTERR_FIELD_OVERFLOW;
2344 * Decode time string which includes delimiters.
2345 * Return 0 if okay, a DTERR code if not.
2347 * Only check the lower limit on hours, since this same code can be
2348 * used to represent time spans.
2351 DecodeTime(char *str, int fmask, int range,
2352 int *tmask, struct pg_tm * tm, fsec_t *fsec)
2357 *tmask = DTK_TIME_M;
2360 tm->tm_hour = strtoi(str, &cp, 10);
2361 if (errno == ERANGE)
2362 return DTERR_FIELD_OVERFLOW;
2364 return DTERR_BAD_FORMAT;
2366 tm->tm_min = strtoi(cp + 1, &cp, 10);
2367 if (errno == ERANGE)
2368 return DTERR_FIELD_OVERFLOW;
2373 /* If it's a MINUTE TO SECOND interval, take 2 fields as being mm:ss */
2374 if (range == (INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND)))
2376 tm->tm_sec = tm->tm_min;
2377 tm->tm_min = tm->tm_hour;
2381 else if (*cp == '.')
2383 /* always assume mm:ss.sss is MINUTE TO SECOND */
2384 dterr = ParseFractionalSecond(cp, fsec);
2387 tm->tm_sec = tm->tm_min;
2388 tm->tm_min = tm->tm_hour;
2391 else if (*cp == ':')
2394 tm->tm_sec = strtoi(cp + 1, &cp, 10);
2395 if (errno == ERANGE)
2396 return DTERR_FIELD_OVERFLOW;
2399 else if (*cp == '.')
2401 dterr = ParseFractionalSecond(cp, fsec);
2406 return DTERR_BAD_FORMAT;
2409 return DTERR_BAD_FORMAT;
2411 /* do a sanity check */
2412 #ifdef HAVE_INT64_TIMESTAMP
2413 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > MINS_PER_HOUR - 1 ||
2414 tm->tm_sec < 0 || tm->tm_sec > SECS_PER_MINUTE ||
2415 *fsec < INT64CONST(0) ||
2416 *fsec > USECS_PER_SEC)
2417 return DTERR_FIELD_OVERFLOW;
2419 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > MINS_PER_HOUR - 1 ||
2420 tm->tm_sec < 0 || tm->tm_sec > SECS_PER_MINUTE ||
2421 *fsec < 0 || *fsec > 1)
2422 return DTERR_FIELD_OVERFLOW;
2430 * Interpret plain numeric field as a date value in context.
2431 * Return 0 if okay, a DTERR code if not.
2434 DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask,
2435 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2444 val = strtoi(str, &cp, 10);
2445 if (errno == ERANGE)
2446 return DTERR_FIELD_OVERFLOW;
2448 return DTERR_BAD_FORMAT;
2453 * More than two digits before decimal point? Then could be a date or
2454 * a run-together time: 2001.360 20011225 040506.789
2458 dterr = DecodeNumberField(flen, str,
2459 (fmask | DTK_DATE_M),
2467 dterr = ParseFractionalSecond(cp, fsec);
2471 else if (*cp != '\0')
2472 return DTERR_BAD_FORMAT;
2474 /* Special case for day of year */
2475 if (flen == 3 && (fmask & DTK_DATE_M) == DTK_M(YEAR) && val >= 1 &&
2478 *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2480 /* tm_mon and tm_mday can't actually be set yet ... */
2484 /* Switch based on what we have so far */
2485 switch (fmask & DTK_DATE_M)
2490 * Nothing so far; make a decision about what we think the input
2491 * is. There used to be lots of heuristics here, but the
2492 * consensus now is to be paranoid. It *must* be either
2493 * YYYY-MM-DD (with a more-than-two-digit year field), or the
2494 * field order defined by DateOrder.
2496 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2498 *tmask = DTK_M(YEAR);
2501 else if (DateOrder == DATEORDER_DMY)
2503 *tmask = DTK_M(DAY);
2508 *tmask = DTK_M(MONTH);
2514 /* Must be at second field of YY-MM-DD */
2515 *tmask = DTK_M(MONTH);
2519 case (DTK_M(MONTH)):
2523 * We are at the first numeric field of a date that included a
2524 * textual month name. We want to support the variants
2525 * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2526 * inputs. We will also accept MON-DD-YY or DD-MON-YY in
2527 * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2529 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2531 *tmask = DTK_M(YEAR);
2536 *tmask = DTK_M(DAY);
2542 /* Must be at second field of MM-DD-YY */
2543 *tmask = DTK_M(DAY);
2548 case (DTK_M(YEAR) | DTK_M(MONTH)):
2551 /* Need to accept DD-MON-YYYY even in YMD mode */
2552 if (flen >= 3 && *is2digits)
2554 /* Guess that first numeric field is day was wrong */
2555 *tmask = DTK_M(DAY); /* YEAR is already set */
2556 tm->tm_mday = tm->tm_year;
2562 *tmask = DTK_M(DAY);
2568 /* Must be at third field of YY-MM-DD */
2569 *tmask = DTK_M(DAY);
2575 /* Must be at second field of DD-MM-YY */
2576 *tmask = DTK_M(MONTH);
2580 case (DTK_M(MONTH) | DTK_M(DAY)):
2581 /* Must be at third field of DD-MM-YY or MM-DD-YY */
2582 *tmask = DTK_M(YEAR);
2586 case (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY)):
2587 /* we have all the date, so it must be a time field */
2588 dterr = DecodeNumberField(flen, str, fmask,
2596 /* Anything else is bogus input */
2597 return DTERR_BAD_FORMAT;
2601 * When processing a year field, mark it for adjustment if it's only one
2604 if (*tmask == DTK_M(YEAR))
2605 *is2digits = (flen <= 2);
2611 /* DecodeNumberField()
2612 * Interpret numeric string as a concatenated date or time field.
2613 * Return a DTK token (>= 0) if successful, a DTERR code (< 0) if not.
2615 * Use the context of previously decoded fields to help with
2616 * the interpretation.
2619 DecodeNumberField(int len, char *str, int fmask,
2620 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2625 * Have a decimal point? Then this is a date or something with a seconds
2628 if ((cp = strchr(str, '.')) != NULL)
2631 * Can we use ParseFractionalSecond here? Not clear whether trailing
2632 * junk should be rejected ...
2637 frac = strtod(cp, NULL);
2639 return DTERR_BAD_FORMAT;
2640 #ifdef HAVE_INT64_TIMESTAMP
2641 *fsec = rint(frac * 1000000);
2645 /* Now truncate off the fraction for further processing */
2649 /* No decimal point and no complete date yet? */
2650 else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2654 *tmask = DTK_DATE_M;
2656 * Start from end and consider first 2 as Day, next 2 as Month,
2657 * and the rest as Year.
2659 tm->tm_mday = atoi(str + (len - 2));
2660 *(str + (len - 2)) = '\0';
2661 tm->tm_mon = atoi(str + (len - 4));
2662 *(str + (len - 4)) = '\0';
2663 tm->tm_year = atoi(str);
2671 /* not all time fields are specified? */
2672 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2677 *tmask = DTK_TIME_M;
2678 tm->tm_sec = atoi(str + 4);
2680 tm->tm_min = atoi(str + 2);
2682 tm->tm_hour = atoi(str);
2689 *tmask = DTK_TIME_M;
2691 tm->tm_min = atoi(str + 2);
2693 tm->tm_hour = atoi(str);
2699 return DTERR_BAD_FORMAT;
2704 * Interpret string as a numeric timezone.
2706 * Return 0 if okay (and set *tzp), a DTERR code if not okay.
2708 * NB: this must *not* ereport on failure; see commands/variable.c.
2711 DecodeTimezone(char *str, int *tzp)
2719 /* leading character must be "+" or "-" */
2720 if (*str != '+' && *str != '-')
2721 return DTERR_BAD_FORMAT;
2724 hr = strtoi(str + 1, &cp, 10);
2725 if (errno == ERANGE)
2726 return DTERR_TZDISP_OVERFLOW;
2728 /* explicit delimiter? */
2732 min = strtoi(cp + 1, &cp, 10);
2733 if (errno == ERANGE)
2734 return DTERR_TZDISP_OVERFLOW;
2738 sec = strtoi(cp + 1, &cp, 10);
2739 if (errno == ERANGE)
2740 return DTERR_TZDISP_OVERFLOW;
2743 /* otherwise, might have run things together... */
2744 else if (*cp == '\0' && strlen(str) > 3)
2748 /* we could, but don't, support a run-together hhmmss format */
2753 /* Range-check the values; see notes in datatype/timestamp.h */
2754 if (hr < 0 || hr > MAX_TZDISP_HOUR)
2755 return DTERR_TZDISP_OVERFLOW;
2756 if (min < 0 || min >= MINS_PER_HOUR)
2757 return DTERR_TZDISP_OVERFLOW;
2758 if (sec < 0 || sec >= SECS_PER_MINUTE)
2759 return DTERR_TZDISP_OVERFLOW;
2761 tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
2768 return DTERR_BAD_FORMAT;
2774 * Decode text string using lookup table.
2776 * Implement a cache lookup since it is likely that dates
2777 * will be related in format.
2779 * NB: this must *not* ereport on failure;
2780 * see commands/variable.c.
2783 DecodeSpecial(int field, char *lowtoken, int *val)
2788 tp = datecache[field];
2789 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
2791 tp = datebsearch(lowtoken, timezonetktbl, sztimezonetktbl);
2793 tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
2797 type = UNKNOWN_FIELD;
2802 datecache[field] = tp;
2824 * Zero out a pg_tm and associated fsec_t
2827 ClearPgTm(struct pg_tm * tm, fsec_t *fsec)
2840 * Interpret previously parsed fields for general time interval.
2841 * Returns 0 if successful, DTERR code if bogus input detected.
2842 * dtype, tm, fsec are output parameters.
2844 * Allow "date" field DTK_DATE since this could be just
2845 * an unsigned floating point number. - thomas 1997-11-16
2847 * Allow ISO-style time span, with implicit units on number of days
2848 * preceding an hh:mm:ss field. - thomas 1998-04-30
2851 DecodeInterval(char **field, int *ftype, int nf, int range,
2852 int *dtype, struct pg_tm * tm, fsec_t *fsec)
2854 bool is_before = FALSE;
2866 ClearPgTm(tm, fsec);
2868 /* read through list backwards to pick up units before values */
2869 for (i = nf - 1; i >= 0; i--)
2874 dterr = DecodeTime(field[i], fmask, range,
2884 * Timezone means a token with a leading sign character and at
2885 * least one digit; there could be ':', '.', '-' embedded in
2888 Assert(*field[i] == '-' || *field[i] == '+');
2891 * Check for signed hh:mm or hh:mm:ss. If so, process exactly
2892 * like DTK_TIME case above, plus handling the sign.
2894 if (strchr(field[i] + 1, ':') != NULL &&
2895 DecodeTime(field[i] + 1, fmask, range,
2896 &tmask, tm, fsec) == 0)
2898 if (*field[i] == '-')
2900 /* flip the sign on all fields */
2901 tm->tm_hour = -tm->tm_hour;
2902 tm->tm_min = -tm->tm_min;
2903 tm->tm_sec = -tm->tm_sec;
2908 * Set the next type to be a day, if units are not
2909 * specified. This handles the case of '1 +02:03' since we
2910 * are reading right to left.
2917 * Otherwise, fall through to DTK_NUMBER case, which can
2918 * handle signed float numbers and signed year-month values.
2925 if (type == IGNORE_DTF)
2927 /* use typmod to decide what rightmost field is */
2930 case INTERVAL_MASK(YEAR):
2933 case INTERVAL_MASK(MONTH):
2934 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
2937 case INTERVAL_MASK(DAY):
2940 case INTERVAL_MASK(HOUR):
2941 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
2944 case INTERVAL_MASK(MINUTE):
2945 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
2946 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
2949 case INTERVAL_MASK(SECOND):
2950 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2951 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2952 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2962 val = strtoi(field[i], &cp, 10);
2963 if (errno == ERANGE)
2964 return DTERR_FIELD_OVERFLOW;
2968 /* SQL "years-months" syntax */
2971 val2 = strtoi(cp + 1, &cp, 10);
2972 if (errno == ERANGE || val2 < 0 || val2 >= MONTHS_PER_YEAR)
2973 return DTERR_FIELD_OVERFLOW;
2975 return DTERR_BAD_FORMAT;
2977 if (*field[i] == '-')
2979 if (((double)val * MONTHS_PER_YEAR + val2) > INT_MAX ||
2980 ((double)val * MONTHS_PER_YEAR + val2) < INT_MIN)
2981 return DTERR_FIELD_OVERFLOW;
2982 val = val * MONTHS_PER_YEAR + val2;
2985 else if (*cp == '.')
2988 fval = strtod(cp, &cp);
2989 if (*cp != '\0' || errno != 0)
2990 return DTERR_BAD_FORMAT;
2992 if (*field[i] == '-')
2995 else if (*cp == '\0')
2998 return DTERR_BAD_FORMAT;
3000 tmask = 0; /* DTK_M(type); */
3005 #ifdef HAVE_INT64_TIMESTAMP
3006 *fsec += rint(val + fval);
3008 *fsec += (val + fval) * 1e-6;
3010 tmask = DTK_M(MICROSECOND);
3014 /* avoid overflowing the fsec field */
3015 tm->tm_sec += val / 1000;
3016 val -= (val / 1000) * 1000;
3017 #ifdef HAVE_INT64_TIMESTAMP
3018 *fsec += rint((val + fval) * 1000);
3020 *fsec += (val + fval) * 1e-3;
3022 tmask = DTK_M(MILLISECOND);
3027 #ifdef HAVE_INT64_TIMESTAMP
3028 *fsec += rint(fval * 1000000);
3034 * If any subseconds were specified, consider this
3035 * microsecond and millisecond input as well.
3038 tmask = DTK_M(SECOND);
3040 tmask = DTK_ALL_SECS_M;
3045 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3046 tmask = DTK_M(MINUTE);
3051 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3052 tmask = DTK_M(HOUR);
3053 type = DTK_DAY; /* set for next field */
3058 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3063 tm->tm_mday += val * 7;
3064 AdjustFractDays(fval, tm, fsec, 7);
3065 tmask = DTK_M(WEEK);
3070 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3071 tmask = DTK_M(MONTH);
3077 tm->tm_mon += fval * MONTHS_PER_YEAR;
3078 tmask = DTK_M(YEAR);
3082 tm->tm_year += val * 10;
3084 tm->tm_mon += fval * MONTHS_PER_YEAR * 10;
3085 tmask = DTK_M(DECADE);
3089 tm->tm_year += val * 100;
3091 tm->tm_mon += fval * MONTHS_PER_YEAR * 100;
3092 tmask = DTK_M(CENTURY);
3095 case DTK_MILLENNIUM:
3096 tm->tm_year += val * 1000;
3098 tm->tm_mon += fval * MONTHS_PER_YEAR * 1000;
3099 tmask = DTK_M(MILLENNIUM);
3103 return DTERR_BAD_FORMAT;
3109 type = DecodeUnits(i, field[i], &val);
3110 if (type == IGNORE_DTF)
3113 tmask = 0; /* DTK_M(type); */
3126 tmask = (DTK_DATE_M | DTK_TIME_M);
3131 return DTERR_BAD_FORMAT;
3136 return DTERR_BAD_FORMAT;
3140 return DTERR_BAD_FORMAT;
3144 /* ensure that at least one time field has been found */
3146 return DTERR_BAD_FORMAT;
3148 /* ensure fractional seconds are fractional */
3153 #ifdef HAVE_INT64_TIMESTAMP
3154 sec = *fsec / USECS_PER_SEC;
3155 *fsec -= sec * USECS_PER_SEC;
3157 TMODULO(*fsec, sec, 1.0);
3163 * The SQL standard defines the interval literal
3165 * to mean "negative 1 days and negative 1 hours", while Postgres
3166 * traditionally treats this as meaning "negative 1 days and positive
3167 * 1 hours". In SQL_STANDARD intervalstyle, we apply the leading sign
3168 * to all fields if there are no other explicit signs.
3170 * We leave the signs alone if there are additional explicit signs.
3171 * This protects us against misinterpreting postgres-style dump output,
3172 * since the postgres-style output code has always put an explicit sign on
3173 * all fields following a negative field. But note that SQL-spec output
3174 * is ambiguous and can be misinterpreted on load! (So it's best practice
3175 * to dump in postgres style, not SQL style.)
3178 if (IntervalStyle == INTSTYLE_SQL_STANDARD && *field[0] == '-')
3180 /* Check for additional explicit signs */
3181 bool more_signs = false;
3183 for (i = 1; i < nf; i++)
3185 if (*field[i] == '-' || *field[i] == '+')
3195 * Rather than re-determining which field was field[0], just force
3201 tm->tm_sec = -tm->tm_sec;
3203 tm->tm_min = -tm->tm_min;
3204 if (tm->tm_hour > 0)
3205 tm->tm_hour = -tm->tm_hour;
3206 if (tm->tm_mday > 0)
3207 tm->tm_mday = -tm->tm_mday;
3209 tm->tm_mon = -tm->tm_mon;
3210 if (tm->tm_year > 0)
3211 tm->tm_year = -tm->tm_year;
3215 /* finally, AGO negates everything */
3219 tm->tm_sec = -tm->tm_sec;
3220 tm->tm_min = -tm->tm_min;
3221 tm->tm_hour = -tm->tm_hour;
3222 tm->tm_mday = -tm->tm_mday;
3223 tm->tm_mon = -tm->tm_mon;
3224 tm->tm_year = -tm->tm_year;
3232 * Helper functions to avoid duplicated code in DecodeISO8601Interval.
3234 * Parse a decimal value and break it into integer and fractional parts.
3235 * Returns 0 or DTERR code.
3238 ParseISO8601Number(char *str, char **endptr, int *ipart, double *fpart)
3242 if (!(isdigit((unsigned char) *str) || *str == '-' || *str == '.'))
3243 return DTERR_BAD_FORMAT;
3245 val = strtod(str, endptr);
3246 /* did we not see anything that looks like a double? */
3247 if (*endptr == str || errno != 0)
3248 return DTERR_BAD_FORMAT;
3249 /* watch out for overflow */
3250 if (val < INT_MIN || val > INT_MAX)
3251 return DTERR_FIELD_OVERFLOW;
3252 /* be very sure we truncate towards zero (cf dtrunc()) */
3254 *ipart = (int) floor(val);
3256 *ipart = (int) -floor(-val);
3257 *fpart = val - *ipart;
3262 * Determine number of integral digits in a valid ISO 8601 number field
3263 * (we should ignore sign and any fraction part)
3266 ISO8601IntegerWidth(char *fieldstart)
3268 /* We might have had a leading '-' */
3269 if (*fieldstart == '-')
3271 return strspn(fieldstart, "0123456789");
3275 /* DecodeISO8601Interval()
3276 * Decode an ISO 8601 time interval of the "format with designators"
3277 * (section 4.4.3.2) or "alternative format" (section 4.4.3.3)
3278 * Examples: P1D for 1 day
3280 * P2Y6M7DT1H30M for 2 years, 6 months, 7 days 1 hour 30 min
3281 * P0002-06-07T01:30:00 the same value in alternative format
3283 * Returns 0 if successful, DTERR code if bogus input detected.
3284 * Note: error code should be DTERR_BAD_FORMAT if input doesn't look like
3285 * ISO8601, otherwise this could cause unexpected error messages.
3286 * dtype, tm, fsec are output parameters.
3288 * A couple exceptions from the spec:
3289 * - a week field ('W') may coexist with other units
3290 * - allows decimals in fields other than the least significant unit.
3293 DecodeISO8601Interval(char *str,
3294 int *dtype, struct pg_tm * tm, fsec_t *fsec)
3296 bool datepart = true;
3297 bool havefield = false;
3300 ClearPgTm(tm, fsec);
3302 if (strlen(str) < 2 || str[0] != 'P')
3303 return DTERR_BAD_FORMAT;
3314 if (*str == 'T') /* T indicates the beginning of the time part */
3323 dterr = ParseISO8601Number(str, &str, &val, &fval);
3328 * Note: we could step off the end of the string here. Code below
3329 * *must* exit the loop if unit == '\0'.
3335 switch (unit) /* before T: Y M W D */
3339 tm->tm_mon += (fval * MONTHS_PER_YEAR);
3343 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3346 tm->tm_mday += val * 7;
3347 AdjustFractDays(fval, tm, fsec, 7);
3351 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3353 case 'T': /* ISO 8601 4.4.3.3 Alternative Format / Basic */
3355 if (ISO8601IntegerWidth(fieldstart) == 8 && !havefield)
3357 tm->tm_year += val / 10000;
3358 tm->tm_mon += (val / 100) % 100;
3359 tm->tm_mday += val % 100;
3360 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3367 /* Else fall through to extended alternative format */
3368 case '-': /* ISO 8601 4.4.3.3 Alternative Format,
3371 return DTERR_BAD_FORMAT;
3374 tm->tm_mon += (fval * MONTHS_PER_YEAR);
3384 dterr = ParseISO8601Number(str, &str, &val, &fval);
3388 AdjustFractDays(fval, tm, fsec, DAYS_PER_MONTH);
3398 return DTERR_BAD_FORMAT;
3401 dterr = ParseISO8601Number(str, &str, &val, &fval);
3405 AdjustFractSeconds(fval, tm, fsec, SECS_PER_DAY);
3414 return DTERR_BAD_FORMAT;
3416 /* not a valid date unit suffix */
3417 return DTERR_BAD_FORMAT;
3422 switch (unit) /* after T: H M S */
3426 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3430 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3434 AdjustFractSeconds(fval, tm, fsec, 1);
3436 case '\0': /* ISO 8601 4.4.3.3 Alternative Format */
3437 if (ISO8601IntegerWidth(fieldstart) == 6 && !havefield)
3439 tm->tm_hour += val / 10000;
3440 tm->tm_min += (val / 100) % 100;
3441 tm->tm_sec += val % 100;
3442 AdjustFractSeconds(fval, tm, fsec, 1);
3445 /* Else fall through to extended alternative format */
3446 case ':': /* ISO 8601 4.4.3.3 Alternative Format,
3449 return DTERR_BAD_FORMAT;
3452 AdjustFractSeconds(fval, tm, fsec, SECS_PER_HOUR);
3456 dterr = ParseISO8601Number(str, &str, &val, &fval);
3460 AdjustFractSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3464 return DTERR_BAD_FORMAT;
3467 dterr = ParseISO8601Number(str, &str, &val, &fval);
3471 AdjustFractSeconds(fval, tm, fsec, 1);
3474 return DTERR_BAD_FORMAT;
3477 /* not a valid time unit suffix */
3478 return DTERR_BAD_FORMAT;
3490 * Decode text string using lookup table.
3491 * This routine supports time interval decoding
3492 * (hence, it need not recognize timezone names).
3495 DecodeUnits(int field, char *lowtoken, int *val)
3500 tp = deltacache[field];
3501 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3503 tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
3507 type = UNKNOWN_FIELD;
3512 deltacache[field] = tp;
3514 if (type == TZ || type == DTZ)
3521 } /* DecodeUnits() */
3524 * Report an error detected by one of the datetime input processing routines.
3526 * dterr is the error code, str is the original input string, datatype is
3527 * the name of the datatype we were trying to accept.
3529 * Note: it might seem useless to distinguish DTERR_INTERVAL_OVERFLOW and
3530 * DTERR_TZDISP_OVERFLOW from DTERR_FIELD_OVERFLOW, but SQL99 mandates three
3531 * separate SQLSTATE codes, so ...
3534 DateTimeParseError(int dterr, const char *str, const char *datatype)
3538 case DTERR_FIELD_OVERFLOW:
3540 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3541 errmsg("date/time field value out of range: \"%s\"",
3544 case DTERR_MD_FIELD_OVERFLOW:
3545 /* <nanny>same as above, but add hint about DateStyle</nanny> */
3547 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3548 errmsg("date/time field value out of range: \"%s\"",
3550 errhint("Perhaps you need a different \"datestyle\" setting.")));
3552 case DTERR_INTERVAL_OVERFLOW:
3554 (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
3555 errmsg("interval field value out of range: \"%s\"",
3558 case DTERR_TZDISP_OVERFLOW:
3560 (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
3561 errmsg("time zone displacement out of range: \"%s\"",
3564 case DTERR_BAD_FORMAT:
3567 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
3568 errmsg("invalid input syntax for type %s: \"%s\"",
3575 * Binary search -- from Knuth (6.2.1) Algorithm B. Special case like this
3576 * is WAY faster than the generic bsearch().
3578 static const datetkn *
3579 datebsearch(const char *key, const datetkn *base, int nel)
3583 const datetkn *last = base + nel - 1,
3587 while (last >= base)
3589 position = base + ((last - base) >> 1);
3590 result = key[0] - position->token[0];
3593 result = strncmp(key, position->token, TOKMAXLEN);
3598 last = position - 1;
3600 base = position + 1;
3607 * Append representation of a numeric timezone offset to str.
3610 EncodeTimezone(char *str, int tz, int style)
3617 min = sec / SECS_PER_MINUTE;
3618 sec -= min * SECS_PER_MINUTE;
3619 hour = min / MINS_PER_HOUR;
3620 min -= hour * MINS_PER_HOUR;
3623 /* TZ is negated compared to sign we wish to display ... */
3624 *str++ = (tz <= 0 ? '+' : '-');
3627 sprintf(str, "%02d:%02d:%02d", hour, min, sec);
3628 else if (min != 0 || style == USE_XSD_DATES)
3629 sprintf(str, "%02d:%02d", hour, min);
3631 sprintf(str, "%02d", hour);
3635 * Encode date as local time.
3638 EncodeDateOnly(struct pg_tm * tm, int style, char *str)
3640 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3646 /* compatible with ISO date formats */
3647 if (tm->tm_year > 0)
3648 sprintf(str, "%04d-%02d-%02d",
3649 tm->tm_year, tm->tm_mon, tm->tm_mday);
3651 sprintf(str, "%04d-%02d-%02d %s",
3652 -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
3656 /* compatible with Oracle/Ingres date formats */
3657 if (DateOrder == DATEORDER_DMY)
3658 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3660 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3661 if (tm->tm_year > 0)
3662 sprintf(str + 5, "/%04d", tm->tm_year);
3664 sprintf(str + 5, "/%04d %s", -(tm->tm_year - 1), "BC");
3667 case USE_GERMAN_DATES:
3668 /* German-style date format */
3669 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3670 if (tm->tm_year > 0)
3671 sprintf(str + 5, ".%04d", tm->tm_year);
3673 sprintf(str + 5, ".%04d %s", -(tm->tm_year - 1), "BC");
3676 case USE_POSTGRES_DATES:
3678 /* traditional date-only style for Postgres */
3679 if (DateOrder == DATEORDER_DMY)
3680 sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
3682 sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
3683 if (tm->tm_year > 0)
3684 sprintf(str + 5, "-%04d", tm->tm_year);
3686 sprintf(str + 5, "-%04d %s", -(tm->tm_year - 1), "BC");
3693 * Encode time fields only.
3695 * tm and fsec are the value to encode, print_tz determines whether to include
3696 * a time zone (the difference between time and timetz types), tz is the
3697 * numeric time zone offset, style is the date style, str is where to write the
3701 EncodeTimeOnly(struct pg_tm * tm, fsec_t fsec, bool print_tz, int tz, int style, char *str)
3703 sprintf(str, "%02d:%02d:", tm->tm_hour, tm->tm_min);
3706 AppendSeconds(str, tm->tm_sec, fsec, MAX_TIME_PRECISION, true);
3709 EncodeTimezone(str, tz, style);
3714 * Encode date and time interpreted as local time.
3716 * tm and fsec are the value to encode, print_tz determines whether to include
3717 * a time zone (the difference between timestamp and timestamptz types), tz is
3718 * the numeric time zone offset, tzn is the textual time zone, which if
3719 * specified will be used instead of tz by some styles, style is the date
3720 * style, str is where to write the output.
3722 * Supported date styles:
3723 * Postgres - day mon hh:mm:ss yyyy tz
3724 * SQL - mm/dd/yyyy hh:mm:ss.ss tz
3725 * ISO - yyyy-mm-dd hh:mm:ss+/-tz
3726 * German - dd.mm.yyyy hh:mm:ss tz
3727 * XSD - yyyy-mm-ddThh:mm:ss.ss+/-tz
3730 EncodeDateTime(struct pg_tm * tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str)
3734 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3737 * Negative tm_isdst means we have no valid time zone translation.
3739 if (tm->tm_isdst < 0)
3746 /* Compatible with ISO-8601 date formats */
3748 if (style == USE_ISO_DATES)
3749 sprintf(str, "%04d-%02d-%02d %02d:%02d:",
3750 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3751 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3753 sprintf(str, "%04d-%02d-%02dT%02d:%02d:",
3754 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3755 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3757 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3760 EncodeTimezone(str, tz, style);
3762 if (tm->tm_year <= 0)
3763 sprintf(str + strlen(str), " BC");
3767 /* Compatible with Oracle/Ingres date formats */
3769 if (DateOrder == DATEORDER_DMY)
3770 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3772 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3774 sprintf(str + 5, "/%04d %02d:%02d:",
3775 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3776 tm->tm_hour, tm->tm_min);
3778 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3781 * Note: the uses of %.*s in this function would be risky if the
3782 * timezone names ever contain non-ASCII characters. However, all
3783 * TZ abbreviations in the Olson database are plain ASCII.
3789 sprintf(str + strlen(str), " %.*s", MAXTZLEN, tzn);
3791 EncodeTimezone(str, tz, style);
3794 if (tm->tm_year <= 0)
3795 sprintf(str + strlen(str), " BC");
3798 case USE_GERMAN_DATES:
3799 /* German variant on European style */
3801 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3803 sprintf(str + 5, ".%04d %02d:%02d:",
3804 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3805 tm->tm_hour, tm->tm_min);
3807 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3812 sprintf(str + strlen(str), " %.*s", MAXTZLEN, tzn);
3814 EncodeTimezone(str, tz, style);
3817 if (tm->tm_year <= 0)
3818 sprintf(str + strlen(str), " BC");
3821 case USE_POSTGRES_DATES:
3823 /* Backward-compatible with traditional Postgres abstime dates */
3825 day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3826 tm->tm_wday = j2day(day);
3828 strncpy(str, days[tm->tm_wday], 3);
3829 strcpy(str + 3, " ");
3831 if (DateOrder == DATEORDER_DMY)
3832 sprintf(str + 4, "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
3834 sprintf(str + 4, "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);
3836 sprintf(str + 10, " %02d:%02d:", tm->tm_hour, tm->tm_min);
3838 AppendTimestampSeconds(str + strlen(str), tm, fsec);
3840 sprintf(str + strlen(str), " %04d",
3841 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1));
3846 sprintf(str + strlen(str), " %.*s", MAXTZLEN, tzn);
3850 * We have a time zone, but no string version. Use the
3851 * numeric form, but be sure to include a leading space to
3852 * avoid formatting something which would be rejected by
3853 * the date/time parser later. - thomas 2001-10-19
3855 sprintf(str + strlen(str), " ");
3856 EncodeTimezone(str, tz, style);
3860 if (tm->tm_year <= 0)
3861 sprintf(str + strlen(str), " BC");
3868 * Helper functions to avoid duplicated code in EncodeInterval.
3871 /* Append an ISO-8601-style interval field, but only if value isn't zero */
3873 AddISO8601IntPart(char *cp, int value, char units)
3877 sprintf(cp, "%d%c", value, units);
3878 return cp + strlen(cp);
3881 /* Append a postgres-style interval field, but only if value isn't zero */
3883 AddPostgresIntPart(char *cp, int value, const char *units,
3884 bool *is_zero, bool *is_before)
3888 sprintf(cp, "%s%s%d %s%s",
3889 (!*is_zero) ? " " : "",
3890 (*is_before && value > 0) ? "+" : "",
3893 (value != 1) ? "s" : "");
3896 * Each nonzero field sets is_before for (only) the next one. This is a
3897 * tad bizarre but it's how it worked before...
3899 *is_before = (value < 0);
3901 return cp + strlen(cp);
3904 /* Append a verbose-style interval field, but only if value isn't zero */
3906 AddVerboseIntPart(char *cp, int value, const char *units,
3907 bool *is_zero, bool *is_before)
3911 /* first nonzero value sets is_before */
3914 *is_before = (value < 0);
3917 else if (*is_before)
3919 sprintf(cp, " %d %s%s", value, units, (value == 1) ? "" : "s");
3921 return cp + strlen(cp);
3926 * Interpret time structure as a delta time and convert to string.
3928 * Support "traditional Postgres" and ISO-8601 styles.
3929 * Actually, afaik ISO does not address time interval formatting,
3930 * but this looks similar to the spec for absolute date/time.
3931 * - thomas 1998-04-30
3933 * Actually, afaik, ISO 8601 does specify formats for "time
3934 * intervals...[of the]...format with time-unit designators", which
3935 * are pretty ugly. The format looks something like
3936 * P1Y1M1DT1H1M1.12345S
3937 * but useful for exchanging data with computers instead of humans.
3940 * And ISO's SQL 2008 standard specifies standards for
3941 * "year-month literal"s (that look like '2-3') and
3942 * "day-time literal"s (that look like ('4 5:6:7')
3945 EncodeInterval(struct pg_tm * tm, fsec_t fsec, int style, char *str)
3948 int year = tm->tm_year;
3949 int mon = tm->tm_mon;
3950 int mday = tm->tm_mday;
3951 int hour = tm->tm_hour;
3952 int min = tm->tm_min;
3953 int sec = tm->tm_sec;
3954 bool is_before = FALSE;
3955 bool is_zero = TRUE;
3958 * The sign of year and month are guaranteed to match, since they are
3959 * stored internally as "month". But we'll need to check for is_before and
3960 * is_zero when determining the signs of day and hour/minute/seconds
3965 /* SQL Standard interval format */
3966 case INTSTYLE_SQL_STANDARD:
3968 bool has_negative = year < 0 || mon < 0 ||
3969 mday < 0 || hour < 0 ||
3970 min < 0 || sec < 0 || fsec < 0;
3971 bool has_positive = year > 0 || mon > 0 ||
3972 mday > 0 || hour > 0 ||
3973 min > 0 || sec > 0 || fsec > 0;
3974 bool has_year_month = year != 0 || mon != 0;
3975 bool has_day_time = mday != 0 || hour != 0 ||
3976 min != 0 || sec != 0 || fsec != 0;
3977 bool has_day = mday != 0;
3978 bool sql_standard_value = !(has_negative && has_positive) &&
3979 !(has_year_month && has_day_time);
3982 * SQL Standard wants only 1 "<sign>" preceding the whole
3983 * interval ... but can't do that if mixed signs.
3985 if (has_negative && sql_standard_value)
3997 if (!has_negative && !has_positive)
4001 else if (!sql_standard_value)
4004 * For non sql-standard interval values, force outputting
4005 * the signs to avoid ambiguities with intervals with
4006 * mixed sign components.
4008 char year_sign = (year < 0 || mon < 0) ? '-' : '+';
4009 char day_sign = (mday < 0) ? '-' : '+';
4010 char sec_sign = (hour < 0 || min < 0 ||
4011 sec < 0 || fsec < 0) ? '-' : '+';
4013 sprintf(cp, "%c%d-%d %c%d %c%d:%02d:",
4014 year_sign, abs(year), abs(mon),
4015 day_sign, abs(mday),
4016 sec_sign, abs(hour), abs(min));
4018 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4020 else if (has_year_month)
4022 sprintf(cp, "%d-%d", year, mon);
4026 sprintf(cp, "%d %d:%02d:", mday, hour, min);
4028 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4032 sprintf(cp, "%d:%02d:", hour, min);
4034 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4039 /* ISO 8601 "time-intervals by duration only" */
4040 case INTSTYLE_ISO_8601:
4041 /* special-case zero to avoid printing nothing */
4042 if (year == 0 && mon == 0 && mday == 0 &&
4043 hour == 0 && min == 0 && sec == 0 && fsec == 0)
4045 sprintf(cp, "PT0S");
4049 cp = AddISO8601IntPart(cp, year, 'Y');
4050 cp = AddISO8601IntPart(cp, mon, 'M');
4051 cp = AddISO8601IntPart(cp, mday, 'D');
4052 if (hour != 0 || min != 0 || sec != 0 || fsec != 0)
4054 cp = AddISO8601IntPart(cp, hour, 'H');
4055 cp = AddISO8601IntPart(cp, min, 'M');
4056 if (sec != 0 || fsec != 0)
4058 if (sec < 0 || fsec < 0)
4060 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4067 /* Compatible with postgresql < 8.4 when DateStyle = 'iso' */
4068 case INTSTYLE_POSTGRES:
4069 cp = AddPostgresIntPart(cp, year, "year", &is_zero, &is_before);
4072 * Ideally we should spell out "month" like we do for "year" and
4073 * "day". However, for backward compatibility, we can't easily
4074 * fix this. bjm 2011-05-24
4076 cp = AddPostgresIntPart(cp, mon, "mon", &is_zero, &is_before);
4077 cp = AddPostgresIntPart(cp, mday, "day", &is_zero, &is_before);
4078 if (is_zero || hour != 0 || min != 0 || sec != 0 || fsec != 0)
4080 bool minus = (hour < 0 || min < 0 || sec < 0 || fsec < 0);
4082 sprintf(cp, "%s%s%02d:%02d:",
4084 (minus ? "-" : (is_before ? "+" : "")),
4085 abs(hour), abs(min));
4087 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4091 /* Compatible with postgresql < 8.4 when DateStyle != 'iso' */
4092 case INTSTYLE_POSTGRES_VERBOSE:
4096 cp = AddVerboseIntPart(cp, year, "year", &is_zero, &is_before);
4097 cp = AddVerboseIntPart(cp, mon, "mon", &is_zero, &is_before);
4098 cp = AddVerboseIntPart(cp, mday, "day", &is_zero, &is_before);
4099 cp = AddVerboseIntPart(cp, hour, "hour", &is_zero, &is_before);
4100 cp = AddVerboseIntPart(cp, min, "min", &is_zero, &is_before);
4101 if (sec != 0 || fsec != 0)
4104 if (sec < 0 || (sec == 0 && fsec < 0))
4108 else if (!is_before)
4113 AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4115 sprintf(cp, " sec%s",
4116 (abs(sec) != 1 || fsec != 0) ? "s" : "");
4119 /* identically zero? then put in a unitless zero... */
4130 * We've been burnt by stupid errors in the ordering of the datetkn tables
4131 * once too often. Arrange to check them during postmaster start.
4134 CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
4139 for (i = 1; i < nel; i++)
4141 if (strncmp(base[i - 1].token, base[i].token, TOKMAXLEN) >= 0)
4143 /* %.*s is safe since all our tokens are ASCII */
4144 elog(LOG, "ordering error in %s table: \"%.*s\" >= \"%.*s\"",
4146 TOKMAXLEN, base[i - 1].token,
4147 TOKMAXLEN, base[i].token);
4155 CheckDateTokenTables(void)
4159 Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
4160 Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
4162 ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
4163 ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
4168 * Common code for temporal protransform functions. Types time, timetz,
4169 * timestamp and timestamptz each have a range of allowed precisions. An
4170 * unspecified precision is rigorously equivalent to the highest specifiable
4173 * Note: timestamp_scale throws an error when the typmod is out of range, but
4174 * we can't get there from a cast: our typmodin will have caught it already.
4177 TemporalTransform(int32 max_precis, Node *node)
4179 FuncExpr *expr = (FuncExpr *) node;
4183 Assert(IsA(expr, FuncExpr));
4184 Assert(list_length(expr->args) >= 2);
4186 typmod = (Node *) lsecond(expr->args);
4188 if (IsA(typmod, Const) &&!((Const *) typmod)->constisnull)
4190 Node *source = (Node *) linitial(expr->args);
4191 int32 old_precis = exprTypmod(source);
4192 int32 new_precis = DatumGetInt32(((Const *) typmod)->constvalue);
4194 if (new_precis < 0 || new_precis == max_precis ||
4195 (old_precis >= 0 && new_precis >= old_precis))
4196 ret = relabel_to_typmod(source, new_precis);
4203 * This function gets called during timezone config file load or reload
4204 * to create the final array of timezone tokens. The argument array
4205 * is already sorted in name order. The data is converted to datetkn
4206 * format and installed in *tbl, which must be allocated by the caller.
4209 ConvertTimeZoneAbbrevs(TimeZoneAbbrevTable *tbl,
4210 struct tzEntry *abbrevs, int n)
4212 datetkn *newtbl = tbl->abbrevs;
4215 tbl->numabbrevs = n;
4216 for (i = 0; i < n; i++)
4218 /* do NOT use strlcpy here; token field need not be null-terminated */
4219 strncpy(newtbl[i].token, abbrevs[i].abbrev, TOKMAXLEN);
4220 newtbl[i].type = abbrevs[i].is_dst ? DTZ : TZ;
4221 TOVAL(&newtbl[i], abbrevs[i].offset / MINS_PER_HOUR);
4224 /* Check the ordering, if testing */
4225 Assert(CheckDateTokenTable("timezone offset", newtbl, n));
4229 * Install a TimeZoneAbbrevTable as the active table.
4231 * Caller is responsible that the passed table doesn't go away while in use.
4234 InstallTimeZoneAbbrevs(TimeZoneAbbrevTable *tbl)
4238 timezonetktbl = tbl->abbrevs;
4239 sztimezonetktbl = tbl->numabbrevs;
4241 /* clear date cache in case it contains any stale timezone names */
4242 for (i = 0; i < MAXDATEFIELDS; i++)
4243 datecache[i] = NULL;
4247 * This set-returning function reads all the available time zone abbreviations
4248 * and returns a set of (abbrev, utc_offset, is_dst).
4251 pg_timezone_abbrevs(PG_FUNCTION_ARGS)
4253 FuncCallContext *funcctx;
4259 char buffer[TOKMAXLEN + 1];
4262 Interval *resInterval;
4264 /* stuff done only on the first call of the function */
4265 if (SRF_IS_FIRSTCALL())
4268 MemoryContext oldcontext;
4270 /* create a function context for cross-call persistence */
4271 funcctx = SRF_FIRSTCALL_INIT();
4274 * switch to memory context appropriate for multiple function calls
4276 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4278 /* allocate memory for user context */
4279 pindex = (int *) palloc(sizeof(int));
4281 funcctx->user_fctx = (void *) pindex;
4284 * build tupdesc for result tuples. This must match this function's
4287 tupdesc = CreateTemplateTupleDesc(3, false);
4288 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "abbrev",
4290 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "utc_offset",
4291 INTERVALOID, -1, 0);
4292 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_dst",
4295 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4296 MemoryContextSwitchTo(oldcontext);
4299 /* stuff done on every call of the function */
4300 funcctx = SRF_PERCALL_SETUP();
4301 pindex = (int *) funcctx->user_fctx;
4303 if (*pindex >= sztimezonetktbl)
4304 SRF_RETURN_DONE(funcctx);
4306 MemSet(nulls, 0, sizeof(nulls));
4309 * Convert name to text, using upcasing conversion that is the inverse of
4310 * what ParseDateTime() uses.
4312 strncpy(buffer, timezonetktbl[*pindex].token, TOKMAXLEN);
4313 buffer[TOKMAXLEN] = '\0'; /* may not be null-terminated */
4314 for (p = (unsigned char *) buffer; *p; p++)
4315 *p = pg_toupper(*p);
4317 values[0] = CStringGetTextDatum(buffer);
4319 MemSet(&tm, 0, sizeof(struct pg_tm));
4320 tm.tm_min = (-1) * FROMVAL(&timezonetktbl[*pindex]);
4321 resInterval = (Interval *) palloc(sizeof(Interval));
4322 tm2interval(&tm, 0, resInterval);
4323 values[1] = IntervalPGetDatum(resInterval);
4325 Assert(timezonetktbl[*pindex].type == DTZ ||
4326 timezonetktbl[*pindex].type == TZ);
4327 values[2] = BoolGetDatum(timezonetktbl[*pindex].type == DTZ);
4331 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4332 result = HeapTupleGetDatum(tuple);
4334 SRF_RETURN_NEXT(funcctx, result);
4338 * This set-returning function reads all the available full time zones
4339 * and returns a set of (name, abbrev, utc_offset, is_dst).
4342 pg_timezone_names(PG_FUNCTION_ARGS)
4344 MemoryContext oldcontext;
4345 FuncCallContext *funcctx;
4356 Interval *resInterval;
4359 /* stuff done only on the first call of the function */
4360 if (SRF_IS_FIRSTCALL())
4364 /* create a function context for cross-call persistence */
4365 funcctx = SRF_FIRSTCALL_INIT();
4368 * switch to memory context appropriate for multiple function calls
4370 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4372 /* initialize timezone scanning code */
4373 tzenum = pg_tzenumerate_start();
4374 funcctx->user_fctx = (void *) tzenum;
4377 * build tupdesc for result tuples. This must match this function's
4380 tupdesc = CreateTemplateTupleDesc(4, false);
4381 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
4383 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "abbrev",
4385 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "utc_offset",
4386 INTERVALOID, -1, 0);
4387 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_dst",
4390 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4391 MemoryContextSwitchTo(oldcontext);
4394 /* stuff done on every call of the function */
4395 funcctx = SRF_PERCALL_SETUP();
4396 tzenum = (pg_tzenum *) funcctx->user_fctx;
4398 /* search for another zone to display */
4401 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4402 tz = pg_tzenumerate_next(tzenum);
4403 MemoryContextSwitchTo(oldcontext);
4407 pg_tzenumerate_end(tzenum);
4408 funcctx->user_fctx = NULL;
4409 SRF_RETURN_DONE(funcctx);
4412 /* Convert now() to local time in this zone */
4413 if (timestamp2tm(GetCurrentTransactionStartTimestamp(),
4414 &tzoff, &tm, &fsec, &tzn, tz) != 0)
4415 continue; /* ignore if conversion fails */
4417 /* Ignore zic's rather silly "Factory" time zone */
4418 if (tzn && strcmp(tzn, "Local time zone must be set--see zic manual page") == 0)
4421 /* Found a displayable zone */
4425 MemSet(nulls, 0, sizeof(nulls));
4427 values[0] = CStringGetTextDatum(pg_get_timezone_name(tz));
4428 values[1] = CStringGetTextDatum(tzn ? tzn : "");
4430 MemSet(&itm, 0, sizeof(struct pg_tm));
4431 itm.tm_sec = -tzoff;
4432 resInterval = (Interval *) palloc(sizeof(Interval));
4433 tm2interval(&itm, 0, resInterval);
4434 values[2] = IntervalPGetDatum(resInterval);
4436 values[3] = BoolGetDatum(tm.tm_isdst > 0);
4438 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4439 result = HeapTupleGetDatum(tuple);
4441 SRF_RETURN_NEXT(funcctx, result);