1 /*-------------------------------------------------------------------------
4 * Support functions for date/time types.
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
13 *-------------------------------------------------------------------------
22 #include "access/xact.h"
23 #include "catalog/pg_type.h"
25 #include "miscadmin.h"
26 #include "utils/builtins.h"
27 #include "utils/date.h"
28 #include "utils/datetime.h"
29 #include "utils/memutils.h"
30 #include "utils/tzparser.h"
33 static int DecodeNumber(int flen
, char *field
, bool haveTextMonth
,
34 int fmask
, int *tmask
,
35 struct pg_tm
* tm
, fsec_t
*fsec
, bool *is2digits
);
36 static int DecodeNumberField(int len
, char *str
,
37 int fmask
, int *tmask
,
38 struct pg_tm
* tm
, fsec_t
*fsec
, bool *is2digits
);
39 static int DecodeTime(char *str
, int fmask
, int range
,
40 int *tmask
, struct pg_tm
* tm
, fsec_t
*fsec
);
41 static int DecodeTimezone(char *str
, int *tzp
);
42 static const datetkn
*datebsearch(const char *key
, const datetkn
*base
, int nel
);
43 static int DecodeDate(char *str
, int fmask
, int *tmask
, bool *is2digits
,
45 static int ValidateDate(int fmask
, bool is2digits
, bool bc
,
47 static void TrimTrailingZeros(char *str
);
48 static void AppendSeconds(char *cp
, int sec
, fsec_t fsec
,
49 int precision
, bool fillzeros
);
50 static void AdjustFractSeconds(double frac
, struct pg_tm
* tm
, fsec_t
*fsec
,
52 static void AdjustFractDays(double frac
, struct pg_tm
* tm
, fsec_t
*fsec
,
56 const int day_tab
[2][13] =
58 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
59 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}
62 char *months
[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
63 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL
};
65 char *days
[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
66 "Thursday", "Friday", "Saturday", NULL
};
69 /*****************************************************************************
71 *****************************************************************************/
74 * Definitions for squeezing values into "value"
75 * We set aside a high bit for a sign, and scale the timezone offsets
76 * in minutes by a factor of 15 (so can represent quarter-hour increments).
78 #define ABS_SIGNBIT ((char) 0200)
79 #define VALMASK ((char) 0177)
81 #define NEG(n) ((n)|ABS_SIGNBIT)
82 #define SIGNEDCHAR(c) ((c)&ABS_SIGNBIT? -((c)&VALMASK): (c))
83 #define FROMVAL(tp) (-SIGNEDCHAR((tp)->value) * 15) /* uncompress */
84 #define TOVAL(tp, v) ((tp)->value = ((v) < 0? NEG((-(v))/15): POS(v)/15))
87 * datetktbl holds date/time keywords.
89 * Note that this table must be strictly alphabetically ordered to allow an
90 * O(ln(N)) search algorithm to be used.
92 * The text field is NOT guaranteed to be NULL-terminated.
94 * To keep this table reasonably small, we divide the lexval for TZ and DTZ
95 * entries by 15 (so they are on 15 minute boundaries) and truncate the text
96 * field at TOKMAXLEN characters.
97 * Formerly, we divided by 10 rather than 15 but there are a few time zones
98 * which are 30 or 45 minutes away from an even hour, most are on an hour
99 * boundary, and none on other boundaries.
101 * The static table contains no TZ or DTZ entries, rather those are loaded
102 * from configuration files and stored in timezonetktbl, which has the same
103 * format as the static datetktbl.
105 static datetkn
*timezonetktbl
= NULL
;
107 static int sztimezonetktbl
= 0;
109 static const datetkn datetktbl
[] = {
110 /* text, token, lexval */
111 {EARLY
, RESERV
, DTK_EARLY
}, /* "-infinity" reserved for "early time" */
112 {DA_D
, ADBC
, AD
}, /* "ad" for years > 0 */
113 {"allballs", RESERV
, DTK_ZULU
}, /* 00:00:00 */
117 {"at", IGNORE_DTF
, 0}, /* "at" (throwaway) */
119 {"august", MONTH
, 8},
120 {DB_C
, ADBC
, BC
}, /* "bc" for years <= 0 */
121 {DCURRENT
, RESERV
, DTK_CURRENT
}, /* "current" is always now */
122 {"d", UNITS
, DTK_DAY
}, /* "day of month" for ISO input */
124 {"december", MONTH
, 12},
125 {"dow", RESERV
, DTK_DOW
}, /* day of week */
126 {"doy", RESERV
, DTK_DOY
}, /* day of year */
128 {EPOCH
, RESERV
, DTK_EPOCH
}, /* "epoch" reserved for system epoch time */
130 {"february", MONTH
, 2},
133 {"h", UNITS
, DTK_HOUR
}, /* "hour" */
134 {LATE
, RESERV
, DTK_LATE
}, /* "infinity" reserved for "late time" */
135 {INVALID
, RESERV
, DTK_INVALID
}, /* "invalid" reserved for bad time */
136 {"isodow", RESERV
, DTK_ISODOW
}, /* ISO day of week, Sunday == 7 */
137 {"isoyear", UNITS
, DTK_ISOYEAR
}, /* year in terms of the ISO week date */
138 {"j", UNITS
, DTK_JULIAN
},
140 {"january", MONTH
, 1},
141 {"jd", UNITS
, DTK_JULIAN
},
143 {"julian", UNITS
, DTK_JULIAN
},
147 {"m", UNITS
, DTK_MONTH
}, /* "month" for ISO input */
151 {"mm", UNITS
, DTK_MINUTE
}, /* "minute" for ISO input */
155 {"november", MONTH
, 11},
156 {NOW
, RESERV
, DTK_NOW
}, /* current transaction time */
158 {"october", MONTH
, 10},
159 {"on", IGNORE_DTF
, 0}, /* "on" (throwaway) */
161 {"s", UNITS
, DTK_SECOND
}, /* "seconds" for ISO input */
163 {"saturday", DOW
, 6},
166 {"september", MONTH
, 9},
169 {"t", ISOTIME
, DTK_TIME
}, /* Filler for ISO time fields */
173 {"thursday", DOW
, 4},
174 {TODAY
, RESERV
, DTK_TODAY
}, /* midnight */
175 {TOMORROW
, RESERV
, DTK_TOMORROW
}, /* tomorrow midnight */
179 {"undefined", RESERV
, DTK_INVALID
}, /* pre-v6.1 invalid time */
181 {"wednesday", DOW
, 3},
183 {"y", UNITS
, DTK_YEAR
}, /* "year" for ISO input */
184 {YESTERDAY
, RESERV
, DTK_YESTERDAY
} /* yesterday midnight */
187 static int szdatetktbl
= sizeof datetktbl
/ sizeof datetktbl
[0];
189 static datetkn deltatktbl
[] = {
190 /* text, token, lexval */
191 {"@", IGNORE_DTF
, 0}, /* postgres relative prefix */
192 {DAGO
, AGO
, 0}, /* "ago" indicates negative time offset */
193 {"c", UNITS
, DTK_CENTURY
}, /* "century" relative */
194 {"cent", UNITS
, DTK_CENTURY
}, /* "century" relative */
195 {"centuries", UNITS
, DTK_CENTURY
}, /* "centuries" relative */
196 {DCENTURY
, UNITS
, DTK_CENTURY
}, /* "century" relative */
197 {"d", UNITS
, DTK_DAY
}, /* "day" relative */
198 {DDAY
, UNITS
, DTK_DAY
}, /* "day" relative */
199 {"days", UNITS
, DTK_DAY
}, /* "days" relative */
200 {"dec", UNITS
, DTK_DECADE
}, /* "decade" relative */
201 {DDECADE
, UNITS
, DTK_DECADE
}, /* "decade" relative */
202 {"decades", UNITS
, DTK_DECADE
}, /* "decades" relative */
203 {"decs", UNITS
, DTK_DECADE
}, /* "decades" relative */
204 {"h", UNITS
, DTK_HOUR
}, /* "hour" relative */
205 {DHOUR
, UNITS
, DTK_HOUR
}, /* "hour" relative */
206 {"hours", UNITS
, DTK_HOUR
}, /* "hours" relative */
207 {"hr", UNITS
, DTK_HOUR
}, /* "hour" relative */
208 {"hrs", UNITS
, DTK_HOUR
}, /* "hours" relative */
209 {INVALID
, RESERV
, DTK_INVALID
}, /* reserved for invalid time */
210 {"m", UNITS
, DTK_MINUTE
}, /* "minute" relative */
211 {"microsecon", UNITS
, DTK_MICROSEC
}, /* "microsecond" relative */
212 {"mil", UNITS
, DTK_MILLENNIUM
}, /* "millennium" relative */
213 {"millennia", UNITS
, DTK_MILLENNIUM
}, /* "millennia" relative */
214 {DMILLENNIUM
, UNITS
, DTK_MILLENNIUM
}, /* "millennium" relative */
215 {"millisecon", UNITS
, DTK_MILLISEC
}, /* relative */
216 {"mils", UNITS
, DTK_MILLENNIUM
}, /* "millennia" relative */
217 {"min", UNITS
, DTK_MINUTE
}, /* "minute" relative */
218 {"mins", UNITS
, DTK_MINUTE
}, /* "minutes" relative */
219 {DMINUTE
, UNITS
, DTK_MINUTE
}, /* "minute" relative */
220 {"minutes", UNITS
, DTK_MINUTE
}, /* "minutes" relative */
221 {"mon", UNITS
, DTK_MONTH
}, /* "months" relative */
222 {"mons", UNITS
, DTK_MONTH
}, /* "months" relative */
223 {DMONTH
, UNITS
, DTK_MONTH
}, /* "month" relative */
224 {"months", UNITS
, DTK_MONTH
},
225 {"ms", UNITS
, DTK_MILLISEC
},
226 {"msec", UNITS
, DTK_MILLISEC
},
227 {DMILLISEC
, UNITS
, DTK_MILLISEC
},
228 {"mseconds", UNITS
, DTK_MILLISEC
},
229 {"msecs", UNITS
, DTK_MILLISEC
},
230 {"qtr", UNITS
, DTK_QUARTER
}, /* "quarter" relative */
231 {DQUARTER
, UNITS
, DTK_QUARTER
}, /* "quarter" relative */
232 {"s", UNITS
, DTK_SECOND
},
233 {"sec", UNITS
, DTK_SECOND
},
234 {DSECOND
, UNITS
, DTK_SECOND
},
235 {"seconds", UNITS
, DTK_SECOND
},
236 {"secs", UNITS
, DTK_SECOND
},
237 {DTIMEZONE
, UNITS
, DTK_TZ
}, /* "timezone" time offset */
238 {"timezone_h", UNITS
, DTK_TZ_HOUR
}, /* timezone hour units */
239 {"timezone_m", UNITS
, DTK_TZ_MINUTE
}, /* timezone minutes units */
240 {"undefined", RESERV
, DTK_INVALID
}, /* pre-v6.1 invalid time */
241 {"us", UNITS
, DTK_MICROSEC
}, /* "microsecond" relative */
242 {"usec", UNITS
, DTK_MICROSEC
}, /* "microsecond" relative */
243 {DMICROSEC
, UNITS
, DTK_MICROSEC
}, /* "microsecond" relative */
244 {"useconds", UNITS
, DTK_MICROSEC
}, /* "microseconds" relative */
245 {"usecs", UNITS
, DTK_MICROSEC
}, /* "microseconds" relative */
246 {"w", UNITS
, DTK_WEEK
}, /* "week" relative */
247 {DWEEK
, UNITS
, DTK_WEEK
}, /* "week" relative */
248 {"weeks", UNITS
, DTK_WEEK
}, /* "weeks" relative */
249 {"y", UNITS
, DTK_YEAR
}, /* "year" relative */
250 {DYEAR
, UNITS
, DTK_YEAR
}, /* "year" relative */
251 {"years", UNITS
, DTK_YEAR
}, /* "years" relative */
252 {"yr", UNITS
, DTK_YEAR
}, /* "year" relative */
253 {"yrs", UNITS
, DTK_YEAR
} /* "years" relative */
256 static int szdeltatktbl
= sizeof deltatktbl
/ sizeof deltatktbl
[0];
258 static const datetkn
*datecache
[MAXDATEFIELDS
] = {NULL
};
260 static const datetkn
*deltacache
[MAXDATEFIELDS
] = {NULL
};
264 * strtoi --- just like strtol, but returns int not long
267 strtoi(const char *nptr
, char **endptr
, int base
)
271 val
= strtol(nptr
, endptr
, base
);
272 #ifdef HAVE_LONG_INT_64
273 if (val
!= (long) ((int32
) val
))
281 * Calendar time to Julian date conversions.
282 * Julian date is commonly used in astronomical applications,
283 * since it is numerically accurate and computationally simple.
284 * The algorithms here will accurately convert between Julian day
285 * and calendar date for all non-negative Julian days
286 * (i.e. from Nov 24, -4713 on).
288 * These routines will be used by other date/time packages
291 * Rewritten to eliminate overflow problems. This now allows the
292 * routines to work correctly for all Julian day counts from
293 * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming
294 * a 32-bit integer. Longer types should also work to the limits
295 * of their precision.
299 date2j(int y
, int m
, int d
)
316 julian
= y
* 365 - 32167;
317 julian
+= y
/ 4 - century
+ century
/ 4;
318 julian
+= 7834 * m
/ 256 + d
;
324 j2date(int jd
, int *year
, int *month
, int *day
)
333 quad
= julian
/ 146097;
334 extra
= (julian
- quad
* 146097) * 4 + 3;
335 julian
+= 60 + quad
* 3 + extra
/ 146097;
336 quad
= julian
/ 1461;
337 julian
-= quad
* 1461;
338 y
= julian
* 4 / 1461;
339 julian
= ((y
!= 0) ? ((julian
+ 305) % 365) : ((julian
+ 306) % 366))
343 quad
= julian
* 2141 / 65536;
344 *day
= julian
- 7834 * quad
/ 256;
345 *month
= (quad
+ 10) % 12 + 1;
352 * j2day - convert Julian date to day-of-week (0..6 == Sun..Sat)
354 * Note: various places use the locution j2day(date - 1) to produce a
355 * result according to the convention 0..6 = Mon..Sun. This is a bit of
356 * a crock, but will work as long as the computation here is just a modulo.
373 * GetCurrentDateTime()
375 * Get the transaction start time ("now()") broken down as a struct pg_tm.
378 GetCurrentDateTime(struct pg_tm
* tm
)
383 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz
, tm
, &fsec
,
385 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
389 * GetCurrentTimeUsec()
391 * Get the transaction start time ("now()") broken down as a struct pg_tm,
392 * including fractional seconds and timezone offset.
395 GetCurrentTimeUsec(struct pg_tm
* tm
, fsec_t
*fsec
, int *tzp
)
399 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz
, tm
, fsec
,
401 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
407 /* TrimTrailingZeros()
408 * ... resulting from printing numbers with full precision.
410 * Before Postgres 8.4, this always left at least 2 fractional digits,
411 * but conversations on the lists suggest this isn't desired
412 * since showing '0.10' is misleading with values of precision(1).
415 TrimTrailingZeros(char *str
)
417 int len
= strlen(str
);
419 while (len
> 1 && *(str
+ len
- 1) == '0' && *(str
+ len
- 2) != '.')
427 * Append sections and fractional seconds (if any) at *cp.
428 * precision is the max number of fraction digits, fillzeros says to
429 * pad to two integral-seconds digits.
430 * Note that any sign is stripped from the input seconds values.
433 AppendSeconds(char *cp
, int sec
, fsec_t fsec
, int precision
, bool fillzeros
)
438 sprintf(cp
, "%02d", abs(sec
));
440 sprintf(cp
, "%d", abs(sec
));
444 #ifdef HAVE_INT64_TIMESTAMP
446 sprintf(cp
, "%02d.%0*d", abs(sec
), precision
, (int) Abs(fsec
));
448 sprintf(cp
, "%d.%0*d", abs(sec
), precision
, (int) Abs(fsec
));
451 sprintf(cp
, "%0*.*f", precision
+ 3, precision
, fabs(sec
+ fsec
));
453 sprintf(cp
, "%.*f", precision
, fabs(sec
+ fsec
));
455 TrimTrailingZeros(cp
);
459 /* Variant of above that's specialized to timestamp case */
461 AppendTimestampSeconds(char *cp
, struct pg_tm
* tm
, fsec_t fsec
)
464 * In float mode, don't print fractional seconds before 1 AD, since it's
465 * unlikely there's any precision left ...
467 #ifndef HAVE_INT64_TIMESTAMP
468 if (tm
->tm_year
<= 0)
471 AppendSeconds(cp
, tm
->tm_sec
, fsec
, MAX_TIMESTAMP_PRECISION
, true);
475 * Multiply frac by scale (to produce seconds) and add to *tm & *fsec.
476 * We assume the input frac is less than 1 so overflow is not an issue.
479 AdjustFractSeconds(double frac
, struct pg_tm
* tm
, fsec_t
*fsec
, int scale
)
489 #ifdef HAVE_INT64_TIMESTAMP
490 *fsec
+= rint(frac
* 1000000);
496 /* As above, but initial scale produces days */
498 AdjustFractDays(double frac
, struct pg_tm
* tm
, fsec_t
*fsec
, int scale
)
505 extra_days
= (int) frac
;
506 tm
->tm_mday
+= extra_days
;
508 AdjustFractSeconds(frac
, tm
, fsec
, SECS_PER_DAY
);
511 /* Fetch a fractional-second value with suitable error checking */
513 ParseFractionalSecond(char *cp
, fsec_t
*fsec
)
517 /* Caller should always pass the start of the fraction part */
520 frac
= strtod(cp
, &cp
);
521 /* check for parse failure */
522 if (*cp
!= '\0' || errno
!= 0)
523 return DTERR_BAD_FORMAT
;
524 #ifdef HAVE_INT64_TIMESTAMP
525 *fsec
= rint(frac
* 1000000);
534 * Break string into tokens based on a date/time context.
535 * Returns 0 if successful, DTERR code if bogus input detected.
537 * timestr - the input string
538 * workbuf - workspace for field string storage. This must be
539 * larger than the largest legal input for this datetime type --
540 * some additional space will be needed to NUL terminate fields.
541 * buflen - the size of workbuf
542 * field[] - pointers to field strings are returned in this array
543 * ftype[] - field type indicators are returned in this array
544 * maxfields - dimensions of the above two arrays
545 * *numfields - set to the actual number of fields detected
547 * The fields extracted from the input are stored as separate,
548 * null-terminated strings in the workspace at workbuf. Any text is
549 * converted to lower case.
551 * Several field types are assigned:
552 * DTK_NUMBER - digits and (possibly) a decimal point
553 * DTK_DATE - digits and two delimiters, or digits and text
554 * DTK_TIME - digits, colon delimiters, and possibly a decimal point
555 * DTK_STRING - text (no digits or punctuation)
556 * DTK_SPECIAL - leading "+" or "-" followed by text
557 * DTK_TZ - leading "+" or "-" followed by digits (also eats ':', '.', '-')
559 * Note that some field types can hold unexpected items:
560 * DTK_NUMBER can hold date fields (yy.ddd)
561 * DTK_STRING can hold months (January) and time zones (PST)
562 * DTK_DATE can hold time zone names (America/New_York, GMT-8)
565 ParseDateTime(const char *timestr
, char *workbuf
, size_t buflen
,
566 char **field
, int *ftype
, int maxfields
, int *numfields
)
569 const char *cp
= timestr
;
570 char *bufp
= workbuf
;
571 const char *bufend
= workbuf
+ buflen
;
574 * Set the character pointed-to by "bufptr" to "newchar", and increment
575 * "bufptr". "end" gives the end of the buffer -- we return an error if
576 * there is no space left to append a character to the buffer. Note that
577 * "bufptr" is evaluated twice.
579 #define APPEND_CHAR(bufptr, end, newchar) \
582 if (((bufptr) + 1) >= (end)) \
583 return DTERR_BAD_FORMAT; \
584 *(bufptr)++ = newchar; \
587 /* outer loop through fields */
590 /* Ignore spaces between fields */
591 if (isspace((unsigned char) *cp
))
597 /* Record start of current field */
599 return DTERR_BAD_FORMAT
;
602 /* leading digit? then date or time */
603 if (isdigit((unsigned char) *cp
))
605 APPEND_CHAR(bufp
, bufend
, *cp
++);
606 while (isdigit((unsigned char) *cp
))
607 APPEND_CHAR(bufp
, bufend
, *cp
++);
612 ftype
[nf
] = DTK_TIME
;
613 APPEND_CHAR(bufp
, bufend
, *cp
++);
614 while (isdigit((unsigned char) *cp
) ||
615 (*cp
== ':') || (*cp
== '.'))
616 APPEND_CHAR(bufp
, bufend
, *cp
++);
618 /* date field? allow embedded text month */
619 else if (*cp
== '-' || *cp
== '/' || *cp
== '.')
621 /* save delimiting character to use later */
624 APPEND_CHAR(bufp
, bufend
, *cp
++);
625 /* second field is all digits? then no embedded text month */
626 if (isdigit((unsigned char) *cp
))
628 ftype
[nf
] = ((delim
== '.') ? DTK_NUMBER
: DTK_DATE
);
629 while (isdigit((unsigned char) *cp
))
630 APPEND_CHAR(bufp
, bufend
, *cp
++);
633 * insist that the delimiters match to get a three-field
638 ftype
[nf
] = DTK_DATE
;
639 APPEND_CHAR(bufp
, bufend
, *cp
++);
640 while (isdigit((unsigned char) *cp
) || *cp
== delim
)
641 APPEND_CHAR(bufp
, bufend
, *cp
++);
646 ftype
[nf
] = DTK_DATE
;
647 while (isalnum((unsigned char) *cp
) || *cp
== delim
)
648 APPEND_CHAR(bufp
, bufend
, pg_tolower((unsigned char) *cp
++));
653 * otherwise, number only and will determine year, month, day, or
654 * concatenated fields later...
657 ftype
[nf
] = DTK_NUMBER
;
659 /* Leading decimal point? Then fractional seconds... */
662 APPEND_CHAR(bufp
, bufend
, *cp
++);
663 while (isdigit((unsigned char) *cp
))
664 APPEND_CHAR(bufp
, bufend
, *cp
++);
666 ftype
[nf
] = DTK_NUMBER
;
670 * text? then date string, month, day of week, special, or timezone
672 else if (isalpha((unsigned char) *cp
))
676 ftype
[nf
] = DTK_STRING
;
677 APPEND_CHAR(bufp
, bufend
, pg_tolower((unsigned char) *cp
++));
678 while (isalpha((unsigned char) *cp
))
679 APPEND_CHAR(bufp
, bufend
, pg_tolower((unsigned char) *cp
++));
682 * Dates can have embedded '-', '/', or '.' separators. It could
683 * also be a timezone name containing embedded '/', '+', '-', '_',
684 * or ':' (but '_' or ':' can't be the first punctuation). If the
685 * next character is a digit or '+', we need to check whether what
686 * we have so far is a recognized non-timezone keyword --- if so,
687 * don't believe that this is the start of a timezone.
690 if (*cp
== '-' || *cp
== '/' || *cp
== '.')
692 else if (*cp
== '+' || isdigit((unsigned char) *cp
))
694 *bufp
= '\0'; /* null-terminate current field value */
695 /* we need search only the core token table, not TZ names */
696 if (datebsearch(field
[nf
], datetktbl
, szdatetktbl
) == NULL
)
701 ftype
[nf
] = DTK_DATE
;
704 APPEND_CHAR(bufp
, bufend
, pg_tolower((unsigned char) *cp
++));
705 } while (*cp
== '+' || *cp
== '-' ||
706 *cp
== '/' || *cp
== '_' ||
707 *cp
== '.' || *cp
== ':' ||
708 isalnum((unsigned char) *cp
));
711 /* sign? then special or numeric timezone */
712 else if (*cp
== '+' || *cp
== '-')
714 APPEND_CHAR(bufp
, bufend
, *cp
++);
715 /* soak up leading whitespace */
716 while (isspace((unsigned char) *cp
))
718 /* numeric timezone? */
719 /* note that "DTK_TZ" could also be a signed float or yyyy-mm */
720 if (isdigit((unsigned char) *cp
))
723 APPEND_CHAR(bufp
, bufend
, *cp
++);
724 while (isdigit((unsigned char) *cp
) ||
725 *cp
== ':' || *cp
== '.' || *cp
== '-')
726 APPEND_CHAR(bufp
, bufend
, *cp
++);
729 else if (isalpha((unsigned char) *cp
))
731 ftype
[nf
] = DTK_SPECIAL
;
732 APPEND_CHAR(bufp
, bufend
, pg_tolower((unsigned char) *cp
++));
733 while (isalpha((unsigned char) *cp
))
734 APPEND_CHAR(bufp
, bufend
, pg_tolower((unsigned char) *cp
++));
736 /* otherwise something wrong... */
738 return DTERR_BAD_FORMAT
;
740 /* ignore other punctuation but use as delimiter */
741 else if (ispunct((unsigned char) *cp
))
746 /* otherwise, something is not right... */
748 return DTERR_BAD_FORMAT
;
750 /* force in a delimiter after each field */
762 * Interpret previously parsed fields for general date and time.
763 * Return 0 if full date, 1 if only time, and negative DTERR code if problems.
764 * (Currently, all callers treat 1 as an error return too.)
766 * External format(s):
767 * "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
768 * "Fri Feb-7-1997 15:23:27"
769 * "Feb-7-1997 15:23:27"
770 * "2-7-1997 15:23:27"
771 * "1997-2-7 15:23:27"
772 * "1997.038 15:23:27" (day of year 1-366)
773 * Also supports input in compact time:
776 * "20011225T040506.789-07"
778 * Use the system-provided functions to get the current time zone
779 * if not specified in the input string.
781 * If the date is outside the range of pg_time_t (in practice that could only
782 * happen if pg_time_t is just 32 bits), then assume UTC time zone - thomas
786 DecodeDateTime(char **field
, int *ftype
, int nf
,
787 int *dtype
, struct pg_tm
* tm
, fsec_t
*fsec
, int *tzp
)
792 int ptype
= 0; /* "prefix type" for ISO y2001m02d04 format */
797 bool haveTextMonth
= FALSE
;
798 bool is2digits
= FALSE
;
800 pg_tz
*namedTz
= NULL
;
803 * We'll insist on at least all of the date fields, but initialize the
804 * remaining fields in case they are not set later...
811 /* don't know daylight savings time status apriori */
816 for (i
= 0; i
< nf
; i
++)
822 * Integral julian day with attached time zone?
823 * All other forms with JD will be separated into
824 * distinct fields, so we handle just this case here.
826 if (ptype
== DTK_JULIAN
)
832 return DTERR_BAD_FORMAT
;
835 val
= strtoi(field
[i
], &cp
, 10);
837 return DTERR_FIELD_OVERFLOW
;
839 j2date(val
, &tm
->tm_year
, &tm
->tm_mon
, &tm
->tm_mday
);
840 /* Get the time zone from the end of the string */
841 dterr
= DecodeTimezone(cp
, tzp
);
845 tmask
= DTK_DATE_M
| DTK_TIME_M
| DTK_M(TZ
);
850 * Already have a date? Then this might be a time zone name
851 * with embedded punctuation (e.g. "America/New_York") or a
852 * run-together time with trailing time zone (e.g. hhmmss-zz).
853 * - thomas 2001-12-25
855 * We consider it a time zone if we already have month & day.
856 * This is to allow the form "mmm dd hhmmss tz year", which
857 * we've historically accepted.
859 else if (ptype
!= 0 ||
860 ((fmask
& (DTK_M(MONTH
) | DTK_M(DAY
))) ==
861 (DTK_M(MONTH
) | DTK_M(DAY
))))
863 /* No time zone accepted? Then quit... */
865 return DTERR_BAD_FORMAT
;
867 if (isdigit((unsigned char) *field
[i
]) || ptype
!= 0)
873 /* Sanity check; should not fail this test */
874 if (ptype
!= DTK_TIME
)
875 return DTERR_BAD_FORMAT
;
880 * Starts with a digit but we already have a time
881 * field? Then we are in trouble with a date and time
884 if ((fmask
& DTK_TIME_M
) == DTK_TIME_M
)
885 return DTERR_BAD_FORMAT
;
887 if ((cp
= strchr(field
[i
], '-')) == NULL
)
888 return DTERR_BAD_FORMAT
;
890 /* Get the time zone from the end of the string */
891 dterr
= DecodeTimezone(cp
, tzp
);
897 * Then read the rest of the field as a concatenated
900 dterr
= DecodeNumberField(strlen(field
[i
]), field
[i
],
908 * modify tmask after returning from
909 * DecodeNumberField()
915 namedTz
= pg_tzset(field
[i
]);
919 * We should return an error code instead of
920 * ereport'ing directly, but then there is no way
921 * to report the bad time zone name.
924 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
925 errmsg("time zone \"%s\" not recognized",
928 /* we'll apply the zone setting below */
934 dterr
= DecodeDate(field
[i
], fmask
,
935 &tmask
, &is2digits
, tm
);
942 dterr
= DecodeTime(field
[i
], fmask
, INTERVAL_FULL_RANGE
,
948 * Check upper limit on hours; other limits checked in
951 /* test for > 24:00:00 */
952 if (tm
->tm_hour
> 24 ||
953 (tm
->tm_hour
== 24 &&
954 (tm
->tm_min
> 0 || tm
->tm_sec
> 0 || *fsec
> 0)))
955 return DTERR_FIELD_OVERFLOW
;
963 return DTERR_BAD_FORMAT
;
965 dterr
= DecodeTimezone(field
[i
], &tz
);
976 * Was this an "ISO date" with embedded field labels? An
977 * example is "y2001m02d04" - thomas 2001-02-04
985 val
= strtoi(field
[i
], &cp
, 10);
987 return DTERR_FIELD_OVERFLOW
;
990 * only a few kinds are allowed to have an embedded
1001 return DTERR_BAD_FORMAT
;
1004 else if (*cp
!= '\0')
1005 return DTERR_BAD_FORMAT
;
1011 tmask
= DTK_M(YEAR
);
1017 * already have a month and hour? then assume
1020 if ((fmask
& DTK_M(MONTH
)) != 0 &&
1021 (fmask
& DTK_M(HOUR
)) != 0)
1024 tmask
= DTK_M(MINUTE
);
1029 tmask
= DTK_M(MONTH
);
1040 tmask
= DTK_M(HOUR
);
1045 tmask
= DTK_M(MINUTE
);
1050 tmask
= DTK_M(SECOND
);
1053 dterr
= ParseFractionalSecond(cp
, fsec
);
1056 tmask
= DTK_ALL_SECS_M
;
1062 dterr
= DecodeTimezone(field
[i
], tzp
);
1069 * previous field was a label for "julian date"?
1072 j2date(val
, &tm
->tm_year
, &tm
->tm_mon
, &tm
->tm_mday
);
1073 /* fractional Julian Day? */
1079 time
= strtod(cp
, &cp
);
1080 if (*cp
!= '\0' || errno
!= 0)
1081 return DTERR_BAD_FORMAT
;
1083 #ifdef HAVE_INT64_TIMESTAMP
1084 time
*= USECS_PER_DAY
;
1086 time
*= SECS_PER_DAY
;
1089 &tm
->tm_hour
, &tm
->tm_min
,
1091 tmask
|= DTK_TIME_M
;
1096 /* previous field was "t" for ISO time */
1097 dterr
= DecodeNumberField(strlen(field
[i
]), field
[i
],
1098 (fmask
| DTK_DATE_M
),
1103 if (tmask
!= DTK_TIME_M
)
1104 return DTERR_BAD_FORMAT
;
1108 return DTERR_BAD_FORMAT
;
1120 flen
= strlen(field
[i
]);
1121 cp
= strchr(field
[i
], '.');
1123 /* Embedded decimal and no date yet? */
1124 if (cp
!= NULL
&& !(fmask
& DTK_DATE_M
))
1126 dterr
= DecodeDate(field
[i
], fmask
,
1127 &tmask
, &is2digits
, tm
);
1131 /* embedded decimal and several digits before? */
1132 else if (cp
!= NULL
&& flen
- strlen(cp
) > 2)
1135 * Interpret as a concatenated date or time Set the
1136 * type field to allow decoding other fields later.
1137 * Example: 20011223 or 040506
1139 dterr
= DecodeNumberField(flen
, field
[i
], fmask
,
1147 dterr
= DecodeNumberField(flen
, field
[i
], fmask
,
1153 /* otherwise it is a single date/time field... */
1156 dterr
= DecodeNumber(flen
, field
[i
],
1157 haveTextMonth
, fmask
,
1168 type
= DecodeSpecial(i
, field
[i
], &val
);
1169 if (type
== IGNORE_DTF
)
1172 tmask
= DTK_M(type
);
1180 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1181 errmsg("date/time value \"current\" is no longer supported")));
1183 return DTERR_BAD_FORMAT
;
1187 tmask
= (DTK_DATE_M
| DTK_TIME_M
| DTK_M(TZ
));
1189 GetCurrentTimeUsec(tm
, fsec
, tzp
);
1195 GetCurrentDateTime(tm
);
1196 j2date(date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
) - 1,
1197 &tm
->tm_year
, &tm
->tm_mon
, &tm
->tm_mday
);
1206 GetCurrentDateTime(tm
);
1215 GetCurrentDateTime(tm
);
1216 j2date(date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
) + 1,
1217 &tm
->tm_year
, &tm
->tm_mon
, &tm
->tm_mday
);
1224 tmask
= (DTK_TIME_M
| DTK_M(TZ
));
1242 * already have a (numeric) month? then see if we can
1245 if ((fmask
& DTK_M(MONTH
)) && !haveTextMonth
&&
1246 !(fmask
& DTK_M(DAY
)) && tm
->tm_mon
>= 1 &&
1249 tm
->tm_mday
= tm
->tm_mon
;
1252 haveTextMonth
= TRUE
;
1259 * daylight savings time modifier (solves "MET DST"
1262 tmask
|= DTK_M(DTZ
);
1265 return DTERR_BAD_FORMAT
;
1266 *tzp
+= val
* MINS_PER_HOUR
;
1272 * set mask for TZ here _or_ check for DTZ later when
1273 * getting default timezone
1278 return DTERR_BAD_FORMAT
;
1279 *tzp
= val
* MINS_PER_HOUR
;
1285 return DTERR_BAD_FORMAT
;
1286 *tzp
= val
* MINS_PER_HOUR
;
1312 * This is a filler field "t" indicating that the next
1313 * field is time. Try to verify that this is sensible.
1317 /* No preceding date? Then quit... */
1318 if ((fmask
& DTK_DATE_M
) != DTK_DATE_M
)
1319 return DTERR_BAD_FORMAT
;
1322 * We will need one of the following fields:
1323 * DTK_NUMBER should be hhmmss.fff
1324 * DTK_TIME should be hh:mm:ss.fff
1325 * DTK_DATE should be hhmmss-zz
1328 (ftype
[i
+ 1] != DTK_NUMBER
&&
1329 ftype
[i
+ 1] != DTK_TIME
&&
1330 ftype
[i
+ 1] != DTK_DATE
))
1331 return DTERR_BAD_FORMAT
;
1339 * Before giving up and declaring error, check to see
1340 * if it is an all-alpha timezone name.
1342 namedTz
= pg_tzset(field
[i
]);
1344 return DTERR_BAD_FORMAT
;
1345 /* we'll apply the zone setting below */
1350 return DTERR_BAD_FORMAT
;
1355 return DTERR_BAD_FORMAT
;
1359 return DTERR_BAD_FORMAT
;
1361 } /* end loop over fields */
1363 /* do final checking/adjustment of Y/M/D fields */
1364 dterr
= ValidateDate(fmask
, is2digits
, bc
, tm
);
1369 if (mer
!= HR24
&& tm
->tm_hour
> 12)
1370 return DTERR_FIELD_OVERFLOW
;
1371 if (mer
== AM
&& tm
->tm_hour
== 12)
1373 else if (mer
== PM
&& tm
->tm_hour
!= 12)
1376 /* do additional checking for full date specs... */
1377 if (*dtype
== DTK_DATE
)
1379 if ((fmask
& DTK_DATE_M
) != DTK_DATE_M
)
1381 if ((fmask
& DTK_TIME_M
) == DTK_TIME_M
)
1383 return DTERR_BAD_FORMAT
;
1387 * If we had a full timezone spec, compute the offset (we could not do
1388 * it before, because we need the date to resolve DST status).
1390 if (namedTz
!= NULL
)
1392 /* daylight savings time modifier disallowed with full TZ */
1393 if (fmask
& DTK_M(DTZMOD
))
1394 return DTERR_BAD_FORMAT
;
1396 *tzp
= DetermineTimeZoneOffset(tm
, namedTz
);
1399 /* timezone not specified? then find local timezone if possible */
1400 if (tzp
!= NULL
&& !(fmask
& DTK_M(TZ
)))
1403 * daylight savings time modifier but no standard timezone? then
1406 if (fmask
& DTK_M(DTZMOD
))
1407 return DTERR_BAD_FORMAT
;
1409 *tzp
= DetermineTimeZoneOffset(tm
, session_timezone
);
1417 /* DetermineTimeZoneOffset()
1419 * Given a struct pg_tm in which tm_year, tm_mon, tm_mday, tm_hour, tm_min, and
1420 * tm_sec fields are set, attempt to determine the applicable time zone
1421 * (ie, regular or daylight-savings time) at that time. Set the struct pg_tm's
1422 * tm_isdst field accordingly, and return the actual timezone offset.
1424 * Note: it might seem that we should use mktime() for this, but bitter
1425 * experience teaches otherwise. This code is much faster than most versions
1426 * of mktime(), anyway.
1429 DetermineTimeZoneOffset(struct pg_tm
* tm
, pg_tz
*tzp
)
1439 long int before_gmtoff
,
1445 if (tzp
== session_timezone
&& HasCTZSet
)
1447 tm
->tm_isdst
= 0; /* for lack of a better idea */
1452 * First, generate the pg_time_t value corresponding to the given
1453 * y/m/d/h/m/s taken as GMT time. If this overflows, punt and decide the
1454 * timezone is GMT. (We only need to worry about overflow on machines
1455 * where pg_time_t is 32 bits.)
1457 if (!IS_VALID_JULIAN(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
))
1459 date
= date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
) - UNIX_EPOCH_JDATE
;
1461 day
= ((pg_time_t
) date
) * SECS_PER_DAY
;
1462 if (day
/ SECS_PER_DAY
!= date
)
1464 sec
= tm
->tm_sec
+ (tm
->tm_min
+ tm
->tm_hour
* MINS_PER_HOUR
) * SECS_PER_MINUTE
;
1466 /* since sec >= 0, overflow could only be from +day to -mytime */
1467 if (mytime
< 0 && day
> 0)
1471 * Find the DST time boundary just before or following the target time. We
1472 * assume that all zones have GMT offsets less than 24 hours, and that DST
1473 * boundaries can't be closer together than 48 hours, so backing up 24
1474 * hours and finding the "next" boundary will work.
1476 prevtime
= mytime
- SECS_PER_DAY
;
1477 if (mytime
< 0 && prevtime
> 0)
1480 res
= pg_next_dst_boundary(&prevtime
,
1481 &before_gmtoff
, &before_isdst
,
1483 &after_gmtoff
, &after_isdst
,
1486 goto overflow
; /* failure? */
1490 /* Non-DST zone, life is simple */
1491 tm
->tm_isdst
= before_isdst
;
1492 return -(int) before_gmtoff
;
1496 * Form the candidate pg_time_t values with local-time adjustment
1498 beforetime
= mytime
- before_gmtoff
;
1499 if ((before_gmtoff
> 0 &&
1500 mytime
< 0 && beforetime
> 0) ||
1501 (before_gmtoff
<= 0 &&
1502 mytime
> 0 && beforetime
< 0))
1504 aftertime
= mytime
- after_gmtoff
;
1505 if ((after_gmtoff
> 0 &&
1506 mytime
< 0 && aftertime
> 0) ||
1507 (after_gmtoff
<= 0 &&
1508 mytime
> 0 && aftertime
< 0))
1512 * If both before or both after the boundary time, we know what to do
1514 if (beforetime
<= boundary
&& aftertime
< boundary
)
1516 tm
->tm_isdst
= before_isdst
;
1517 return -(int) before_gmtoff
;
1519 if (beforetime
> boundary
&& aftertime
>= boundary
)
1521 tm
->tm_isdst
= after_isdst
;
1522 return -(int) after_gmtoff
;
1526 * It's an invalid or ambiguous time due to timezone transition. Prefer
1527 * the standard-time interpretation.
1529 if (after_isdst
== 0)
1531 tm
->tm_isdst
= after_isdst
;
1532 return -(int) after_gmtoff
;
1534 tm
->tm_isdst
= before_isdst
;
1535 return -(int) before_gmtoff
;
1538 /* Given date is out of range, so assume UTC */
1545 * Interpret parsed string as time fields only.
1546 * Returns 0 if successful, DTERR code if bogus input detected.
1548 * Note that support for time zone is here for
1549 * SQL92 TIME WITH TIME ZONE, but it reveals
1550 * bogosity with SQL92 date/time standards, since
1551 * we must infer a time zone from current time.
1552 * - thomas 2000-03-10
1553 * Allow specifying date to get a better time zone,
1554 * if time zones are allowed. - thomas 2001-12-26
1557 DecodeTimeOnly(char **field
, int *ftype
, int nf
,
1558 int *dtype
, struct pg_tm
* tm
, fsec_t
*fsec
, int *tzp
)
1563 int ptype
= 0; /* "prefix type" for ISO h04mm05s06 format */
1567 bool is2digits
= FALSE
;
1570 pg_tz
*namedTz
= NULL
;
1577 /* don't know daylight savings time status apriori */
1583 for (i
= 0; i
< nf
; i
++)
1590 * Time zone not allowed? Then should not accept dates or time
1591 * zones no matter what else!
1594 return DTERR_BAD_FORMAT
;
1596 /* Under limited circumstances, we will accept a date... */
1597 if (i
== 0 && nf
>= 2 &&
1598 (ftype
[nf
- 1] == DTK_DATE
|| ftype
[1] == DTK_TIME
))
1600 dterr
= DecodeDate(field
[i
], fmask
,
1601 &tmask
, &is2digits
, tm
);
1605 /* otherwise, this is a time and/or time zone */
1608 if (isdigit((unsigned char) *field
[i
]))
1613 * Starts with a digit but we already have a time
1614 * field? Then we are in trouble with time already...
1616 if ((fmask
& DTK_TIME_M
) == DTK_TIME_M
)
1617 return DTERR_BAD_FORMAT
;
1620 * Should not get here and fail. Sanity check only...
1622 if ((cp
= strchr(field
[i
], '-')) == NULL
)
1623 return DTERR_BAD_FORMAT
;
1625 /* Get the time zone from the end of the string */
1626 dterr
= DecodeTimezone(cp
, tzp
);
1632 * Then read the rest of the field as a concatenated
1635 dterr
= DecodeNumberField(strlen(field
[i
]), field
[i
],
1636 (fmask
| DTK_DATE_M
),
1647 namedTz
= pg_tzset(field
[i
]);
1651 * We should return an error code instead of
1652 * ereport'ing directly, but then there is no way
1653 * to report the bad time zone name.
1656 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
1657 errmsg("time zone \"%s\" not recognized",
1660 /* we'll apply the zone setting below */
1668 dterr
= DecodeTime(field
[i
], (fmask
| DTK_DATE_M
),
1669 INTERVAL_FULL_RANGE
,
1680 return DTERR_BAD_FORMAT
;
1682 dterr
= DecodeTimezone(field
[i
], &tz
);
1693 * Was this an "ISO time" with embedded field labels? An
1694 * example is "h04m05s06" - thomas 2001-02-04
1701 /* Only accept a date under limited circumstances */
1709 return DTERR_BAD_FORMAT
;
1715 val
= strtoi(field
[i
], &cp
, 10);
1716 if (errno
== ERANGE
)
1717 return DTERR_FIELD_OVERFLOW
;
1720 * only a few kinds are allowed to have an embedded
1731 return DTERR_BAD_FORMAT
;
1734 else if (*cp
!= '\0')
1735 return DTERR_BAD_FORMAT
;
1741 tmask
= DTK_M(YEAR
);
1747 * already have a month and hour? then assume
1750 if ((fmask
& DTK_M(MONTH
)) != 0 &&
1751 (fmask
& DTK_M(HOUR
)) != 0)
1754 tmask
= DTK_M(MINUTE
);
1759 tmask
= DTK_M(MONTH
);
1770 tmask
= DTK_M(HOUR
);
1775 tmask
= DTK_M(MINUTE
);
1780 tmask
= DTK_M(SECOND
);
1783 dterr
= ParseFractionalSecond(cp
, fsec
);
1786 tmask
= DTK_ALL_SECS_M
;
1792 dterr
= DecodeTimezone(field
[i
], tzp
);
1799 * previous field was a label for "julian date"?
1802 j2date(val
, &tm
->tm_year
, &tm
->tm_mon
, &tm
->tm_mday
);
1808 time
= strtod(cp
, &cp
);
1809 if (*cp
!= '\0' || errno
!= 0)
1810 return DTERR_BAD_FORMAT
;
1812 #ifdef HAVE_INT64_TIMESTAMP
1813 time
*= USECS_PER_DAY
;
1815 time
*= SECS_PER_DAY
;
1818 &tm
->tm_hour
, &tm
->tm_min
,
1820 tmask
|= DTK_TIME_M
;
1825 /* previous field was "t" for ISO time */
1826 dterr
= DecodeNumberField(strlen(field
[i
]), field
[i
],
1827 (fmask
| DTK_DATE_M
),
1834 if (tmask
!= DTK_TIME_M
)
1835 return DTERR_BAD_FORMAT
;
1839 return DTERR_BAD_FORMAT
;
1851 flen
= strlen(field
[i
]);
1852 cp
= strchr(field
[i
], '.');
1854 /* Embedded decimal? */
1858 * Under limited circumstances, we will accept a
1861 if (i
== 0 && nf
>= 2 && ftype
[nf
- 1] == DTK_DATE
)
1863 dterr
= DecodeDate(field
[i
], fmask
,
1864 &tmask
, &is2digits
, tm
);
1868 /* embedded decimal and several digits before? */
1869 else if (flen
- strlen(cp
) > 2)
1872 * Interpret as a concatenated date or time Set
1873 * the type field to allow decoding other fields
1874 * later. Example: 20011223 or 040506
1876 dterr
= DecodeNumberField(flen
, field
[i
],
1877 (fmask
| DTK_DATE_M
),
1885 return DTERR_BAD_FORMAT
;
1889 dterr
= DecodeNumberField(flen
, field
[i
],
1890 (fmask
| DTK_DATE_M
),
1897 /* otherwise it is a single date/time field... */
1900 dterr
= DecodeNumber(flen
, field
[i
],
1902 (fmask
| DTK_DATE_M
),
1913 type
= DecodeSpecial(i
, field
[i
], &val
);
1914 if (type
== IGNORE_DTF
)
1917 tmask
= DTK_M(type
);
1925 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1926 errmsg("date/time value \"current\" is no longer supported")));
1927 return DTERR_BAD_FORMAT
;
1933 GetCurrentTimeUsec(tm
, fsec
, NULL
);
1937 tmask
= (DTK_TIME_M
| DTK_M(TZ
));
1946 return DTERR_BAD_FORMAT
;
1954 * daylight savings time modifier (solves "MET DST"
1957 tmask
|= DTK_M(DTZ
);
1960 return DTERR_BAD_FORMAT
;
1961 *tzp
+= val
* MINS_PER_HOUR
;
1967 * set mask for TZ here _or_ check for DTZ later when
1968 * getting default timezone
1973 return DTERR_BAD_FORMAT
;
1974 *tzp
= val
* MINS_PER_HOUR
;
1981 return DTERR_BAD_FORMAT
;
1982 *tzp
= val
* MINS_PER_HOUR
;
2006 * We will need one of the following fields:
2007 * DTK_NUMBER should be hhmmss.fff
2008 * DTK_TIME should be hh:mm:ss.fff
2009 * DTK_DATE should be hhmmss-zz
2012 (ftype
[i
+ 1] != DTK_NUMBER
&&
2013 ftype
[i
+ 1] != DTK_TIME
&&
2014 ftype
[i
+ 1] != DTK_DATE
))
2015 return DTERR_BAD_FORMAT
;
2023 * Before giving up and declaring error, check to see
2024 * if it is an all-alpha timezone name.
2026 namedTz
= pg_tzset(field
[i
]);
2028 return DTERR_BAD_FORMAT
;
2029 /* we'll apply the zone setting below */
2034 return DTERR_BAD_FORMAT
;
2039 return DTERR_BAD_FORMAT
;
2043 return DTERR_BAD_FORMAT
;
2045 } /* end loop over fields */
2047 /* do final checking/adjustment of Y/M/D fields */
2048 dterr
= ValidateDate(fmask
, is2digits
, bc
, tm
);
2053 if (mer
!= HR24
&& tm
->tm_hour
> 12)
2054 return DTERR_FIELD_OVERFLOW
;
2055 if (mer
== AM
&& tm
->tm_hour
== 12)
2057 else if (mer
== PM
&& tm
->tm_hour
!= 12)
2060 if (tm
->tm_hour
< 0 || tm
->tm_min
< 0 || tm
->tm_min
> 59 ||
2061 tm
->tm_sec
< 0 || tm
->tm_sec
> 60 || tm
->tm_hour
> 24 ||
2062 /* test for > 24:00:00 */
2063 (tm
->tm_hour
== 24 &&
2064 (tm
->tm_min
> 0 || tm
->tm_sec
> 0 || *fsec
> 0)) ||
2065 #ifdef HAVE_INT64_TIMESTAMP
2066 *fsec
< INT64CONST(0) || *fsec
> USECS_PER_SEC
2068 *fsec
< 0 || *fsec
> 1
2071 return DTERR_FIELD_OVERFLOW
;
2073 if ((fmask
& DTK_TIME_M
) != DTK_TIME_M
)
2074 return DTERR_BAD_FORMAT
;
2077 * If we had a full timezone spec, compute the offset (we could not do it
2078 * before, because we may need the date to resolve DST status).
2080 if (namedTz
!= NULL
)
2084 /* daylight savings time modifier disallowed with full TZ */
2085 if (fmask
& DTK_M(DTZMOD
))
2086 return DTERR_BAD_FORMAT
;
2088 /* if non-DST zone, we do not need to know the date */
2089 if (pg_get_timezone_offset(namedTz
, &gmtoff
))
2091 *tzp
= -(int) gmtoff
;
2095 /* a date has to be specified */
2096 if ((fmask
& DTK_DATE_M
) != DTK_DATE_M
)
2097 return DTERR_BAD_FORMAT
;
2098 *tzp
= DetermineTimeZoneOffset(tm
, namedTz
);
2102 /* timezone not specified? then find local timezone if possible */
2103 if (tzp
!= NULL
&& !(fmask
& DTK_M(TZ
)))
2109 * daylight savings time modifier but no standard timezone? then error
2111 if (fmask
& DTK_M(DTZMOD
))
2112 return DTERR_BAD_FORMAT
;
2114 if ((fmask
& DTK_DATE_M
) == 0)
2115 GetCurrentDateTime(tmp
);
2118 tmp
->tm_year
= tm
->tm_year
;
2119 tmp
->tm_mon
= tm
->tm_mon
;
2120 tmp
->tm_mday
= tm
->tm_mday
;
2122 tmp
->tm_hour
= tm
->tm_hour
;
2123 tmp
->tm_min
= tm
->tm_min
;
2124 tmp
->tm_sec
= tm
->tm_sec
;
2125 *tzp
= DetermineTimeZoneOffset(tmp
, session_timezone
);
2126 tm
->tm_isdst
= tmp
->tm_isdst
;
2133 * Decode date string which includes delimiters.
2134 * Return 0 if okay, a DTERR code if not.
2136 * str: field to be parsed
2137 * fmask: bitmask for field types already seen
2138 * *tmask: receives bitmask for fields found here
2139 * *is2digits: set to TRUE if we find 2-digit year
2140 * *tm: field values are stored into appropriate members of this struct
2143 DecodeDate(char *str
, int fmask
, int *tmask
, bool *is2digits
,
2151 bool haveTextMonth
= FALSE
;
2155 char *field
[MAXDATEFIELDS
];
2159 /* parse this string... */
2160 while (*str
!= '\0' && nf
< MAXDATEFIELDS
)
2162 /* skip field separators */
2163 while (!isalnum((unsigned char) *str
))
2167 if (isdigit((unsigned char) *str
))
2169 while (isdigit((unsigned char) *str
))
2172 else if (isalpha((unsigned char) *str
))
2174 while (isalpha((unsigned char) *str
))
2178 /* Just get rid of any non-digit, non-alpha characters... */
2184 /* look first for text fields, since that will be unambiguous month */
2185 for (i
= 0; i
< nf
; i
++)
2187 if (isalpha((unsigned char) *field
[i
]))
2189 type
= DecodeSpecial(i
, field
[i
], &val
);
2190 if (type
== IGNORE_DTF
)
2193 dmask
= DTK_M(type
);
2198 haveTextMonth
= TRUE
;
2202 return DTERR_BAD_FORMAT
;
2205 return DTERR_BAD_FORMAT
;
2210 /* mark this field as being completed */
2215 /* now pick up remaining numeric fields */
2216 for (i
= 0; i
< nf
; i
++)
2218 if (field
[i
] == NULL
)
2221 if ((len
= strlen(field
[i
])) <= 0)
2222 return DTERR_BAD_FORMAT
;
2224 dterr
= DecodeNumber(len
, field
[i
], haveTextMonth
, fmask
,
2231 return DTERR_BAD_FORMAT
;
2237 if ((fmask
& ~(DTK_M(DOY
) | DTK_M(TZ
))) != DTK_DATE_M
)
2238 return DTERR_BAD_FORMAT
;
2240 /* validation of the field values must wait until ValidateDate() */
2246 * Check valid year/month/day values, handle BC and DOY cases
2247 * Return 0 if okay, a DTERR code if not.
2250 ValidateDate(int fmask
, bool is2digits
, bool bc
, struct pg_tm
* tm
)
2252 if (fmask
& DTK_M(YEAR
))
2256 /* there is no year zero in AD/BC notation */
2257 if (tm
->tm_year
<= 0)
2258 return DTERR_FIELD_OVERFLOW
;
2259 /* internally, we represent 1 BC as year zero, 2 BC as -1, etc */
2260 tm
->tm_year
= -(tm
->tm_year
- 1);
2264 /* process 1 or 2-digit input as 1970-2069 AD, allow '0' and '00' */
2265 if (tm
->tm_year
< 0) /* just paranoia */
2266 return DTERR_FIELD_OVERFLOW
;
2267 if (tm
->tm_year
< 70)
2268 tm
->tm_year
+= 2000;
2269 else if (tm
->tm_year
< 100)
2270 tm
->tm_year
+= 1900;
2274 /* there is no year zero in AD/BC notation */
2275 if (tm
->tm_year
<= 0)
2276 return DTERR_FIELD_OVERFLOW
;
2280 /* now that we have correct year, decode DOY */
2281 if (fmask
& DTK_M(DOY
))
2283 j2date(date2j(tm
->tm_year
, 1, 1) + tm
->tm_yday
- 1,
2284 &tm
->tm_year
, &tm
->tm_mon
, &tm
->tm_mday
);
2287 /* check for valid month */
2288 if (fmask
& DTK_M(MONTH
))
2290 if (tm
->tm_mon
< 1 || tm
->tm_mon
> MONTHS_PER_YEAR
)
2291 return DTERR_MD_FIELD_OVERFLOW
;
2294 /* minimal check for valid day */
2295 if (fmask
& DTK_M(DAY
))
2297 if (tm
->tm_mday
< 1 || tm
->tm_mday
> 31)
2298 return DTERR_MD_FIELD_OVERFLOW
;
2301 if ((fmask
& DTK_DATE_M
) == DTK_DATE_M
)
2304 * Check for valid day of month, now that we know for sure the month
2305 * and year. Note we don't use MD_FIELD_OVERFLOW here, since it seems
2306 * unlikely that "Feb 29" is a YMD-order error.
2308 if (tm
->tm_mday
> day_tab
[isleap(tm
->tm_year
)][tm
->tm_mon
- 1])
2309 return DTERR_FIELD_OVERFLOW
;
2317 * Decode time string which includes delimiters.
2318 * Return 0 if okay, a DTERR code if not.
2320 * Only check the lower limit on hours, since this same code can be
2321 * used to represent time spans.
2324 DecodeTime(char *str
, int fmask
, int range
,
2325 int *tmask
, struct pg_tm
* tm
, fsec_t
*fsec
)
2330 *tmask
= DTK_TIME_M
;
2333 tm
->tm_hour
= strtoi(str
, &cp
, 10);
2334 if (errno
== ERANGE
)
2335 return DTERR_FIELD_OVERFLOW
;
2337 return DTERR_BAD_FORMAT
;
2339 tm
->tm_min
= strtoi(cp
+ 1, &cp
, 10);
2340 if (errno
== ERANGE
)
2341 return DTERR_FIELD_OVERFLOW
;
2346 /* If it's a MINUTE TO SECOND interval, take 2 fields as being mm:ss */
2347 if (range
== (INTERVAL_MASK(MINUTE
) | INTERVAL_MASK(SECOND
)))
2349 tm
->tm_sec
= tm
->tm_min
;
2350 tm
->tm_min
= tm
->tm_hour
;
2354 else if (*cp
== '.')
2356 /* always assume mm:ss.sss is MINUTE TO SECOND */
2357 dterr
= ParseFractionalSecond(cp
, fsec
);
2360 tm
->tm_sec
= tm
->tm_min
;
2361 tm
->tm_min
= tm
->tm_hour
;
2364 else if (*cp
== ':')
2367 tm
->tm_sec
= strtoi(cp
+ 1, &cp
, 10);
2368 if (errno
== ERANGE
)
2369 return DTERR_FIELD_OVERFLOW
;
2372 else if (*cp
== '.')
2374 dterr
= ParseFractionalSecond(cp
, fsec
);
2379 return DTERR_BAD_FORMAT
;
2382 return DTERR_BAD_FORMAT
;
2384 /* do a sanity check */
2385 #ifdef HAVE_INT64_TIMESTAMP
2386 if (tm
->tm_hour
< 0 || tm
->tm_min
< 0 || tm
->tm_min
> 59 ||
2387 tm
->tm_sec
< 0 || tm
->tm_sec
> 60 || *fsec
< INT64CONST(0) ||
2388 *fsec
> USECS_PER_SEC
)
2389 return DTERR_FIELD_OVERFLOW
;
2391 if (tm
->tm_hour
< 0 || tm
->tm_min
< 0 || tm
->tm_min
> 59 ||
2392 tm
->tm_sec
< 0 || tm
->tm_sec
> 60 || *fsec
< 0 || *fsec
> 1)
2393 return DTERR_FIELD_OVERFLOW
;
2401 * Interpret plain numeric field as a date value in context.
2402 * Return 0 if okay, a DTERR code if not.
2405 DecodeNumber(int flen
, char *str
, bool haveTextMonth
, int fmask
,
2406 int *tmask
, struct pg_tm
* tm
, fsec_t
*fsec
, bool *is2digits
)
2415 val
= strtoi(str
, &cp
, 10);
2416 if (errno
== ERANGE
)
2417 return DTERR_FIELD_OVERFLOW
;
2419 return DTERR_BAD_FORMAT
;
2424 * More than two digits before decimal point? Then could be a date or
2425 * a run-together time: 2001.360 20011225 040506.789
2429 dterr
= DecodeNumberField(flen
, str
,
2430 (fmask
| DTK_DATE_M
),
2438 dterr
= ParseFractionalSecond(cp
, fsec
);
2442 else if (*cp
!= '\0')
2443 return DTERR_BAD_FORMAT
;
2445 /* Special case for day of year */
2446 if (flen
== 3 && (fmask
& DTK_DATE_M
) == DTK_M(YEAR
) && val
>= 1 &&
2449 *tmask
= (DTK_M(DOY
) | DTK_M(MONTH
) | DTK_M(DAY
));
2451 /* tm_mon and tm_mday can't actually be set yet ... */
2455 /* Switch based on what we have so far */
2456 switch (fmask
& DTK_DATE_M
)
2461 * Nothing so far; make a decision about what we think the input
2462 * is. There used to be lots of heuristics here, but the
2463 * consensus now is to be paranoid. It *must* be either
2464 * YYYY-MM-DD (with a more-than-two-digit year field), or the
2465 * field order defined by DateOrder.
2467 if (flen
>= 3 || DateOrder
== DATEORDER_YMD
)
2469 *tmask
= DTK_M(YEAR
);
2472 else if (DateOrder
== DATEORDER_DMY
)
2474 *tmask
= DTK_M(DAY
);
2479 *tmask
= DTK_M(MONTH
);
2485 /* Must be at second field of YY-MM-DD */
2486 *tmask
= DTK_M(MONTH
);
2490 case (DTK_M(MONTH
)):
2494 * We are at the first numeric field of a date that included a
2495 * textual month name. We want to support the variants
2496 * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2497 * inputs. We will also accept MON-DD-YY or DD-MON-YY in
2498 * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2500 if (flen
>= 3 || DateOrder
== DATEORDER_YMD
)
2502 *tmask
= DTK_M(YEAR
);
2507 *tmask
= DTK_M(DAY
);
2513 /* Must be at second field of MM-DD-YY */
2514 *tmask
= DTK_M(DAY
);
2519 case (DTK_M(YEAR
) | DTK_M(MONTH
)):
2522 /* Need to accept DD-MON-YYYY even in YMD mode */
2523 if (flen
>= 3 && *is2digits
)
2525 /* Guess that first numeric field is day was wrong */
2526 *tmask
= DTK_M(DAY
); /* YEAR is already set */
2527 tm
->tm_mday
= tm
->tm_year
;
2533 *tmask
= DTK_M(DAY
);
2539 /* Must be at third field of YY-MM-DD */
2540 *tmask
= DTK_M(DAY
);
2546 /* Must be at second field of DD-MM-YY */
2547 *tmask
= DTK_M(MONTH
);
2551 case (DTK_M(MONTH
) | DTK_M(DAY
)):
2552 /* Must be at third field of DD-MM-YY or MM-DD-YY */
2553 *tmask
= DTK_M(YEAR
);
2557 case (DTK_M(YEAR
) | DTK_M(MONTH
) | DTK_M(DAY
)):
2558 /* we have all the date, so it must be a time field */
2559 dterr
= DecodeNumberField(flen
, str
, fmask
,
2567 /* Anything else is bogus input */
2568 return DTERR_BAD_FORMAT
;
2572 * When processing a year field, mark it for adjustment if it's only one
2575 if (*tmask
== DTK_M(YEAR
))
2576 *is2digits
= (flen
<= 2);
2582 /* DecodeNumberField()
2583 * Interpret numeric string as a concatenated date or time field.
2584 * Return a DTK token (>= 0) if successful, a DTERR code (< 0) if not.
2586 * Use the context of previously decoded fields to help with
2587 * the interpretation.
2590 DecodeNumberField(int len
, char *str
, int fmask
,
2591 int *tmask
, struct pg_tm
* tm
, fsec_t
*fsec
, bool *is2digits
)
2596 * Have a decimal point? Then this is a date or something with a seconds
2599 if ((cp
= strchr(str
, '.')) != NULL
)
2602 * Can we use ParseFractionalSecond here? Not clear whether trailing
2603 * junk should be rejected ...
2608 frac
= strtod(cp
, NULL
);
2610 return DTERR_BAD_FORMAT
;
2611 #ifdef HAVE_INT64_TIMESTAMP
2612 *fsec
= rint(frac
* 1000000);
2616 /* Now truncate off the fraction for further processing */
2620 /* No decimal point and no complete date yet? */
2621 else if ((fmask
& DTK_DATE_M
) != DTK_DATE_M
)
2626 *tmask
= DTK_DATE_M
;
2628 tm
->tm_mday
= atoi(str
+ 6);
2630 tm
->tm_mon
= atoi(str
+ 4);
2632 tm
->tm_year
= atoi(str
+ 0);
2639 *tmask
= DTK_DATE_M
;
2640 tm
->tm_mday
= atoi(str
+ 4);
2642 tm
->tm_mon
= atoi(str
+ 2);
2644 tm
->tm_year
= atoi(str
+ 0);
2651 /* not all time fields are specified? */
2652 if ((fmask
& DTK_TIME_M
) != DTK_TIME_M
)
2657 *tmask
= DTK_TIME_M
;
2658 tm
->tm_sec
= atoi(str
+ 4);
2660 tm
->tm_min
= atoi(str
+ 2);
2662 tm
->tm_hour
= atoi(str
+ 0);
2669 *tmask
= DTK_TIME_M
;
2671 tm
->tm_min
= atoi(str
+ 2);
2673 tm
->tm_hour
= atoi(str
+ 0);
2679 return DTERR_BAD_FORMAT
;
2684 * Interpret string as a numeric timezone.
2686 * Return 0 if okay (and set *tzp), a DTERR code if not okay.
2688 * NB: this must *not* ereport on failure; see commands/variable.c.
2690 * Note: we allow timezone offsets up to 13:59. There are places that
2691 * use +1300 summer time.
2694 DecodeTimezone(char *str
, int *tzp
)
2702 /* leading character must be "+" or "-" */
2703 if (*str
!= '+' && *str
!= '-')
2704 return DTERR_BAD_FORMAT
;
2707 hr
= strtoi(str
+ 1, &cp
, 10);
2708 if (errno
== ERANGE
)
2709 return DTERR_TZDISP_OVERFLOW
;
2711 /* explicit delimiter? */
2715 min
= strtoi(cp
+ 1, &cp
, 10);
2716 if (errno
== ERANGE
)
2717 return DTERR_TZDISP_OVERFLOW
;
2721 sec
= strtoi(cp
+ 1, &cp
, 10);
2722 if (errno
== ERANGE
)
2723 return DTERR_TZDISP_OVERFLOW
;
2726 /* otherwise, might have run things together... */
2727 else if (*cp
== '\0' && strlen(str
) > 3)
2731 /* we could, but don't, support a run-together hhmmss format */
2736 if (hr
< 0 || hr
> 14)
2737 return DTERR_TZDISP_OVERFLOW
;
2738 if (min
< 0 || min
>= 60)
2739 return DTERR_TZDISP_OVERFLOW
;
2740 if (sec
< 0 || sec
>= 60)
2741 return DTERR_TZDISP_OVERFLOW
;
2743 tz
= (hr
* MINS_PER_HOUR
+ min
) * SECS_PER_MINUTE
+ sec
;
2750 return DTERR_BAD_FORMAT
;
2756 * Decode text string using lookup table.
2758 * Implement a cache lookup since it is likely that dates
2759 * will be related in format.
2761 * NB: this must *not* ereport on failure;
2762 * see commands/variable.c.
2765 DecodeSpecial(int field
, char *lowtoken
, int *val
)
2770 tp
= datecache
[field
];
2771 if (tp
== NULL
|| strncmp(lowtoken
, tp
->token
, TOKMAXLEN
) != 0)
2773 tp
= datebsearch(lowtoken
, timezonetktbl
, sztimezonetktbl
);
2775 tp
= datebsearch(lowtoken
, datetktbl
, szdatetktbl
);
2779 type
= UNKNOWN_FIELD
;
2784 datecache
[field
] = tp
;
2806 * Zero out a pg_tm and associated fsec_t
2809 ClearPgTm(struct pg_tm
* tm
, fsec_t
*fsec
)
2822 * Interpret previously parsed fields for general time interval.
2823 * Returns 0 if successful, DTERR code if bogus input detected.
2824 * dtype, tm, fsec are output parameters.
2826 * Allow "date" field DTK_DATE since this could be just
2827 * an unsigned floating point number. - thomas 1997-11-16
2829 * Allow ISO-style time span, with implicit units on number of days
2830 * preceding an hh:mm:ss field. - thomas 1998-04-30
2833 DecodeInterval(char **field
, int *ftype
, int nf
, int range
,
2834 int *dtype
, struct pg_tm
* tm
, fsec_t
*fsec
)
2836 bool is_before
= FALSE
;
2848 ClearPgTm(tm
, fsec
);
2850 /* read through list backwards to pick up units before values */
2851 for (i
= nf
- 1; i
>= 0; i
--)
2856 dterr
= DecodeTime(field
[i
], fmask
, range
,
2866 * Timezone is a token with a leading sign character and at
2867 * least one digit; there could be ':', '.', '-' embedded in
2870 Assert(*field
[i
] == '-' || *field
[i
] == '+');
2873 * Try for hh:mm or hh:mm:ss. If not, fall through to
2874 * DTK_NUMBER case, which can handle signed float numbers and
2875 * signed year-month values.
2877 if (strchr(field
[i
] + 1, ':') != NULL
&&
2878 DecodeTime(field
[i
] + 1, fmask
, INTERVAL_FULL_RANGE
,
2879 &tmask
, tm
, fsec
) == 0)
2881 if (*field
[i
] == '-')
2883 /* flip the sign on all fields */
2884 tm
->tm_hour
= -tm
->tm_hour
;
2885 tm
->tm_min
= -tm
->tm_min
;
2886 tm
->tm_sec
= -tm
->tm_sec
;
2891 * Set the next type to be a day, if units are not
2892 * specified. This handles the case of '1 +02:03' since we
2893 * are reading right to left.
2903 if (type
== IGNORE_DTF
)
2905 /* use typmod to decide what rightmost field is */
2908 case INTERVAL_MASK(YEAR
):
2911 case INTERVAL_MASK(MONTH
):
2912 case INTERVAL_MASK(YEAR
) | INTERVAL_MASK(MONTH
):
2915 case INTERVAL_MASK(DAY
):
2918 case INTERVAL_MASK(HOUR
):
2919 case INTERVAL_MASK(DAY
) | INTERVAL_MASK(HOUR
):
2922 case INTERVAL_MASK(MINUTE
):
2923 case INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
):
2924 case INTERVAL_MASK(DAY
) | INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
):
2927 case INTERVAL_MASK(SECOND
):
2928 case INTERVAL_MASK(MINUTE
) | INTERVAL_MASK(SECOND
):
2929 case INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
) | INTERVAL_MASK(SECOND
):
2930 case INTERVAL_MASK(DAY
) | INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
) | INTERVAL_MASK(SECOND
):
2940 val
= strtoi(field
[i
], &cp
, 10);
2941 if (errno
== ERANGE
)
2942 return DTERR_FIELD_OVERFLOW
;
2946 /* SQL "years-months" syntax */
2949 val2
= strtoi(cp
+ 1, &cp
, 10);
2950 if (errno
== ERANGE
|| val2
< 0 || val2
>= MONTHS_PER_YEAR
)
2951 return DTERR_FIELD_OVERFLOW
;
2953 return DTERR_BAD_FORMAT
;
2955 if (*field
[i
] == '-')
2957 val
= val
* MONTHS_PER_YEAR
+ val2
;
2960 else if (*cp
== '.')
2963 fval
= strtod(cp
, &cp
);
2964 if (*cp
!= '\0' || errno
!= 0)
2965 return DTERR_BAD_FORMAT
;
2967 if (*field
[i
] == '-')
2970 else if (*cp
== '\0')
2973 return DTERR_BAD_FORMAT
;
2975 tmask
= 0; /* DTK_M(type); */
2980 #ifdef HAVE_INT64_TIMESTAMP
2981 *fsec
+= rint(val
+ fval
);
2983 *fsec
+= (val
+ fval
) * 1e-6;
2985 tmask
= DTK_M(MICROSECOND
);
2989 #ifdef HAVE_INT64_TIMESTAMP
2990 *fsec
+= rint((val
+ fval
) * 1000);
2992 *fsec
+= (val
+ fval
) * 1e-3;
2994 tmask
= DTK_M(MILLISECOND
);
2999 #ifdef HAVE_INT64_TIMESTAMP
3000 *fsec
+= rint(fval
* 1000000);
3006 * If any subseconds were specified, consider this
3007 * microsecond and millisecond input as well.
3010 tmask
= DTK_M(SECOND
);
3012 tmask
= DTK_ALL_SECS_M
;
3017 AdjustFractSeconds(fval
, tm
, fsec
, SECS_PER_MINUTE
);
3018 tmask
= DTK_M(MINUTE
);
3023 AdjustFractSeconds(fval
, tm
, fsec
, SECS_PER_HOUR
);
3024 tmask
= DTK_M(HOUR
);
3025 type
= DTK_DAY
; /* set for next field */
3030 AdjustFractSeconds(fval
, tm
, fsec
, SECS_PER_DAY
);
3035 tm
->tm_mday
+= val
* 7;
3036 AdjustFractDays(fval
, tm
, fsec
, 7);
3037 tmask
= DTK_M(WEEK
);
3042 AdjustFractDays(fval
, tm
, fsec
, DAYS_PER_MONTH
);
3043 tmask
= DTK_M(MONTH
);
3049 tm
->tm_mon
+= fval
* MONTHS_PER_YEAR
;
3050 tmask
= DTK_M(YEAR
);
3054 tm
->tm_year
+= val
* 10;
3056 tm
->tm_mon
+= fval
* MONTHS_PER_YEAR
* 10;
3057 tmask
= DTK_M(DECADE
);
3061 tm
->tm_year
+= val
* 100;
3063 tm
->tm_mon
+= fval
* MONTHS_PER_YEAR
* 100;
3064 tmask
= DTK_M(CENTURY
);
3067 case DTK_MILLENNIUM
:
3068 tm
->tm_year
+= val
* 1000;
3070 tm
->tm_mon
+= fval
* MONTHS_PER_YEAR
* 1000;
3071 tmask
= DTK_M(MILLENNIUM
);
3075 return DTERR_BAD_FORMAT
;
3081 type
= DecodeUnits(i
, field
[i
], &val
);
3082 if (type
== IGNORE_DTF
)
3085 tmask
= 0; /* DTK_M(type); */
3098 tmask
= (DTK_DATE_M
|| DTK_TIME_M
);
3103 return DTERR_BAD_FORMAT
;
3108 return DTERR_BAD_FORMAT
;
3112 return DTERR_BAD_FORMAT
;
3116 /* ensure that at least one time field has been found */
3118 return DTERR_BAD_FORMAT
;
3120 /* ensure fractional seconds are fractional */
3125 #ifdef HAVE_INT64_TIMESTAMP
3126 sec
= *fsec
/ USECS_PER_SEC
;
3127 *fsec
-= sec
* USECS_PER_SEC
;
3129 TMODULO(*fsec
, sec
, 1.0);
3135 * The SQL standard defines the interval literal
3137 * to mean "negative 1 days and negative 1 hours", while Postgres
3138 * traditionally treats this as meaning "negative 1 days and positive
3139 * 1 hours". In SQL_STANDARD intervalstyle, we apply the leading sign
3140 * to all fields if there are no other explicit signs.
3142 * We leave the signs alone if there are additional explicit signs.
3143 * This protects us against misinterpreting postgres-style dump output,
3144 * since the postgres-style output code has always put an explicit sign on
3145 * all fields following a negative field. But note that SQL-spec output
3146 * is ambiguous and can be misinterpreted on load! (So it's best practice
3147 * to dump in postgres style, not SQL style.)
3150 if (IntervalStyle
== INTSTYLE_SQL_STANDARD
&& *field
[0] == '-')
3152 /* Check for additional explicit signs */
3153 bool more_signs
= false;
3155 for (i
= 1; i
< nf
; i
++)
3157 if (*field
[i
] == '-' || *field
[i
] == '+')
3167 * Rather than re-determining which field was field[0], just force
3173 tm
->tm_sec
= -tm
->tm_sec
;
3175 tm
->tm_min
= -tm
->tm_min
;
3176 if (tm
->tm_hour
> 0)
3177 tm
->tm_hour
= -tm
->tm_hour
;
3178 if (tm
->tm_mday
> 0)
3179 tm
->tm_mday
= -tm
->tm_mday
;
3181 tm
->tm_mon
= -tm
->tm_mon
;
3182 if (tm
->tm_year
> 0)
3183 tm
->tm_year
= -tm
->tm_year
;
3187 /* finally, AGO negates everything */
3191 tm
->tm_sec
= -tm
->tm_sec
;
3192 tm
->tm_min
= -tm
->tm_min
;
3193 tm
->tm_hour
= -tm
->tm_hour
;
3194 tm
->tm_mday
= -tm
->tm_mday
;
3195 tm
->tm_mon
= -tm
->tm_mon
;
3196 tm
->tm_year
= -tm
->tm_year
;
3204 * Helper functions to avoid duplicated code in DecodeISO8601Interval.
3206 * Parse a decimal value and break it into integer and fractional parts.
3207 * Returns 0 or DTERR code.
3210 ParseISO8601Number(char *str
, char **endptr
, int *ipart
, double *fpart
)
3214 if (!(isdigit((unsigned char) *str
) || *str
== '-' || *str
== '.'))
3215 return DTERR_BAD_FORMAT
;
3217 val
= strtod(str
, endptr
);
3218 /* did we not see anything that looks like a double? */
3219 if (*endptr
== str
|| errno
!= 0)
3220 return DTERR_BAD_FORMAT
;
3221 /* watch out for overflow */
3222 if (val
< INT_MIN
|| val
> INT_MAX
)
3223 return DTERR_FIELD_OVERFLOW
;
3224 /* be very sure we truncate towards zero (cf dtrunc()) */
3226 *ipart
= (int) floor(val
);
3228 *ipart
= (int) -floor(-val
);
3229 *fpart
= val
- *ipart
;
3234 * Determine number of integral digits in a valid ISO 8601 number field
3235 * (we should ignore sign and any fraction part)
3238 ISO8601IntegerWidth(char *fieldstart
)
3240 /* We might have had a leading '-' */
3241 if (*fieldstart
== '-')
3243 return strspn(fieldstart
, "0123456789");
3247 /* DecodeISO8601Interval()
3248 * Decode an ISO 8601 time interval of the "format with designators"
3249 * (section 4.4.3.2) or "alternative format" (section 4.4.3.3)
3250 * Examples: P1D for 1 day
3252 * P2Y6M7DT1H30M for 2 years, 6 months, 7 days 1 hour 30 min
3253 * P0002-06-07T01:30:00 the same value in alternative format
3255 * Returns 0 if successful, DTERR code if bogus input detected.
3256 * Note: error code should be DTERR_BAD_FORMAT if input doesn't look like
3257 * ISO8601, otherwise this could cause unexpected error messages.
3258 * dtype, tm, fsec are output parameters.
3260 * A couple exceptions from the spec:
3261 * - a week field ('W') may coexist with other units
3262 * - allows decimals in fields other than the least significant unit.
3265 DecodeISO8601Interval(char *str
,
3266 int *dtype
, struct pg_tm
* tm
, fsec_t
*fsec
)
3268 bool datepart
= true;
3269 bool havefield
= false;
3272 ClearPgTm(tm
, fsec
);
3274 if (strlen(str
) < 2 || str
[0] != 'P')
3275 return DTERR_BAD_FORMAT
;
3286 if (*str
== 'T') /* T indicates the beginning of the time part */
3295 dterr
= ParseISO8601Number(str
, &str
, &val
, &fval
);
3300 * Note: we could step off the end of the string here. Code below
3301 * *must* exit the loop if unit == '\0'.
3307 switch (unit
) /* before T: Y M W D */
3311 tm
->tm_mon
+= (fval
* 12);
3315 AdjustFractDays(fval
, tm
, fsec
, DAYS_PER_MONTH
);
3318 tm
->tm_mday
+= val
* 7;
3319 AdjustFractDays(fval
, tm
, fsec
, 7);
3323 AdjustFractSeconds(fval
, tm
, fsec
, SECS_PER_DAY
);
3325 case 'T': /* ISO 8601 4.4.3.3 Alternative Format / Basic */
3327 if (ISO8601IntegerWidth(fieldstart
) == 8 && !havefield
)
3329 tm
->tm_year
+= val
/ 10000;
3330 tm
->tm_mon
+= (val
/ 100) % 100;
3331 tm
->tm_mday
+= val
% 100;
3332 AdjustFractSeconds(fval
, tm
, fsec
, SECS_PER_DAY
);
3339 /* Else fall through to extended alternative format */
3340 case '-': /* ISO 8601 4.4.3.3 Alternative Format,
3343 return DTERR_BAD_FORMAT
;
3346 tm
->tm_mon
+= (fval
* 12);
3356 dterr
= ParseISO8601Number(str
, &str
, &val
, &fval
);
3360 AdjustFractDays(fval
, tm
, fsec
, DAYS_PER_MONTH
);
3370 return DTERR_BAD_FORMAT
;
3373 dterr
= ParseISO8601Number(str
, &str
, &val
, &fval
);
3377 AdjustFractSeconds(fval
, tm
, fsec
, SECS_PER_DAY
);
3386 return DTERR_BAD_FORMAT
;
3388 /* not a valid date unit suffix */
3389 return DTERR_BAD_FORMAT
;
3394 switch (unit
) /* after T: H M S */
3398 AdjustFractSeconds(fval
, tm
, fsec
, SECS_PER_HOUR
);
3402 AdjustFractSeconds(fval
, tm
, fsec
, SECS_PER_MINUTE
);
3406 AdjustFractSeconds(fval
, tm
, fsec
, 1);
3408 case '\0': /* ISO 8601 4.4.3.3 Alternative Format */
3409 if (ISO8601IntegerWidth(fieldstart
) == 6 && !havefield
)
3411 tm
->tm_hour
+= val
/ 10000;
3412 tm
->tm_min
+= (val
/ 100) % 100;
3413 tm
->tm_sec
+= val
% 100;
3414 AdjustFractSeconds(fval
, tm
, fsec
, 1);
3417 /* Else fall through to extended alternative format */
3418 case ':': /* ISO 8601 4.4.3.3 Alternative Format,
3421 return DTERR_BAD_FORMAT
;
3424 AdjustFractSeconds(fval
, tm
, fsec
, SECS_PER_HOUR
);
3428 dterr
= ParseISO8601Number(str
, &str
, &val
, &fval
);
3432 AdjustFractSeconds(fval
, tm
, fsec
, SECS_PER_MINUTE
);
3436 return DTERR_BAD_FORMAT
;
3439 dterr
= ParseISO8601Number(str
, &str
, &val
, &fval
);
3443 AdjustFractSeconds(fval
, tm
, fsec
, 1);
3446 return DTERR_BAD_FORMAT
;
3449 /* not a valid time unit suffix */
3450 return DTERR_BAD_FORMAT
;
3462 * Decode text string using lookup table.
3463 * This routine supports time interval decoding
3464 * (hence, it need not recognize timezone names).
3467 DecodeUnits(int field
, char *lowtoken
, int *val
)
3472 tp
= deltacache
[field
];
3473 if (tp
== NULL
|| strncmp(lowtoken
, tp
->token
, TOKMAXLEN
) != 0)
3475 tp
= datebsearch(lowtoken
, deltatktbl
, szdeltatktbl
);
3479 type
= UNKNOWN_FIELD
;
3484 deltacache
[field
] = tp
;
3486 if (type
== TZ
|| type
== DTZ
)
3493 } /* DecodeUnits() */
3496 * Report an error detected by one of the datetime input processing routines.
3498 * dterr is the error code, str is the original input string, datatype is
3499 * the name of the datatype we were trying to accept.
3501 * Note: it might seem useless to distinguish DTERR_INTERVAL_OVERFLOW and
3502 * DTERR_TZDISP_OVERFLOW from DTERR_FIELD_OVERFLOW, but SQL99 mandates three
3503 * separate SQLSTATE codes, so ...
3506 DateTimeParseError(int dterr
, const char *str
, const char *datatype
)
3510 case DTERR_FIELD_OVERFLOW
:
3512 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW
),
3513 errmsg("date/time field value out of range: \"%s\"",
3516 case DTERR_MD_FIELD_OVERFLOW
:
3517 /* <nanny>same as above, but add hint about DateStyle</nanny> */
3519 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW
),
3520 errmsg("date/time field value out of range: \"%s\"",
3522 errhint("Perhaps you need a different \"datestyle\" setting.")));
3524 case DTERR_INTERVAL_OVERFLOW
:
3526 (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW
),
3527 errmsg("interval field value out of range: \"%s\"",
3530 case DTERR_TZDISP_OVERFLOW
:
3532 (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE
),
3533 errmsg("time zone displacement out of range: \"%s\"",
3536 case DTERR_BAD_FORMAT
:
3539 (errcode(ERRCODE_INVALID_DATETIME_FORMAT
),
3540 errmsg("invalid input syntax for type %s: \"%s\"",
3547 * Binary search -- from Knuth (6.2.1) Algorithm B. Special case like this
3548 * is WAY faster than the generic bsearch().
3550 static const datetkn
*
3551 datebsearch(const char *key
, const datetkn
*base
, int nel
)
3553 const datetkn
*last
= base
+ nel
- 1,
3557 while (last
>= base
)
3559 position
= base
+ ((last
- base
) >> 1);
3560 result
= key
[0] - position
->token
[0];
3563 result
= strncmp(key
, position
->token
, TOKMAXLEN
);
3568 last
= position
- 1;
3570 base
= position
+ 1;
3576 * Append representation of a numeric timezone offset to str.
3579 EncodeTimezone(char *str
, int tz
, int style
)
3586 min
= sec
/ SECS_PER_MINUTE
;
3587 sec
-= min
* SECS_PER_MINUTE
;
3588 hour
= min
/ MINS_PER_HOUR
;
3589 min
-= hour
* MINS_PER_HOUR
;
3592 /* TZ is negated compared to sign we wish to display ... */
3593 *str
++ = (tz
<= 0 ? '+' : '-');
3596 sprintf(str
, "%02d:%02d:%02d", hour
, min
, sec
);
3597 else if (min
!= 0 || style
== USE_XSD_DATES
)
3598 sprintf(str
, "%02d:%02d", hour
, min
);
3600 sprintf(str
, "%02d", hour
);
3604 * Encode date as local time.
3607 EncodeDateOnly(struct pg_tm
* tm
, int style
, char *str
)
3609 Assert(tm
->tm_mon
>= 1 && tm
->tm_mon
<= MONTHS_PER_YEAR
);
3615 /* compatible with ISO date formats */
3616 if (tm
->tm_year
> 0)
3617 sprintf(str
, "%04d-%02d-%02d",
3618 tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
);
3620 sprintf(str
, "%04d-%02d-%02d %s",
3621 -(tm
->tm_year
- 1), tm
->tm_mon
, tm
->tm_mday
, "BC");
3625 /* compatible with Oracle/Ingres date formats */
3626 if (DateOrder
== DATEORDER_DMY
)
3627 sprintf(str
, "%02d/%02d", tm
->tm_mday
, tm
->tm_mon
);
3629 sprintf(str
, "%02d/%02d", tm
->tm_mon
, tm
->tm_mday
);
3630 if (tm
->tm_year
> 0)
3631 sprintf(str
+ 5, "/%04d", tm
->tm_year
);
3633 sprintf(str
+ 5, "/%04d %s", -(tm
->tm_year
- 1), "BC");
3636 case USE_GERMAN_DATES
:
3637 /* German-style date format */
3638 sprintf(str
, "%02d.%02d", tm
->tm_mday
, tm
->tm_mon
);
3639 if (tm
->tm_year
> 0)
3640 sprintf(str
+ 5, ".%04d", tm
->tm_year
);
3642 sprintf(str
+ 5, ".%04d %s", -(tm
->tm_year
- 1), "BC");
3645 case USE_POSTGRES_DATES
:
3647 /* traditional date-only style for Postgres */
3648 if (DateOrder
== DATEORDER_DMY
)
3649 sprintf(str
, "%02d-%02d", tm
->tm_mday
, tm
->tm_mon
);
3651 sprintf(str
, "%02d-%02d", tm
->tm_mon
, tm
->tm_mday
);
3652 if (tm
->tm_year
> 0)
3653 sprintf(str
+ 5, "-%04d", tm
->tm_year
);
3655 sprintf(str
+ 5, "-%04d %s", -(tm
->tm_year
- 1), "BC");
3662 * Encode time fields only.
3665 EncodeTimeOnly(struct pg_tm
* tm
, fsec_t fsec
, int *tzp
, int style
, char *str
)
3667 sprintf(str
, "%02d:%02d:", tm
->tm_hour
, tm
->tm_min
);
3670 AppendSeconds(str
, tm
->tm_sec
, fsec
, MAX_TIME_PRECISION
, true);
3673 EncodeTimezone(str
, *tzp
, style
);
3678 * Encode date and time interpreted as local time.
3679 * Support several date styles:
3680 * Postgres - day mon hh:mm:ss yyyy tz
3681 * SQL - mm/dd/yyyy hh:mm:ss.ss tz
3682 * ISO - yyyy-mm-dd hh:mm:ss+/-tz
3683 * German - dd.mm.yyyy hh:mm:ss tz
3684 * XSD - yyyy-mm-ddThh:mm:ss.ss+/-tz
3685 * Variants (affects order of month and day for Postgres and SQL styles):
3687 * European - dd/mm/yyyy
3690 EncodeDateTime(struct pg_tm
* tm
, fsec_t fsec
, int *tzp
, char **tzn
, int style
, char *str
)
3694 Assert(tm
->tm_mon
>= 1 && tm
->tm_mon
<= MONTHS_PER_YEAR
);
3700 /* Compatible with ISO-8601 date formats */
3702 if (style
== USE_ISO_DATES
)
3703 sprintf(str
, "%04d-%02d-%02d %02d:%02d:",
3704 (tm
->tm_year
> 0) ? tm
->tm_year
: -(tm
->tm_year
- 1),
3705 tm
->tm_mon
, tm
->tm_mday
, tm
->tm_hour
, tm
->tm_min
);
3707 sprintf(str
, "%04d-%02d-%02dT%02d:%02d:",
3708 (tm
->tm_year
> 0) ? tm
->tm_year
: -(tm
->tm_year
- 1),
3709 tm
->tm_mon
, tm
->tm_mday
, tm
->tm_hour
, tm
->tm_min
);
3711 AppendTimestampSeconds(str
+ strlen(str
), tm
, fsec
);
3714 * tzp == NULL indicates that we don't want *any* time zone info
3715 * in the output string. *tzn != NULL indicates that we have alpha
3716 * time zone info available. tm_isdst != -1 indicates that we have
3717 * a valid time zone translation.
3719 if (tzp
!= NULL
&& tm
->tm_isdst
>= 0)
3720 EncodeTimezone(str
, *tzp
, style
);
3722 if (tm
->tm_year
<= 0)
3723 sprintf(str
+ strlen(str
), " BC");
3727 /* Compatible with Oracle/Ingres date formats */
3729 if (DateOrder
== DATEORDER_DMY
)
3730 sprintf(str
, "%02d/%02d", tm
->tm_mday
, tm
->tm_mon
);
3732 sprintf(str
, "%02d/%02d", tm
->tm_mon
, tm
->tm_mday
);
3734 sprintf(str
+ 5, "/%04d %02d:%02d:",
3735 (tm
->tm_year
> 0) ? tm
->tm_year
: -(tm
->tm_year
- 1),
3736 tm
->tm_hour
, tm
->tm_min
);
3738 AppendTimestampSeconds(str
+ strlen(str
), tm
, fsec
);
3740 if (tzp
!= NULL
&& tm
->tm_isdst
>= 0)
3743 sprintf(str
+ strlen(str
), " %.*s", MAXTZLEN
, *tzn
);
3745 EncodeTimezone(str
, *tzp
, style
);
3748 if (tm
->tm_year
<= 0)
3749 sprintf(str
+ strlen(str
), " BC");
3752 case USE_GERMAN_DATES
:
3753 /* German variant on European style */
3755 sprintf(str
, "%02d.%02d", tm
->tm_mday
, tm
->tm_mon
);
3757 sprintf(str
+ 5, ".%04d %02d:%02d:",
3758 (tm
->tm_year
> 0) ? tm
->tm_year
: -(tm
->tm_year
- 1),
3759 tm
->tm_hour
, tm
->tm_min
);
3761 AppendTimestampSeconds(str
+ strlen(str
), tm
, fsec
);
3763 if (tzp
!= NULL
&& tm
->tm_isdst
>= 0)
3766 sprintf(str
+ strlen(str
), " %.*s", MAXTZLEN
, *tzn
);
3768 EncodeTimezone(str
, *tzp
, style
);
3771 if (tm
->tm_year
<= 0)
3772 sprintf(str
+ strlen(str
), " BC");
3775 case USE_POSTGRES_DATES
:
3777 /* Backward-compatible with traditional Postgres abstime dates */
3779 day
= date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
);
3780 tm
->tm_wday
= j2day(day
);
3782 strncpy(str
, days
[tm
->tm_wday
], 3);
3783 strcpy(str
+ 3, " ");
3785 if (DateOrder
== DATEORDER_DMY
)
3786 sprintf(str
+ 4, "%02d %3s", tm
->tm_mday
, months
[tm
->tm_mon
- 1]);
3788 sprintf(str
+ 4, "%3s %02d", months
[tm
->tm_mon
- 1], tm
->tm_mday
);
3790 sprintf(str
+ 10, " %02d:%02d:", tm
->tm_hour
, tm
->tm_min
);
3792 AppendTimestampSeconds(str
+ strlen(str
), tm
, fsec
);
3794 sprintf(str
+ strlen(str
), " %04d",
3795 (tm
->tm_year
> 0) ? tm
->tm_year
: -(tm
->tm_year
- 1));
3797 if (tzp
!= NULL
&& tm
->tm_isdst
>= 0)
3800 sprintf(str
+ strlen(str
), " %.*s", MAXTZLEN
, *tzn
);
3804 * We have a time zone, but no string version. Use the
3805 * numeric form, but be sure to include a leading space to
3806 * avoid formatting something which would be rejected by
3807 * the date/time parser later. - thomas 2001-10-19
3809 sprintf(str
+ strlen(str
), " ");
3810 EncodeTimezone(str
, *tzp
, style
);
3814 if (tm
->tm_year
<= 0)
3815 sprintf(str
+ strlen(str
), " BC");
3822 * Helper functions to avoid duplicated code in EncodeInterval.
3825 /* Append an ISO-8601-style interval field, but only if value isn't zero */
3827 AddISO8601IntPart(char *cp
, int value
, char units
)
3831 sprintf(cp
, "%d%c", value
, units
);
3832 return cp
+ strlen(cp
);
3835 /* Append a postgres-style interval field, but only if value isn't zero */
3837 AddPostgresIntPart(char *cp
, int value
, const char *units
,
3838 bool *is_zero
, bool *is_before
)
3842 sprintf(cp
, "%s%s%d %s%s",
3843 (!*is_zero
) ? " " : "",
3844 (*is_before
&& value
> 0) ? "+" : "",
3847 (value
!= 1) ? "s" : "");
3850 * Each nonzero field sets is_before for (only) the next one. This is a
3851 * tad bizarre but it's how it worked before...
3853 *is_before
= (value
< 0);
3855 return cp
+ strlen(cp
);
3858 /* Append a verbose-style interval field, but only if value isn't zero */
3860 AddVerboseIntPart(char *cp
, int value
, const char *units
,
3861 bool *is_zero
, bool *is_before
)
3865 /* first nonzero value sets is_before */
3868 *is_before
= (value
< 0);
3871 else if (*is_before
)
3873 sprintf(cp
, " %d %s%s", value
, units
, (value
== 1) ? "" : "s");
3875 return cp
+ strlen(cp
);
3880 * Interpret time structure as a delta time and convert to string.
3882 * Support "traditional Postgres" and ISO-8601 styles.
3883 * Actually, afaik ISO does not address time interval formatting,
3884 * but this looks similar to the spec for absolute date/time.
3885 * - thomas 1998-04-30
3887 * Actually, afaik, ISO 8601 does specify formats for "time
3888 * intervals...[of the]...format with time-unit designators", which
3889 * are pretty ugly. The format looks something like
3890 * P1Y1M1DT1H1M1.12345S
3891 * but useful for exchanging data with computers instead of humans.
3894 * And ISO's SQL 2008 standard specifies standards for
3895 * "year-month literal"s (that look like '2-3') and
3896 * "day-time literal"s (that look like ('4 5:6:7')
3899 EncodeInterval(struct pg_tm
* tm
, fsec_t fsec
, int style
, char *str
)
3902 int year
= tm
->tm_year
;
3903 int mon
= tm
->tm_mon
;
3904 int mday
= tm
->tm_mday
;
3905 int hour
= tm
->tm_hour
;
3906 int min
= tm
->tm_min
;
3907 int sec
= tm
->tm_sec
;
3908 bool is_before
= FALSE
;
3909 bool is_zero
= TRUE
;
3912 * The sign of year and month are guaranteed to match, since they are
3913 * stored internally as "month". But we'll need to check for is_before and
3914 * is_zero when determining the signs of day and hour/minute/seconds
3919 /* SQL Standard interval format */
3920 case INTSTYLE_SQL_STANDARD
:
3922 bool has_negative
= year
< 0 || mon
< 0 ||
3923 mday
< 0 || hour
< 0 ||
3924 min
< 0 || sec
< 0 || fsec
< 0;
3925 bool has_positive
= year
> 0 || mon
> 0 ||
3926 mday
> 0 || hour
> 0 ||
3927 min
> 0 || sec
> 0 || fsec
> 0;
3928 bool has_year_month
= year
!= 0 || mon
!= 0;
3929 bool has_day_time
= mday
!= 0 || hour
!= 0 ||
3930 min
!= 0 || sec
!= 0 || fsec
!= 0;
3931 bool has_day
= mday
!= 0;
3932 bool sql_standard_value
= !(has_negative
&& has_positive
) &&
3933 !(has_year_month
&& has_day_time
);
3936 * SQL Standard wants only 1 "<sign>" preceding the whole
3937 * interval ... but can't do that if mixed signs.
3939 if (has_negative
&& sql_standard_value
)
3951 if (!has_negative
&& !has_positive
)
3955 else if (!sql_standard_value
)
3958 * For non sql-standard interval values, force outputting
3959 * the signs to avoid ambiguities with intervals with
3960 * mixed sign components.
3962 char year_sign
= (year
< 0 || mon
< 0) ? '-' : '+';
3963 char day_sign
= (mday
< 0) ? '-' : '+';
3964 char sec_sign
= (hour
< 0 || min
< 0 ||
3965 sec
< 0 || fsec
< 0) ? '-' : '+';
3967 sprintf(cp
, "%c%d-%d %c%d %c%d:%02d:",
3968 year_sign
, abs(year
), abs(mon
),
3969 day_sign
, abs(mday
),
3970 sec_sign
, abs(hour
), abs(min
));
3972 AppendSeconds(cp
, sec
, fsec
, MAX_INTERVAL_PRECISION
, true);
3974 else if (has_year_month
)
3976 sprintf(cp
, "%d-%d", year
, mon
);
3980 sprintf(cp
, "%d %d:%02d:", mday
, hour
, min
);
3982 AppendSeconds(cp
, sec
, fsec
, MAX_INTERVAL_PRECISION
, true);
3986 sprintf(cp
, "%d:%02d:", hour
, min
);
3988 AppendSeconds(cp
, sec
, fsec
, MAX_INTERVAL_PRECISION
, true);
3993 /* ISO 8601 "time-intervals by duration only" */
3994 case INTSTYLE_ISO_8601
:
3995 /* special-case zero to avoid printing nothing */
3996 if (year
== 0 && mon
== 0 && mday
== 0 &&
3997 hour
== 0 && min
== 0 && sec
== 0 && fsec
== 0)
3999 sprintf(cp
, "PT0S");
4003 cp
= AddISO8601IntPart(cp
, year
, 'Y');
4004 cp
= AddISO8601IntPart(cp
, mon
, 'M');
4005 cp
= AddISO8601IntPart(cp
, mday
, 'D');
4006 if (hour
!= 0 || min
!= 0 || sec
!= 0 || fsec
!= 0)
4008 cp
= AddISO8601IntPart(cp
, hour
, 'H');
4009 cp
= AddISO8601IntPart(cp
, min
, 'M');
4010 if (sec
!= 0 || fsec
!= 0)
4012 if (sec
< 0 || fsec
< 0)
4014 AppendSeconds(cp
, sec
, fsec
, MAX_INTERVAL_PRECISION
, false);
4021 /* Compatible with postgresql < 8.4 when DateStyle = 'iso' */
4022 case INTSTYLE_POSTGRES
:
4023 cp
= AddPostgresIntPart(cp
, year
, "year", &is_zero
, &is_before
);
4024 cp
= AddPostgresIntPart(cp
, mon
, "mon", &is_zero
, &is_before
);
4025 cp
= AddPostgresIntPart(cp
, mday
, "day", &is_zero
, &is_before
);
4026 if (is_zero
|| hour
!= 0 || min
!= 0 || sec
!= 0 || fsec
!= 0)
4028 bool minus
= (hour
< 0 || min
< 0 || sec
< 0 || fsec
< 0);
4030 sprintf(cp
, "%s%s%02d:%02d:",
4032 (minus
? "-" : (is_before
? "+" : "")),
4033 abs(hour
), abs(min
));
4035 AppendSeconds(cp
, sec
, fsec
, MAX_INTERVAL_PRECISION
, true);
4039 /* Compatible with postgresql < 8.4 when DateStyle != 'iso' */
4040 case INTSTYLE_POSTGRES_VERBOSE
:
4044 cp
= AddVerboseIntPart(cp
, year
, "year", &is_zero
, &is_before
);
4045 cp
= AddVerboseIntPart(cp
, mon
, "mon", &is_zero
, &is_before
);
4046 cp
= AddVerboseIntPart(cp
, mday
, "day", &is_zero
, &is_before
);
4047 cp
= AddVerboseIntPart(cp
, hour
, "hour", &is_zero
, &is_before
);
4048 cp
= AddVerboseIntPart(cp
, min
, "min", &is_zero
, &is_before
);
4049 if (sec
!= 0 || fsec
!= 0)
4052 if (sec
< 0 || (sec
== 0 && fsec
< 0))
4056 else if (!is_before
)
4061 AppendSeconds(cp
, sec
, fsec
, MAX_INTERVAL_PRECISION
, false);
4063 sprintf(cp
, " sec%s",
4064 (abs(sec
) != 1 || fsec
!= 0) ? "s" : "");
4067 /* identically zero? then put in a unitless zero... */
4078 * We've been burnt by stupid errors in the ordering of the datetkn tables
4079 * once too often. Arrange to check them during postmaster start.
4082 CheckDateTokenTable(const char *tablename
, const datetkn
*base
, int nel
)
4087 for (i
= 1; i
< nel
; i
++)
4089 if (strncmp(base
[i
- 1].token
, base
[i
].token
, TOKMAXLEN
) >= 0)
4091 elog(LOG
, "ordering error in %s table: \"%.*s\" >= \"%.*s\"",
4093 TOKMAXLEN
, base
[i
- 1].token
,
4094 TOKMAXLEN
, base
[i
].token
);
4102 CheckDateTokenTables(void)
4106 Assert(UNIX_EPOCH_JDATE
== date2j(1970, 1, 1));
4107 Assert(POSTGRES_EPOCH_JDATE
== date2j(2000, 1, 1));
4109 ok
&= CheckDateTokenTable("datetktbl", datetktbl
, szdatetktbl
);
4110 ok
&= CheckDateTokenTable("deltatktbl", deltatktbl
, szdeltatktbl
);
4115 * This function gets called during timezone config file load or reload
4116 * to create the final array of timezone tokens. The argument array
4117 * is already sorted in name order. This data is in a temporary memory
4118 * context and must be copied to somewhere permanent.
4121 InstallTimeZoneAbbrevs(tzEntry
*abbrevs
, int n
)
4127 * Copy the data into TopMemoryContext and convert to datetkn format.
4129 newtbl
= (datetkn
*) MemoryContextAlloc(TopMemoryContext
,
4130 n
* sizeof(datetkn
));
4131 for (i
= 0; i
< n
; i
++)
4133 strncpy(newtbl
[i
].token
, abbrevs
[i
].abbrev
, TOKMAXLEN
);
4134 newtbl
[i
].type
= abbrevs
[i
].is_dst
? DTZ
: TZ
;
4135 TOVAL(&newtbl
[i
], abbrevs
[i
].offset
/ 60);
4138 /* Check the ordering, if testing */
4139 Assert(CheckDateTokenTable("timezone offset", newtbl
, n
));
4141 /* Now safe to replace existing table (if any) */
4143 pfree(timezonetktbl
);
4144 timezonetktbl
= newtbl
;
4145 sztimezonetktbl
= n
;
4147 /* clear date cache in case it contains any stale timezone names */
4148 for (i
= 0; i
< MAXDATEFIELDS
; i
++)
4149 datecache
[i
] = NULL
;
4153 * This set-returning function reads all the available time zone abbreviations
4154 * and returns a set of (abbrev, utc_offset, is_dst).
4157 pg_timezone_abbrevs(PG_FUNCTION_ARGS
)
4159 FuncCallContext
*funcctx
;
4165 char buffer
[TOKMAXLEN
+ 1];
4168 Interval
*resInterval
;
4170 /* stuff done only on the first call of the function */
4171 if (SRF_IS_FIRSTCALL())
4174 MemoryContext oldcontext
;
4176 /* create a function context for cross-call persistence */
4177 funcctx
= SRF_FIRSTCALL_INIT();
4180 * switch to memory context appropriate for multiple function calls
4182 oldcontext
= MemoryContextSwitchTo(funcctx
->multi_call_memory_ctx
);
4184 /* allocate memory for user context */
4185 pindex
= (int *) palloc(sizeof(int));
4187 funcctx
->user_fctx
= (void *) pindex
;
4190 * build tupdesc for result tuples. This must match this function's
4193 tupdesc
= CreateTemplateTupleDesc(3, false);
4194 TupleDescInitEntry(tupdesc
, (AttrNumber
) 1, "abbrev",
4196 TupleDescInitEntry(tupdesc
, (AttrNumber
) 2, "utc_offset",
4197 INTERVALOID
, -1, 0);
4198 TupleDescInitEntry(tupdesc
, (AttrNumber
) 3, "is_dst",
4201 funcctx
->tuple_desc
= BlessTupleDesc(tupdesc
);
4202 MemoryContextSwitchTo(oldcontext
);
4205 /* stuff done on every call of the function */
4206 funcctx
= SRF_PERCALL_SETUP();
4207 pindex
= (int *) funcctx
->user_fctx
;
4209 if (*pindex
>= sztimezonetktbl
)
4210 SRF_RETURN_DONE(funcctx
);
4212 MemSet(nulls
, 0, sizeof(nulls
));
4215 * Convert name to text, using upcasing conversion that is the inverse of
4216 * what ParseDateTime() uses.
4218 strncpy(buffer
, timezonetktbl
[*pindex
].token
, TOKMAXLEN
);
4219 buffer
[TOKMAXLEN
] = '\0'; /* may not be null-terminated */
4220 for (p
= (unsigned char *) buffer
; *p
; p
++)
4221 *p
= pg_toupper(*p
);
4223 values
[0] = CStringGetTextDatum(buffer
);
4225 MemSet(&tm
, 0, sizeof(struct pg_tm
));
4226 tm
.tm_min
= (-1) * FROMVAL(&timezonetktbl
[*pindex
]);
4227 resInterval
= (Interval
*) palloc(sizeof(Interval
));
4228 tm2interval(&tm
, 0, resInterval
);
4229 values
[1] = IntervalPGetDatum(resInterval
);
4231 Assert(timezonetktbl
[*pindex
].type
== DTZ
||
4232 timezonetktbl
[*pindex
].type
== TZ
);
4233 values
[2] = BoolGetDatum(timezonetktbl
[*pindex
].type
== DTZ
);
4237 tuple
= heap_form_tuple(funcctx
->tuple_desc
, values
, nulls
);
4238 result
= HeapTupleGetDatum(tuple
);
4240 SRF_RETURN_NEXT(funcctx
, result
);
4244 * This set-returning function reads all the available full time zones
4245 * and returns a set of (name, abbrev, utc_offset, is_dst).
4248 pg_timezone_names(PG_FUNCTION_ARGS
)
4250 MemoryContext oldcontext
;
4251 FuncCallContext
*funcctx
;
4262 Interval
*resInterval
;
4265 /* stuff done only on the first call of the function */
4266 if (SRF_IS_FIRSTCALL())
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 /* initialize timezone scanning code */
4279 tzenum
= pg_tzenumerate_start();
4280 funcctx
->user_fctx
= (void *) tzenum
;
4283 * build tupdesc for result tuples. This must match this function's
4286 tupdesc
= CreateTemplateTupleDesc(4, false);
4287 TupleDescInitEntry(tupdesc
, (AttrNumber
) 1, "name",
4289 TupleDescInitEntry(tupdesc
, (AttrNumber
) 2, "abbrev",
4291 TupleDescInitEntry(tupdesc
, (AttrNumber
) 3, "utc_offset",
4292 INTERVALOID
, -1, 0);
4293 TupleDescInitEntry(tupdesc
, (AttrNumber
) 4, "is_dst",
4296 funcctx
->tuple_desc
= BlessTupleDesc(tupdesc
);
4297 MemoryContextSwitchTo(oldcontext
);
4300 /* stuff done on every call of the function */
4301 funcctx
= SRF_PERCALL_SETUP();
4302 tzenum
= (pg_tzenum
*) funcctx
->user_fctx
;
4304 /* search for another zone to display */
4307 oldcontext
= MemoryContextSwitchTo(funcctx
->multi_call_memory_ctx
);
4308 tz
= pg_tzenumerate_next(tzenum
);
4309 MemoryContextSwitchTo(oldcontext
);
4313 pg_tzenumerate_end(tzenum
);
4314 funcctx
->user_fctx
= NULL
;
4315 SRF_RETURN_DONE(funcctx
);
4318 /* Convert now() to local time in this zone */
4319 if (timestamp2tm(GetCurrentTransactionStartTimestamp(),
4320 &tzoff
, &tm
, &fsec
, &tzn
, tz
) != 0)
4321 continue; /* ignore if conversion fails */
4323 /* Ignore zic's rather silly "Factory" time zone */
4324 if (tzn
&& strcmp(tzn
, "Local time zone must be set--see zic manual page") == 0)
4327 /* Found a displayable zone */
4331 MemSet(nulls
, 0, sizeof(nulls
));
4333 values
[0] = CStringGetTextDatum(pg_get_timezone_name(tz
));
4334 values
[1] = CStringGetTextDatum(tzn
? tzn
: "");
4336 MemSet(&itm
, 0, sizeof(struct pg_tm
));
4337 itm
.tm_sec
= -tzoff
;
4338 resInterval
= (Interval
*) palloc(sizeof(Interval
));
4339 tm2interval(&itm
, 0, resInterval
);
4340 values
[2] = IntervalPGetDatum(resInterval
);
4342 values
[3] = BoolGetDatum(tm
.tm_isdst
> 0);
4344 tuple
= heap_form_tuple(funcctx
->tuple_desc
, values
, nulls
);
4345 result
= HeapTupleGetDatum(tuple
);
4347 SRF_RETURN_NEXT(funcctx
, result
);