Fix datetime input functions to correctly detect integer overflow when
[PostgreSQL.git] / src / backend / utils / adt / datetime.c
blobe2ea50267c1d7994d1d4f7e9cd54cc25e12bda0a
1 /*-------------------------------------------------------------------------
3 * datetime.c
4 * Support functions for date/time types.
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * $PostgreSQL$
13 *-------------------------------------------------------------------------
15 #include "postgres.h"
17 #include <ctype.h>
18 #include <float.h>
19 #include <limits.h>
20 #include <math.h>
22 #include "access/xact.h"
23 #include "catalog/pg_type.h"
24 #include "funcapi.h"
25 #include "miscadmin.h"
26 #include "utils/builtins.h"
27 #include "utils/datetime.h"
28 #include "utils/memutils.h"
29 #include "utils/tzparser.h"
32 static int DecodeNumber(int flen, char *field, bool haveTextMonth,
33 int fmask, int *tmask,
34 struct pg_tm * tm, fsec_t *fsec, bool *is2digits);
35 static int DecodeNumberField(int len, char *str,
36 int fmask, int *tmask,
37 struct pg_tm * tm, fsec_t *fsec, bool *is2digits);
38 static int DecodeTime(char *str, int fmask, int *tmask,
39 struct pg_tm * tm, fsec_t *fsec);
40 static int DecodeTimezone(char *str, int *tzp);
41 static const datetkn *datebsearch(const char *key, const datetkn *base, int nel);
42 static int DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
43 struct pg_tm * tm);
44 static int ValidateDate(int fmask, bool is2digits, bool bc,
45 struct pg_tm * tm);
46 static void TrimTrailingZeros(char *str);
49 const int day_tab[2][13] =
51 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
52 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}
55 char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
56 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
58 char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
59 "Thursday", "Friday", "Saturday", NULL};
62 /*****************************************************************************
63 * PRIVATE ROUTINES *
64 *****************************************************************************/
67 * Definitions for squeezing values into "value"
68 * We set aside a high bit for a sign, and scale the timezone offsets
69 * in minutes by a factor of 15 (so can represent quarter-hour increments).
71 #define ABS_SIGNBIT ((char) 0200)
72 #define VALMASK ((char) 0177)
73 #define POS(n) (n)
74 #define NEG(n) ((n)|ABS_SIGNBIT)
75 #define SIGNEDCHAR(c) ((c)&ABS_SIGNBIT? -((c)&VALMASK): (c))
76 #define FROMVAL(tp) (-SIGNEDCHAR((tp)->value) * 15) /* uncompress */
77 #define TOVAL(tp, v) ((tp)->value = ((v) < 0? NEG((-(v))/15): POS(v)/15))
80 * datetktbl holds date/time keywords.
82 * Note that this table must be strictly alphabetically ordered to allow an
83 * O(ln(N)) search algorithm to be used.
85 * The text field is NOT guaranteed to be NULL-terminated.
87 * To keep this table reasonably small, we divide the lexval for TZ and DTZ
88 * entries by 15 (so they are on 15 minute boundaries) and truncate the text
89 * field at TOKMAXLEN characters.
90 * Formerly, we divided by 10 rather than 15 but there are a few time zones
91 * which are 30 or 45 minutes away from an even hour, most are on an hour
92 * boundary, and none on other boundaries.
94 * The static table contains no TZ or DTZ entries, rather those are loaded
95 * from configuration files and stored in timezonetktbl, which has the same
96 * format as the static datetktbl.
98 static datetkn *timezonetktbl = NULL;
100 static int sztimezonetktbl = 0;
102 static const datetkn datetktbl[] = {
103 /* text, token, lexval */
104 {EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
105 {"abstime", IGNORE_DTF, 0}, /* for pre-v6.1 "Invalid Abstime" */
106 {DA_D, ADBC, AD}, /* "ad" for years > 0 */
107 {"allballs", RESERV, DTK_ZULU}, /* 00:00:00 */
108 {"am", AMPM, AM},
109 {"apr", MONTH, 4},
110 {"april", MONTH, 4},
111 {"at", IGNORE_DTF, 0}, /* "at" (throwaway) */
112 {"aug", MONTH, 8},
113 {"august", MONTH, 8},
114 {DB_C, ADBC, BC}, /* "bc" for years <= 0 */
115 {DCURRENT, RESERV, DTK_CURRENT}, /* "current" is always now */
116 {"d", UNITS, DTK_DAY}, /* "day of month" for ISO input */
117 {"dec", MONTH, 12},
118 {"december", MONTH, 12},
119 {"dow", RESERV, DTK_DOW}, /* day of week */
120 {"doy", RESERV, DTK_DOY}, /* day of year */
121 {"dst", DTZMOD, 6},
122 {EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
123 {"feb", MONTH, 2},
124 {"february", MONTH, 2},
125 {"fri", DOW, 5},
126 {"friday", DOW, 5},
127 {"h", UNITS, DTK_HOUR}, /* "hour" */
128 {LATE, RESERV, DTK_LATE}, /* "infinity" reserved for "late time" */
129 {INVALID, RESERV, DTK_INVALID}, /* "invalid" reserved for bad time */
130 {"isodow", RESERV, DTK_ISODOW}, /* ISO day of week, Sunday == 7 */
131 {"isoyear", UNITS, DTK_ISOYEAR}, /* year in terms of the ISO week date */
132 {"j", UNITS, DTK_JULIAN},
133 {"jan", MONTH, 1},
134 {"january", MONTH, 1},
135 {"jd", UNITS, DTK_JULIAN},
136 {"jul", MONTH, 7},
137 {"julian", UNITS, DTK_JULIAN},
138 {"july", MONTH, 7},
139 {"jun", MONTH, 6},
140 {"june", MONTH, 6},
141 {"m", UNITS, DTK_MONTH}, /* "month" for ISO input */
142 {"mar", MONTH, 3},
143 {"march", MONTH, 3},
144 {"may", MONTH, 5},
145 {"mm", UNITS, DTK_MINUTE}, /* "minute" for ISO input */
146 {"mon", DOW, 1},
147 {"monday", DOW, 1},
148 {"nov", MONTH, 11},
149 {"november", MONTH, 11},
150 {NOW, RESERV, DTK_NOW}, /* current transaction time */
151 {"oct", MONTH, 10},
152 {"october", MONTH, 10},
153 {"on", IGNORE_DTF, 0}, /* "on" (throwaway) */
154 {"pm", AMPM, PM},
155 {"s", UNITS, DTK_SECOND}, /* "seconds" for ISO input */
156 {"sat", DOW, 6},
157 {"saturday", DOW, 6},
158 {"sep", MONTH, 9},
159 {"sept", MONTH, 9},
160 {"september", MONTH, 9},
161 {"sun", DOW, 0},
162 {"sunday", DOW, 0},
163 {"t", ISOTIME, DTK_TIME}, /* Filler for ISO time fields */
164 {"thu", DOW, 4},
165 {"thur", DOW, 4},
166 {"thurs", DOW, 4},
167 {"thursday", DOW, 4},
168 {TODAY, RESERV, DTK_TODAY}, /* midnight */
169 {TOMORROW, RESERV, DTK_TOMORROW}, /* tomorrow midnight */
170 {"tue", DOW, 2},
171 {"tues", DOW, 2},
172 {"tuesday", DOW, 2},
173 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
174 {"wed", DOW, 3},
175 {"wednesday", DOW, 3},
176 {"weds", DOW, 3},
177 {"y", UNITS, DTK_YEAR}, /* "year" for ISO input */
178 {YESTERDAY, RESERV, DTK_YESTERDAY} /* yesterday midnight */
181 static int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];
183 static datetkn deltatktbl[] = {
184 /* text, token, lexval */
185 {"@", IGNORE_DTF, 0}, /* postgres relative prefix */
186 {DAGO, AGO, 0}, /* "ago" indicates negative time offset */
187 {"c", UNITS, DTK_CENTURY}, /* "century" relative */
188 {"cent", UNITS, DTK_CENTURY}, /* "century" relative */
189 {"centuries", UNITS, DTK_CENTURY}, /* "centuries" relative */
190 {DCENTURY, UNITS, DTK_CENTURY}, /* "century" relative */
191 {"d", UNITS, DTK_DAY}, /* "day" relative */
192 {DDAY, UNITS, DTK_DAY}, /* "day" relative */
193 {"days", UNITS, DTK_DAY}, /* "days" relative */
194 {"dec", UNITS, DTK_DECADE}, /* "decade" relative */
195 {DDECADE, UNITS, DTK_DECADE}, /* "decade" relative */
196 {"decades", UNITS, DTK_DECADE}, /* "decades" relative */
197 {"decs", UNITS, DTK_DECADE}, /* "decades" relative */
198 {"h", UNITS, DTK_HOUR}, /* "hour" relative */
199 {DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */
200 {"hours", UNITS, DTK_HOUR}, /* "hours" relative */
201 {"hr", UNITS, DTK_HOUR}, /* "hour" relative */
202 {"hrs", UNITS, DTK_HOUR}, /* "hours" relative */
203 {INVALID, RESERV, DTK_INVALID}, /* reserved for invalid time */
204 {"m", UNITS, DTK_MINUTE}, /* "minute" relative */
205 {"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
206 {"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
207 {"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
208 {DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
209 {"millisecon", UNITS, DTK_MILLISEC}, /* relative */
210 {"mils", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
211 {"min", UNITS, DTK_MINUTE}, /* "minute" relative */
212 {"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */
213 {DMINUTE, UNITS, DTK_MINUTE}, /* "minute" relative */
214 {"minutes", UNITS, DTK_MINUTE}, /* "minutes" relative */
215 {"mon", UNITS, DTK_MONTH}, /* "months" relative */
216 {"mons", UNITS, DTK_MONTH}, /* "months" relative */
217 {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
218 {"months", UNITS, DTK_MONTH},
219 {"ms", UNITS, DTK_MILLISEC},
220 {"msec", UNITS, DTK_MILLISEC},
221 {DMILLISEC, UNITS, DTK_MILLISEC},
222 {"mseconds", UNITS, DTK_MILLISEC},
223 {"msecs", UNITS, DTK_MILLISEC},
224 {"qtr", UNITS, DTK_QUARTER}, /* "quarter" relative */
225 {DQUARTER, UNITS, DTK_QUARTER}, /* "quarter" relative */
226 {"reltime", IGNORE_DTF, 0}, /* pre-v6.1 "Undefined Reltime" */
227 {"s", UNITS, DTK_SECOND},
228 {"sec", UNITS, DTK_SECOND},
229 {DSECOND, UNITS, DTK_SECOND},
230 {"seconds", UNITS, DTK_SECOND},
231 {"secs", UNITS, DTK_SECOND},
232 {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
233 {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
234 {"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */
235 {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
236 {"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
237 {"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
238 {DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */
239 {"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
240 {"usecs", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
241 {"w", UNITS, DTK_WEEK}, /* "week" relative */
242 {DWEEK, UNITS, DTK_WEEK}, /* "week" relative */
243 {"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
244 {"y", UNITS, DTK_YEAR}, /* "year" relative */
245 {DYEAR, UNITS, DTK_YEAR}, /* "year" relative */
246 {"years", UNITS, DTK_YEAR}, /* "years" relative */
247 {"yr", UNITS, DTK_YEAR}, /* "year" relative */
248 {"yrs", UNITS, DTK_YEAR} /* "years" relative */
251 static int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];
253 static const datetkn *datecache[MAXDATEFIELDS] = {NULL};
255 static const datetkn *deltacache[MAXDATEFIELDS] = {NULL};
259 * strtoi --- just like strtol, but returns int not long
261 static int
262 strtoi(const char *nptr, char **endptr, int base)
264 long val;
266 val = strtol(nptr, endptr, base);
267 #ifdef HAVE_LONG_INT_64
268 if (val != (long) ((int32) val))
269 errno = ERANGE;
270 #endif
271 return (int) val;
276 * Calendar time to Julian date conversions.
277 * Julian date is commonly used in astronomical applications,
278 * since it is numerically accurate and computationally simple.
279 * The algorithms here will accurately convert between Julian day
280 * and calendar date for all non-negative Julian days
281 * (i.e. from Nov 24, -4713 on).
283 * These routines will be used by other date/time packages
284 * - thomas 97/02/25
286 * Rewritten to eliminate overflow problems. This now allows the
287 * routines to work correctly for all Julian day counts from
288 * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming
289 * a 32-bit integer. Longer types should also work to the limits
290 * of their precision.
294 date2j(int y, int m, int d)
296 int julian;
297 int century;
299 if (m > 2)
301 m += 1;
302 y += 4800;
304 else
306 m += 13;
307 y += 4799;
310 century = y / 100;
311 julian = y * 365 - 32167;
312 julian += y / 4 - century + century / 4;
313 julian += 7834 * m / 256 + d;
315 return julian;
316 } /* date2j() */
318 void
319 j2date(int jd, int *year, int *month, int *day)
321 unsigned int julian;
322 unsigned int quad;
323 unsigned int extra;
324 int y;
326 julian = jd;
327 julian += 32044;
328 quad = julian / 146097;
329 extra = (julian - quad * 146097) * 4 + 3;
330 julian += 60 + quad * 3 + extra / 146097;
331 quad = julian / 1461;
332 julian -= quad * 1461;
333 y = julian * 4 / 1461;
334 julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
335 + 123;
336 y += quad * 4;
337 *year = y - 4800;
338 quad = julian * 2141 / 65536;
339 *day = julian - 7834 * quad / 256;
340 *month = (quad + 10) % 12 + 1;
342 return;
343 } /* j2date() */
347 * j2day - convert Julian date to day-of-week (0..6 == Sun..Sat)
349 * Note: various places use the locution j2day(date - 1) to produce a
350 * result according to the convention 0..6 = Mon..Sun. This is a bit of
351 * a crock, but will work as long as the computation here is just a modulo.
354 j2day(int date)
356 unsigned int day;
358 day = date;
360 day += 1;
361 day %= 7;
363 return (int) day;
364 } /* j2day() */
368 * GetCurrentDateTime()
370 * Get the transaction start time ("now()") broken down as a struct pg_tm.
372 void
373 GetCurrentDateTime(struct pg_tm * tm)
375 int tz;
376 fsec_t fsec;
378 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, &fsec,
379 NULL, NULL);
380 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
384 * GetCurrentTimeUsec()
386 * Get the transaction start time ("now()") broken down as a struct pg_tm,
387 * including fractional seconds and timezone offset.
389 void
390 GetCurrentTimeUsec(struct pg_tm * tm, fsec_t *fsec, int *tzp)
392 int tz;
394 timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, fsec,
395 NULL, NULL);
396 /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
397 if (tzp != NULL)
398 *tzp = tz;
402 /* TrimTrailingZeros()
403 * ... resulting from printing numbers with full precision.
405 static void
406 TrimTrailingZeros(char *str)
408 int len = strlen(str);
410 #if 0
411 /* chop off trailing one to cope with interval rounding */
412 if (strcmp(str + len - 4, "0001") == 0)
414 len -= 4;
415 *(str + len) = '\0';
417 #endif
419 /* chop off trailing zeros... but leave at least 2 fractional digits */
420 while (*(str + len - 1) == '0' && *(str + len - 3) != '.')
422 len--;
423 *(str + len) = '\0';
427 /* ParseDateTime()
428 * Break string into tokens based on a date/time context.
429 * Returns 0 if successful, DTERR code if bogus input detected.
431 * timestr - the input string
432 * workbuf - workspace for field string storage. This must be
433 * larger than the largest legal input for this datetime type --
434 * some additional space will be needed to NUL terminate fields.
435 * buflen - the size of workbuf
436 * field[] - pointers to field strings are returned in this array
437 * ftype[] - field type indicators are returned in this array
438 * maxfields - dimensions of the above two arrays
439 * *numfields - set to the actual number of fields detected
441 * The fields extracted from the input are stored as separate,
442 * null-terminated strings in the workspace at workbuf. Any text is
443 * converted to lower case.
445 * Several field types are assigned:
446 * DTK_NUMBER - digits and (possibly) a decimal point
447 * DTK_DATE - digits and two delimiters, or digits and text
448 * DTK_TIME - digits, colon delimiters, and possibly a decimal point
449 * DTK_STRING - text (no digits or punctuation)
450 * DTK_SPECIAL - leading "+" or "-" followed by text
451 * DTK_TZ - leading "+" or "-" followed by digits (also eats ':' or '.')
453 * Note that some field types can hold unexpected items:
454 * DTK_NUMBER can hold date fields (yy.ddd)
455 * DTK_STRING can hold months (January) and time zones (PST)
456 * DTK_DATE can hold time zone names (America/New_York, GMT-8)
459 ParseDateTime(const char *timestr, char *workbuf, size_t buflen,
460 char **field, int *ftype, int maxfields, int *numfields)
462 int nf = 0;
463 const char *cp = timestr;
464 char *bufp = workbuf;
465 const char *bufend = workbuf + buflen;
468 * Set the character pointed-to by "bufptr" to "newchar", and increment
469 * "bufptr". "end" gives the end of the buffer -- we return an error if
470 * there is no space left to append a character to the buffer. Note that
471 * "bufptr" is evaluated twice.
473 #define APPEND_CHAR(bufptr, end, newchar) \
474 do \
476 if (((bufptr) + 1) >= (end)) \
477 return DTERR_BAD_FORMAT; \
478 *(bufptr)++ = newchar; \
479 } while (0)
481 /* outer loop through fields */
482 while (*cp != '\0')
484 /* Ignore spaces between fields */
485 if (isspace((unsigned char) *cp))
487 cp++;
488 continue;
491 /* Record start of current field */
492 if (nf >= maxfields)
493 return DTERR_BAD_FORMAT;
494 field[nf] = bufp;
496 /* leading digit? then date or time */
497 if (isdigit((unsigned char) *cp))
499 APPEND_CHAR(bufp, bufend, *cp++);
500 while (isdigit((unsigned char) *cp))
501 APPEND_CHAR(bufp, bufend, *cp++);
503 /* time field? */
504 if (*cp == ':')
506 ftype[nf] = DTK_TIME;
507 APPEND_CHAR(bufp, bufend, *cp++);
508 while (isdigit((unsigned char) *cp) ||
509 (*cp == ':') || (*cp == '.'))
510 APPEND_CHAR(bufp, bufend, *cp++);
512 /* date field? allow embedded text month */
513 else if (*cp == '-' || *cp == '/' || *cp == '.')
515 /* save delimiting character to use later */
516 char delim = *cp;
518 APPEND_CHAR(bufp, bufend, *cp++);
519 /* second field is all digits? then no embedded text month */
520 if (isdigit((unsigned char) *cp))
522 ftype[nf] = ((delim == '.') ? DTK_NUMBER : DTK_DATE);
523 while (isdigit((unsigned char) *cp))
524 APPEND_CHAR(bufp, bufend, *cp++);
527 * insist that the delimiters match to get a three-field
528 * date.
530 if (*cp == delim)
532 ftype[nf] = DTK_DATE;
533 APPEND_CHAR(bufp, bufend, *cp++);
534 while (isdigit((unsigned char) *cp) || *cp == delim)
535 APPEND_CHAR(bufp, bufend, *cp++);
538 else
540 ftype[nf] = DTK_DATE;
541 while (isalnum((unsigned char) *cp) || *cp == delim)
542 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
547 * otherwise, number only and will determine year, month, day, or
548 * concatenated fields later...
550 else
551 ftype[nf] = DTK_NUMBER;
553 /* Leading decimal point? Then fractional seconds... */
554 else if (*cp == '.')
556 APPEND_CHAR(bufp, bufend, *cp++);
557 while (isdigit((unsigned char) *cp))
558 APPEND_CHAR(bufp, bufend, *cp++);
560 ftype[nf] = DTK_NUMBER;
564 * text? then date string, month, day of week, special, or timezone
566 else if (isalpha((unsigned char) *cp))
568 bool is_date;
570 ftype[nf] = DTK_STRING;
571 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
572 while (isalpha((unsigned char) *cp))
573 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
576 * Dates can have embedded '-', '/', or '.' separators. It could
577 * also be a timezone name containing embedded '/', '+', '-', '_',
578 * or ':' (but '_' or ':' can't be the first punctuation). If the
579 * next character is a digit or '+', we need to check whether what
580 * we have so far is a recognized non-timezone keyword --- if so,
581 * don't believe that this is the start of a timezone.
583 is_date = false;
584 if (*cp == '-' || *cp == '/' || *cp == '.')
585 is_date = true;
586 else if (*cp == '+' || isdigit((unsigned char) *cp))
588 *bufp = '\0'; /* null-terminate current field value */
589 /* we need search only the core token table, not TZ names */
590 if (datebsearch(field[nf], datetktbl, szdatetktbl) == NULL)
591 is_date = true;
593 if (is_date)
595 ftype[nf] = DTK_DATE;
598 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
599 } while (*cp == '+' || *cp == '-' ||
600 *cp == '/' || *cp == '_' ||
601 *cp == '.' || *cp == ':' ||
602 isalnum((unsigned char) *cp));
605 /* sign? then special or numeric timezone */
606 else if (*cp == '+' || *cp == '-')
608 APPEND_CHAR(bufp, bufend, *cp++);
609 /* soak up leading whitespace */
610 while (isspace((unsigned char) *cp))
611 cp++;
612 /* numeric timezone? */
613 if (isdigit((unsigned char) *cp))
615 ftype[nf] = DTK_TZ;
616 APPEND_CHAR(bufp, bufend, *cp++);
617 while (isdigit((unsigned char) *cp) ||
618 *cp == ':' || *cp == '.')
619 APPEND_CHAR(bufp, bufend, *cp++);
621 /* special? */
622 else if (isalpha((unsigned char) *cp))
624 ftype[nf] = DTK_SPECIAL;
625 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
626 while (isalpha((unsigned char) *cp))
627 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
629 /* otherwise something wrong... */
630 else
631 return DTERR_BAD_FORMAT;
633 /* ignore other punctuation but use as delimiter */
634 else if (ispunct((unsigned char) *cp))
636 cp++;
637 continue;
639 /* otherwise, something is not right... */
640 else
641 return DTERR_BAD_FORMAT;
643 /* force in a delimiter after each field */
644 *bufp++ = '\0';
645 nf++;
648 *numfields = nf;
650 return 0;
654 /* DecodeDateTime()
655 * Interpret previously parsed fields for general date and time.
656 * Return 0 if full date, 1 if only time, and negative DTERR code if problems.
657 * (Currently, all callers treat 1 as an error return too.)
659 * External format(s):
660 * "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
661 * "Fri Feb-7-1997 15:23:27"
662 * "Feb-7-1997 15:23:27"
663 * "2-7-1997 15:23:27"
664 * "1997-2-7 15:23:27"
665 * "1997.038 15:23:27" (day of year 1-366)
666 * Also supports input in compact time:
667 * "970207 152327"
668 * "97038 152327"
669 * "20011225T040506.789-07"
671 * Use the system-provided functions to get the current time zone
672 * if not specified in the input string.
674 * If the date is outside the range of pg_time_t (in practice that could only
675 * happen if pg_time_t is just 32 bits), then assume UTC time zone - thomas
676 * 1997-05-27
679 DecodeDateTime(char **field, int *ftype, int nf,
680 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
682 int fmask = 0,
683 tmask,
684 type;
685 int ptype = 0; /* "prefix type" for ISO y2001m02d04 format */
686 int i;
687 int val;
688 int dterr;
689 int mer = HR24;
690 bool haveTextMonth = FALSE;
691 bool is2digits = FALSE;
692 bool bc = FALSE;
693 pg_tz *namedTz = NULL;
696 * We'll insist on at least all of the date fields, but initialize the
697 * remaining fields in case they are not set later...
699 *dtype = DTK_DATE;
700 tm->tm_hour = 0;
701 tm->tm_min = 0;
702 tm->tm_sec = 0;
703 *fsec = 0;
704 /* don't know daylight savings time status apriori */
705 tm->tm_isdst = -1;
706 if (tzp != NULL)
707 *tzp = 0;
709 for (i = 0; i < nf; i++)
711 switch (ftype[i])
713 case DTK_DATE:
714 /***
715 * Integral julian day with attached time zone?
716 * All other forms with JD will be separated into
717 * distinct fields, so we handle just this case here.
718 ***/
719 if (ptype == DTK_JULIAN)
721 char *cp;
722 int val;
724 if (tzp == NULL)
725 return DTERR_BAD_FORMAT;
727 errno = 0;
728 val = strtoi(field[i], &cp, 10);
729 if (errno == ERANGE)
730 return DTERR_FIELD_OVERFLOW;
732 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
733 /* Get the time zone from the end of the string */
734 dterr = DecodeTimezone(cp, tzp);
735 if (dterr)
736 return dterr;
738 tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
739 ptype = 0;
740 break;
742 /***
743 * Already have a date? Then this might be a time zone name
744 * with embedded punctuation (e.g. "America/New_York") or a
745 * run-together time with trailing time zone (e.g. hhmmss-zz).
746 * - thomas 2001-12-25
748 * We consider it a time zone if we already have month & day.
749 * This is to allow the form "mmm dd hhmmss tz year", which
750 * we've historically accepted.
751 ***/
752 else if (ptype != 0 ||
753 ((fmask & (DTK_M(MONTH) | DTK_M(DAY))) ==
754 (DTK_M(MONTH) | DTK_M(DAY))))
756 /* No time zone accepted? Then quit... */
757 if (tzp == NULL)
758 return DTERR_BAD_FORMAT;
760 if (isdigit((unsigned char) *field[i]) || ptype != 0)
762 char *cp;
764 if (ptype != 0)
766 /* Sanity check; should not fail this test */
767 if (ptype != DTK_TIME)
768 return DTERR_BAD_FORMAT;
769 ptype = 0;
773 * Starts with a digit but we already have a time
774 * field? Then we are in trouble with a date and time
775 * already...
777 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
778 return DTERR_BAD_FORMAT;
780 if ((cp = strchr(field[i], '-')) == NULL)
781 return DTERR_BAD_FORMAT;
783 /* Get the time zone from the end of the string */
784 dterr = DecodeTimezone(cp, tzp);
785 if (dterr)
786 return dterr;
787 *cp = '\0';
790 * Then read the rest of the field as a concatenated
791 * time
793 dterr = DecodeNumberField(strlen(field[i]), field[i],
794 fmask,
795 &tmask, tm,
796 fsec, &is2digits);
797 if (dterr < 0)
798 return dterr;
801 * modify tmask after returning from
802 * DecodeNumberField()
804 tmask |= DTK_M(TZ);
806 else
808 namedTz = pg_tzset(field[i]);
809 if (!namedTz)
812 * We should return an error code instead of
813 * ereport'ing directly, but then there is no way
814 * to report the bad time zone name.
816 ereport(ERROR,
817 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
818 errmsg("time zone \"%s\" not recognized",
819 field[i])));
821 /* we'll apply the zone setting below */
822 tmask = DTK_M(TZ);
825 else
827 dterr = DecodeDate(field[i], fmask,
828 &tmask, &is2digits, tm);
829 if (dterr)
830 return dterr;
832 break;
834 case DTK_TIME:
835 dterr = DecodeTime(field[i], fmask, &tmask, tm, fsec);
836 if (dterr)
837 return dterr;
840 * Check upper limit on hours; other limits checked in
841 * DecodeTime()
843 /* test for > 24:00:00 */
844 if (tm->tm_hour > 24 ||
845 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0)))
846 return DTERR_FIELD_OVERFLOW;
847 break;
849 case DTK_TZ:
851 int tz;
853 if (tzp == NULL)
854 return DTERR_BAD_FORMAT;
856 dterr = DecodeTimezone(field[i], &tz);
857 if (dterr)
858 return dterr;
859 *tzp = tz;
860 tmask = DTK_M(TZ);
862 break;
864 case DTK_NUMBER:
867 * Was this an "ISO date" with embedded field labels? An
868 * example is "y2001m02d04" - thomas 2001-02-04
870 if (ptype != 0)
872 char *cp;
873 int val;
875 errno = 0;
876 val = strtoi(field[i], &cp, 10);
877 if (errno == ERANGE)
878 return DTERR_FIELD_OVERFLOW;
881 * only a few kinds are allowed to have an embedded
882 * decimal
884 if (*cp == '.')
885 switch (ptype)
887 case DTK_JULIAN:
888 case DTK_TIME:
889 case DTK_SECOND:
890 break;
891 default:
892 return DTERR_BAD_FORMAT;
893 break;
895 else if (*cp != '\0')
896 return DTERR_BAD_FORMAT;
898 switch (ptype)
900 case DTK_YEAR:
901 tm->tm_year = val;
902 tmask = DTK_M(YEAR);
903 break;
905 case DTK_MONTH:
908 * already have a month and hour? then assume
909 * minutes
911 if ((fmask & DTK_M(MONTH)) != 0 &&
912 (fmask & DTK_M(HOUR)) != 0)
914 tm->tm_min = val;
915 tmask = DTK_M(MINUTE);
917 else
919 tm->tm_mon = val;
920 tmask = DTK_M(MONTH);
922 break;
924 case DTK_DAY:
925 tm->tm_mday = val;
926 tmask = DTK_M(DAY);
927 break;
929 case DTK_HOUR:
930 tm->tm_hour = val;
931 tmask = DTK_M(HOUR);
932 break;
934 case DTK_MINUTE:
935 tm->tm_min = val;
936 tmask = DTK_M(MINUTE);
937 break;
939 case DTK_SECOND:
940 tm->tm_sec = val;
941 tmask = DTK_M(SECOND);
942 if (*cp == '.')
944 double frac;
946 frac = strtod(cp, &cp);
947 if (*cp != '\0')
948 return DTERR_BAD_FORMAT;
949 #ifdef HAVE_INT64_TIMESTAMP
950 *fsec = rint(frac * 1000000);
951 #else
952 *fsec = frac;
953 #endif
954 tmask = DTK_ALL_SECS_M;
956 break;
958 case DTK_TZ:
959 tmask = DTK_M(TZ);
960 dterr = DecodeTimezone(field[i], tzp);
961 if (dterr)
962 return dterr;
963 break;
965 case DTK_JULIAN:
966 /***
967 * previous field was a label for "julian date"?
968 ***/
969 tmask = DTK_DATE_M;
970 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
971 /* fractional Julian Day? */
972 if (*cp == '.')
974 double time;
976 time = strtod(cp, &cp);
977 if (*cp != '\0')
978 return DTERR_BAD_FORMAT;
980 tmask |= DTK_TIME_M;
981 #ifdef HAVE_INT64_TIMESTAMP
982 dt2time(time * USECS_PER_DAY,
983 &tm->tm_hour, &tm->tm_min,
984 &tm->tm_sec, fsec);
985 #else
986 dt2time(time * SECS_PER_DAY, &tm->tm_hour,
987 &tm->tm_min, &tm->tm_sec, fsec);
988 #endif
990 break;
992 case DTK_TIME:
993 /* previous field was "t" for ISO time */
994 dterr = DecodeNumberField(strlen(field[i]), field[i],
995 (fmask | DTK_DATE_M),
996 &tmask, tm,
997 fsec, &is2digits);
998 if (dterr < 0)
999 return dterr;
1000 if (tmask != DTK_TIME_M)
1001 return DTERR_BAD_FORMAT;
1002 break;
1004 default:
1005 return DTERR_BAD_FORMAT;
1006 break;
1009 ptype = 0;
1010 *dtype = DTK_DATE;
1012 else
1014 char *cp;
1015 int flen;
1017 flen = strlen(field[i]);
1018 cp = strchr(field[i], '.');
1020 /* Embedded decimal and no date yet? */
1021 if (cp != NULL && !(fmask & DTK_DATE_M))
1023 dterr = DecodeDate(field[i], fmask,
1024 &tmask, &is2digits, tm);
1025 if (dterr)
1026 return dterr;
1028 /* embedded decimal and several digits before? */
1029 else if (cp != NULL && flen - strlen(cp) > 2)
1032 * Interpret as a concatenated date or time Set the
1033 * type field to allow decoding other fields later.
1034 * Example: 20011223 or 040506
1036 dterr = DecodeNumberField(flen, field[i], fmask,
1037 &tmask, tm,
1038 fsec, &is2digits);
1039 if (dterr < 0)
1040 return dterr;
1042 else if (flen > 4)
1044 dterr = DecodeNumberField(flen, field[i], fmask,
1045 &tmask, tm,
1046 fsec, &is2digits);
1047 if (dterr < 0)
1048 return dterr;
1050 /* otherwise it is a single date/time field... */
1051 else
1053 dterr = DecodeNumber(flen, field[i],
1054 haveTextMonth, fmask,
1055 &tmask, tm,
1056 fsec, &is2digits);
1057 if (dterr)
1058 return dterr;
1061 break;
1063 case DTK_STRING:
1064 case DTK_SPECIAL:
1065 type = DecodeSpecial(i, field[i], &val);
1066 if (type == IGNORE_DTF)
1067 continue;
1069 tmask = DTK_M(type);
1070 switch (type)
1072 case RESERV:
1073 switch (val)
1075 case DTK_CURRENT:
1076 ereport(ERROR,
1077 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1078 errmsg("date/time value \"current\" is no longer supported")));
1080 return DTERR_BAD_FORMAT;
1081 break;
1083 case DTK_NOW:
1084 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1085 *dtype = DTK_DATE;
1086 GetCurrentTimeUsec(tm, fsec, tzp);
1087 break;
1089 case DTK_YESTERDAY:
1090 tmask = DTK_DATE_M;
1091 *dtype = DTK_DATE;
1092 GetCurrentDateTime(tm);
1093 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - 1,
1094 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1095 tm->tm_hour = 0;
1096 tm->tm_min = 0;
1097 tm->tm_sec = 0;
1098 break;
1100 case DTK_TODAY:
1101 tmask = DTK_DATE_M;
1102 *dtype = DTK_DATE;
1103 GetCurrentDateTime(tm);
1104 tm->tm_hour = 0;
1105 tm->tm_min = 0;
1106 tm->tm_sec = 0;
1107 break;
1109 case DTK_TOMORROW:
1110 tmask = DTK_DATE_M;
1111 *dtype = DTK_DATE;
1112 GetCurrentDateTime(tm);
1113 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1,
1114 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1115 tm->tm_hour = 0;
1116 tm->tm_min = 0;
1117 tm->tm_sec = 0;
1118 break;
1120 case DTK_ZULU:
1121 tmask = (DTK_TIME_M | DTK_M(TZ));
1122 *dtype = DTK_DATE;
1123 tm->tm_hour = 0;
1124 tm->tm_min = 0;
1125 tm->tm_sec = 0;
1126 if (tzp != NULL)
1127 *tzp = 0;
1128 break;
1130 default:
1131 *dtype = val;
1134 break;
1136 case MONTH:
1139 * already have a (numeric) month? then see if we can
1140 * substitute...
1142 if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
1143 !(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 &&
1144 tm->tm_mon <= 31)
1146 tm->tm_mday = tm->tm_mon;
1147 tmask = DTK_M(DAY);
1149 haveTextMonth = TRUE;
1150 tm->tm_mon = val;
1151 break;
1153 case DTZMOD:
1156 * daylight savings time modifier (solves "MET DST"
1157 * syntax)
1159 tmask |= DTK_M(DTZ);
1160 tm->tm_isdst = 1;
1161 if (tzp == NULL)
1162 return DTERR_BAD_FORMAT;
1163 *tzp += val * MINS_PER_HOUR;
1164 break;
1166 case DTZ:
1169 * set mask for TZ here _or_ check for DTZ later when
1170 * getting default timezone
1172 tmask |= DTK_M(TZ);
1173 tm->tm_isdst = 1;
1174 if (tzp == NULL)
1175 return DTERR_BAD_FORMAT;
1176 *tzp = val * MINS_PER_HOUR;
1177 break;
1179 case TZ:
1180 tm->tm_isdst = 0;
1181 if (tzp == NULL)
1182 return DTERR_BAD_FORMAT;
1183 *tzp = val * MINS_PER_HOUR;
1184 break;
1186 case IGNORE_DTF:
1187 break;
1189 case AMPM:
1190 mer = val;
1191 break;
1193 case ADBC:
1194 bc = (val == BC);
1195 break;
1197 case DOW:
1198 tm->tm_wday = val;
1199 break;
1201 case UNITS:
1202 tmask = 0;
1203 ptype = val;
1204 break;
1206 case ISOTIME:
1209 * This is a filler field "t" indicating that the next
1210 * field is time. Try to verify that this is sensible.
1212 tmask = 0;
1214 /* No preceding date? Then quit... */
1215 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1216 return DTERR_BAD_FORMAT;
1218 /***
1219 * We will need one of the following fields:
1220 * DTK_NUMBER should be hhmmss.fff
1221 * DTK_TIME should be hh:mm:ss.fff
1222 * DTK_DATE should be hhmmss-zz
1223 ***/
1224 if (i >= nf - 1 ||
1225 (ftype[i + 1] != DTK_NUMBER &&
1226 ftype[i + 1] != DTK_TIME &&
1227 ftype[i + 1] != DTK_DATE))
1228 return DTERR_BAD_FORMAT;
1230 ptype = val;
1231 break;
1233 case UNKNOWN_FIELD:
1236 * Before giving up and declaring error, check to see
1237 * if it is an all-alpha timezone name.
1239 namedTz = pg_tzset(field[i]);
1240 if (!namedTz)
1241 return DTERR_BAD_FORMAT;
1242 /* we'll apply the zone setting below */
1243 tmask = DTK_M(TZ);
1244 break;
1246 default:
1247 return DTERR_BAD_FORMAT;
1249 break;
1251 default:
1252 return DTERR_BAD_FORMAT;
1255 if (tmask & fmask)
1256 return DTERR_BAD_FORMAT;
1257 fmask |= tmask;
1258 } /* end loop over fields */
1260 /* do final checking/adjustment of Y/M/D fields */
1261 dterr = ValidateDate(fmask, is2digits, bc, tm);
1262 if (dterr)
1263 return dterr;
1265 /* handle AM/PM */
1266 if (mer != HR24 && tm->tm_hour > 12)
1267 return DTERR_FIELD_OVERFLOW;
1268 if (mer == AM && tm->tm_hour == 12)
1269 tm->tm_hour = 0;
1270 else if (mer == PM && tm->tm_hour != 12)
1271 tm->tm_hour += 12;
1273 /* do additional checking for full date specs... */
1274 if (*dtype == DTK_DATE)
1276 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1278 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1279 return 1;
1280 return DTERR_BAD_FORMAT;
1284 * If we had a full timezone spec, compute the offset (we could not do
1285 * it before, because we need the date to resolve DST status).
1287 if (namedTz != NULL)
1289 /* daylight savings time modifier disallowed with full TZ */
1290 if (fmask & DTK_M(DTZMOD))
1291 return DTERR_BAD_FORMAT;
1293 *tzp = DetermineTimeZoneOffset(tm, namedTz);
1296 /* timezone not specified? then find local timezone if possible */
1297 if (tzp != NULL && !(fmask & DTK_M(TZ)))
1300 * daylight savings time modifier but no standard timezone? then
1301 * error
1303 if (fmask & DTK_M(DTZMOD))
1304 return DTERR_BAD_FORMAT;
1306 *tzp = DetermineTimeZoneOffset(tm, session_timezone);
1310 return 0;
1314 /* DetermineTimeZoneOffset()
1316 * Given a struct pg_tm in which tm_year, tm_mon, tm_mday, tm_hour, tm_min, and
1317 * tm_sec fields are set, attempt to determine the applicable time zone
1318 * (ie, regular or daylight-savings time) at that time. Set the struct pg_tm's
1319 * tm_isdst field accordingly, and return the actual timezone offset.
1321 * Note: it might seem that we should use mktime() for this, but bitter
1322 * experience teaches otherwise. This code is much faster than most versions
1323 * of mktime(), anyway.
1326 DetermineTimeZoneOffset(struct pg_tm * tm, pg_tz *tzp)
1328 int date,
1329 sec;
1330 pg_time_t day,
1331 mytime,
1332 prevtime,
1333 boundary,
1334 beforetime,
1335 aftertime;
1336 long int before_gmtoff,
1337 after_gmtoff;
1338 int before_isdst,
1339 after_isdst;
1340 int res;
1342 if (tzp == session_timezone && HasCTZSet)
1344 tm->tm_isdst = 0; /* for lack of a better idea */
1345 return CTimeZone;
1349 * First, generate the pg_time_t value corresponding to the given
1350 * y/m/d/h/m/s taken as GMT time. If this overflows, punt and decide the
1351 * timezone is GMT. (We only need to worry about overflow on machines
1352 * where pg_time_t is 32 bits.)
1354 if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
1355 goto overflow;
1356 date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - UNIX_EPOCH_JDATE;
1358 day = ((pg_time_t) date) * SECS_PER_DAY;
1359 if (day / SECS_PER_DAY != date)
1360 goto overflow;
1361 sec = tm->tm_sec + (tm->tm_min + tm->tm_hour * MINS_PER_HOUR) * SECS_PER_MINUTE;
1362 mytime = day + sec;
1363 /* since sec >= 0, overflow could only be from +day to -mytime */
1364 if (mytime < 0 && day > 0)
1365 goto overflow;
1368 * Find the DST time boundary just before or following the target time. We
1369 * assume that all zones have GMT offsets less than 24 hours, and that DST
1370 * boundaries can't be closer together than 48 hours, so backing up 24
1371 * hours and finding the "next" boundary will work.
1373 prevtime = mytime - SECS_PER_DAY;
1374 if (mytime < 0 && prevtime > 0)
1375 goto overflow;
1377 res = pg_next_dst_boundary(&prevtime,
1378 &before_gmtoff, &before_isdst,
1379 &boundary,
1380 &after_gmtoff, &after_isdst,
1381 tzp);
1382 if (res < 0)
1383 goto overflow; /* failure? */
1385 if (res == 0)
1387 /* Non-DST zone, life is simple */
1388 tm->tm_isdst = before_isdst;
1389 return -(int) before_gmtoff;
1393 * Form the candidate pg_time_t values with local-time adjustment
1395 beforetime = mytime - before_gmtoff;
1396 if ((before_gmtoff > 0 &&
1397 mytime < 0 && beforetime > 0) ||
1398 (before_gmtoff <= 0 &&
1399 mytime > 0 && beforetime < 0))
1400 goto overflow;
1401 aftertime = mytime - after_gmtoff;
1402 if ((after_gmtoff > 0 &&
1403 mytime < 0 && aftertime > 0) ||
1404 (after_gmtoff <= 0 &&
1405 mytime > 0 && aftertime < 0))
1406 goto overflow;
1409 * If both before or both after the boundary time, we know what to do
1411 if (beforetime <= boundary && aftertime < boundary)
1413 tm->tm_isdst = before_isdst;
1414 return -(int) before_gmtoff;
1416 if (beforetime > boundary && aftertime >= boundary)
1418 tm->tm_isdst = after_isdst;
1419 return -(int) after_gmtoff;
1423 * It's an invalid or ambiguous time due to timezone transition. Prefer
1424 * the standard-time interpretation.
1426 if (after_isdst == 0)
1428 tm->tm_isdst = after_isdst;
1429 return -(int) after_gmtoff;
1431 tm->tm_isdst = before_isdst;
1432 return -(int) before_gmtoff;
1434 overflow:
1435 /* Given date is out of range, so assume UTC */
1436 tm->tm_isdst = 0;
1437 return 0;
1441 /* DecodeTimeOnly()
1442 * Interpret parsed string as time fields only.
1443 * Returns 0 if successful, DTERR code if bogus input detected.
1445 * Note that support for time zone is here for
1446 * SQL92 TIME WITH TIME ZONE, but it reveals
1447 * bogosity with SQL92 date/time standards, since
1448 * we must infer a time zone from current time.
1449 * - thomas 2000-03-10
1450 * Allow specifying date to get a better time zone,
1451 * if time zones are allowed. - thomas 2001-12-26
1454 DecodeTimeOnly(char **field, int *ftype, int nf,
1455 int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
1457 int fmask = 0,
1458 tmask,
1459 type;
1460 int ptype = 0; /* "prefix type" for ISO h04mm05s06 format */
1461 int i;
1462 int val;
1463 int dterr;
1464 bool is2digits = FALSE;
1465 bool bc = FALSE;
1466 int mer = HR24;
1467 pg_tz *namedTz = NULL;
1469 *dtype = DTK_TIME;
1470 tm->tm_hour = 0;
1471 tm->tm_min = 0;
1472 tm->tm_sec = 0;
1473 *fsec = 0;
1474 /* don't know daylight savings time status apriori */
1475 tm->tm_isdst = -1;
1477 if (tzp != NULL)
1478 *tzp = 0;
1480 for (i = 0; i < nf; i++)
1482 switch (ftype[i])
1484 case DTK_DATE:
1487 * Time zone not allowed? Then should not accept dates or time
1488 * zones no matter what else!
1490 if (tzp == NULL)
1491 return DTERR_BAD_FORMAT;
1493 /* Under limited circumstances, we will accept a date... */
1494 if (i == 0 && nf >= 2 &&
1495 (ftype[nf - 1] == DTK_DATE || ftype[1] == DTK_TIME))
1497 dterr = DecodeDate(field[i], fmask,
1498 &tmask, &is2digits, tm);
1499 if (dterr)
1500 return dterr;
1502 /* otherwise, this is a time and/or time zone */
1503 else
1505 if (isdigit((unsigned char) *field[i]))
1507 char *cp;
1510 * Starts with a digit but we already have a time
1511 * field? Then we are in trouble with time already...
1513 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1514 return DTERR_BAD_FORMAT;
1517 * Should not get here and fail. Sanity check only...
1519 if ((cp = strchr(field[i], '-')) == NULL)
1520 return DTERR_BAD_FORMAT;
1522 /* Get the time zone from the end of the string */
1523 dterr = DecodeTimezone(cp, tzp);
1524 if (dterr)
1525 return dterr;
1526 *cp = '\0';
1529 * Then read the rest of the field as a concatenated
1530 * time
1532 dterr = DecodeNumberField(strlen(field[i]), field[i],
1533 (fmask | DTK_DATE_M),
1534 &tmask, tm,
1535 fsec, &is2digits);
1536 if (dterr < 0)
1537 return dterr;
1538 ftype[i] = dterr;
1540 tmask |= DTK_M(TZ);
1542 else
1544 namedTz = pg_tzset(field[i]);
1545 if (!namedTz)
1548 * We should return an error code instead of
1549 * ereport'ing directly, but then there is no way
1550 * to report the bad time zone name.
1552 ereport(ERROR,
1553 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1554 errmsg("time zone \"%s\" not recognized",
1555 field[i])));
1557 /* we'll apply the zone setting below */
1558 ftype[i] = DTK_TZ;
1559 tmask = DTK_M(TZ);
1562 break;
1564 case DTK_TIME:
1565 dterr = DecodeTime(field[i], (fmask | DTK_DATE_M),
1566 &tmask, tm, fsec);
1567 if (dterr)
1568 return dterr;
1569 break;
1571 case DTK_TZ:
1573 int tz;
1575 if (tzp == NULL)
1576 return DTERR_BAD_FORMAT;
1578 dterr = DecodeTimezone(field[i], &tz);
1579 if (dterr)
1580 return dterr;
1581 *tzp = tz;
1582 tmask = DTK_M(TZ);
1584 break;
1586 case DTK_NUMBER:
1589 * Was this an "ISO time" with embedded field labels? An
1590 * example is "h04m05s06" - thomas 2001-02-04
1592 if (ptype != 0)
1594 char *cp;
1595 int val;
1597 /* Only accept a date under limited circumstances */
1598 switch (ptype)
1600 case DTK_JULIAN:
1601 case DTK_YEAR:
1602 case DTK_MONTH:
1603 case DTK_DAY:
1604 if (tzp == NULL)
1605 return DTERR_BAD_FORMAT;
1606 default:
1607 break;
1610 errno = 0;
1611 val = strtoi(field[i], &cp, 10);
1612 if (errno == ERANGE)
1613 return DTERR_FIELD_OVERFLOW;
1616 * only a few kinds are allowed to have an embedded
1617 * decimal
1619 if (*cp == '.')
1620 switch (ptype)
1622 case DTK_JULIAN:
1623 case DTK_TIME:
1624 case DTK_SECOND:
1625 break;
1626 default:
1627 return DTERR_BAD_FORMAT;
1628 break;
1630 else if (*cp != '\0')
1631 return DTERR_BAD_FORMAT;
1633 switch (ptype)
1635 case DTK_YEAR:
1636 tm->tm_year = val;
1637 tmask = DTK_M(YEAR);
1638 break;
1640 case DTK_MONTH:
1643 * already have a month and hour? then assume
1644 * minutes
1646 if ((fmask & DTK_M(MONTH)) != 0 &&
1647 (fmask & DTK_M(HOUR)) != 0)
1649 tm->tm_min = val;
1650 tmask = DTK_M(MINUTE);
1652 else
1654 tm->tm_mon = val;
1655 tmask = DTK_M(MONTH);
1657 break;
1659 case DTK_DAY:
1660 tm->tm_mday = val;
1661 tmask = DTK_M(DAY);
1662 break;
1664 case DTK_HOUR:
1665 tm->tm_hour = val;
1666 tmask = DTK_M(HOUR);
1667 break;
1669 case DTK_MINUTE:
1670 tm->tm_min = val;
1671 tmask = DTK_M(MINUTE);
1672 break;
1674 case DTK_SECOND:
1675 tm->tm_sec = val;
1676 tmask = DTK_M(SECOND);
1677 if (*cp == '.')
1679 double frac;
1681 frac = strtod(cp, &cp);
1682 if (*cp != '\0')
1683 return DTERR_BAD_FORMAT;
1684 #ifdef HAVE_INT64_TIMESTAMP
1685 *fsec = rint(frac * 1000000);
1686 #else
1687 *fsec = frac;
1688 #endif
1689 tmask = DTK_ALL_SECS_M;
1691 break;
1693 case DTK_TZ:
1694 tmask = DTK_M(TZ);
1695 dterr = DecodeTimezone(field[i], tzp);
1696 if (dterr)
1697 return dterr;
1698 break;
1700 case DTK_JULIAN:
1701 /***
1702 * previous field was a label for "julian date"?
1703 ***/
1704 tmask = DTK_DATE_M;
1705 j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1706 if (*cp == '.')
1708 double time;
1710 time = strtod(cp, &cp);
1711 if (*cp != '\0')
1712 return DTERR_BAD_FORMAT;
1714 tmask |= DTK_TIME_M;
1715 #ifdef HAVE_INT64_TIMESTAMP
1716 dt2time(time * USECS_PER_DAY,
1717 &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1718 #else
1719 dt2time(time * SECS_PER_DAY,
1720 &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1721 #endif
1723 break;
1725 case DTK_TIME:
1726 /* previous field was "t" for ISO time */
1727 dterr = DecodeNumberField(strlen(field[i]), field[i],
1728 (fmask | DTK_DATE_M),
1729 &tmask, tm,
1730 fsec, &is2digits);
1731 if (dterr < 0)
1732 return dterr;
1733 ftype[i] = dterr;
1735 if (tmask != DTK_TIME_M)
1736 return DTERR_BAD_FORMAT;
1737 break;
1739 default:
1740 return DTERR_BAD_FORMAT;
1741 break;
1744 ptype = 0;
1745 *dtype = DTK_DATE;
1747 else
1749 char *cp;
1750 int flen;
1752 flen = strlen(field[i]);
1753 cp = strchr(field[i], '.');
1755 /* Embedded decimal? */
1756 if (cp != NULL)
1759 * Under limited circumstances, we will accept a
1760 * date...
1762 if (i == 0 && nf >= 2 && ftype[nf - 1] == DTK_DATE)
1764 dterr = DecodeDate(field[i], fmask,
1765 &tmask, &is2digits, tm);
1766 if (dterr)
1767 return dterr;
1769 /* embedded decimal and several digits before? */
1770 else if (flen - strlen(cp) > 2)
1773 * Interpret as a concatenated date or time Set
1774 * the type field to allow decoding other fields
1775 * later. Example: 20011223 or 040506
1777 dterr = DecodeNumberField(flen, field[i],
1778 (fmask | DTK_DATE_M),
1779 &tmask, tm,
1780 fsec, &is2digits);
1781 if (dterr < 0)
1782 return dterr;
1783 ftype[i] = dterr;
1785 else
1786 return DTERR_BAD_FORMAT;
1788 else if (flen > 4)
1790 dterr = DecodeNumberField(flen, field[i],
1791 (fmask | DTK_DATE_M),
1792 &tmask, tm,
1793 fsec, &is2digits);
1794 if (dterr < 0)
1795 return dterr;
1796 ftype[i] = dterr;
1798 /* otherwise it is a single date/time field... */
1799 else
1801 dterr = DecodeNumber(flen, field[i],
1802 FALSE,
1803 (fmask | DTK_DATE_M),
1804 &tmask, tm,
1805 fsec, &is2digits);
1806 if (dterr)
1807 return dterr;
1810 break;
1812 case DTK_STRING:
1813 case DTK_SPECIAL:
1814 type = DecodeSpecial(i, field[i], &val);
1815 if (type == IGNORE_DTF)
1816 continue;
1818 tmask = DTK_M(type);
1819 switch (type)
1821 case RESERV:
1822 switch (val)
1824 case DTK_CURRENT:
1825 ereport(ERROR,
1826 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1827 errmsg("date/time value \"current\" is no longer supported")));
1828 return DTERR_BAD_FORMAT;
1829 break;
1831 case DTK_NOW:
1832 tmask = DTK_TIME_M;
1833 *dtype = DTK_TIME;
1834 GetCurrentTimeUsec(tm, fsec, NULL);
1835 break;
1837 case DTK_ZULU:
1838 tmask = (DTK_TIME_M | DTK_M(TZ));
1839 *dtype = DTK_TIME;
1840 tm->tm_hour = 0;
1841 tm->tm_min = 0;
1842 tm->tm_sec = 0;
1843 tm->tm_isdst = 0;
1844 break;
1846 default:
1847 return DTERR_BAD_FORMAT;
1850 break;
1852 case DTZMOD:
1855 * daylight savings time modifier (solves "MET DST"
1856 * syntax)
1858 tmask |= DTK_M(DTZ);
1859 tm->tm_isdst = 1;
1860 if (tzp == NULL)
1861 return DTERR_BAD_FORMAT;
1862 *tzp += val * MINS_PER_HOUR;
1863 break;
1865 case DTZ:
1868 * set mask for TZ here _or_ check for DTZ later when
1869 * getting default timezone
1871 tmask |= DTK_M(TZ);
1872 tm->tm_isdst = 1;
1873 if (tzp == NULL)
1874 return DTERR_BAD_FORMAT;
1875 *tzp = val * MINS_PER_HOUR;
1876 ftype[i] = DTK_TZ;
1877 break;
1879 case TZ:
1880 tm->tm_isdst = 0;
1881 if (tzp == NULL)
1882 return DTERR_BAD_FORMAT;
1883 *tzp = val * MINS_PER_HOUR;
1884 ftype[i] = DTK_TZ;
1885 break;
1887 case IGNORE_DTF:
1888 break;
1890 case AMPM:
1891 mer = val;
1892 break;
1894 case ADBC:
1895 bc = (val == BC);
1896 break;
1898 case UNITS:
1899 tmask = 0;
1900 ptype = val;
1901 break;
1903 case ISOTIME:
1904 tmask = 0;
1906 /***
1907 * We will need one of the following fields:
1908 * DTK_NUMBER should be hhmmss.fff
1909 * DTK_TIME should be hh:mm:ss.fff
1910 * DTK_DATE should be hhmmss-zz
1911 ***/
1912 if (i >= nf - 1 ||
1913 (ftype[i + 1] != DTK_NUMBER &&
1914 ftype[i + 1] != DTK_TIME &&
1915 ftype[i + 1] != DTK_DATE))
1916 return DTERR_BAD_FORMAT;
1918 ptype = val;
1919 break;
1921 case UNKNOWN_FIELD:
1924 * Before giving up and declaring error, check to see
1925 * if it is an all-alpha timezone name.
1927 namedTz = pg_tzset(field[i]);
1928 if (!namedTz)
1929 return DTERR_BAD_FORMAT;
1930 /* we'll apply the zone setting below */
1931 tmask = DTK_M(TZ);
1932 break;
1934 default:
1935 return DTERR_BAD_FORMAT;
1937 break;
1939 default:
1940 return DTERR_BAD_FORMAT;
1943 if (tmask & fmask)
1944 return DTERR_BAD_FORMAT;
1945 fmask |= tmask;
1946 } /* end loop over fields */
1948 /* do final checking/adjustment of Y/M/D fields */
1949 dterr = ValidateDate(fmask, is2digits, bc, tm);
1950 if (dterr)
1951 return dterr;
1953 /* handle AM/PM */
1954 if (mer != HR24 && tm->tm_hour > 12)
1955 return DTERR_FIELD_OVERFLOW;
1956 if (mer == AM && tm->tm_hour == 12)
1957 tm->tm_hour = 0;
1958 else if (mer == PM && tm->tm_hour != 12)
1959 tm->tm_hour += 12;
1961 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
1962 tm->tm_sec < 0 || tm->tm_sec > 60 || tm->tm_hour > 24 ||
1963 /* test for > 24:00:00 */
1964 #ifdef HAVE_INT64_TIMESTAMP
1965 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0 ||
1966 *fsec > INT64CONST(0))) ||
1967 *fsec < INT64CONST(0) || *fsec >= USECS_PER_SEC
1968 #else
1969 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0 ||
1970 *fsec > 0)) ||
1971 *fsec < 0 || *fsec >= 1
1972 #endif
1974 return DTERR_FIELD_OVERFLOW;
1976 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
1977 return DTERR_BAD_FORMAT;
1980 * If we had a full timezone spec, compute the offset (we could not do it
1981 * before, because we may need the date to resolve DST status).
1983 if (namedTz != NULL)
1985 long int gmtoff;
1987 /* daylight savings time modifier disallowed with full TZ */
1988 if (fmask & DTK_M(DTZMOD))
1989 return DTERR_BAD_FORMAT;
1991 /* if non-DST zone, we do not need to know the date */
1992 if (pg_get_timezone_offset(namedTz, &gmtoff))
1994 *tzp = -(int) gmtoff;
1996 else
1998 /* a date has to be specified */
1999 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2000 return DTERR_BAD_FORMAT;
2001 *tzp = DetermineTimeZoneOffset(tm, namedTz);
2005 /* timezone not specified? then find local timezone if possible */
2006 if (tzp != NULL && !(fmask & DTK_M(TZ)))
2008 struct pg_tm tt,
2009 *tmp = &tt;
2012 * daylight savings time modifier but no standard timezone? then error
2014 if (fmask & DTK_M(DTZMOD))
2015 return DTERR_BAD_FORMAT;
2017 if ((fmask & DTK_DATE_M) == 0)
2018 GetCurrentDateTime(tmp);
2019 else
2021 tmp->tm_year = tm->tm_year;
2022 tmp->tm_mon = tm->tm_mon;
2023 tmp->tm_mday = tm->tm_mday;
2025 tmp->tm_hour = tm->tm_hour;
2026 tmp->tm_min = tm->tm_min;
2027 tmp->tm_sec = tm->tm_sec;
2028 *tzp = DetermineTimeZoneOffset(tmp, session_timezone);
2029 tm->tm_isdst = tmp->tm_isdst;
2032 return 0;
2035 /* DecodeDate()
2036 * Decode date string which includes delimiters.
2037 * Return 0 if okay, a DTERR code if not.
2039 * str: field to be parsed
2040 * fmask: bitmask for field types already seen
2041 * *tmask: receives bitmask for fields found here
2042 * *is2digits: set to TRUE if we find 2-digit year
2043 * *tm: field values are stored into appropriate members of this struct
2045 static int
2046 DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
2047 struct pg_tm * tm)
2049 fsec_t fsec;
2050 int nf = 0;
2051 int i,
2052 len;
2053 int dterr;
2054 bool haveTextMonth = FALSE;
2055 int type,
2056 val,
2057 dmask = 0;
2058 char *field[MAXDATEFIELDS];
2060 *tmask = 0;
2062 /* parse this string... */
2063 while (*str != '\0' && nf < MAXDATEFIELDS)
2065 /* skip field separators */
2066 while (!isalnum((unsigned char) *str))
2067 str++;
2069 field[nf] = str;
2070 if (isdigit((unsigned char) *str))
2072 while (isdigit((unsigned char) *str))
2073 str++;
2075 else if (isalpha((unsigned char) *str))
2077 while (isalpha((unsigned char) *str))
2078 str++;
2081 /* Just get rid of any non-digit, non-alpha characters... */
2082 if (*str != '\0')
2083 *str++ = '\0';
2084 nf++;
2087 /* look first for text fields, since that will be unambiguous month */
2088 for (i = 0; i < nf; i++)
2090 if (isalpha((unsigned char) *field[i]))
2092 type = DecodeSpecial(i, field[i], &val);
2093 if (type == IGNORE_DTF)
2094 continue;
2096 dmask = DTK_M(type);
2097 switch (type)
2099 case MONTH:
2100 tm->tm_mon = val;
2101 haveTextMonth = TRUE;
2102 break;
2104 default:
2105 return DTERR_BAD_FORMAT;
2107 if (fmask & dmask)
2108 return DTERR_BAD_FORMAT;
2110 fmask |= dmask;
2111 *tmask |= dmask;
2113 /* mark this field as being completed */
2114 field[i] = NULL;
2118 /* now pick up remaining numeric fields */
2119 for (i = 0; i < nf; i++)
2121 if (field[i] == NULL)
2122 continue;
2124 if ((len = strlen(field[i])) <= 0)
2125 return DTERR_BAD_FORMAT;
2127 dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2128 &dmask, tm,
2129 &fsec, is2digits);
2130 if (dterr)
2131 return dterr;
2133 if (fmask & dmask)
2134 return DTERR_BAD_FORMAT;
2136 fmask |= dmask;
2137 *tmask |= dmask;
2140 if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
2141 return DTERR_BAD_FORMAT;
2143 /* validation of the field values must wait until ValidateDate() */
2145 return 0;
2148 /* ValidateDate()
2149 * Check valid year/month/day values, handle BC and DOY cases
2150 * Return 0 if okay, a DTERR code if not.
2152 static int
2153 ValidateDate(int fmask, bool is2digits, bool bc, struct pg_tm * tm)
2155 if (fmask & DTK_M(YEAR))
2157 if (bc)
2159 /* there is no year zero in AD/BC notation */
2160 if (tm->tm_year <= 0)
2161 return DTERR_FIELD_OVERFLOW;
2162 /* internally, we represent 1 BC as year zero, 2 BC as -1, etc */
2163 tm->tm_year = -(tm->tm_year - 1);
2165 else if (is2digits)
2167 /* allow 2-digit input for 1970-2069 AD; 00 is allowed */
2168 if (tm->tm_year < 0) /* just paranoia */
2169 return DTERR_FIELD_OVERFLOW;
2170 if (tm->tm_year < 70)
2171 tm->tm_year += 2000;
2172 else if (tm->tm_year < 100)
2173 tm->tm_year += 1900;
2175 else
2177 /* there is no year zero in AD/BC notation */
2178 if (tm->tm_year <= 0)
2179 return DTERR_FIELD_OVERFLOW;
2183 /* now that we have correct year, decode DOY */
2184 if (fmask & DTK_M(DOY))
2186 j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
2187 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2190 /* check for valid month */
2191 if (fmask & DTK_M(MONTH))
2193 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
2194 return DTERR_MD_FIELD_OVERFLOW;
2197 /* minimal check for valid day */
2198 if (fmask & DTK_M(DAY))
2200 if (tm->tm_mday < 1 || tm->tm_mday > 31)
2201 return DTERR_MD_FIELD_OVERFLOW;
2204 if ((fmask & DTK_DATE_M) == DTK_DATE_M)
2207 * Check for valid day of month, now that we know for sure the month
2208 * and year. Note we don't use MD_FIELD_OVERFLOW here, since it seems
2209 * unlikely that "Feb 29" is a YMD-order error.
2211 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2212 return DTERR_FIELD_OVERFLOW;
2215 return 0;
2219 /* DecodeTime()
2220 * Decode time string which includes delimiters.
2221 * Return 0 if okay, a DTERR code if not.
2223 * Only check the lower limit on hours, since this same code can be
2224 * used to represent time spans.
2226 static int
2227 DecodeTime(char *str, int fmask, int *tmask, struct pg_tm * tm, fsec_t *fsec)
2229 char *cp;
2231 *tmask = DTK_TIME_M;
2233 errno = 0;
2234 tm->tm_hour = strtoi(str, &cp, 10);
2235 if (errno == ERANGE)
2236 return DTERR_FIELD_OVERFLOW;
2237 if (*cp != ':')
2238 return DTERR_BAD_FORMAT;
2239 str = cp + 1;
2240 errno = 0;
2241 tm->tm_min = strtoi(str, &cp, 10);
2242 if (errno == ERANGE)
2243 return DTERR_FIELD_OVERFLOW;
2244 if (*cp == '\0')
2246 tm->tm_sec = 0;
2247 *fsec = 0;
2249 else if (*cp != ':')
2250 return DTERR_BAD_FORMAT;
2251 else
2253 str = cp + 1;
2254 errno = 0;
2255 tm->tm_sec = strtoi(str, &cp, 10);
2256 if (errno == ERANGE)
2257 return DTERR_FIELD_OVERFLOW;
2258 if (*cp == '\0')
2259 *fsec = 0;
2260 else if (*cp == '.')
2262 double frac;
2264 str = cp;
2265 frac = strtod(str, &cp);
2266 if (*cp != '\0')
2267 return DTERR_BAD_FORMAT;
2268 #ifdef HAVE_INT64_TIMESTAMP
2269 *fsec = rint(frac * 1000000);
2270 #else
2271 *fsec = frac;
2272 #endif
2274 else
2275 return DTERR_BAD_FORMAT;
2278 /* do a sanity check */
2279 #ifdef HAVE_INT64_TIMESTAMP
2280 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2281 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < INT64CONST(0) ||
2282 *fsec >= USECS_PER_SEC)
2283 return DTERR_FIELD_OVERFLOW;
2284 #else
2285 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2286 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < 0 || *fsec >= 1)
2287 return DTERR_FIELD_OVERFLOW;
2288 #endif
2290 return 0;
2294 /* DecodeNumber()
2295 * Interpret plain numeric field as a date value in context.
2296 * Return 0 if okay, a DTERR code if not.
2298 static int
2299 DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask,
2300 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2302 int val;
2303 char *cp;
2304 int dterr;
2306 *tmask = 0;
2308 errno = 0;
2309 val = strtoi(str, &cp, 10);
2310 if (errno == ERANGE)
2311 return DTERR_FIELD_OVERFLOW;
2312 if (cp == str)
2313 return DTERR_BAD_FORMAT;
2315 if (*cp == '.')
2317 double frac;
2320 * More than two digits before decimal point? Then could be a date or
2321 * a run-together time: 2001.360 20011225 040506.789
2323 if (cp - str > 2)
2325 dterr = DecodeNumberField(flen, str,
2326 (fmask | DTK_DATE_M),
2327 tmask, tm,
2328 fsec, is2digits);
2329 if (dterr < 0)
2330 return dterr;
2331 return 0;
2334 frac = strtod(cp, &cp);
2335 if (*cp != '\0')
2336 return DTERR_BAD_FORMAT;
2337 #ifdef HAVE_INT64_TIMESTAMP
2338 *fsec = rint(frac * 1000000);
2339 #else
2340 *fsec = frac;
2341 #endif
2343 else if (*cp != '\0')
2344 return DTERR_BAD_FORMAT;
2346 /* Special case for day of year */
2347 if (flen == 3 && (fmask & DTK_DATE_M) == DTK_M(YEAR) && val >= 1 &&
2348 val <= 366)
2350 *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2351 tm->tm_yday = val;
2352 /* tm_mon and tm_mday can't actually be set yet ... */
2353 return 0;
2356 /* Switch based on what we have so far */
2357 switch (fmask & DTK_DATE_M)
2359 case 0:
2362 * Nothing so far; make a decision about what we think the input
2363 * is. There used to be lots of heuristics here, but the
2364 * consensus now is to be paranoid. It *must* be either
2365 * YYYY-MM-DD (with a more-than-two-digit year field), or the
2366 * field order defined by DateOrder.
2368 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2370 *tmask = DTK_M(YEAR);
2371 tm->tm_year = val;
2373 else if (DateOrder == DATEORDER_DMY)
2375 *tmask = DTK_M(DAY);
2376 tm->tm_mday = val;
2378 else
2380 *tmask = DTK_M(MONTH);
2381 tm->tm_mon = val;
2383 break;
2385 case (DTK_M(YEAR)):
2386 /* Must be at second field of YY-MM-DD */
2387 *tmask = DTK_M(MONTH);
2388 tm->tm_mon = val;
2389 break;
2391 case (DTK_M(MONTH)):
2392 if (haveTextMonth)
2395 * We are at the first numeric field of a date that included a
2396 * textual month name. We want to support the variants
2397 * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2398 * inputs. We will also accept MON-DD-YY or DD-MON-YY in
2399 * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2401 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2403 *tmask = DTK_M(YEAR);
2404 tm->tm_year = val;
2406 else
2408 *tmask = DTK_M(DAY);
2409 tm->tm_mday = val;
2412 else
2414 /* Must be at second field of MM-DD-YY */
2415 *tmask = DTK_M(DAY);
2416 tm->tm_mday = val;
2418 break;
2420 case (DTK_M(YEAR) | DTK_M(MONTH)):
2421 if (haveTextMonth)
2423 /* Need to accept DD-MON-YYYY even in YMD mode */
2424 if (flen >= 3 && *is2digits)
2426 /* Guess that first numeric field is day was wrong */
2427 *tmask = DTK_M(DAY); /* YEAR is already set */
2428 tm->tm_mday = tm->tm_year;
2429 tm->tm_year = val;
2430 *is2digits = FALSE;
2432 else
2434 *tmask = DTK_M(DAY);
2435 tm->tm_mday = val;
2438 else
2440 /* Must be at third field of YY-MM-DD */
2441 *tmask = DTK_M(DAY);
2442 tm->tm_mday = val;
2444 break;
2446 case (DTK_M(DAY)):
2447 /* Must be at second field of DD-MM-YY */
2448 *tmask = DTK_M(MONTH);
2449 tm->tm_mon = val;
2450 break;
2452 case (DTK_M(MONTH) | DTK_M(DAY)):
2453 /* Must be at third field of DD-MM-YY or MM-DD-YY */
2454 *tmask = DTK_M(YEAR);
2455 tm->tm_year = val;
2456 break;
2458 case (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY)):
2459 /* we have all the date, so it must be a time field */
2460 dterr = DecodeNumberField(flen, str, fmask,
2461 tmask, tm,
2462 fsec, is2digits);
2463 if (dterr < 0)
2464 return dterr;
2465 return 0;
2467 default:
2468 /* Anything else is bogus input */
2469 return DTERR_BAD_FORMAT;
2473 * When processing a year field, mark it for adjustment if it's only one
2474 * or two digits.
2476 if (*tmask == DTK_M(YEAR))
2477 *is2digits = (flen <= 2);
2479 return 0;
2483 /* DecodeNumberField()
2484 * Interpret numeric string as a concatenated date or time field.
2485 * Return a DTK token (>= 0) if successful, a DTERR code (< 0) if not.
2487 * Use the context of previously decoded fields to help with
2488 * the interpretation.
2490 static int
2491 DecodeNumberField(int len, char *str, int fmask,
2492 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2494 char *cp;
2497 * Have a decimal point? Then this is a date or something with a seconds
2498 * field...
2500 if ((cp = strchr(str, '.')) != NULL)
2502 double frac;
2504 frac = strtod(cp, NULL);
2505 #ifdef HAVE_INT64_TIMESTAMP
2506 *fsec = rint(frac * 1000000);
2507 #else
2508 *fsec = frac;
2509 #endif
2510 *cp = '\0';
2511 len = strlen(str);
2513 /* No decimal point and no complete date yet? */
2514 else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2516 /* yyyymmdd? */
2517 if (len == 8)
2519 *tmask = DTK_DATE_M;
2521 tm->tm_mday = atoi(str + 6);
2522 *(str + 6) = '\0';
2523 tm->tm_mon = atoi(str + 4);
2524 *(str + 4) = '\0';
2525 tm->tm_year = atoi(str + 0);
2527 return DTK_DATE;
2529 /* yymmdd? */
2530 else if (len == 6)
2532 *tmask = DTK_DATE_M;
2533 tm->tm_mday = atoi(str + 4);
2534 *(str + 4) = '\0';
2535 tm->tm_mon = atoi(str + 2);
2536 *(str + 2) = '\0';
2537 tm->tm_year = atoi(str + 0);
2538 *is2digits = TRUE;
2540 return DTK_DATE;
2544 /* not all time fields are specified? */
2545 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2547 /* hhmmss */
2548 if (len == 6)
2550 *tmask = DTK_TIME_M;
2551 tm->tm_sec = atoi(str + 4);
2552 *(str + 4) = '\0';
2553 tm->tm_min = atoi(str + 2);
2554 *(str + 2) = '\0';
2555 tm->tm_hour = atoi(str + 0);
2557 return DTK_TIME;
2559 /* hhmm? */
2560 else if (len == 4)
2562 *tmask = DTK_TIME_M;
2563 tm->tm_sec = 0;
2564 tm->tm_min = atoi(str + 2);
2565 *(str + 2) = '\0';
2566 tm->tm_hour = atoi(str + 0);
2568 return DTK_TIME;
2572 return DTERR_BAD_FORMAT;
2576 /* DecodeTimezone()
2577 * Interpret string as a numeric timezone.
2579 * Return 0 if okay (and set *tzp), a DTERR code if not okay.
2581 * NB: this must *not* ereport on failure; see commands/variable.c.
2583 * Note: we allow timezone offsets up to 13:59. There are places that
2584 * use +1300 summer time.
2586 static int
2587 DecodeTimezone(char *str, int *tzp)
2589 int tz;
2590 int hr,
2591 min,
2592 sec = 0;
2593 char *cp;
2595 /* leading character must be "+" or "-" */
2596 if (*str != '+' && *str != '-')
2597 return DTERR_BAD_FORMAT;
2599 errno = 0;
2600 hr = strtoi(str + 1, &cp, 10);
2601 if (errno == ERANGE)
2602 return DTERR_TZDISP_OVERFLOW;
2604 /* explicit delimiter? */
2605 if (*cp == ':')
2607 errno = 0;
2608 min = strtoi(cp + 1, &cp, 10);
2609 if (errno == ERANGE)
2610 return DTERR_TZDISP_OVERFLOW;
2611 if (*cp == ':')
2613 errno = 0;
2614 sec = strtoi(cp + 1, &cp, 10);
2615 if (errno == ERANGE)
2616 return DTERR_TZDISP_OVERFLOW;
2619 /* otherwise, might have run things together... */
2620 else if (*cp == '\0' && strlen(str) > 3)
2622 min = hr % 100;
2623 hr = hr / 100;
2624 /* we could, but don't, support a run-together hhmmss format */
2626 else
2627 min = 0;
2629 if (hr < 0 || hr > 14)
2630 return DTERR_TZDISP_OVERFLOW;
2631 if (min < 0 || min >= 60)
2632 return DTERR_TZDISP_OVERFLOW;
2633 if (sec < 0 || sec >= 60)
2634 return DTERR_TZDISP_OVERFLOW;
2636 tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
2637 if (*str == '-')
2638 tz = -tz;
2640 *tzp = -tz;
2642 if (*cp != '\0')
2643 return DTERR_BAD_FORMAT;
2645 return 0;
2648 /* DecodeSpecial()
2649 * Decode text string using lookup table.
2651 * Implement a cache lookup since it is likely that dates
2652 * will be related in format.
2654 * NB: this must *not* ereport on failure;
2655 * see commands/variable.c.
2658 DecodeSpecial(int field, char *lowtoken, int *val)
2660 int type;
2661 const datetkn *tp;
2663 tp = datecache[field];
2664 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
2666 tp = datebsearch(lowtoken, timezonetktbl, sztimezonetktbl);
2667 if (tp == NULL)
2668 tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
2670 if (tp == NULL)
2672 type = UNKNOWN_FIELD;
2673 *val = 0;
2675 else
2677 datecache[field] = tp;
2678 type = tp->type;
2679 switch (type)
2681 case TZ:
2682 case DTZ:
2683 case DTZMOD:
2684 *val = FROMVAL(tp);
2685 break;
2687 default:
2688 *val = tp->value;
2689 break;
2693 return type;
2697 /* DecodeInterval()
2698 * Interpret previously parsed fields for general time interval.
2699 * Returns 0 if successful, DTERR code if bogus input detected.
2701 * Allow "date" field DTK_DATE since this could be just
2702 * an unsigned floating point number. - thomas 1997-11-16
2704 * Allow ISO-style time span, with implicit units on number of days
2705 * preceding an hh:mm:ss field. - thomas 1998-04-30
2708 DecodeInterval(char **field, int *ftype, int nf, int *dtype, struct pg_tm * tm, fsec_t *fsec)
2710 bool is_before = FALSE;
2711 char *cp;
2712 int fmask = 0,
2713 tmask,
2714 type;
2715 int i;
2716 int dterr;
2717 int val;
2718 double fval;
2720 *dtype = DTK_DELTA;
2722 type = IGNORE_DTF;
2723 tm->tm_year = 0;
2724 tm->tm_mon = 0;
2725 tm->tm_mday = 0;
2726 tm->tm_hour = 0;
2727 tm->tm_min = 0;
2728 tm->tm_sec = 0;
2729 *fsec = 0;
2731 /* read through list backwards to pick up units before values */
2732 for (i = nf - 1; i >= 0; i--)
2734 switch (ftype[i])
2736 case DTK_TIME:
2737 dterr = DecodeTime(field[i], fmask, &tmask, tm, fsec);
2738 if (dterr)
2739 return dterr;
2740 type = DTK_DAY;
2741 break;
2743 case DTK_TZ:
2746 * Timezone is a token with a leading sign character and
2747 * otherwise the same as a non-signed time field
2749 Assert(*field[i] == '-' || *field[i] == '+');
2752 * A single signed number ends up here, but will be rejected
2753 * by DecodeTime(). So, work this out to drop through to
2754 * DTK_NUMBER, which *can* tolerate this.
2756 cp = field[i] + 1;
2757 while (*cp != '\0' && *cp != ':' && *cp != '.')
2758 cp++;
2759 if (*cp == ':' &&
2760 DecodeTime(field[i] + 1, fmask, &tmask, tm, fsec) == 0)
2762 if (*field[i] == '-')
2764 /* flip the sign on all fields */
2765 tm->tm_hour = -tm->tm_hour;
2766 tm->tm_min = -tm->tm_min;
2767 tm->tm_sec = -tm->tm_sec;
2768 *fsec = -(*fsec);
2772 * Set the next type to be a day, if units are not
2773 * specified. This handles the case of '1 +02:03' since we
2774 * are reading right to left.
2776 type = DTK_DAY;
2777 tmask = DTK_M(TZ);
2778 break;
2780 else if (type == IGNORE_DTF)
2782 if (*cp == '.')
2785 * Got a decimal point? Then assume some sort of
2786 * seconds specification
2788 type = DTK_SECOND;
2790 else if (*cp == '\0')
2793 * Only a signed integer? Then must assume a
2794 * timezone-like usage
2796 type = DTK_HOUR;
2799 /* DROP THROUGH */
2801 case DTK_DATE:
2802 case DTK_NUMBER:
2803 errno = 0;
2804 val = strtoi(field[i], &cp, 10);
2805 if (errno == ERANGE)
2806 return DTERR_FIELD_OVERFLOW;
2808 if (type == IGNORE_DTF)
2809 type = DTK_SECOND;
2811 if (*cp == '.')
2813 fval = strtod(cp, &cp);
2814 if (*cp != '\0')
2815 return DTERR_BAD_FORMAT;
2817 if (*field[i] == '-')
2818 fval = -fval;
2820 else if (*cp == '\0')
2821 fval = 0;
2822 else
2823 return DTERR_BAD_FORMAT;
2825 tmask = 0; /* DTK_M(type); */
2827 switch (type)
2829 case DTK_MICROSEC:
2830 #ifdef HAVE_INT64_TIMESTAMP
2831 *fsec += val + fval;
2832 #else
2833 *fsec += (val + fval) * 1e-6;
2834 #endif
2835 tmask = DTK_M(MICROSECOND);
2836 break;
2838 case DTK_MILLISEC:
2839 #ifdef HAVE_INT64_TIMESTAMP
2840 *fsec += (val + fval) * 1000;
2841 #else
2842 *fsec += (val + fval) * 1e-3;
2843 #endif
2844 tmask = DTK_M(MILLISECOND);
2845 break;
2847 case DTK_SECOND:
2848 tm->tm_sec += val;
2849 #ifdef HAVE_INT64_TIMESTAMP
2850 *fsec += fval * 1000000;
2851 #else
2852 *fsec += fval;
2853 #endif
2856 * If any subseconds were specified, consider this
2857 * microsecond and millisecond input as well.
2859 if (fval == 0)
2860 tmask = DTK_M(SECOND);
2861 else
2862 tmask = DTK_ALL_SECS_M;
2863 break;
2865 case DTK_MINUTE:
2866 tm->tm_min += val;
2867 if (fval != 0)
2869 int sec;
2871 fval *= SECS_PER_MINUTE;
2872 sec = fval;
2873 tm->tm_sec += sec;
2874 #ifdef HAVE_INT64_TIMESTAMP
2875 *fsec += (fval - sec) * 1000000;
2876 #else
2877 *fsec += fval - sec;
2878 #endif
2880 tmask = DTK_M(MINUTE);
2881 break;
2883 case DTK_HOUR:
2884 tm->tm_hour += val;
2885 if (fval != 0)
2887 int sec;
2889 fval *= SECS_PER_HOUR;
2890 sec = fval;
2891 tm->tm_sec += sec;
2892 #ifdef HAVE_INT64_TIMESTAMP
2893 *fsec += (fval - sec) * 1000000;
2894 #else
2895 *fsec += fval - sec;
2896 #endif
2898 tmask = DTK_M(HOUR);
2899 break;
2901 case DTK_DAY:
2902 tm->tm_mday += val;
2903 if (fval != 0)
2905 int sec;
2907 fval *= SECS_PER_DAY;
2908 sec = fval;
2909 tm->tm_sec += sec;
2910 #ifdef HAVE_INT64_TIMESTAMP
2911 *fsec += (fval - sec) * 1000000;
2912 #else
2913 *fsec += fval - sec;
2914 #endif
2916 tmask = (fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY);
2917 break;
2919 case DTK_WEEK:
2920 tm->tm_mday += val * 7;
2921 if (fval != 0)
2923 int extra_days;
2925 fval *= 7;
2926 extra_days = (int32) fval;
2927 tm->tm_mday += extra_days;
2928 fval -= extra_days;
2929 if (fval != 0)
2931 int sec;
2933 fval *= SECS_PER_DAY;
2934 sec = fval;
2935 tm->tm_sec += sec;
2936 #ifdef HAVE_INT64_TIMESTAMP
2937 *fsec += (fval - sec) * 1000000;
2938 #else
2939 *fsec += fval - sec;
2940 #endif
2943 tmask = (fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY);
2944 break;
2946 case DTK_MONTH:
2947 tm->tm_mon += val;
2948 if (fval != 0)
2950 int day;
2952 fval *= DAYS_PER_MONTH;
2953 day = fval;
2954 tm->tm_mday += day;
2955 fval -= day;
2956 if (fval != 0)
2958 int sec;
2960 fval *= SECS_PER_DAY;
2961 sec = fval;
2962 tm->tm_sec += sec;
2963 #ifdef HAVE_INT64_TIMESTAMP
2964 *fsec += (fval - sec) * 1000000;
2965 #else
2966 *fsec += fval - sec;
2967 #endif
2970 tmask = DTK_M(MONTH);
2971 break;
2973 case DTK_YEAR:
2974 tm->tm_year += val;
2975 if (fval != 0)
2976 tm->tm_mon += fval * MONTHS_PER_YEAR;
2977 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2978 break;
2980 case DTK_DECADE:
2981 tm->tm_year += val * 10;
2982 if (fval != 0)
2983 tm->tm_mon += fval * MONTHS_PER_YEAR * 10;
2984 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2985 break;
2987 case DTK_CENTURY:
2988 tm->tm_year += val * 100;
2989 if (fval != 0)
2990 tm->tm_mon += fval * MONTHS_PER_YEAR * 100;
2991 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2992 break;
2994 case DTK_MILLENNIUM:
2995 tm->tm_year += val * 1000;
2996 if (fval != 0)
2997 tm->tm_mon += fval * MONTHS_PER_YEAR * 1000;
2998 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2999 break;
3001 default:
3002 return DTERR_BAD_FORMAT;
3004 break;
3006 case DTK_STRING:
3007 case DTK_SPECIAL:
3008 type = DecodeUnits(i, field[i], &val);
3009 if (type == IGNORE_DTF)
3010 continue;
3012 tmask = 0; /* DTK_M(type); */
3013 switch (type)
3015 case UNITS:
3016 type = val;
3017 break;
3019 case AGO:
3020 is_before = TRUE;
3021 type = val;
3022 break;
3024 case RESERV:
3025 tmask = (DTK_DATE_M || DTK_TIME_M);
3026 *dtype = val;
3027 break;
3029 default:
3030 return DTERR_BAD_FORMAT;
3032 break;
3034 default:
3035 return DTERR_BAD_FORMAT;
3038 if (tmask & fmask)
3039 return DTERR_BAD_FORMAT;
3040 fmask |= tmask;
3043 if (*fsec != 0)
3045 int sec;
3047 #ifdef HAVE_INT64_TIMESTAMP
3048 sec = *fsec / USECS_PER_SEC;
3049 *fsec -= sec * USECS_PER_SEC;
3050 #else
3051 TMODULO(*fsec, sec, 1.0);
3052 #endif
3053 tm->tm_sec += sec;
3056 if (is_before)
3058 *fsec = -(*fsec);
3059 tm->tm_sec = -tm->tm_sec;
3060 tm->tm_min = -tm->tm_min;
3061 tm->tm_hour = -tm->tm_hour;
3062 tm->tm_mday = -tm->tm_mday;
3063 tm->tm_mon = -tm->tm_mon;
3064 tm->tm_year = -tm->tm_year;
3067 /* ensure that at least one time field has been found */
3068 if (fmask == 0)
3069 return DTERR_BAD_FORMAT;
3071 return 0;
3075 /* DecodeUnits()
3076 * Decode text string using lookup table.
3077 * This routine supports time interval decoding
3078 * (hence, it need not recognize timezone names).
3081 DecodeUnits(int field, char *lowtoken, int *val)
3083 int type;
3084 const datetkn *tp;
3086 tp = deltacache[field];
3087 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3089 tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
3091 if (tp == NULL)
3093 type = UNKNOWN_FIELD;
3094 *val = 0;
3096 else
3098 deltacache[field] = tp;
3099 type = tp->type;
3100 if (type == TZ || type == DTZ)
3101 *val = FROMVAL(tp);
3102 else
3103 *val = tp->value;
3106 return type;
3107 } /* DecodeUnits() */
3110 * Report an error detected by one of the datetime input processing routines.
3112 * dterr is the error code, str is the original input string, datatype is
3113 * the name of the datatype we were trying to accept.
3115 * Note: it might seem useless to distinguish DTERR_INTERVAL_OVERFLOW and
3116 * DTERR_TZDISP_OVERFLOW from DTERR_FIELD_OVERFLOW, but SQL99 mandates three
3117 * separate SQLSTATE codes, so ...
3119 void
3120 DateTimeParseError(int dterr, const char *str, const char *datatype)
3122 switch (dterr)
3124 case DTERR_FIELD_OVERFLOW:
3125 ereport(ERROR,
3126 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3127 errmsg("date/time field value out of range: \"%s\"",
3128 str)));
3129 break;
3130 case DTERR_MD_FIELD_OVERFLOW:
3131 /* <nanny>same as above, but add hint about DateStyle</nanny> */
3132 ereport(ERROR,
3133 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3134 errmsg("date/time field value out of range: \"%s\"",
3135 str),
3136 errhint("Perhaps you need a different \"datestyle\" setting.")));
3137 break;
3138 case DTERR_INTERVAL_OVERFLOW:
3139 ereport(ERROR,
3140 (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
3141 errmsg("interval field value out of range: \"%s\"",
3142 str)));
3143 break;
3144 case DTERR_TZDISP_OVERFLOW:
3145 ereport(ERROR,
3146 (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
3147 errmsg("time zone displacement out of range: \"%s\"",
3148 str)));
3149 break;
3150 case DTERR_BAD_FORMAT:
3151 default:
3152 ereport(ERROR,
3153 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
3154 errmsg("invalid input syntax for type %s: \"%s\"",
3155 datatype, str)));
3156 break;
3160 /* datebsearch()
3161 * Binary search -- from Knuth (6.2.1) Algorithm B. Special case like this
3162 * is WAY faster than the generic bsearch().
3164 static const datetkn *
3165 datebsearch(const char *key, const datetkn *base, int nel)
3167 const datetkn *last = base + nel - 1,
3168 *position;
3169 int result;
3171 while (last >= base)
3173 position = base + ((last - base) >> 1);
3174 result = key[0] - position->token[0];
3175 if (result == 0)
3177 result = strncmp(key, position->token, TOKMAXLEN);
3178 if (result == 0)
3179 return position;
3181 if (result < 0)
3182 last = position - 1;
3183 else
3184 base = position + 1;
3186 return NULL;
3189 /* EncodeTimezone()
3190 * Append representation of a numeric timezone offset to str.
3192 static void
3193 EncodeTimezone(char *str, int tz, int style)
3195 int hour,
3196 min,
3197 sec;
3199 sec = abs(tz);
3200 min = sec / SECS_PER_MINUTE;
3201 sec -= min * SECS_PER_MINUTE;
3202 hour = min / MINS_PER_HOUR;
3203 min -= hour * MINS_PER_HOUR;
3205 str += strlen(str);
3206 /* TZ is negated compared to sign we wish to display ... */
3207 *str++ = (tz <= 0 ? '+' : '-');
3209 if (sec != 0)
3210 sprintf(str, "%02d:%02d:%02d", hour, min, sec);
3211 else if (min != 0 || style == USE_XSD_DATES)
3212 sprintf(str, "%02d:%02d", hour, min);
3213 else
3214 sprintf(str, "%02d", hour);
3217 /* EncodeDateOnly()
3218 * Encode date as local time.
3221 EncodeDateOnly(struct pg_tm * tm, int style, char *str)
3223 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
3224 return -1;
3226 switch (style)
3228 case USE_ISO_DATES:
3229 case USE_XSD_DATES:
3230 /* compatible with ISO date formats */
3231 if (tm->tm_year > 0)
3232 sprintf(str, "%04d-%02d-%02d",
3233 tm->tm_year, tm->tm_mon, tm->tm_mday);
3234 else
3235 sprintf(str, "%04d-%02d-%02d %s",
3236 -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
3237 break;
3239 case USE_SQL_DATES:
3240 /* compatible with Oracle/Ingres date formats */
3241 if (DateOrder == DATEORDER_DMY)
3242 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3243 else
3244 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3245 if (tm->tm_year > 0)
3246 sprintf(str + 5, "/%04d", tm->tm_year);
3247 else
3248 sprintf(str + 5, "/%04d %s", -(tm->tm_year - 1), "BC");
3249 break;
3251 case USE_GERMAN_DATES:
3252 /* German-style date format */
3253 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3254 if (tm->tm_year > 0)
3255 sprintf(str + 5, ".%04d", tm->tm_year);
3256 else
3257 sprintf(str + 5, ".%04d %s", -(tm->tm_year - 1), "BC");
3258 break;
3260 case USE_POSTGRES_DATES:
3261 default:
3262 /* traditional date-only style for Postgres */
3263 if (DateOrder == DATEORDER_DMY)
3264 sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
3265 else
3266 sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
3267 if (tm->tm_year > 0)
3268 sprintf(str + 5, "-%04d", tm->tm_year);
3269 else
3270 sprintf(str + 5, "-%04d %s", -(tm->tm_year - 1), "BC");
3271 break;
3274 return TRUE;
3275 } /* EncodeDateOnly() */
3278 /* EncodeTimeOnly()
3279 * Encode time fields only.
3282 EncodeTimeOnly(struct pg_tm * tm, fsec_t fsec, int *tzp, int style, char *str)
3284 if (tm->tm_hour < 0 || tm->tm_hour > HOURS_PER_DAY)
3285 return -1;
3287 sprintf(str, "%02d:%02d", tm->tm_hour, tm->tm_min);
3290 * Print fractional seconds if any. The fractional field widths here
3291 * should be equal to the larger of MAX_TIME_PRECISION and
3292 * MAX_TIMESTAMP_PRECISION.
3294 if (fsec != 0)
3296 #ifdef HAVE_INT64_TIMESTAMP
3297 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3298 #else
3299 sprintf(str + strlen(str), ":%013.10f", tm->tm_sec + fsec);
3300 #endif
3301 TrimTrailingZeros(str);
3303 else
3304 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3306 if (tzp != NULL)
3307 EncodeTimezone(str, *tzp, style);
3309 return TRUE;
3310 } /* EncodeTimeOnly() */
3313 /* EncodeDateTime()
3314 * Encode date and time interpreted as local time.
3315 * Support several date styles:
3316 * Postgres - day mon hh:mm:ss yyyy tz
3317 * SQL - mm/dd/yyyy hh:mm:ss.ss tz
3318 * ISO - yyyy-mm-dd hh:mm:ss+/-tz
3319 * German - dd.mm.yyyy hh:mm:ss tz
3320 * XSD - yyyy-mm-ddThh:mm:ss.ss+/-tz
3321 * Variants (affects order of month and day for Postgres and SQL styles):
3322 * US - mm/dd/yyyy
3323 * European - dd/mm/yyyy
3326 EncodeDateTime(struct pg_tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, char *str)
3328 int day;
3331 * Why are we checking only the month field? Change this to an assert...
3332 * if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR) return -1;
3334 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3336 switch (style)
3338 case USE_ISO_DATES:
3339 case USE_XSD_DATES:
3340 /* Compatible with ISO-8601 date formats */
3342 if (style == USE_ISO_DATES)
3343 sprintf(str, "%04d-%02d-%02d %02d:%02d",
3344 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3345 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3346 else
3347 sprintf(str, "%04d-%02d-%02dT%02d:%02d",
3348 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3349 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3353 * Print fractional seconds if any. The field widths here should
3354 * be at least equal to MAX_TIMESTAMP_PRECISION.
3356 * In float mode, don't print fractional seconds before 1 AD,
3357 * since it's unlikely there's any precision left ...
3359 #ifdef HAVE_INT64_TIMESTAMP
3360 if (fsec != 0)
3362 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3363 TrimTrailingZeros(str);
3365 #else
3366 if (fsec != 0 && tm->tm_year > 0)
3368 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3369 TrimTrailingZeros(str);
3371 #endif
3372 else
3373 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3376 * tzp == NULL indicates that we don't want *any* time zone info
3377 * in the output string. *tzn != NULL indicates that we have alpha
3378 * time zone info available. tm_isdst != -1 indicates that we have
3379 * a valid time zone translation.
3381 if (tzp != NULL && tm->tm_isdst >= 0)
3382 EncodeTimezone(str, *tzp, style);
3384 if (tm->tm_year <= 0)
3385 sprintf(str + strlen(str), " BC");
3386 break;
3388 case USE_SQL_DATES:
3389 /* Compatible with Oracle/Ingres date formats */
3391 if (DateOrder == DATEORDER_DMY)
3392 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3393 else
3394 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3396 sprintf(str + 5, "/%04d %02d:%02d",
3397 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3398 tm->tm_hour, tm->tm_min);
3401 * Print fractional seconds if any. The field widths here should
3402 * be at least equal to MAX_TIMESTAMP_PRECISION.
3404 * In float mode, don't print fractional seconds before 1 AD,
3405 * since it's unlikely there's any precision left ...
3407 #ifdef HAVE_INT64_TIMESTAMP
3408 if (fsec != 0)
3410 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3411 TrimTrailingZeros(str);
3413 #else
3414 if (fsec != 0 && tm->tm_year > 0)
3416 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3417 TrimTrailingZeros(str);
3419 #endif
3420 else
3421 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3423 if (tzp != NULL && tm->tm_isdst >= 0)
3425 if (*tzn != NULL)
3426 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3427 else
3428 EncodeTimezone(str, *tzp, style);
3431 if (tm->tm_year <= 0)
3432 sprintf(str + strlen(str), " BC");
3433 break;
3435 case USE_GERMAN_DATES:
3436 /* German variant on European style */
3438 sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3440 sprintf(str + 5, ".%04d %02d:%02d",
3441 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3442 tm->tm_hour, tm->tm_min);
3445 * Print fractional seconds if any. The field widths here should
3446 * be at least equal to MAX_TIMESTAMP_PRECISION.
3448 * In float mode, don't print fractional seconds before 1 AD,
3449 * since it's unlikely there's any precision left ...
3451 #ifdef HAVE_INT64_TIMESTAMP
3452 if (fsec != 0)
3454 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3455 TrimTrailingZeros(str);
3457 #else
3458 if (fsec != 0 && tm->tm_year > 0)
3460 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3461 TrimTrailingZeros(str);
3463 #endif
3464 else
3465 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3467 if (tzp != NULL && tm->tm_isdst >= 0)
3469 if (*tzn != NULL)
3470 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3471 else
3472 EncodeTimezone(str, *tzp, style);
3475 if (tm->tm_year <= 0)
3476 sprintf(str + strlen(str), " BC");
3477 break;
3479 case USE_POSTGRES_DATES:
3480 default:
3481 /* Backward-compatible with traditional Postgres abstime dates */
3483 day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3484 tm->tm_wday = j2day(day);
3486 strncpy(str, days[tm->tm_wday], 3);
3487 strcpy(str + 3, " ");
3489 if (DateOrder == DATEORDER_DMY)
3490 sprintf(str + 4, "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
3491 else
3492 sprintf(str + 4, "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);
3494 sprintf(str + 10, " %02d:%02d", tm->tm_hour, tm->tm_min);
3497 * Print fractional seconds if any. The field widths here should
3498 * be at least equal to MAX_TIMESTAMP_PRECISION.
3500 * In float mode, don't print fractional seconds before 1 AD,
3501 * since it's unlikely there's any precision left ...
3503 #ifdef HAVE_INT64_TIMESTAMP
3504 if (fsec != 0)
3506 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3507 TrimTrailingZeros(str);
3509 #else
3510 if (fsec != 0 && tm->tm_year > 0)
3512 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3513 TrimTrailingZeros(str);
3515 #endif
3516 else
3517 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3519 sprintf(str + strlen(str), " %04d",
3520 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1));
3522 if (tzp != NULL && tm->tm_isdst >= 0)
3524 if (*tzn != NULL)
3525 sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3526 else
3529 * We have a time zone, but no string version. Use the
3530 * numeric form, but be sure to include a leading space to
3531 * avoid formatting something which would be rejected by
3532 * the date/time parser later. - thomas 2001-10-19
3534 sprintf(str + strlen(str), " ");
3535 EncodeTimezone(str, *tzp, style);
3539 if (tm->tm_year <= 0)
3540 sprintf(str + strlen(str), " BC");
3541 break;
3544 return TRUE;
3548 /* EncodeInterval()
3549 * Interpret time structure as a delta time and convert to string.
3551 * Support "traditional Postgres" and ISO-8601 styles.
3552 * Actually, afaik ISO does not address time interval formatting,
3553 * but this looks similar to the spec for absolute date/time.
3554 * - thomas 1998-04-30
3557 EncodeInterval(struct pg_tm * tm, fsec_t fsec, int style, char *str)
3559 bool is_before = FALSE;
3560 bool is_nonzero = FALSE;
3561 char *cp = str;
3564 * The sign of year and month are guaranteed to match, since they are
3565 * stored internally as "month". But we'll need to check for is_before and
3566 * is_nonzero when determining the signs of hour/minute/seconds fields.
3568 switch (style)
3570 /* compatible with ISO date formats */
3571 case USE_ISO_DATES:
3572 if (tm->tm_year != 0)
3574 sprintf(cp, "%d year%s",
3575 tm->tm_year, (tm->tm_year != 1) ? "s" : "");
3576 cp += strlen(cp);
3577 is_before = (tm->tm_year < 0);
3578 is_nonzero = TRUE;
3581 if (tm->tm_mon != 0)
3583 sprintf(cp, "%s%s%d mon%s", is_nonzero ? " " : "",
3584 (is_before && tm->tm_mon > 0) ? "+" : "",
3585 tm->tm_mon, (tm->tm_mon != 1) ? "s" : "");
3586 cp += strlen(cp);
3587 is_before = (tm->tm_mon < 0);
3588 is_nonzero = TRUE;
3591 if (tm->tm_mday != 0)
3593 sprintf(cp, "%s%s%d day%s", is_nonzero ? " " : "",
3594 (is_before && tm->tm_mday > 0) ? "+" : "",
3595 tm->tm_mday, (tm->tm_mday != 1) ? "s" : "");
3596 cp += strlen(cp);
3597 is_before = (tm->tm_mday < 0);
3598 is_nonzero = TRUE;
3601 if (!is_nonzero || tm->tm_hour != 0 || tm->tm_min != 0 ||
3602 tm->tm_sec != 0 || fsec != 0)
3604 int minus = (tm->tm_hour < 0 || tm->tm_min < 0 ||
3605 tm->tm_sec < 0 || fsec < 0);
3607 sprintf(cp, "%s%s%02d:%02d", is_nonzero ? " " : "",
3608 (minus ? "-" : (is_before ? "+" : "")),
3609 abs(tm->tm_hour), abs(tm->tm_min));
3610 cp += strlen(cp);
3611 /* Mark as "non-zero" since the fields are now filled in */
3612 is_nonzero = TRUE;
3614 /* need fractional seconds? */
3615 if (fsec != 0)
3617 #ifdef HAVE_INT64_TIMESTAMP
3618 sprintf(cp, ":%02d", abs(tm->tm_sec));
3619 cp += strlen(cp);
3620 sprintf(cp, ".%06d", Abs(fsec));
3621 #else
3622 fsec += tm->tm_sec;
3623 sprintf(cp, ":%012.9f", fabs(fsec));
3624 #endif
3625 TrimTrailingZeros(cp);
3626 cp += strlen(cp);
3628 else
3630 sprintf(cp, ":%02d", abs(tm->tm_sec));
3631 cp += strlen(cp);
3634 break;
3636 case USE_POSTGRES_DATES:
3637 default:
3638 strcpy(cp, "@ ");
3639 cp += strlen(cp);
3641 if (tm->tm_year != 0)
3643 int year = tm->tm_year;
3645 if (tm->tm_year < 0)
3646 year = -year;
3648 sprintf(cp, "%d year%s", year,
3649 (year != 1) ? "s" : "");
3650 cp += strlen(cp);
3651 is_before = (tm->tm_year < 0);
3652 is_nonzero = TRUE;
3655 if (tm->tm_mon != 0)
3657 int mon = tm->tm_mon;
3659 if (is_before || (!is_nonzero && tm->tm_mon < 0))
3660 mon = -mon;
3662 sprintf(cp, "%s%d mon%s", is_nonzero ? " " : "", mon,
3663 (mon != 1) ? "s" : "");
3664 cp += strlen(cp);
3665 if (!is_nonzero)
3666 is_before = (tm->tm_mon < 0);
3667 is_nonzero = TRUE;
3670 if (tm->tm_mday != 0)
3672 int day = tm->tm_mday;
3674 if (is_before || (!is_nonzero && tm->tm_mday < 0))
3675 day = -day;
3677 sprintf(cp, "%s%d day%s", is_nonzero ? " " : "", day,
3678 (day != 1) ? "s" : "");
3679 cp += strlen(cp);
3680 if (!is_nonzero)
3681 is_before = (tm->tm_mday < 0);
3682 is_nonzero = TRUE;
3684 if (tm->tm_hour != 0)
3686 int hour = tm->tm_hour;
3688 if (is_before || (!is_nonzero && tm->tm_hour < 0))
3689 hour = -hour;
3691 sprintf(cp, "%s%d hour%s", is_nonzero ? " " : "", hour,
3692 (hour != 1) ? "s" : "");
3693 cp += strlen(cp);
3694 if (!is_nonzero)
3695 is_before = (tm->tm_hour < 0);
3696 is_nonzero = TRUE;
3699 if (tm->tm_min != 0)
3701 int min = tm->tm_min;
3703 if (is_before || (!is_nonzero && tm->tm_min < 0))
3704 min = -min;
3706 sprintf(cp, "%s%d min%s", is_nonzero ? " " : "", min,
3707 (min != 1) ? "s" : "");
3708 cp += strlen(cp);
3709 if (!is_nonzero)
3710 is_before = (tm->tm_min < 0);
3711 is_nonzero = TRUE;
3714 /* fractional seconds? */
3715 if (fsec != 0)
3717 fsec_t sec;
3719 #ifdef HAVE_INT64_TIMESTAMP
3720 sec = fsec;
3721 if (is_before || (!is_nonzero && tm->tm_sec < 0))
3723 tm->tm_sec = -tm->tm_sec;
3724 sec = -sec;
3725 is_before = TRUE;
3727 else if (!is_nonzero && tm->tm_sec == 0 && fsec < 0)
3729 sec = -sec;
3730 is_before = TRUE;
3732 sprintf(cp, "%s%d.%02d secs", is_nonzero ? " " : "",
3733 tm->tm_sec, ((int) sec) / 10000);
3734 cp += strlen(cp);
3735 #else
3736 fsec += tm->tm_sec;
3737 sec = fsec;
3738 if (is_before || (!is_nonzero && fsec < 0))
3739 sec = -sec;
3741 sprintf(cp, "%s%.2f secs", is_nonzero ? " " : "", sec);
3742 cp += strlen(cp);
3743 if (!is_nonzero)
3744 is_before = (fsec < 0);
3745 #endif
3746 is_nonzero = TRUE;
3748 /* otherwise, integer seconds only? */
3749 else if (tm->tm_sec != 0)
3751 int sec = tm->tm_sec;
3753 if (is_before || (!is_nonzero && tm->tm_sec < 0))
3754 sec = -sec;
3756 sprintf(cp, "%s%d sec%s", is_nonzero ? " " : "", sec,
3757 (sec != 1) ? "s" : "");
3758 cp += strlen(cp);
3759 if (!is_nonzero)
3760 is_before = (tm->tm_sec < 0);
3761 is_nonzero = TRUE;
3763 break;
3766 /* identically zero? then put in a unitless zero... */
3767 if (!is_nonzero)
3769 strcat(cp, "0");
3770 cp += strlen(cp);
3773 if (is_before && (style != USE_ISO_DATES))
3775 strcat(cp, " ago");
3776 cp += strlen(cp);
3779 return 0;
3780 } /* EncodeInterval() */
3784 * We've been burnt by stupid errors in the ordering of the datetkn tables
3785 * once too often. Arrange to check them during postmaster start.
3787 static bool
3788 CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
3790 bool ok = true;
3791 int i;
3793 for (i = 1; i < nel; i++)
3795 if (strncmp(base[i - 1].token, base[i].token, TOKMAXLEN) >= 0)
3797 elog(LOG, "ordering error in %s table: \"%.*s\" >= \"%.*s\"",
3798 tablename,
3799 TOKMAXLEN, base[i - 1].token,
3800 TOKMAXLEN, base[i].token);
3801 ok = false;
3804 return ok;
3807 bool
3808 CheckDateTokenTables(void)
3810 bool ok = true;
3812 Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
3813 Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
3815 ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
3816 ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
3817 return ok;
3821 * This function gets called during timezone config file load or reload
3822 * to create the final array of timezone tokens. The argument array
3823 * is already sorted in name order. This data is in a temporary memory
3824 * context and must be copied to somewhere permanent.
3826 void
3827 InstallTimeZoneAbbrevs(tzEntry *abbrevs, int n)
3829 datetkn *newtbl;
3830 int i;
3833 * Copy the data into TopMemoryContext and convert to datetkn format.
3835 newtbl = (datetkn *) MemoryContextAlloc(TopMemoryContext,
3836 n * sizeof(datetkn));
3837 for (i = 0; i < n; i++)
3839 strncpy(newtbl[i].token, abbrevs[i].abbrev, TOKMAXLEN);
3840 newtbl[i].type = abbrevs[i].is_dst ? DTZ : TZ;
3841 TOVAL(&newtbl[i], abbrevs[i].offset / 60);
3844 /* Check the ordering, if testing */
3845 Assert(CheckDateTokenTable("timezone offset", newtbl, n));
3847 /* Now safe to replace existing table (if any) */
3848 if (timezonetktbl)
3849 pfree(timezonetktbl);
3850 timezonetktbl = newtbl;
3851 sztimezonetktbl = n;
3853 /* clear date cache in case it contains any stale timezone names */
3854 for (i = 0; i < MAXDATEFIELDS; i++)
3855 datecache[i] = NULL;
3859 * This set-returning function reads all the available time zone abbreviations
3860 * and returns a set of (abbrev, utc_offset, is_dst).
3862 Datum
3863 pg_timezone_abbrevs(PG_FUNCTION_ARGS)
3865 FuncCallContext *funcctx;
3866 int *pindex;
3867 Datum result;
3868 HeapTuple tuple;
3869 Datum values[3];
3870 bool nulls[3];
3871 char buffer[TOKMAXLEN + 1];
3872 unsigned char *p;
3873 struct pg_tm tm;
3874 Interval *resInterval;
3876 /* stuff done only on the first call of the function */
3877 if (SRF_IS_FIRSTCALL())
3879 TupleDesc tupdesc;
3880 MemoryContext oldcontext;
3882 /* create a function context for cross-call persistence */
3883 funcctx = SRF_FIRSTCALL_INIT();
3886 * switch to memory context appropriate for multiple function calls
3888 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
3890 /* allocate memory for user context */
3891 pindex = (int *) palloc(sizeof(int));
3892 *pindex = 0;
3893 funcctx->user_fctx = (void *) pindex;
3896 * build tupdesc for result tuples. This must match this function's
3897 * pg_proc entry!
3899 tupdesc = CreateTemplateTupleDesc(3, false);
3900 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "abbrev",
3901 TEXTOID, -1, 0);
3902 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "utc_offset",
3903 INTERVALOID, -1, 0);
3904 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_dst",
3905 BOOLOID, -1, 0);
3907 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
3908 MemoryContextSwitchTo(oldcontext);
3911 /* stuff done on every call of the function */
3912 funcctx = SRF_PERCALL_SETUP();
3913 pindex = (int *) funcctx->user_fctx;
3915 if (*pindex >= sztimezonetktbl)
3916 SRF_RETURN_DONE(funcctx);
3918 MemSet(nulls, 0, sizeof(nulls));
3921 * Convert name to text, using upcasing conversion that is the inverse of
3922 * what ParseDateTime() uses.
3924 strncpy(buffer, timezonetktbl[*pindex].token, TOKMAXLEN);
3925 buffer[TOKMAXLEN] = '\0'; /* may not be null-terminated */
3926 for (p = (unsigned char *) buffer; *p; p++)
3927 *p = pg_toupper(*p);
3929 values[0] = CStringGetTextDatum(buffer);
3931 MemSet(&tm, 0, sizeof(struct pg_tm));
3932 tm.tm_min = (-1) * FROMVAL(&timezonetktbl[*pindex]);
3933 resInterval = (Interval *) palloc(sizeof(Interval));
3934 tm2interval(&tm, 0, resInterval);
3935 values[1] = IntervalPGetDatum(resInterval);
3937 Assert(timezonetktbl[*pindex].type == DTZ ||
3938 timezonetktbl[*pindex].type == TZ);
3939 values[2] = BoolGetDatum(timezonetktbl[*pindex].type == DTZ);
3941 (*pindex)++;
3943 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
3944 result = HeapTupleGetDatum(tuple);
3946 SRF_RETURN_NEXT(funcctx, result);
3950 * This set-returning function reads all the available full time zones
3951 * and returns a set of (name, abbrev, utc_offset, is_dst).
3953 Datum
3954 pg_timezone_names(PG_FUNCTION_ARGS)
3956 MemoryContext oldcontext;
3957 FuncCallContext *funcctx;
3958 pg_tzenum *tzenum;
3959 pg_tz *tz;
3960 Datum result;
3961 HeapTuple tuple;
3962 Datum values[4];
3963 bool nulls[4];
3964 int tzoff;
3965 struct pg_tm tm;
3966 fsec_t fsec;
3967 char *tzn;
3968 Interval *resInterval;
3969 struct pg_tm itm;
3971 /* stuff done only on the first call of the function */
3972 if (SRF_IS_FIRSTCALL())
3974 TupleDesc tupdesc;
3976 /* create a function context for cross-call persistence */
3977 funcctx = SRF_FIRSTCALL_INIT();
3980 * switch to memory context appropriate for multiple function calls
3982 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
3984 /* initialize timezone scanning code */
3985 tzenum = pg_tzenumerate_start();
3986 funcctx->user_fctx = (void *) tzenum;
3989 * build tupdesc for result tuples. This must match this function's
3990 * pg_proc entry!
3992 tupdesc = CreateTemplateTupleDesc(4, false);
3993 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
3994 TEXTOID, -1, 0);
3995 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "abbrev",
3996 TEXTOID, -1, 0);
3997 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "utc_offset",
3998 INTERVALOID, -1, 0);
3999 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_dst",
4000 BOOLOID, -1, 0);
4002 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4003 MemoryContextSwitchTo(oldcontext);
4006 /* stuff done on every call of the function */
4007 funcctx = SRF_PERCALL_SETUP();
4008 tzenum = (pg_tzenum *) funcctx->user_fctx;
4010 /* search for another zone to display */
4011 for (;;)
4013 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4014 tz = pg_tzenumerate_next(tzenum);
4015 MemoryContextSwitchTo(oldcontext);
4017 if (!tz)
4019 pg_tzenumerate_end(tzenum);
4020 funcctx->user_fctx = NULL;
4021 SRF_RETURN_DONE(funcctx);
4024 /* Convert now() to local time in this zone */
4025 if (timestamp2tm(GetCurrentTransactionStartTimestamp(),
4026 &tzoff, &tm, &fsec, &tzn, tz) != 0)
4027 continue; /* ignore if conversion fails */
4029 /* Ignore zic's rather silly "Factory" time zone */
4030 if (tzn && strcmp(tzn, "Local time zone must be set--see zic manual page") == 0)
4031 continue;
4033 /* Found a displayable zone */
4034 break;
4037 MemSet(nulls, 0, sizeof(nulls));
4039 values[0] = CStringGetTextDatum(pg_get_timezone_name(tz));
4040 values[1] = CStringGetTextDatum(tzn ? tzn : "");
4042 MemSet(&itm, 0, sizeof(struct pg_tm));
4043 itm.tm_sec = -tzoff;
4044 resInterval = (Interval *) palloc(sizeof(Interval));
4045 tm2interval(&itm, 0, resInterval);
4046 values[2] = IntervalPGetDatum(resInterval);
4048 values[3] = BoolGetDatum(tm.tm_isdst > 0);
4050 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4051 result = HeapTupleGetDatum(tuple);
4053 SRF_RETURN_NEXT(funcctx, result);