]> granicus.if.org Git - postgresql/blob - src/backend/utils/adt/datetime.c
Add support for input and output of interval values formatted per ISO 8601;
[postgresql] / src / backend / utils / adt / datetime.c
1 /*-------------------------------------------------------------------------
2  *
3  * datetime.c
4  *        Support functions for date/time types.
5  *
6  * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/utils/adt/datetime.c,v 1.198 2008/11/11 02:42:32 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <ctype.h>
18 #include <float.h>
19 #include <limits.h>
20 #include <math.h>
21
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"
30
31
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 range,
39                    int *tmask, 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);
47
48
49 const int       day_tab[2][13] =
50 {
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}
53 };
54
55 char       *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
56 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
57
58 char       *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
59 "Thursday", "Friday", "Saturday", NULL};
60
61
62 /*****************************************************************************
63  *       PRIVATE ROUTINES                                                                                                                *
64  *****************************************************************************/
65
66 /*
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).
70  */
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))
78
79 /*
80  * datetktbl holds date/time keywords.
81  *
82  * Note that this table must be strictly alphabetically ordered to allow an
83  * O(ln(N)) search algorithm to be used.
84  *
85  * The text field is NOT guaranteed to be NULL-terminated.
86  *
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.
93  *
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.
97  */
98 static datetkn *timezonetktbl = NULL;
99
100 static int      sztimezonetktbl = 0;
101
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 */
179 };
180
181 static int      szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];
182
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 */
249 };
250
251 static int      szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];
252
253 static const datetkn *datecache[MAXDATEFIELDS] = {NULL};
254
255 static const datetkn *deltacache[MAXDATEFIELDS] = {NULL};
256
257
258 /*
259  * strtoi --- just like strtol, but returns int not long
260  */
261 static int
262 strtoi(const char *nptr, char **endptr, int base)
263 {
264         long    val;
265
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;
272 }
273
274
275 /*
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).
282  *
283  * These routines will be used by other date/time packages
284  * - thomas 97/02/25
285  *
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.
291  */
292
293 int
294 date2j(int y, int m, int d)
295 {
296         int                     julian;
297         int                     century;
298
299         if (m > 2)
300         {
301                 m += 1;
302                 y += 4800;
303         }
304         else
305         {
306                 m += 13;
307                 y += 4799;
308         }
309
310         century = y / 100;
311         julian = y * 365 - 32167;
312         julian += y / 4 - century + century / 4;
313         julian += 7834 * m / 256 + d;
314
315         return julian;
316 }       /* date2j() */
317
318 void
319 j2date(int jd, int *year, int *month, int *day)
320 {
321         unsigned int julian;
322         unsigned int quad;
323         unsigned int extra;
324         int                     y;
325
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;
341
342         return;
343 }       /* j2date() */
344
345
346 /*
347  * j2day - convert Julian date to day-of-week (0..6 == Sun..Sat)
348  *
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.
352  */
353 int
354 j2day(int date)
355 {
356         unsigned int day;
357
358         day = date;
359
360         day += 1;
361         day %= 7;
362
363         return (int) day;
364 }       /* j2day() */
365
366
367 /*
368  * GetCurrentDateTime()
369  *
370  * Get the transaction start time ("now()") broken down as a struct pg_tm.
371  */
372 void
373 GetCurrentDateTime(struct pg_tm * tm)
374 {
375         int                     tz;
376         fsec_t          fsec;
377
378         timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, &fsec,
379                                  NULL, NULL);
380         /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
381 }
382
383 /*
384  * GetCurrentTimeUsec()
385  *
386  * Get the transaction start time ("now()") broken down as a struct pg_tm,
387  * including fractional seconds and timezone offset.
388  */
389 void
390 GetCurrentTimeUsec(struct pg_tm * tm, fsec_t *fsec, int *tzp)
391 {
392         int                     tz;
393
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;
399 }
400
401
402 /* TrimTrailingZeros()
403  * ... resulting from printing numbers with full precision.
404  */
405 static void
406 TrimTrailingZeros(char *str)
407 {
408         int                     len = strlen(str);
409
410 #if 0
411         /* chop off trailing one to cope with interval rounding */
412         if (strcmp(str + len - 4, "0001") == 0)
413         {
414                 len -= 4;
415                 *(str + len) = '\0';
416         }
417 #endif
418
419         /* chop off trailing zeros... but leave at least 2 fractional digits */
420         while (*(str + len - 1) == '0' && *(str + len - 3) != '.')
421         {
422                 len--;
423                 *(str + len) = '\0';
424         }
425 }
426
427 /* ParseDateTime()
428  *      Break string into tokens based on a date/time context.
429  *      Returns 0 if successful, DTERR code if bogus input detected.
430  *
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
440  *
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.
444  *
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 ':', '.', '-')
452  *
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)
457  */
458 int
459 ParseDateTime(const char *timestr, char *workbuf, size_t buflen,
460                           char **field, int *ftype, int maxfields, int *numfields)
461 {
462         int                     nf = 0;
463         const char *cp = timestr;
464         char       *bufp = workbuf;
465         const char *bufend = workbuf + buflen;
466
467         /*
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.
472          */
473 #define APPEND_CHAR(bufptr, end, newchar)               \
474         do                                                                                      \
475         {                                                                                       \
476                 if (((bufptr) + 1) >= (end))                    \
477                         return DTERR_BAD_FORMAT;                        \
478                 *(bufptr)++ = newchar;                                  \
479         } while (0)
480
481         /* outer loop through fields */
482         while (*cp != '\0')
483         {
484                 /* Ignore spaces between fields */
485                 if (isspace((unsigned char) *cp))
486                 {
487                         cp++;
488                         continue;
489                 }
490
491                 /* Record start of current field */
492                 if (nf >= maxfields)
493                         return DTERR_BAD_FORMAT;
494                 field[nf] = bufp;
495
496                 /* leading digit? then date or time */
497                 if (isdigit((unsigned char) *cp))
498                 {
499                         APPEND_CHAR(bufp, bufend, *cp++);
500                         while (isdigit((unsigned char) *cp))
501                                 APPEND_CHAR(bufp, bufend, *cp++);
502
503                         /* time field? */
504                         if (*cp == ':')
505                         {
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++);
511                         }
512                         /* date field? allow embedded text month */
513                         else if (*cp == '-' || *cp == '/' || *cp == '.')
514                         {
515                                 /* save delimiting character to use later */
516                                 char            delim = *cp;
517
518                                 APPEND_CHAR(bufp, bufend, *cp++);
519                                 /* second field is all digits? then no embedded text month */
520                                 if (isdigit((unsigned char) *cp))
521                                 {
522                                         ftype[nf] = ((delim == '.') ? DTK_NUMBER : DTK_DATE);
523                                         while (isdigit((unsigned char) *cp))
524                                                 APPEND_CHAR(bufp, bufend, *cp++);
525
526                                         /*
527                                          * insist that the delimiters match to get a three-field
528                                          * date.
529                                          */
530                                         if (*cp == delim)
531                                         {
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++);
536                                         }
537                                 }
538                                 else
539                                 {
540                                         ftype[nf] = DTK_DATE;
541                                         while (isalnum((unsigned char) *cp) || *cp == delim)
542                                                 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
543                                 }
544                         }
545
546                         /*
547                          * otherwise, number only and will determine year, month, day, or
548                          * concatenated fields later...
549                          */
550                         else
551                                 ftype[nf] = DTK_NUMBER;
552                 }
553                 /* Leading decimal point? Then fractional seconds... */
554                 else if (*cp == '.')
555                 {
556                         APPEND_CHAR(bufp, bufend, *cp++);
557                         while (isdigit((unsigned char) *cp))
558                                 APPEND_CHAR(bufp, bufend, *cp++);
559
560                         ftype[nf] = DTK_NUMBER;
561                 }
562
563                 /*
564                  * text? then date string, month, day of week, special, or timezone
565                  */
566                 else if (isalpha((unsigned char) *cp))
567                 {
568                         bool            is_date;
569
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++));
574
575                         /*
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.
582                          */
583                         is_date = false;
584                         if (*cp == '-' || *cp == '/' || *cp == '.')
585                                 is_date = true;
586                         else if (*cp == '+' || isdigit((unsigned char) *cp))
587                         {
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;
592                         }
593                         if (is_date)
594                         {
595                                 ftype[nf] = DTK_DATE;
596                                 do
597                                 {
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));
603                         }
604                 }
605                 /* sign? then special or numeric timezone */
606                 else if (*cp == '+' || *cp == '-')
607                 {
608                         APPEND_CHAR(bufp, bufend, *cp++);
609                         /* soak up leading whitespace */
610                         while (isspace((unsigned char) *cp))
611                                 cp++;
612                         /* numeric timezone? */
613                         /* note that "DTK_TZ" could also be a signed float or yyyy-mm */
614                         if (isdigit((unsigned char) *cp))
615                         {
616                                 ftype[nf] = DTK_TZ;
617                                 APPEND_CHAR(bufp, bufend, *cp++);
618                                 while (isdigit((unsigned char) *cp) ||
619                                            *cp == ':' || *cp == '.' || *cp == '-')
620                                         APPEND_CHAR(bufp, bufend, *cp++);
621                         }
622                         /* special? */
623                         else if (isalpha((unsigned char) *cp))
624                         {
625                                 ftype[nf] = DTK_SPECIAL;
626                                 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
627                                 while (isalpha((unsigned char) *cp))
628                                         APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
629                         }
630                         /* otherwise something wrong... */
631                         else
632                                 return DTERR_BAD_FORMAT;
633                 }
634                 /* ignore other punctuation but use as delimiter */
635                 else if (ispunct((unsigned char) *cp))
636                 {
637                         cp++;
638                         continue;
639                 }
640                 /* otherwise, something is not right... */
641                 else
642                         return DTERR_BAD_FORMAT;
643
644                 /* force in a delimiter after each field */
645                 *bufp++ = '\0';
646                 nf++;
647         }
648
649         *numfields = nf;
650
651         return 0;
652 }
653
654
655 /* DecodeDateTime()
656  * Interpret previously parsed fields for general date and time.
657  * Return 0 if full date, 1 if only time, and negative DTERR code if problems.
658  * (Currently, all callers treat 1 as an error return too.)
659  *
660  *              External format(s):
661  *                              "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
662  *                              "Fri Feb-7-1997 15:23:27"
663  *                              "Feb-7-1997 15:23:27"
664  *                              "2-7-1997 15:23:27"
665  *                              "1997-2-7 15:23:27"
666  *                              "1997.038 15:23:27"             (day of year 1-366)
667  *              Also supports input in compact time:
668  *                              "970207 152327"
669  *                              "97038 152327"
670  *                              "20011225T040506.789-07"
671  *
672  * Use the system-provided functions to get the current time zone
673  * if not specified in the input string.
674  *
675  * If the date is outside the range of pg_time_t (in practice that could only
676  * happen if pg_time_t is just 32 bits), then assume UTC time zone - thomas
677  * 1997-05-27
678  */
679 int
680 DecodeDateTime(char **field, int *ftype, int nf,
681                            int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
682 {
683         int                     fmask = 0,
684                                 tmask,
685                                 type;
686         int                     ptype = 0;              /* "prefix type" for ISO y2001m02d04 format */
687         int                     i;
688         int                     val;
689         int                     dterr;
690         int                     mer = HR24;
691         bool            haveTextMonth = FALSE;
692         bool            is2digits = FALSE;
693         bool            bc = FALSE;
694         pg_tz      *namedTz = NULL;
695
696         /*
697          * We'll insist on at least all of the date fields, but initialize the
698          * remaining fields in case they are not set later...
699          */
700         *dtype = DTK_DATE;
701         tm->tm_hour = 0;
702         tm->tm_min = 0;
703         tm->tm_sec = 0;
704         *fsec = 0;
705         /* don't know daylight savings time status apriori */
706         tm->tm_isdst = -1;
707         if (tzp != NULL)
708                 *tzp = 0;
709
710         for (i = 0; i < nf; i++)
711         {
712                 switch (ftype[i])
713                 {
714                         case DTK_DATE:
715                                 /***
716                                  * Integral julian day with attached time zone?
717                                  * All other forms with JD will be separated into
718                                  * distinct fields, so we handle just this case here.
719                                  ***/
720                                 if (ptype == DTK_JULIAN)
721                                 {
722                                         char       *cp;
723                                         int                     val;
724
725                                         if (tzp == NULL)
726                                                 return DTERR_BAD_FORMAT;
727
728                                         errno = 0;
729                                         val = strtoi(field[i], &cp, 10);
730                                         if (errno == ERANGE)
731                                                 return DTERR_FIELD_OVERFLOW;
732
733                                         j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
734                                         /* Get the time zone from the end of the string */
735                                         dterr = DecodeTimezone(cp, tzp);
736                                         if (dterr)
737                                                 return dterr;
738
739                                         tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
740                                         ptype = 0;
741                                         break;
742                                 }
743                                 /***
744                                  * Already have a date? Then this might be a time zone name
745                                  * with embedded punctuation (e.g. "America/New_York") or a
746                                  * run-together time with trailing time zone (e.g. hhmmss-zz).
747                                  * - thomas 2001-12-25
748                                  *
749                                  * We consider it a time zone if we already have month & day.
750                                  * This is to allow the form "mmm dd hhmmss tz year", which
751                                  * we've historically accepted.
752                                  ***/
753                                 else if (ptype != 0 ||
754                                                  ((fmask & (DTK_M(MONTH) | DTK_M(DAY))) ==
755                                                   (DTK_M(MONTH) | DTK_M(DAY))))
756                                 {
757                                         /* No time zone accepted? Then quit... */
758                                         if (tzp == NULL)
759                                                 return DTERR_BAD_FORMAT;
760
761                                         if (isdigit((unsigned char) *field[i]) || ptype != 0)
762                                         {
763                                                 char       *cp;
764
765                                                 if (ptype != 0)
766                                                 {
767                                                         /* Sanity check; should not fail this test */
768                                                         if (ptype != DTK_TIME)
769                                                                 return DTERR_BAD_FORMAT;
770                                                         ptype = 0;
771                                                 }
772
773                                                 /*
774                                                  * Starts with a digit but we already have a time
775                                                  * field? Then we are in trouble with a date and time
776                                                  * already...
777                                                  */
778                                                 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
779                                                         return DTERR_BAD_FORMAT;
780
781                                                 if ((cp = strchr(field[i], '-')) == NULL)
782                                                         return DTERR_BAD_FORMAT;
783
784                                                 /* Get the time zone from the end of the string */
785                                                 dterr = DecodeTimezone(cp, tzp);
786                                                 if (dterr)
787                                                         return dterr;
788                                                 *cp = '\0';
789
790                                                 /*
791                                                  * Then read the rest of the field as a concatenated
792                                                  * time
793                                                  */
794                                                 dterr = DecodeNumberField(strlen(field[i]), field[i],
795                                                                                                   fmask,
796                                                                                                   &tmask, tm,
797                                                                                                   fsec, &is2digits);
798                                                 if (dterr < 0)
799                                                         return dterr;
800
801                                                 /*
802                                                  * modify tmask after returning from
803                                                  * DecodeNumberField()
804                                                  */
805                                                 tmask |= DTK_M(TZ);
806                                         }
807                                         else
808                                         {
809                                                 namedTz = pg_tzset(field[i]);
810                                                 if (!namedTz)
811                                                 {
812                                                         /*
813                                                          * We should return an error code instead of
814                                                          * ereport'ing directly, but then there is no way
815                                                          * to report the bad time zone name.
816                                                          */
817                                                         ereport(ERROR,
818                                                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
819                                                                          errmsg("time zone \"%s\" not recognized",
820                                                                                         field[i])));
821                                                 }
822                                                 /* we'll apply the zone setting below */
823                                                 tmask = DTK_M(TZ);
824                                         }
825                                 }
826                                 else
827                                 {
828                                         dterr = DecodeDate(field[i], fmask,
829                                                                            &tmask, &is2digits, tm);
830                                         if (dterr)
831                                                 return dterr;
832                                 }
833                                 break;
834
835                         case DTK_TIME:
836                                 dterr = DecodeTime(field[i], fmask, INTERVAL_FULL_RANGE,
837                                                                    &tmask, tm, fsec);
838                                 if (dterr)
839                                         return dterr;
840
841                                 /*
842                                  * Check upper limit on hours; other limits checked in
843                                  * DecodeTime()
844                                  */
845                                 /* test for > 24:00:00 */
846                                 if (tm->tm_hour > 24 ||
847                                         (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0)))
848                                         return DTERR_FIELD_OVERFLOW;
849                                 break;
850
851                         case DTK_TZ:
852                                 {
853                                         int                     tz;
854
855                                         if (tzp == NULL)
856                                                 return DTERR_BAD_FORMAT;
857
858                                         dterr = DecodeTimezone(field[i], &tz);
859                                         if (dterr)
860                                                 return dterr;
861                                         *tzp = tz;
862                                         tmask = DTK_M(TZ);
863                                 }
864                                 break;
865
866                         case DTK_NUMBER:
867
868                                 /*
869                                  * Was this an "ISO date" with embedded field labels? An
870                                  * example is "y2001m02d04" - thomas 2001-02-04
871                                  */
872                                 if (ptype != 0)
873                                 {
874                                         char       *cp;
875                                         int                     val;
876
877                                         errno = 0;
878                                         val = strtoi(field[i], &cp, 10);
879                                         if (errno == ERANGE)
880                                                 return DTERR_FIELD_OVERFLOW;
881
882                                         /*
883                                          * only a few kinds are allowed to have an embedded
884                                          * decimal
885                                          */
886                                         if (*cp == '.')
887                                                 switch (ptype)
888                                                 {
889                                                         case DTK_JULIAN:
890                                                         case DTK_TIME:
891                                                         case DTK_SECOND:
892                                                                 break;
893                                                         default:
894                                                                 return DTERR_BAD_FORMAT;
895                                                                 break;
896                                                 }
897                                         else if (*cp != '\0')
898                                                 return DTERR_BAD_FORMAT;
899
900                                         switch (ptype)
901                                         {
902                                                 case DTK_YEAR:
903                                                         tm->tm_year = val;
904                                                         tmask = DTK_M(YEAR);
905                                                         break;
906
907                                                 case DTK_MONTH:
908
909                                                         /*
910                                                          * already have a month and hour? then assume
911                                                          * minutes
912                                                          */
913                                                         if ((fmask & DTK_M(MONTH)) != 0 &&
914                                                                 (fmask & DTK_M(HOUR)) != 0)
915                                                         {
916                                                                 tm->tm_min = val;
917                                                                 tmask = DTK_M(MINUTE);
918                                                         }
919                                                         else
920                                                         {
921                                                                 tm->tm_mon = val;
922                                                                 tmask = DTK_M(MONTH);
923                                                         }
924                                                         break;
925
926                                                 case DTK_DAY:
927                                                         tm->tm_mday = val;
928                                                         tmask = DTK_M(DAY);
929                                                         break;
930
931                                                 case DTK_HOUR:
932                                                         tm->tm_hour = val;
933                                                         tmask = DTK_M(HOUR);
934                                                         break;
935
936                                                 case DTK_MINUTE:
937                                                         tm->tm_min = val;
938                                                         tmask = DTK_M(MINUTE);
939                                                         break;
940
941                                                 case DTK_SECOND:
942                                                         tm->tm_sec = val;
943                                                         tmask = DTK_M(SECOND);
944                                                         if (*cp == '.')
945                                                         {
946                                                                 double          frac;
947
948                                                                 frac = strtod(cp, &cp);
949                                                                 if (*cp != '\0')
950                                                                         return DTERR_BAD_FORMAT;
951 #ifdef HAVE_INT64_TIMESTAMP
952                                                                 *fsec = rint(frac * 1000000);
953 #else
954                                                                 *fsec = frac;
955 #endif
956                                                                 tmask = DTK_ALL_SECS_M;
957                                                         }
958                                                         break;
959
960                                                 case DTK_TZ:
961                                                         tmask = DTK_M(TZ);
962                                                         dterr = DecodeTimezone(field[i], tzp);
963                                                         if (dterr)
964                                                                 return dterr;
965                                                         break;
966
967                                                 case DTK_JULIAN:
968                                                         /***
969                                                          * previous field was a label for "julian date"?
970                                                          ***/
971                                                         tmask = DTK_DATE_M;
972                                                         j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
973                                                         /* fractional Julian Day? */
974                                                         if (*cp == '.')
975                                                         {
976                                                                 double          time;
977
978                                                                 time = strtod(cp, &cp);
979                                                                 if (*cp != '\0')
980                                                                         return DTERR_BAD_FORMAT;
981
982                                                                 tmask |= DTK_TIME_M;
983 #ifdef HAVE_INT64_TIMESTAMP
984                                                                 dt2time(time * USECS_PER_DAY,
985                                                                                 &tm->tm_hour, &tm->tm_min,
986                                                                                 &tm->tm_sec, fsec);
987 #else
988                                                                 dt2time(time * SECS_PER_DAY, &tm->tm_hour,
989                                                                                 &tm->tm_min, &tm->tm_sec, fsec);
990 #endif
991                                                         }
992                                                         break;
993
994                                                 case DTK_TIME:
995                                                         /* previous field was "t" for ISO time */
996                                                         dterr = DecodeNumberField(strlen(field[i]), field[i],
997                                                                                                           (fmask | DTK_DATE_M),
998                                                                                                           &tmask, tm,
999                                                                                                           fsec, &is2digits);
1000                                                         if (dterr < 0)
1001                                                                 return dterr;
1002                                                         if (tmask != DTK_TIME_M)
1003                                                                 return DTERR_BAD_FORMAT;
1004                                                         break;
1005
1006                                                 default:
1007                                                         return DTERR_BAD_FORMAT;
1008                                                         break;
1009                                         }
1010
1011                                         ptype = 0;
1012                                         *dtype = DTK_DATE;
1013                                 }
1014                                 else
1015                                 {
1016                                         char       *cp;
1017                                         int                     flen;
1018
1019                                         flen = strlen(field[i]);
1020                                         cp = strchr(field[i], '.');
1021
1022                                         /* Embedded decimal and no date yet? */
1023                                         if (cp != NULL && !(fmask & DTK_DATE_M))
1024                                         {
1025                                                 dterr = DecodeDate(field[i], fmask,
1026                                                                                    &tmask, &is2digits, tm);
1027                                                 if (dterr)
1028                                                         return dterr;
1029                                         }
1030                                         /* embedded decimal and several digits before? */
1031                                         else if (cp != NULL && flen - strlen(cp) > 2)
1032                                         {
1033                                                 /*
1034                                                  * Interpret as a concatenated date or time Set the
1035                                                  * type field to allow decoding other fields later.
1036                                                  * Example: 20011223 or 040506
1037                                                  */
1038                                                 dterr = DecodeNumberField(flen, field[i], fmask,
1039                                                                                                   &tmask, tm,
1040                                                                                                   fsec, &is2digits);
1041                                                 if (dterr < 0)
1042                                                         return dterr;
1043                                         }
1044                                         else if (flen > 4)
1045                                         {
1046                                                 dterr = DecodeNumberField(flen, field[i], fmask,
1047                                                                                                   &tmask, tm,
1048                                                                                                   fsec, &is2digits);
1049                                                 if (dterr < 0)
1050                                                         return dterr;
1051                                         }
1052                                         /* otherwise it is a single date/time field... */
1053                                         else
1054                                         {
1055                                                 dterr = DecodeNumber(flen, field[i],
1056                                                                                          haveTextMonth, fmask,
1057                                                                                          &tmask, tm,
1058                                                                                          fsec, &is2digits);
1059                                                 if (dterr)
1060                                                         return dterr;
1061                                         }
1062                                 }
1063                                 break;
1064
1065                         case DTK_STRING:
1066                         case DTK_SPECIAL:
1067                                 type = DecodeSpecial(i, field[i], &val);
1068                                 if (type == IGNORE_DTF)
1069                                         continue;
1070
1071                                 tmask = DTK_M(type);
1072                                 switch (type)
1073                                 {
1074                                         case RESERV:
1075                                                 switch (val)
1076                                                 {
1077                                                         case DTK_CURRENT:
1078                                                                 ereport(ERROR,
1079                                                                          (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1080                                                                           errmsg("date/time value \"current\" is no longer supported")));
1081
1082                                                                 return DTERR_BAD_FORMAT;
1083                                                                 break;
1084
1085                                                         case DTK_NOW:
1086                                                                 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1087                                                                 *dtype = DTK_DATE;
1088                                                                 GetCurrentTimeUsec(tm, fsec, tzp);
1089                                                                 break;
1090
1091                                                         case DTK_YESTERDAY:
1092                                                                 tmask = DTK_DATE_M;
1093                                                                 *dtype = DTK_DATE;
1094                                                                 GetCurrentDateTime(tm);
1095                                                                 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - 1,
1096                                                                         &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1097                                                                 tm->tm_hour = 0;
1098                                                                 tm->tm_min = 0;
1099                                                                 tm->tm_sec = 0;
1100                                                                 break;
1101
1102                                                         case DTK_TODAY:
1103                                                                 tmask = DTK_DATE_M;
1104                                                                 *dtype = DTK_DATE;
1105                                                                 GetCurrentDateTime(tm);
1106                                                                 tm->tm_hour = 0;
1107                                                                 tm->tm_min = 0;
1108                                                                 tm->tm_sec = 0;
1109                                                                 break;
1110
1111                                                         case DTK_TOMORROW:
1112                                                                 tmask = DTK_DATE_M;
1113                                                                 *dtype = DTK_DATE;
1114                                                                 GetCurrentDateTime(tm);
1115                                                                 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1,
1116                                                                         &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1117                                                                 tm->tm_hour = 0;
1118                                                                 tm->tm_min = 0;
1119                                                                 tm->tm_sec = 0;
1120                                                                 break;
1121
1122                                                         case DTK_ZULU:
1123                                                                 tmask = (DTK_TIME_M | DTK_M(TZ));
1124                                                                 *dtype = DTK_DATE;
1125                                                                 tm->tm_hour = 0;
1126                                                                 tm->tm_min = 0;
1127                                                                 tm->tm_sec = 0;
1128                                                                 if (tzp != NULL)
1129                                                                         *tzp = 0;
1130                                                                 break;
1131
1132                                                         default:
1133                                                                 *dtype = val;
1134                                                 }
1135
1136                                                 break;
1137
1138                                         case MONTH:
1139
1140                                                 /*
1141                                                  * already have a (numeric) month? then see if we can
1142                                                  * substitute...
1143                                                  */
1144                                                 if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
1145                                                         !(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 &&
1146                                                         tm->tm_mon <= 31)
1147                                                 {
1148                                                         tm->tm_mday = tm->tm_mon;
1149                                                         tmask = DTK_M(DAY);
1150                                                 }
1151                                                 haveTextMonth = TRUE;
1152                                                 tm->tm_mon = val;
1153                                                 break;
1154
1155                                         case DTZMOD:
1156
1157                                                 /*
1158                                                  * daylight savings time modifier (solves "MET DST"
1159                                                  * syntax)
1160                                                  */
1161                                                 tmask |= DTK_M(DTZ);
1162                                                 tm->tm_isdst = 1;
1163                                                 if (tzp == NULL)
1164                                                         return DTERR_BAD_FORMAT;
1165                                                 *tzp += val * MINS_PER_HOUR;
1166                                                 break;
1167
1168                                         case DTZ:
1169
1170                                                 /*
1171                                                  * set mask for TZ here _or_ check for DTZ later when
1172                                                  * getting default timezone
1173                                                  */
1174                                                 tmask |= DTK_M(TZ);
1175                                                 tm->tm_isdst = 1;
1176                                                 if (tzp == NULL)
1177                                                         return DTERR_BAD_FORMAT;
1178                                                 *tzp = val * MINS_PER_HOUR;
1179                                                 break;
1180
1181                                         case TZ:
1182                                                 tm->tm_isdst = 0;
1183                                                 if (tzp == NULL)
1184                                                         return DTERR_BAD_FORMAT;
1185                                                 *tzp = val * MINS_PER_HOUR;
1186                                                 break;
1187
1188                                         case IGNORE_DTF:
1189                                                 break;
1190
1191                                         case AMPM:
1192                                                 mer = val;
1193                                                 break;
1194
1195                                         case ADBC:
1196                                                 bc = (val == BC);
1197                                                 break;
1198
1199                                         case DOW:
1200                                                 tm->tm_wday = val;
1201                                                 break;
1202
1203                                         case UNITS:
1204                                                 tmask = 0;
1205                                                 ptype = val;
1206                                                 break;
1207
1208                                         case ISOTIME:
1209
1210                                                 /*
1211                                                  * This is a filler field "t" indicating that the next
1212                                                  * field is time. Try to verify that this is sensible.
1213                                                  */
1214                                                 tmask = 0;
1215
1216                                                 /* No preceding date? Then quit... */
1217                                                 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1218                                                         return DTERR_BAD_FORMAT;
1219
1220                                                 /***
1221                                                  * We will need one of the following fields:
1222                                                  *      DTK_NUMBER should be hhmmss.fff
1223                                                  *      DTK_TIME should be hh:mm:ss.fff
1224                                                  *      DTK_DATE should be hhmmss-zz
1225                                                  ***/
1226                                                 if (i >= nf - 1 ||
1227                                                         (ftype[i + 1] != DTK_NUMBER &&
1228                                                          ftype[i + 1] != DTK_TIME &&
1229                                                          ftype[i + 1] != DTK_DATE))
1230                                                         return DTERR_BAD_FORMAT;
1231
1232                                                 ptype = val;
1233                                                 break;
1234
1235                                         case UNKNOWN_FIELD:
1236
1237                                                 /*
1238                                                  * Before giving up and declaring error, check to see
1239                                                  * if it is an all-alpha timezone name.
1240                                                  */
1241                                                 namedTz = pg_tzset(field[i]);
1242                                                 if (!namedTz)
1243                                                         return DTERR_BAD_FORMAT;
1244                                                 /* we'll apply the zone setting below */
1245                                                 tmask = DTK_M(TZ);
1246                                                 break;
1247
1248                                         default:
1249                                                 return DTERR_BAD_FORMAT;
1250                                 }
1251                                 break;
1252
1253                         default:
1254                                 return DTERR_BAD_FORMAT;
1255                 }
1256
1257                 if (tmask & fmask)
1258                         return DTERR_BAD_FORMAT;
1259                 fmask |= tmask;
1260         }                               /* end loop over fields */
1261
1262         /* do final checking/adjustment of Y/M/D fields */
1263         dterr = ValidateDate(fmask, is2digits, bc, tm);
1264         if (dterr)
1265                 return dterr;
1266
1267         /* handle AM/PM */
1268         if (mer != HR24 && tm->tm_hour > 12)
1269                 return DTERR_FIELD_OVERFLOW;
1270         if (mer == AM && tm->tm_hour == 12)
1271                 tm->tm_hour = 0;
1272         else if (mer == PM && tm->tm_hour != 12)
1273                 tm->tm_hour += 12;
1274
1275         /* do additional checking for full date specs... */
1276         if (*dtype == DTK_DATE)
1277         {
1278                 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1279                 {
1280                         if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1281                                 return 1;
1282                         return DTERR_BAD_FORMAT;
1283                 }
1284
1285                 /*
1286                  * If we had a full timezone spec, compute the offset (we could not do
1287                  * it before, because we need the date to resolve DST status).
1288                  */
1289                 if (namedTz != NULL)
1290                 {
1291                         /* daylight savings time modifier disallowed with full TZ */
1292                         if (fmask & DTK_M(DTZMOD))
1293                                 return DTERR_BAD_FORMAT;
1294
1295                         *tzp = DetermineTimeZoneOffset(tm, namedTz);
1296                 }
1297
1298                 /* timezone not specified? then find local timezone if possible */
1299                 if (tzp != NULL && !(fmask & DTK_M(TZ)))
1300                 {
1301                         /*
1302                          * daylight savings time modifier but no standard timezone? then
1303                          * error
1304                          */
1305                         if (fmask & DTK_M(DTZMOD))
1306                                 return DTERR_BAD_FORMAT;
1307
1308                         *tzp = DetermineTimeZoneOffset(tm, session_timezone);
1309                 }
1310         }
1311
1312         return 0;
1313 }
1314
1315
1316 /* DetermineTimeZoneOffset()
1317  *
1318  * Given a struct pg_tm in which tm_year, tm_mon, tm_mday, tm_hour, tm_min, and
1319  * tm_sec fields are set, attempt to determine the applicable time zone
1320  * (ie, regular or daylight-savings time) at that time.  Set the struct pg_tm's
1321  * tm_isdst field accordingly, and return the actual timezone offset.
1322  *
1323  * Note: it might seem that we should use mktime() for this, but bitter
1324  * experience teaches otherwise.  This code is much faster than most versions
1325  * of mktime(), anyway.
1326  */
1327 int
1328 DetermineTimeZoneOffset(struct pg_tm * tm, pg_tz *tzp)
1329 {
1330         int                     date,
1331                                 sec;
1332         pg_time_t       day,
1333                                 mytime,
1334                                 prevtime,
1335                                 boundary,
1336                                 beforetime,
1337                                 aftertime;
1338         long int        before_gmtoff,
1339                                 after_gmtoff;
1340         int                     before_isdst,
1341                                 after_isdst;
1342         int                     res;
1343
1344         if (tzp == session_timezone && HasCTZSet)
1345         {
1346                 tm->tm_isdst = 0;               /* for lack of a better idea */
1347                 return CTimeZone;
1348         }
1349
1350         /*
1351          * First, generate the pg_time_t value corresponding to the given
1352          * y/m/d/h/m/s taken as GMT time.  If this overflows, punt and decide the
1353          * timezone is GMT.  (We only need to worry about overflow on machines
1354          * where pg_time_t is 32 bits.)
1355          */
1356         if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
1357                 goto overflow;
1358         date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - UNIX_EPOCH_JDATE;
1359
1360         day = ((pg_time_t) date) * SECS_PER_DAY;
1361         if (day / SECS_PER_DAY != date)
1362                 goto overflow;
1363         sec = tm->tm_sec + (tm->tm_min + tm->tm_hour * MINS_PER_HOUR) * SECS_PER_MINUTE;
1364         mytime = day + sec;
1365         /* since sec >= 0, overflow could only be from +day to -mytime */
1366         if (mytime < 0 && day > 0)
1367                 goto overflow;
1368
1369         /*
1370          * Find the DST time boundary just before or following the target time. We
1371          * assume that all zones have GMT offsets less than 24 hours, and that DST
1372          * boundaries can't be closer together than 48 hours, so backing up 24
1373          * hours and finding the "next" boundary will work.
1374          */
1375         prevtime = mytime - SECS_PER_DAY;
1376         if (mytime < 0 && prevtime > 0)
1377                 goto overflow;
1378
1379         res = pg_next_dst_boundary(&prevtime,
1380                                                            &before_gmtoff, &before_isdst,
1381                                                            &boundary,
1382                                                            &after_gmtoff, &after_isdst,
1383                                                            tzp);
1384         if (res < 0)
1385                 goto overflow;                  /* failure? */
1386
1387         if (res == 0)
1388         {
1389                 /* Non-DST zone, life is simple */
1390                 tm->tm_isdst = before_isdst;
1391                 return -(int) before_gmtoff;
1392         }
1393
1394         /*
1395          * Form the candidate pg_time_t values with local-time adjustment
1396          */
1397         beforetime = mytime - before_gmtoff;
1398         if ((before_gmtoff > 0 &&
1399                  mytime < 0 && beforetime > 0) ||
1400                 (before_gmtoff <= 0 &&
1401                  mytime > 0 && beforetime < 0))
1402                 goto overflow;
1403         aftertime = mytime - after_gmtoff;
1404         if ((after_gmtoff > 0 &&
1405                  mytime < 0 && aftertime > 0) ||
1406                 (after_gmtoff <= 0 &&
1407                  mytime > 0 && aftertime < 0))
1408                 goto overflow;
1409
1410         /*
1411          * If both before or both after the boundary time, we know what to do
1412          */
1413         if (beforetime <= boundary && aftertime < boundary)
1414         {
1415                 tm->tm_isdst = before_isdst;
1416                 return -(int) before_gmtoff;
1417         }
1418         if (beforetime > boundary && aftertime >= boundary)
1419         {
1420                 tm->tm_isdst = after_isdst;
1421                 return -(int) after_gmtoff;
1422         }
1423
1424         /*
1425          * It's an invalid or ambiguous time due to timezone transition. Prefer
1426          * the standard-time interpretation.
1427          */
1428         if (after_isdst == 0)
1429         {
1430                 tm->tm_isdst = after_isdst;
1431                 return -(int) after_gmtoff;
1432         }
1433         tm->tm_isdst = before_isdst;
1434         return -(int) before_gmtoff;
1435
1436 overflow:
1437         /* Given date is out of range, so assume UTC */
1438         tm->tm_isdst = 0;
1439         return 0;
1440 }
1441
1442
1443 /* DecodeTimeOnly()
1444  * Interpret parsed string as time fields only.
1445  * Returns 0 if successful, DTERR code if bogus input detected.
1446  *
1447  * Note that support for time zone is here for
1448  * SQL92 TIME WITH TIME ZONE, but it reveals
1449  * bogosity with SQL92 date/time standards, since
1450  * we must infer a time zone from current time.
1451  * - thomas 2000-03-10
1452  * Allow specifying date to get a better time zone,
1453  * if time zones are allowed. - thomas 2001-12-26
1454  */
1455 int
1456 DecodeTimeOnly(char **field, int *ftype, int nf,
1457                            int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
1458 {
1459         int                     fmask = 0,
1460                                 tmask,
1461                                 type;
1462         int                     ptype = 0;              /* "prefix type" for ISO h04mm05s06 format */
1463         int                     i;
1464         int                     val;
1465         int                     dterr;
1466         bool            is2digits = FALSE;
1467         bool            bc = FALSE;
1468         int                     mer = HR24;
1469         pg_tz      *namedTz = NULL;
1470
1471         *dtype = DTK_TIME;
1472         tm->tm_hour = 0;
1473         tm->tm_min = 0;
1474         tm->tm_sec = 0;
1475         *fsec = 0;
1476         /* don't know daylight savings time status apriori */
1477         tm->tm_isdst = -1;
1478
1479         if (tzp != NULL)
1480                 *tzp = 0;
1481
1482         for (i = 0; i < nf; i++)
1483         {
1484                 switch (ftype[i])
1485                 {
1486                         case DTK_DATE:
1487
1488                                 /*
1489                                  * Time zone not allowed? Then should not accept dates or time
1490                                  * zones no matter what else!
1491                                  */
1492                                 if (tzp == NULL)
1493                                         return DTERR_BAD_FORMAT;
1494
1495                                 /* Under limited circumstances, we will accept a date... */
1496                                 if (i == 0 && nf >= 2 &&
1497                                         (ftype[nf - 1] == DTK_DATE || ftype[1] == DTK_TIME))
1498                                 {
1499                                         dterr = DecodeDate(field[i], fmask,
1500                                                                            &tmask, &is2digits, tm);
1501                                         if (dterr)
1502                                                 return dterr;
1503                                 }
1504                                 /* otherwise, this is a time and/or time zone */
1505                                 else
1506                                 {
1507                                         if (isdigit((unsigned char) *field[i]))
1508                                         {
1509                                                 char       *cp;
1510
1511                                                 /*
1512                                                  * Starts with a digit but we already have a time
1513                                                  * field? Then we are in trouble with time already...
1514                                                  */
1515                                                 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1516                                                         return DTERR_BAD_FORMAT;
1517
1518                                                 /*
1519                                                  * Should not get here and fail. Sanity check only...
1520                                                  */
1521                                                 if ((cp = strchr(field[i], '-')) == NULL)
1522                                                         return DTERR_BAD_FORMAT;
1523
1524                                                 /* Get the time zone from the end of the string */
1525                                                 dterr = DecodeTimezone(cp, tzp);
1526                                                 if (dterr)
1527                                                         return dterr;
1528                                                 *cp = '\0';
1529
1530                                                 /*
1531                                                  * Then read the rest of the field as a concatenated
1532                                                  * time
1533                                                  */
1534                                                 dterr = DecodeNumberField(strlen(field[i]), field[i],
1535                                                                                                   (fmask | DTK_DATE_M),
1536                                                                                                   &tmask, tm,
1537                                                                                                   fsec, &is2digits);
1538                                                 if (dterr < 0)
1539                                                         return dterr;
1540                                                 ftype[i] = dterr;
1541
1542                                                 tmask |= DTK_M(TZ);
1543                                         }
1544                                         else
1545                                         {
1546                                                 namedTz = pg_tzset(field[i]);
1547                                                 if (!namedTz)
1548                                                 {
1549                                                         /*
1550                                                          * We should return an error code instead of
1551                                                          * ereport'ing directly, but then there is no way
1552                                                          * to report the bad time zone name.
1553                                                          */
1554                                                         ereport(ERROR,
1555                                                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1556                                                                          errmsg("time zone \"%s\" not recognized",
1557                                                                                         field[i])));
1558                                                 }
1559                                                 /* we'll apply the zone setting below */
1560                                                 ftype[i] = DTK_TZ;
1561                                                 tmask = DTK_M(TZ);
1562                                         }
1563                                 }
1564                                 break;
1565
1566                         case DTK_TIME:
1567                                 dterr = DecodeTime(field[i], (fmask | DTK_DATE_M),
1568                                                                    INTERVAL_FULL_RANGE,
1569                                                                    &tmask, tm, fsec);
1570                                 if (dterr)
1571                                         return dterr;
1572                                 break;
1573
1574                         case DTK_TZ:
1575                                 {
1576                                         int                     tz;
1577
1578                                         if (tzp == NULL)
1579                                                 return DTERR_BAD_FORMAT;
1580
1581                                         dterr = DecodeTimezone(field[i], &tz);
1582                                         if (dterr)
1583                                                 return dterr;
1584                                         *tzp = tz;
1585                                         tmask = DTK_M(TZ);
1586                                 }
1587                                 break;
1588
1589                         case DTK_NUMBER:
1590
1591                                 /*
1592                                  * Was this an "ISO time" with embedded field labels? An
1593                                  * example is "h04m05s06" - thomas 2001-02-04
1594                                  */
1595                                 if (ptype != 0)
1596                                 {
1597                                         char       *cp;
1598                                         int                     val;
1599
1600                                         /* Only accept a date under limited circumstances */
1601                                         switch (ptype)
1602                                         {
1603                                                 case DTK_JULIAN:
1604                                                 case DTK_YEAR:
1605                                                 case DTK_MONTH:
1606                                                 case DTK_DAY:
1607                                                         if (tzp == NULL)
1608                                                                 return DTERR_BAD_FORMAT;
1609                                                 default:
1610                                                         break;
1611                                         }
1612
1613                                         errno = 0;
1614                                         val = strtoi(field[i], &cp, 10);
1615                                         if (errno == ERANGE)
1616                                                 return DTERR_FIELD_OVERFLOW;
1617
1618                                         /*
1619                                          * only a few kinds are allowed to have an embedded
1620                                          * decimal
1621                                          */
1622                                         if (*cp == '.')
1623                                                 switch (ptype)
1624                                                 {
1625                                                         case DTK_JULIAN:
1626                                                         case DTK_TIME:
1627                                                         case DTK_SECOND:
1628                                                                 break;
1629                                                         default:
1630                                                                 return DTERR_BAD_FORMAT;
1631                                                                 break;
1632                                                 }
1633                                         else if (*cp != '\0')
1634                                                 return DTERR_BAD_FORMAT;
1635
1636                                         switch (ptype)
1637                                         {
1638                                                 case DTK_YEAR:
1639                                                         tm->tm_year = val;
1640                                                         tmask = DTK_M(YEAR);
1641                                                         break;
1642
1643                                                 case DTK_MONTH:
1644
1645                                                         /*
1646                                                          * already have a month and hour? then assume
1647                                                          * minutes
1648                                                          */
1649                                                         if ((fmask & DTK_M(MONTH)) != 0 &&
1650                                                                 (fmask & DTK_M(HOUR)) != 0)
1651                                                         {
1652                                                                 tm->tm_min = val;
1653                                                                 tmask = DTK_M(MINUTE);
1654                                                         }
1655                                                         else
1656                                                         {
1657                                                                 tm->tm_mon = val;
1658                                                                 tmask = DTK_M(MONTH);
1659                                                         }
1660                                                         break;
1661
1662                                                 case DTK_DAY:
1663                                                         tm->tm_mday = val;
1664                                                         tmask = DTK_M(DAY);
1665                                                         break;
1666
1667                                                 case DTK_HOUR:
1668                                                         tm->tm_hour = val;
1669                                                         tmask = DTK_M(HOUR);
1670                                                         break;
1671
1672                                                 case DTK_MINUTE:
1673                                                         tm->tm_min = val;
1674                                                         tmask = DTK_M(MINUTE);
1675                                                         break;
1676
1677                                                 case DTK_SECOND:
1678                                                         tm->tm_sec = val;
1679                                                         tmask = DTK_M(SECOND);
1680                                                         if (*cp == '.')
1681                                                         {
1682                                                                 double          frac;
1683
1684                                                                 frac = strtod(cp, &cp);
1685                                                                 if (*cp != '\0')
1686                                                                         return DTERR_BAD_FORMAT;
1687 #ifdef HAVE_INT64_TIMESTAMP
1688                                                                 *fsec = rint(frac * 1000000);
1689 #else
1690                                                                 *fsec = frac;
1691 #endif
1692                                                                 tmask = DTK_ALL_SECS_M;
1693                                                         }
1694                                                         break;
1695
1696                                                 case DTK_TZ:
1697                                                         tmask = DTK_M(TZ);
1698                                                         dterr = DecodeTimezone(field[i], tzp);
1699                                                         if (dterr)
1700                                                                 return dterr;
1701                                                         break;
1702
1703                                                 case DTK_JULIAN:
1704                                                         /***
1705                                                          * previous field was a label for "julian date"?
1706                                                          ***/
1707                                                         tmask = DTK_DATE_M;
1708                                                         j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1709                                                         if (*cp == '.')
1710                                                         {
1711                                                                 double          time;
1712
1713                                                                 time = strtod(cp, &cp);
1714                                                                 if (*cp != '\0')
1715                                                                         return DTERR_BAD_FORMAT;
1716
1717                                                                 tmask |= DTK_TIME_M;
1718 #ifdef HAVE_INT64_TIMESTAMP
1719                                                                 dt2time(time * USECS_PER_DAY,
1720                                                                 &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1721 #else
1722                                                                 dt2time(time * SECS_PER_DAY,
1723                                                                 &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1724 #endif
1725                                                         }
1726                                                         break;
1727
1728                                                 case DTK_TIME:
1729                                                         /* previous field was "t" for ISO time */
1730                                                         dterr = DecodeNumberField(strlen(field[i]), field[i],
1731                                                                                                           (fmask | DTK_DATE_M),
1732                                                                                                           &tmask, tm,
1733                                                                                                           fsec, &is2digits);
1734                                                         if (dterr < 0)
1735                                                                 return dterr;
1736                                                         ftype[i] = dterr;
1737
1738                                                         if (tmask != DTK_TIME_M)
1739                                                                 return DTERR_BAD_FORMAT;
1740                                                         break;
1741
1742                                                 default:
1743                                                         return DTERR_BAD_FORMAT;
1744                                                         break;
1745                                         }
1746
1747                                         ptype = 0;
1748                                         *dtype = DTK_DATE;
1749                                 }
1750                                 else
1751                                 {
1752                                         char       *cp;
1753                                         int                     flen;
1754
1755                                         flen = strlen(field[i]);
1756                                         cp = strchr(field[i], '.');
1757
1758                                         /* Embedded decimal? */
1759                                         if (cp != NULL)
1760                                         {
1761                                                 /*
1762                                                  * Under limited circumstances, we will accept a
1763                                                  * date...
1764                                                  */
1765                                                 if (i == 0 && nf >= 2 && ftype[nf - 1] == DTK_DATE)
1766                                                 {
1767                                                         dterr = DecodeDate(field[i], fmask,
1768                                                                                            &tmask, &is2digits, tm);
1769                                                         if (dterr)
1770                                                                 return dterr;
1771                                                 }
1772                                                 /* embedded decimal and several digits before? */
1773                                                 else if (flen - strlen(cp) > 2)
1774                                                 {
1775                                                         /*
1776                                                          * Interpret as a concatenated date or time Set
1777                                                          * the type field to allow decoding other fields
1778                                                          * later. Example: 20011223 or 040506
1779                                                          */
1780                                                         dterr = DecodeNumberField(flen, field[i],
1781                                                                                                           (fmask | DTK_DATE_M),
1782                                                                                                           &tmask, tm,
1783                                                                                                           fsec, &is2digits);
1784                                                         if (dterr < 0)
1785                                                                 return dterr;
1786                                                         ftype[i] = dterr;
1787                                                 }
1788                                                 else
1789                                                         return DTERR_BAD_FORMAT;
1790                                         }
1791                                         else if (flen > 4)
1792                                         {
1793                                                 dterr = DecodeNumberField(flen, field[i],
1794                                                                                                   (fmask | DTK_DATE_M),
1795                                                                                                   &tmask, tm,
1796                                                                                                   fsec, &is2digits);
1797                                                 if (dterr < 0)
1798                                                         return dterr;
1799                                                 ftype[i] = dterr;
1800                                         }
1801                                         /* otherwise it is a single date/time field... */
1802                                         else
1803                                         {
1804                                                 dterr = DecodeNumber(flen, field[i],
1805                                                                                          FALSE,
1806                                                                                          (fmask | DTK_DATE_M),
1807                                                                                          &tmask, tm,
1808                                                                                          fsec, &is2digits);
1809                                                 if (dterr)
1810                                                         return dterr;
1811                                         }
1812                                 }
1813                                 break;
1814
1815                         case DTK_STRING:
1816                         case DTK_SPECIAL:
1817                                 type = DecodeSpecial(i, field[i], &val);
1818                                 if (type == IGNORE_DTF)
1819                                         continue;
1820
1821                                 tmask = DTK_M(type);
1822                                 switch (type)
1823                                 {
1824                                         case RESERV:
1825                                                 switch (val)
1826                                                 {
1827                                                         case DTK_CURRENT:
1828                                                                 ereport(ERROR,
1829                                                                          (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1830                                                                           errmsg("date/time value \"current\" is no longer supported")));
1831                                                                 return DTERR_BAD_FORMAT;
1832                                                                 break;
1833
1834                                                         case DTK_NOW:
1835                                                                 tmask = DTK_TIME_M;
1836                                                                 *dtype = DTK_TIME;
1837                                                                 GetCurrentTimeUsec(tm, fsec, NULL);
1838                                                                 break;
1839
1840                                                         case DTK_ZULU:
1841                                                                 tmask = (DTK_TIME_M | DTK_M(TZ));
1842                                                                 *dtype = DTK_TIME;
1843                                                                 tm->tm_hour = 0;
1844                                                                 tm->tm_min = 0;
1845                                                                 tm->tm_sec = 0;
1846                                                                 tm->tm_isdst = 0;
1847                                                                 break;
1848
1849                                                         default:
1850                                                                 return DTERR_BAD_FORMAT;
1851                                                 }
1852
1853                                                 break;
1854
1855                                         case DTZMOD:
1856
1857                                                 /*
1858                                                  * daylight savings time modifier (solves "MET DST"
1859                                                  * syntax)
1860                                                  */
1861                                                 tmask |= DTK_M(DTZ);
1862                                                 tm->tm_isdst = 1;
1863                                                 if (tzp == NULL)
1864                                                         return DTERR_BAD_FORMAT;
1865                                                 *tzp += val * MINS_PER_HOUR;
1866                                                 break;
1867
1868                                         case DTZ:
1869
1870                                                 /*
1871                                                  * set mask for TZ here _or_ check for DTZ later when
1872                                                  * getting default timezone
1873                                                  */
1874                                                 tmask |= DTK_M(TZ);
1875                                                 tm->tm_isdst = 1;
1876                                                 if (tzp == NULL)
1877                                                         return DTERR_BAD_FORMAT;
1878                                                 *tzp = val * MINS_PER_HOUR;
1879                                                 ftype[i] = DTK_TZ;
1880                                                 break;
1881
1882                                         case TZ:
1883                                                 tm->tm_isdst = 0;
1884                                                 if (tzp == NULL)
1885                                                         return DTERR_BAD_FORMAT;
1886                                                 *tzp = val * MINS_PER_HOUR;
1887                                                 ftype[i] = DTK_TZ;
1888                                                 break;
1889
1890                                         case IGNORE_DTF:
1891                                                 break;
1892
1893                                         case AMPM:
1894                                                 mer = val;
1895                                                 break;
1896
1897                                         case ADBC:
1898                                                 bc = (val == BC);
1899                                                 break;
1900
1901                                         case UNITS:
1902                                                 tmask = 0;
1903                                                 ptype = val;
1904                                                 break;
1905
1906                                         case ISOTIME:
1907                                                 tmask = 0;
1908
1909                                                 /***
1910                                                  * We will need one of the following fields:
1911                                                  *      DTK_NUMBER should be hhmmss.fff
1912                                                  *      DTK_TIME should be hh:mm:ss.fff
1913                                                  *      DTK_DATE should be hhmmss-zz
1914                                                  ***/
1915                                                 if (i >= nf - 1 ||
1916                                                         (ftype[i + 1] != DTK_NUMBER &&
1917                                                          ftype[i + 1] != DTK_TIME &&
1918                                                          ftype[i + 1] != DTK_DATE))
1919                                                         return DTERR_BAD_FORMAT;
1920
1921                                                 ptype = val;
1922                                                 break;
1923
1924                                         case UNKNOWN_FIELD:
1925
1926                                                 /*
1927                                                  * Before giving up and declaring error, check to see
1928                                                  * if it is an all-alpha timezone name.
1929                                                  */
1930                                                 namedTz = pg_tzset(field[i]);
1931                                                 if (!namedTz)
1932                                                         return DTERR_BAD_FORMAT;
1933                                                 /* we'll apply the zone setting below */
1934                                                 tmask = DTK_M(TZ);
1935                                                 break;
1936
1937                                         default:
1938                                                 return DTERR_BAD_FORMAT;
1939                                 }
1940                                 break;
1941
1942                         default:
1943                                 return DTERR_BAD_FORMAT;
1944                 }
1945
1946                 if (tmask & fmask)
1947                         return DTERR_BAD_FORMAT;
1948                 fmask |= tmask;
1949         }                               /* end loop over fields */
1950
1951         /* do final checking/adjustment of Y/M/D fields */
1952         dterr = ValidateDate(fmask, is2digits, bc, tm);
1953         if (dterr)
1954                 return dterr;
1955
1956         /* handle AM/PM */
1957         if (mer != HR24 && tm->tm_hour > 12)
1958                 return DTERR_FIELD_OVERFLOW;
1959         if (mer == AM && tm->tm_hour == 12)
1960                 tm->tm_hour = 0;
1961         else if (mer == PM && tm->tm_hour != 12)
1962                 tm->tm_hour += 12;
1963
1964         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
1965                 tm->tm_sec < 0 || tm->tm_sec > 60 || tm->tm_hour > 24 ||
1966         /* test for > 24:00:00 */
1967 #ifdef HAVE_INT64_TIMESTAMP
1968                 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0 ||
1969                                                            *fsec > INT64CONST(0))) ||
1970                 *fsec < INT64CONST(0) || *fsec >= USECS_PER_SEC
1971 #else
1972                 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0 ||
1973                                                            *fsec > 0)) ||
1974                 *fsec < 0 || *fsec >= 1
1975 #endif
1976                 )
1977                 return DTERR_FIELD_OVERFLOW;
1978
1979         if ((fmask & DTK_TIME_M) != DTK_TIME_M)
1980                 return DTERR_BAD_FORMAT;
1981
1982         /*
1983          * If we had a full timezone spec, compute the offset (we could not do it
1984          * before, because we may need the date to resolve DST status).
1985          */
1986         if (namedTz != NULL)
1987         {
1988                 long int        gmtoff;
1989
1990                 /* daylight savings time modifier disallowed with full TZ */
1991                 if (fmask & DTK_M(DTZMOD))
1992                         return DTERR_BAD_FORMAT;
1993
1994                 /* if non-DST zone, we do not need to know the date */
1995                 if (pg_get_timezone_offset(namedTz, &gmtoff))
1996                 {
1997                         *tzp = -(int) gmtoff;
1998                 }
1999                 else
2000                 {
2001                         /* a date has to be specified */
2002                         if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2003                                 return DTERR_BAD_FORMAT;
2004                         *tzp = DetermineTimeZoneOffset(tm, namedTz);
2005                 }
2006         }
2007
2008         /* timezone not specified? then find local timezone if possible */
2009         if (tzp != NULL && !(fmask & DTK_M(TZ)))
2010         {
2011                 struct pg_tm tt,
2012                                    *tmp = &tt;
2013
2014                 /*
2015                  * daylight savings time modifier but no standard timezone? then error
2016                  */
2017                 if (fmask & DTK_M(DTZMOD))
2018                         return DTERR_BAD_FORMAT;
2019
2020                 if ((fmask & DTK_DATE_M) == 0)
2021                         GetCurrentDateTime(tmp);
2022                 else
2023                 {
2024                         tmp->tm_year = tm->tm_year;
2025                         tmp->tm_mon = tm->tm_mon;
2026                         tmp->tm_mday = tm->tm_mday;
2027                 }
2028                 tmp->tm_hour = tm->tm_hour;
2029                 tmp->tm_min = tm->tm_min;
2030                 tmp->tm_sec = tm->tm_sec;
2031                 *tzp = DetermineTimeZoneOffset(tmp, session_timezone);
2032                 tm->tm_isdst = tmp->tm_isdst;
2033         }
2034
2035         return 0;
2036 }
2037
2038 /* DecodeDate()
2039  * Decode date string which includes delimiters.
2040  * Return 0 if okay, a DTERR code if not.
2041  *
2042  *      str: field to be parsed
2043  *      fmask: bitmask for field types already seen
2044  *      *tmask: receives bitmask for fields found here
2045  *      *is2digits: set to TRUE if we find 2-digit year
2046  *      *tm: field values are stored into appropriate members of this struct
2047  */
2048 static int
2049 DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
2050                    struct pg_tm * tm)
2051 {
2052         fsec_t          fsec;
2053         int                     nf = 0;
2054         int                     i,
2055                                 len;
2056         int                     dterr;
2057         bool            haveTextMonth = FALSE;
2058         int                     type,
2059                                 val,
2060                                 dmask = 0;
2061         char       *field[MAXDATEFIELDS];
2062
2063         *tmask = 0;
2064
2065         /* parse this string... */
2066         while (*str != '\0' && nf < MAXDATEFIELDS)
2067         {
2068                 /* skip field separators */
2069                 while (!isalnum((unsigned char) *str))
2070                         str++;
2071
2072                 field[nf] = str;
2073                 if (isdigit((unsigned char) *str))
2074                 {
2075                         while (isdigit((unsigned char) *str))
2076                                 str++;
2077                 }
2078                 else if (isalpha((unsigned char) *str))
2079                 {
2080                         while (isalpha((unsigned char) *str))
2081                                 str++;
2082                 }
2083
2084                 /* Just get rid of any non-digit, non-alpha characters... */
2085                 if (*str != '\0')
2086                         *str++ = '\0';
2087                 nf++;
2088         }
2089
2090         /* look first for text fields, since that will be unambiguous month */
2091         for (i = 0; i < nf; i++)
2092         {
2093                 if (isalpha((unsigned char) *field[i]))
2094                 {
2095                         type = DecodeSpecial(i, field[i], &val);
2096                         if (type == IGNORE_DTF)
2097                                 continue;
2098
2099                         dmask = DTK_M(type);
2100                         switch (type)
2101                         {
2102                                 case MONTH:
2103                                         tm->tm_mon = val;
2104                                         haveTextMonth = TRUE;
2105                                         break;
2106
2107                                 default:
2108                                         return DTERR_BAD_FORMAT;
2109                         }
2110                         if (fmask & dmask)
2111                                 return DTERR_BAD_FORMAT;
2112
2113                         fmask |= dmask;
2114                         *tmask |= dmask;
2115
2116                         /* mark this field as being completed */
2117                         field[i] = NULL;
2118                 }
2119         }
2120
2121         /* now pick up remaining numeric fields */
2122         for (i = 0; i < nf; i++)
2123         {
2124                 if (field[i] == NULL)
2125                         continue;
2126
2127                 if ((len = strlen(field[i])) <= 0)
2128                         return DTERR_BAD_FORMAT;
2129
2130                 dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2131                                                          &dmask, tm,
2132                                                          &fsec, is2digits);
2133                 if (dterr)
2134                         return dterr;
2135
2136                 if (fmask & dmask)
2137                         return DTERR_BAD_FORMAT;
2138
2139                 fmask |= dmask;
2140                 *tmask |= dmask;
2141         }
2142
2143         if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
2144                 return DTERR_BAD_FORMAT;
2145
2146         /* validation of the field values must wait until ValidateDate() */
2147
2148         return 0;
2149 }
2150
2151 /* ValidateDate()
2152  * Check valid year/month/day values, handle BC and DOY cases
2153  * Return 0 if okay, a DTERR code if not.
2154  */
2155 static int
2156 ValidateDate(int fmask, bool is2digits, bool bc, struct pg_tm * tm)
2157 {
2158         if (fmask & DTK_M(YEAR))
2159         {
2160                 if (bc)
2161                 {
2162                         /* there is no year zero in AD/BC notation */
2163                         if (tm->tm_year <= 0)
2164                                 return DTERR_FIELD_OVERFLOW;
2165                         /* internally, we represent 1 BC as year zero, 2 BC as -1, etc */
2166                         tm->tm_year = -(tm->tm_year - 1);
2167                 }
2168                 else if (is2digits)
2169                 {
2170                         /* allow 2-digit input for 1970-2069 AD; 00 is allowed */
2171                         if (tm->tm_year < 0)                            /* just paranoia */
2172                                 return DTERR_FIELD_OVERFLOW;
2173                         if (tm->tm_year < 70)
2174                                 tm->tm_year += 2000;
2175                         else if (tm->tm_year < 100)
2176                                 tm->tm_year += 1900;
2177                 }
2178                 else
2179                 {
2180                         /* there is no year zero in AD/BC notation */
2181                         if (tm->tm_year <= 0)
2182                                 return DTERR_FIELD_OVERFLOW;
2183                 }
2184         }
2185
2186         /* now that we have correct year, decode DOY */
2187         if (fmask & DTK_M(DOY))
2188         {
2189                 j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
2190                            &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2191         }
2192
2193         /* check for valid month */
2194         if (fmask & DTK_M(MONTH))
2195         {
2196                 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
2197                         return DTERR_MD_FIELD_OVERFLOW;
2198         }
2199
2200         /* minimal check for valid day */
2201         if (fmask & DTK_M(DAY))
2202         {
2203                 if (tm->tm_mday < 1 || tm->tm_mday > 31)
2204                         return DTERR_MD_FIELD_OVERFLOW;
2205         }
2206
2207         if ((fmask & DTK_DATE_M) == DTK_DATE_M)
2208         {
2209                 /*
2210                  * Check for valid day of month, now that we know for sure the month
2211                  * and year.  Note we don't use MD_FIELD_OVERFLOW here, since it seems
2212                  * unlikely that "Feb 29" is a YMD-order error.
2213                  */
2214                 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2215                         return DTERR_FIELD_OVERFLOW;
2216         }
2217
2218         return 0;
2219 }
2220
2221
2222 /* DecodeTime()
2223  * Decode time string which includes delimiters.
2224  * Return 0 if okay, a DTERR code if not.
2225  *
2226  * Only check the lower limit on hours, since this same code can be
2227  * used to represent time spans.
2228  */
2229 static int
2230 DecodeTime(char *str, int fmask, int range,
2231                    int *tmask, struct pg_tm * tm, fsec_t *fsec)
2232 {
2233         char       *cp;
2234
2235         *tmask = DTK_TIME_M;
2236
2237         errno = 0;
2238         tm->tm_hour = strtoi(str, &cp, 10);
2239         if (errno == ERANGE)
2240                 return DTERR_FIELD_OVERFLOW;
2241         if (*cp != ':')
2242                 return DTERR_BAD_FORMAT;
2243         str = cp + 1;
2244         errno = 0;
2245         tm->tm_min = strtoi(str, &cp, 10);
2246         if (errno == ERANGE)
2247                 return DTERR_FIELD_OVERFLOW;
2248         if (*cp == '\0')
2249         {
2250                 tm->tm_sec = 0;
2251                 *fsec = 0;
2252                 /* If it's a MINUTE TO SECOND interval, take 2 fields as being mm:ss */
2253                 if (range == (INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND)))
2254                 {
2255                         tm->tm_sec = tm->tm_min;
2256                         tm->tm_min = tm->tm_hour;
2257                         tm->tm_hour = 0;
2258                 }
2259         }
2260         else if (*cp == '.')
2261         {
2262                 /* always assume mm:ss.sss is MINUTE TO SECOND */
2263                 double          frac;
2264
2265                 str = cp;
2266                 frac = strtod(str, &cp);
2267                 if (*cp != '\0')
2268                         return DTERR_BAD_FORMAT;
2269 #ifdef HAVE_INT64_TIMESTAMP
2270                 *fsec = rint(frac * 1000000);
2271 #else
2272                 *fsec = frac;
2273 #endif
2274                 tm->tm_sec = tm->tm_min;
2275                 tm->tm_min = tm->tm_hour;
2276                 tm->tm_hour = 0;
2277         }
2278         else if (*cp == ':')
2279         {
2280                 str = cp + 1;
2281                 errno = 0;
2282                 tm->tm_sec = strtoi(str, &cp, 10);
2283                 if (errno == ERANGE)
2284                         return DTERR_FIELD_OVERFLOW;
2285                 if (*cp == '\0')
2286                         *fsec = 0;
2287                 else if (*cp == '.')
2288                 {
2289                         double          frac;
2290
2291                         str = cp;
2292                         frac = strtod(str, &cp);
2293                         if (*cp != '\0')
2294                                 return DTERR_BAD_FORMAT;
2295 #ifdef HAVE_INT64_TIMESTAMP
2296                         *fsec = rint(frac * 1000000);
2297 #else
2298                         *fsec = frac;
2299 #endif
2300                 }
2301                 else
2302                         return DTERR_BAD_FORMAT;
2303         }
2304         else
2305                 return DTERR_BAD_FORMAT;
2306
2307         /* do a sanity check */
2308 #ifdef HAVE_INT64_TIMESTAMP
2309         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2310                 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < INT64CONST(0) ||
2311                 *fsec >= USECS_PER_SEC)
2312                 return DTERR_FIELD_OVERFLOW;
2313 #else
2314         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2315                 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < 0 || *fsec >= 1)
2316                 return DTERR_FIELD_OVERFLOW;
2317 #endif
2318
2319         return 0;
2320 }
2321
2322
2323 /* DecodeNumber()
2324  * Interpret plain numeric field as a date value in context.
2325  * Return 0 if okay, a DTERR code if not.
2326  */
2327 static int
2328 DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask,
2329                          int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2330 {
2331         int                     val;
2332         char       *cp;
2333         int                     dterr;
2334
2335         *tmask = 0;
2336
2337         errno = 0;
2338         val = strtoi(str, &cp, 10);
2339         if (errno == ERANGE)
2340                 return DTERR_FIELD_OVERFLOW;
2341         if (cp == str)
2342                 return DTERR_BAD_FORMAT;
2343
2344         if (*cp == '.')
2345         {
2346                 double          frac;
2347
2348                 /*
2349                  * More than two digits before decimal point? Then could be a date or
2350                  * a run-together time: 2001.360 20011225 040506.789
2351                  */
2352                 if (cp - str > 2)
2353                 {
2354                         dterr = DecodeNumberField(flen, str,
2355                                                                           (fmask | DTK_DATE_M),
2356                                                                           tmask, tm,
2357                                                                           fsec, is2digits);
2358                         if (dterr < 0)
2359                                 return dterr;
2360                         return 0;
2361                 }
2362
2363                 frac = strtod(cp, &cp);
2364                 if (*cp != '\0')
2365                         return DTERR_BAD_FORMAT;
2366 #ifdef HAVE_INT64_TIMESTAMP
2367                 *fsec = rint(frac * 1000000);
2368 #else
2369                 *fsec = frac;
2370 #endif
2371         }
2372         else if (*cp != '\0')
2373                 return DTERR_BAD_FORMAT;
2374
2375         /* Special case for day of year */
2376         if (flen == 3 && (fmask & DTK_DATE_M) == DTK_M(YEAR) && val >= 1 &&
2377                 val <= 366)
2378         {
2379                 *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2380                 tm->tm_yday = val;
2381                 /* tm_mon and tm_mday can't actually be set yet ... */
2382                 return 0;
2383         }
2384
2385         /* Switch based on what we have so far */
2386         switch (fmask & DTK_DATE_M)
2387         {
2388                 case 0:
2389
2390                         /*
2391                          * Nothing so far; make a decision about what we think the input
2392                          * is.  There used to be lots of heuristics here, but the
2393                          * consensus now is to be paranoid.  It *must* be either
2394                          * YYYY-MM-DD (with a more-than-two-digit year field), or the
2395                          * field order defined by DateOrder.
2396                          */
2397                         if (flen >= 3 || DateOrder == DATEORDER_YMD)
2398                         {
2399                                 *tmask = DTK_M(YEAR);
2400                                 tm->tm_year = val;
2401                         }
2402                         else if (DateOrder == DATEORDER_DMY)
2403                         {
2404                                 *tmask = DTK_M(DAY);
2405                                 tm->tm_mday = val;
2406                         }
2407                         else
2408                         {
2409                                 *tmask = DTK_M(MONTH);
2410                                 tm->tm_mon = val;
2411                         }
2412                         break;
2413
2414                 case (DTK_M(YEAR)):
2415                         /* Must be at second field of YY-MM-DD */
2416                         *tmask = DTK_M(MONTH);
2417                         tm->tm_mon = val;
2418                         break;
2419
2420                 case (DTK_M(MONTH)):
2421                         if (haveTextMonth)
2422                         {
2423                                 /*
2424                                  * We are at the first numeric field of a date that included a
2425                                  * textual month name.  We want to support the variants
2426                                  * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2427                                  * inputs.      We will also accept MON-DD-YY or DD-MON-YY in
2428                                  * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2429                                  */
2430                                 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2431                                 {
2432                                         *tmask = DTK_M(YEAR);
2433                                         tm->tm_year = val;
2434                                 }
2435                                 else
2436                                 {
2437                                         *tmask = DTK_M(DAY);
2438                                         tm->tm_mday = val;
2439                                 }
2440                         }
2441                         else
2442                         {
2443                                 /* Must be at second field of MM-DD-YY */
2444                                 *tmask = DTK_M(DAY);
2445                                 tm->tm_mday = val;
2446                         }
2447                         break;
2448
2449                 case (DTK_M(YEAR) | DTK_M(MONTH)):
2450                         if (haveTextMonth)
2451                         {
2452                                 /* Need to accept DD-MON-YYYY even in YMD mode */
2453                                 if (flen >= 3 && *is2digits)
2454                                 {
2455                                         /* Guess that first numeric field is day was wrong */
2456                                         *tmask = DTK_M(DAY);            /* YEAR is already set */
2457                                         tm->tm_mday = tm->tm_year;
2458                                         tm->tm_year = val;
2459                                         *is2digits = FALSE;
2460                                 }
2461                                 else
2462                                 {
2463                                         *tmask = DTK_M(DAY);
2464                                         tm->tm_mday = val;
2465                                 }
2466                         }
2467                         else
2468                         {
2469                                 /* Must be at third field of YY-MM-DD */
2470                                 *tmask = DTK_M(DAY);
2471                                 tm->tm_mday = val;
2472                         }
2473                         break;
2474
2475                 case (DTK_M(DAY)):
2476                         /* Must be at second field of DD-MM-YY */
2477                         *tmask = DTK_M(MONTH);
2478                         tm->tm_mon = val;
2479                         break;
2480
2481                 case (DTK_M(MONTH) | DTK_M(DAY)):
2482                         /* Must be at third field of DD-MM-YY or MM-DD-YY */
2483                         *tmask = DTK_M(YEAR);
2484                         tm->tm_year = val;
2485                         break;
2486
2487                 case (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY)):
2488                         /* we have all the date, so it must be a time field */
2489                         dterr = DecodeNumberField(flen, str, fmask,
2490                                                                           tmask, tm,
2491                                                                           fsec, is2digits);
2492                         if (dterr < 0)
2493                                 return dterr;
2494                         return 0;
2495
2496                 default:
2497                         /* Anything else is bogus input */
2498                         return DTERR_BAD_FORMAT;
2499         }
2500
2501         /*
2502          * When processing a year field, mark it for adjustment if it's only one
2503          * or two digits.
2504          */
2505         if (*tmask == DTK_M(YEAR))
2506                 *is2digits = (flen <= 2);
2507
2508         return 0;
2509 }
2510
2511
2512 /* DecodeNumberField()
2513  * Interpret numeric string as a concatenated date or time field.
2514  * Return a DTK token (>= 0) if successful, a DTERR code (< 0) if not.
2515  *
2516  * Use the context of previously decoded fields to help with
2517  * the interpretation.
2518  */
2519 static int
2520 DecodeNumberField(int len, char *str, int fmask,
2521                                 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2522 {
2523         char       *cp;
2524
2525         /*
2526          * Have a decimal point? Then this is a date or something with a seconds
2527          * field...
2528          */
2529         if ((cp = strchr(str, '.')) != NULL)
2530         {
2531                 double          frac;
2532
2533                 frac = strtod(cp, NULL);
2534 #ifdef HAVE_INT64_TIMESTAMP
2535                 *fsec = rint(frac * 1000000);
2536 #else
2537                 *fsec = frac;
2538 #endif
2539                 *cp = '\0';
2540                 len = strlen(str);
2541         }
2542         /* No decimal point and no complete date yet? */
2543         else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2544         {
2545                 /* yyyymmdd? */
2546                 if (len == 8)
2547                 {
2548                         *tmask = DTK_DATE_M;
2549
2550                         tm->tm_mday = atoi(str + 6);
2551                         *(str + 6) = '\0';
2552                         tm->tm_mon = atoi(str + 4);
2553                         *(str + 4) = '\0';
2554                         tm->tm_year = atoi(str + 0);
2555
2556                         return DTK_DATE;
2557                 }
2558                 /* yymmdd? */
2559                 else if (len == 6)
2560                 {
2561                         *tmask = DTK_DATE_M;
2562                         tm->tm_mday = atoi(str + 4);
2563                         *(str + 4) = '\0';
2564                         tm->tm_mon = atoi(str + 2);
2565                         *(str + 2) = '\0';
2566                         tm->tm_year = atoi(str + 0);
2567                         *is2digits = TRUE;
2568
2569                         return DTK_DATE;
2570                 }
2571         }
2572
2573         /* not all time fields are specified? */
2574         if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2575         {
2576                 /* hhmmss */
2577                 if (len == 6)
2578                 {
2579                         *tmask = DTK_TIME_M;
2580                         tm->tm_sec = atoi(str + 4);
2581                         *(str + 4) = '\0';
2582                         tm->tm_min = atoi(str + 2);
2583                         *(str + 2) = '\0';
2584                         tm->tm_hour = atoi(str + 0);
2585
2586                         return DTK_TIME;
2587                 }
2588                 /* hhmm? */
2589                 else if (len == 4)
2590                 {
2591                         *tmask = DTK_TIME_M;
2592                         tm->tm_sec = 0;
2593                         tm->tm_min = atoi(str + 2);
2594                         *(str + 2) = '\0';
2595                         tm->tm_hour = atoi(str + 0);
2596
2597                         return DTK_TIME;
2598                 }
2599         }
2600
2601         return DTERR_BAD_FORMAT;
2602 }
2603
2604
2605 /* DecodeTimezone()
2606  * Interpret string as a numeric timezone.
2607  *
2608  * Return 0 if okay (and set *tzp), a DTERR code if not okay.
2609  *
2610  * NB: this must *not* ereport on failure; see commands/variable.c.
2611  *
2612  * Note: we allow timezone offsets up to 13:59.  There are places that
2613  * use +1300 summer time.
2614  */
2615 static int
2616 DecodeTimezone(char *str, int *tzp)
2617 {
2618         int                     tz;
2619         int                     hr,
2620                                 min,
2621                                 sec = 0;
2622         char       *cp;
2623
2624         /* leading character must be "+" or "-" */
2625         if (*str != '+' && *str != '-')
2626                 return DTERR_BAD_FORMAT;
2627
2628         errno = 0;
2629         hr = strtoi(str + 1, &cp, 10);
2630         if (errno == ERANGE)
2631                 return DTERR_TZDISP_OVERFLOW;
2632
2633         /* explicit delimiter? */
2634         if (*cp == ':')
2635         {
2636                 errno = 0;
2637                 min = strtoi(cp + 1, &cp, 10);
2638                 if (errno == ERANGE)
2639                         return DTERR_TZDISP_OVERFLOW;
2640                 if (*cp == ':')
2641                 {
2642                         errno = 0;
2643                         sec = strtoi(cp + 1, &cp, 10);
2644                         if (errno == ERANGE)
2645                                 return DTERR_TZDISP_OVERFLOW;
2646                 }
2647         }
2648         /* otherwise, might have run things together... */
2649         else if (*cp == '\0' && strlen(str) > 3)
2650         {
2651                 min = hr % 100;
2652                 hr = hr / 100;
2653                 /* we could, but don't, support a run-together hhmmss format */
2654         }
2655         else
2656                 min = 0;
2657
2658         if (hr < 0 || hr > 14)
2659                 return DTERR_TZDISP_OVERFLOW;
2660         if (min < 0 || min >= 60)
2661                 return DTERR_TZDISP_OVERFLOW;
2662         if (sec < 0 || sec >= 60)
2663                 return DTERR_TZDISP_OVERFLOW;
2664
2665         tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
2666         if (*str == '-')
2667                 tz = -tz;
2668
2669         *tzp = -tz;
2670
2671         if (*cp != '\0')
2672                 return DTERR_BAD_FORMAT;
2673
2674         return 0;
2675 }
2676
2677 /* DecodeSpecial()
2678  * Decode text string using lookup table.
2679  *
2680  * Implement a cache lookup since it is likely that dates
2681  *      will be related in format.
2682  *
2683  * NB: this must *not* ereport on failure;
2684  * see commands/variable.c.
2685  */
2686 int
2687 DecodeSpecial(int field, char *lowtoken, int *val)
2688 {
2689         int                     type;
2690         const datetkn *tp;
2691
2692         tp = datecache[field];
2693         if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
2694         {
2695                 tp = datebsearch(lowtoken, timezonetktbl, sztimezonetktbl);
2696                 if (tp == NULL)
2697                         tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
2698         }
2699         if (tp == NULL)
2700         {
2701                 type = UNKNOWN_FIELD;
2702                 *val = 0;
2703         }
2704         else
2705         {
2706                 datecache[field] = tp;
2707                 type = tp->type;
2708                 switch (type)
2709                 {
2710                         case TZ:
2711                         case DTZ:
2712                         case DTZMOD:
2713                                 *val = FROMVAL(tp);
2714                                 break;
2715
2716                         default:
2717                                 *val = tp->value;
2718                                 break;
2719                 }
2720         }
2721
2722         return type;
2723 }
2724
2725
2726 /* DecodeInterval()
2727  * Interpret previously parsed fields for general time interval.
2728  * Returns 0 if successful, DTERR code if bogus input detected.
2729  * dtype, tm, fsec are output parameters.
2730  *
2731  * Allow "date" field DTK_DATE since this could be just
2732  *      an unsigned floating point number. - thomas 1997-11-16
2733  *
2734  * Allow ISO-style time span, with implicit units on number of days
2735  *      preceding an hh:mm:ss field. - thomas 1998-04-30
2736  */
2737 int
2738 DecodeInterval(char **field, int *ftype, int nf, int range,
2739                            int *dtype, struct pg_tm * tm, fsec_t *fsec)
2740 {
2741         bool            is_before = FALSE;
2742         char       *cp;
2743         int                     fmask = 0,
2744                                 tmask,
2745                                 type;
2746         int                     i;
2747         int                     dterr;
2748         int                     val;
2749         double          fval;
2750
2751         *dtype = DTK_DELTA;
2752
2753         type = IGNORE_DTF;
2754         tm->tm_year = 0;
2755         tm->tm_mon = 0;
2756         tm->tm_mday = 0;
2757         tm->tm_hour = 0;
2758         tm->tm_min = 0;
2759         tm->tm_sec = 0;
2760         *fsec = 0;
2761
2762         /* read through list backwards to pick up units before values */
2763         for (i = nf - 1; i >= 0; i--)
2764         {
2765                 switch (ftype[i])
2766                 {
2767                         case DTK_TIME:
2768                                 dterr = DecodeTime(field[i], fmask, range,
2769                                                                    &tmask, tm, fsec);
2770                                 if (dterr)
2771                                         return dterr;
2772                                 type = DTK_DAY;
2773                                 break;
2774
2775                         case DTK_TZ:
2776
2777                                 /*
2778                                  * Timezone is a token with a leading sign character and
2779                                  * at least one digit; there could be ':', '.', '-'
2780                                  * embedded in it as well.
2781                                  */
2782                                 Assert(*field[i] == '-' || *field[i] == '+');
2783
2784                                 /*
2785                                  * Try for hh:mm or hh:mm:ss.  If not, fall through to
2786                                  * DTK_NUMBER case, which can handle signed float numbers
2787                                  * and signed year-month values.
2788                                  */
2789                                 if (strchr(field[i] + 1, ':') != NULL &&
2790                                         DecodeTime(field[i] + 1, fmask, INTERVAL_FULL_RANGE,
2791                                                            &tmask, tm, fsec) == 0)
2792                                 {
2793                                         if (*field[i] == '-')
2794                                         {
2795                                                 /* flip the sign on all fields */
2796                                                 tm->tm_hour = -tm->tm_hour;
2797                                                 tm->tm_min = -tm->tm_min;
2798                                                 tm->tm_sec = -tm->tm_sec;
2799                                                 *fsec = -(*fsec);
2800                                         }
2801
2802                                         /*
2803                                          * Set the next type to be a day, if units are not
2804                                          * specified. This handles the case of '1 +02:03' since we
2805                                          * are reading right to left.
2806                                          */
2807                                         type = DTK_DAY;
2808                                         tmask = DTK_M(TZ);
2809                                         break;
2810                                 }
2811                                 /* FALL THROUGH */
2812
2813                         case DTK_DATE:
2814                         case DTK_NUMBER:
2815                                 if (type == IGNORE_DTF)
2816                                 {
2817                                         /* use typmod to decide what rightmost field is */
2818                                         switch (range)
2819                                         {
2820                                                 case INTERVAL_MASK(YEAR):
2821                                                         type = DTK_YEAR;
2822                                                         break;
2823                                                 case INTERVAL_MASK(MONTH):
2824                                                 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
2825                                                         type = DTK_MONTH;
2826                                                         break;
2827                                                 case INTERVAL_MASK(DAY):
2828                                                         type = DTK_DAY;
2829                                                         break;
2830                                                 case INTERVAL_MASK(HOUR):
2831                                                 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
2832                                                 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
2833                                                 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2834                                                         type = DTK_HOUR;
2835                                                         break;
2836                                                 case INTERVAL_MASK(MINUTE):
2837                                                 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
2838                                                         type = DTK_MINUTE;
2839                                                         break;
2840                                                 case INTERVAL_MASK(SECOND):
2841                                                 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2842                                                 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
2843                                                         type = DTK_SECOND;
2844                                                         break;
2845                                                 default:
2846                                                         type = DTK_SECOND;
2847                                                         break;
2848                                         }
2849                                 }
2850
2851                                 errno = 0;
2852                                 val = strtoi(field[i], &cp, 10);
2853                                 if (errno == ERANGE)
2854                                         return DTERR_FIELD_OVERFLOW;
2855
2856                                 if (*cp == '-')
2857                                 {
2858                                         /* SQL "years-months" syntax */
2859                                         int             val2;
2860
2861                                         val2 = strtoi(cp + 1, &cp, 10);
2862                                         if (errno == ERANGE || val2 < 0 || val2 >= MONTHS_PER_YEAR)
2863                                                 return DTERR_FIELD_OVERFLOW;
2864                                         if (*cp != '\0')
2865                                                 return DTERR_BAD_FORMAT;
2866                                         type = DTK_MONTH;
2867                                         if (*field[i] == '-')
2868                                                 val2 = -val2;
2869                                         val = val * MONTHS_PER_YEAR + val2;
2870                                         fval = 0;
2871                                 }
2872                                 else if (*cp == '.')
2873                                 {
2874                                         fval = strtod(cp, &cp);
2875                                         if (*cp != '\0')
2876                                                 return DTERR_BAD_FORMAT;
2877
2878                                         if (*field[i] == '-')
2879                                                 fval = -fval;
2880                                 }
2881                                 else if (*cp == '\0')
2882                                         fval = 0;
2883                                 else
2884                                         return DTERR_BAD_FORMAT;
2885
2886                                 tmask = 0;              /* DTK_M(type); */
2887
2888                                 switch (type)
2889                                 {
2890                                         case DTK_MICROSEC:
2891 #ifdef HAVE_INT64_TIMESTAMP
2892                                                 *fsec += rint(val + fval);
2893 #else
2894                                                 *fsec += (val + fval) * 1e-6;
2895 #endif
2896                                                 tmask = DTK_M(MICROSECOND);
2897                                                 break;
2898
2899                                         case DTK_MILLISEC:
2900 #ifdef HAVE_INT64_TIMESTAMP
2901                                                 *fsec += rint((val + fval) * 1000);
2902 #else
2903                                                 *fsec += (val + fval) * 1e-3;
2904 #endif
2905                                                 tmask = DTK_M(MILLISECOND);
2906                                                 break;
2907
2908                                         case DTK_SECOND:
2909                                                 tm->tm_sec += val;
2910 #ifdef HAVE_INT64_TIMESTAMP
2911                                                 *fsec += rint(fval * 1000000);
2912 #else
2913                                                 *fsec += fval;
2914 #endif
2915
2916                                                 /*
2917                                                  * If any subseconds were specified, consider this
2918                                                  * microsecond and millisecond input as well.
2919                                                  */
2920                                                 if (fval == 0)
2921                                                         tmask = DTK_M(SECOND);
2922                                                 else
2923                                                         tmask = DTK_ALL_SECS_M;
2924                                                 break;
2925
2926                                         case DTK_MINUTE:
2927                                                 tm->tm_min += val;
2928                                                 if (fval != 0)
2929                                                 {
2930                                                         int                     sec;
2931
2932                                                         fval *= SECS_PER_MINUTE;
2933                                                         sec = fval;
2934                                                         tm->tm_sec += sec;
2935 #ifdef HAVE_INT64_TIMESTAMP
2936                                                         *fsec += rint((fval - sec) * 1000000);
2937 #else
2938                                                         *fsec += fval - sec;
2939 #endif
2940                                                 }
2941                                                 tmask = DTK_M(MINUTE);
2942                                                 break;
2943
2944                                         case DTK_HOUR:
2945                                                 tm->tm_hour += val;
2946                                                 if (fval != 0)
2947                                                 {
2948                                                         int                     sec;
2949
2950                                                         fval *= SECS_PER_HOUR;
2951                                                         sec = fval;
2952                                                         tm->tm_sec += sec;
2953 #ifdef HAVE_INT64_TIMESTAMP
2954                                                         *fsec += rint((fval - sec) * 1000000);
2955 #else
2956                                                         *fsec += fval - sec;
2957 #endif
2958                                                 }
2959                                                 tmask = DTK_M(HOUR);
2960                                                 type = DTK_DAY;
2961                                                 break;
2962
2963                                         case DTK_DAY:
2964                                                 tm->tm_mday += val;
2965                                                 if (fval != 0)
2966                                                 {
2967                                                         int                     sec;
2968
2969                                                         fval *= SECS_PER_DAY;
2970                                                         sec = fval;
2971                                                         tm->tm_sec += sec;
2972 #ifdef HAVE_INT64_TIMESTAMP
2973                                                         *fsec += rint((fval - sec) * 1000000);
2974 #else
2975                                                         *fsec += fval - sec;
2976 #endif
2977                                                 }
2978                                                 tmask = (fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY);
2979                                                 break;
2980
2981                                         case DTK_WEEK:
2982                                                 tm->tm_mday += val * 7;
2983                                                 if (fval != 0)
2984                                                 {
2985                                                         int                     extra_days;
2986
2987                                                         fval *= 7;
2988                                                         extra_days = (int32) fval;
2989                                                         tm->tm_mday += extra_days;
2990                                                         fval -= extra_days;
2991                                                         if (fval != 0)
2992                                                         {
2993                                                                 int                     sec;
2994
2995                                                                 fval *= SECS_PER_DAY;
2996                                                                 sec = fval;
2997                                                                 tm->tm_sec += sec;
2998 #ifdef HAVE_INT64_TIMESTAMP
2999                                                                 *fsec += rint((fval - sec) * 1000000);
3000 #else
3001                                                                 *fsec += fval - sec;
3002 #endif
3003                                                         }
3004                                                 }
3005                                                 tmask = (fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY);
3006                                                 break;
3007
3008                                         case DTK_MONTH:
3009                                                 tm->tm_mon += val;
3010                                                 if (fval != 0)
3011                                                 {
3012                                                         int                     day;
3013
3014                                                         fval *= DAYS_PER_MONTH;
3015                                                         day = fval;
3016                                                         tm->tm_mday += day;
3017                                                         fval -= day;
3018                                                         if (fval != 0)
3019                                                         {
3020                                                                 int                     sec;
3021
3022                                                                 fval *= SECS_PER_DAY;
3023                                                                 sec = fval;
3024                                                                 tm->tm_sec += sec;
3025 #ifdef HAVE_INT64_TIMESTAMP
3026                                                                 *fsec += rint((fval - sec) * 1000000);
3027 #else
3028                                                                 *fsec += fval - sec;
3029 #endif
3030                                                         }
3031                                                 }
3032                                                 tmask = DTK_M(MONTH);
3033                                                 break;
3034
3035                                         case DTK_YEAR:
3036                                                 tm->tm_year += val;
3037                                                 if (fval != 0)
3038                                                         tm->tm_mon += fval * MONTHS_PER_YEAR;
3039                                                 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
3040                                                 break;
3041
3042                                         case DTK_DECADE:
3043                                                 tm->tm_year += val * 10;
3044                                                 if (fval != 0)
3045                                                         tm->tm_mon += fval * MONTHS_PER_YEAR * 10;
3046                                                 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
3047                                                 break;
3048
3049                                         case DTK_CENTURY:
3050                                                 tm->tm_year += val * 100;
3051                                                 if (fval != 0)
3052                                                         tm->tm_mon += fval * MONTHS_PER_YEAR * 100;
3053                                                 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
3054                                                 break;
3055
3056                                         case DTK_MILLENNIUM:
3057                                                 tm->tm_year += val * 1000;
3058                                                 if (fval != 0)
3059                                                         tm->tm_mon += fval * MONTHS_PER_YEAR * 1000;
3060                                                 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
3061                                                 break;
3062
3063                                         default:
3064                                                 return DTERR_BAD_FORMAT;
3065                                 }
3066                                 break;
3067
3068                         case DTK_STRING:
3069                         case DTK_SPECIAL:
3070                                 type = DecodeUnits(i, field[i], &val);
3071                                 if (type == IGNORE_DTF)
3072                                         continue;
3073
3074                                 tmask = 0;              /* DTK_M(type); */
3075                                 switch (type)
3076                                 {
3077                                         case UNITS:
3078                                                 type = val;
3079                                                 break;
3080
3081                                         case AGO:
3082                                                 is_before = TRUE;
3083                                                 type = val;
3084                                                 break;
3085
3086                                         case RESERV:
3087                                                 tmask = (DTK_DATE_M || DTK_TIME_M);
3088                                                 *dtype = val;
3089                                                 break;
3090
3091                                         default:
3092                                                 return DTERR_BAD_FORMAT;
3093                                 }
3094                                 break;
3095
3096                         default:
3097                                 return DTERR_BAD_FORMAT;
3098                 }
3099
3100                 if (tmask & fmask)
3101                         return DTERR_BAD_FORMAT;
3102                 fmask |= tmask;
3103         }
3104
3105         /* ensure that at least one time field has been found */
3106         if (fmask == 0)
3107                 return DTERR_BAD_FORMAT;
3108
3109         /* ensure fractional seconds are fractional */
3110         if (*fsec != 0)
3111         {
3112                 int                     sec;
3113
3114 #ifdef HAVE_INT64_TIMESTAMP
3115                 sec = *fsec / USECS_PER_SEC;
3116                 *fsec -= sec * USECS_PER_SEC;
3117 #else
3118                 TMODULO(*fsec, sec, 1.0);
3119 #endif
3120                 tm->tm_sec += sec;
3121         }
3122
3123         /*----------
3124          * The SQL standard defines the interval literal
3125          *   '-1 1:00:00'
3126          * to mean "negative 1 days and negative 1 hours", while Postgres
3127          * traditionally treats this as meaning "negative 1 days and positive
3128          * 1 hours".  In SQL_STANDARD intervalstyle, we apply the leading sign
3129          * to all fields if there are no other explicit signs.
3130          *
3131          * We leave the signs alone if there are additional explicit signs.
3132          * This protects us against misinterpreting postgres-style dump output,
3133          * since the postgres-style output code has always put an explicit sign on
3134          * all fields following a negative field.  But note that SQL-spec output
3135          * is ambiguous and can be misinterpreted on load!  (So it's best practice
3136          * to dump in postgres style, not SQL style.)
3137          *----------
3138          */
3139         if (IntervalStyle == INTSTYLE_SQL_STANDARD && *field[0] == '-')
3140         {
3141                 /* Check for additional explicit signs */
3142                 bool    more_signs = false;
3143
3144                 for (i = 1; i < nf; i++)
3145                 {
3146                         if (*field[i] == '-' || *field[i] == '+')
3147                         {
3148                                 more_signs = true;
3149                                 break;
3150                         }
3151                 }
3152
3153                 if (!more_signs)
3154                 {
3155                         /*
3156                          * Rather than re-determining which field was field[0], just
3157                          * force 'em all negative.
3158                          */
3159                         if (*fsec > 0)
3160                                 *fsec = -(*fsec);
3161                         if (tm->tm_sec > 0)
3162                                 tm->tm_sec = -tm->tm_sec;
3163                         if (tm->tm_min > 0)
3164                                 tm->tm_min = -tm->tm_min;
3165                         if (tm->tm_hour > 0)
3166                                 tm->tm_hour = -tm->tm_hour;
3167                         if (tm->tm_mday > 0)
3168                                 tm->tm_mday = -tm->tm_mday;
3169                         if (tm->tm_mon > 0)
3170                                 tm->tm_mon = -tm->tm_mon;
3171                         if (tm->tm_year > 0)
3172                                 tm->tm_year = -tm->tm_year;
3173                 }
3174         }
3175
3176         /* finally, AGO negates everything */
3177         if (is_before)
3178         {
3179                 *fsec = -(*fsec);
3180                 tm->tm_sec = -tm->tm_sec;
3181                 tm->tm_min = -tm->tm_min;
3182                 tm->tm_hour = -tm->tm_hour;
3183                 tm->tm_mday = -tm->tm_mday;
3184                 tm->tm_mon = -tm->tm_mon;
3185                 tm->tm_year = -tm->tm_year;
3186         }
3187
3188         return 0;
3189 }
3190
3191
3192 /*
3193  * Helper functions to avoid duplicated code in DecodeISO8601Interval.
3194  *
3195  * Parse a decimal value and break it into integer and fractional parts.
3196  * Returns 0 or DTERR code.
3197  */
3198 static int
3199 ParseISO8601Number(char *str, char **endptr, int *ipart, double *fpart)
3200 {
3201         double          val;
3202
3203         if (!(isdigit((unsigned char) *str) || *str == '-' || *str == '.'))
3204                 return DTERR_BAD_FORMAT;
3205         errno = 0;
3206         val = strtod(str, endptr);
3207         /* did we not see anything that looks like a double? */
3208         if (*endptr == str || errno != 0)
3209                 return DTERR_BAD_FORMAT;
3210         /* watch out for overflow */
3211         if (val < INT_MIN || val > INT_MAX)
3212                 return DTERR_FIELD_OVERFLOW;
3213         /* be very sure we truncate towards zero (cf dtrunc()) */
3214         if (val >= 0)
3215                 *ipart = (int) floor(val);
3216         else
3217                 *ipart = (int) -floor(-val);
3218         *fpart = val - *ipart;
3219         return 0;
3220 }
3221
3222 /*
3223  * Determine number of integral digits in a valid ISO 8601 number field
3224  * (we should ignore sign and any fraction part)
3225  */
3226 static int
3227 ISO8601IntegerWidth(char *fieldstart)
3228 {
3229         /* We might have had a leading '-' */
3230         if (*fieldstart == '-')
3231                 fieldstart++;
3232         return strspn(fieldstart, "0123456789");
3233 }
3234
3235 /*
3236  * Multiply frac by scale (to produce seconds) and add to *tm & *fsec.
3237  * We assume the input frac is less than 1 so overflow is not an issue.
3238  */
3239 static void
3240 AdjustFractionalSeconds(double frac, struct pg_tm * tm, fsec_t *fsec,
3241                                                 int scale)
3242 {
3243         int     sec;
3244
3245         if (frac == 0)
3246                 return;
3247         frac       *= scale;
3248         sec         = (int) frac;
3249         tm->tm_sec += sec;
3250         frac       -= sec;
3251 #ifdef HAVE_INT64_TIMESTAMP
3252         *fsec      += rint(frac * 1000000);
3253 #else
3254         *fsec      += frac;
3255 #endif
3256 }
3257
3258 /* As above, but initial scale produces days */
3259 static void
3260 AdjustFractionalDays(double frac, struct pg_tm * tm, fsec_t *fsec, int scale)
3261 {
3262         int     extra_days;
3263
3264         if (frac == 0)
3265                 return;
3266         frac        *= scale;
3267         extra_days   = (int) frac;
3268         tm->tm_mday += extra_days;
3269         frac        -= extra_days;
3270         AdjustFractionalSeconds(frac, tm, fsec, SECS_PER_DAY);
3271 }
3272
3273
3274 /* DecodeISO8601Interval()
3275  *  Decode an ISO 8601 time interval of the "format with designators"
3276  *  (section 4.4.3.2) or "alternative format" (section 4.4.3.3)
3277  *  Examples:  P1D  for 1 day
3278  *             PT1H for 1 hour
3279  *             P2Y6M7DT1H30M for 2 years, 6 months, 7 days 1 hour 30 min
3280  *             P0002-06-07T01:30:00 the same value in alternative format
3281  *
3282  * Returns 0 if successful, DTERR code if bogus input detected.
3283  * Note: error code should be DTERR_BAD_FORMAT if input doesn't look like
3284  * ISO8601, otherwise this could cause unexpected error messages.
3285  * dtype, tm, fsec are output parameters.
3286  *
3287  *  A couple exceptions from the spec:
3288  *   - a week field ('W') may coexist with other units
3289  *   - allows decimals in fields other than the least significant unit.
3290  */
3291 int
3292 DecodeISO8601Interval(char *str,
3293                                           int *dtype, struct pg_tm * tm, fsec_t *fsec)
3294 {
3295         bool    datepart = true;
3296         bool    havefield = false;
3297
3298         *dtype = DTK_DELTA;
3299
3300         tm->tm_year = 0;
3301         tm->tm_mon = 0;
3302         tm->tm_mday = 0;
3303         tm->tm_hour = 0;
3304         tm->tm_min = 0;
3305         tm->tm_sec = 0;
3306         *fsec = 0;
3307
3308         if (strlen(str) < 2 || str[0] != 'P')
3309                 return DTERR_BAD_FORMAT;
3310
3311         str++;
3312         while (*str)
3313         {
3314                 char   *fieldstart;
3315                 int             val;
3316                 double  fval;
3317                 char    unit;
3318                 int             dterr;
3319
3320                 if (*str == 'T') /* T indicates the beginning of the time part */
3321                 {
3322                         datepart = false;
3323                         havefield = false;
3324                         str++;
3325                         continue;
3326                 }
3327
3328                 fieldstart = str;
3329                 dterr = ParseISO8601Number(str, &str, &val, &fval);
3330                 if (dterr)
3331                         return dterr;
3332
3333                 /*
3334                  * Note: we could step off the end of the string here.  Code below
3335                  * *must* exit the loop if unit == '\0'.
3336                  */
3337                 unit = *str++;
3338
3339                 if (datepart)
3340                 {
3341                         switch (unit) /* before T: Y M W D */
3342                         {
3343                                 case 'Y':
3344                                         tm->tm_year += val;
3345                                         tm->tm_mon += (fval * 12);
3346                                         break;
3347                                 case 'M':
3348                                         tm->tm_mon += val;
3349                                         AdjustFractionalDays(fval, tm, fsec, DAYS_PER_MONTH);
3350                                         break;
3351                                 case 'W':
3352                                         tm->tm_mday += val * 7;
3353                                         AdjustFractionalDays(fval, tm, fsec, 7);
3354                                         break;
3355                                 case 'D':
3356                                         tm->tm_mday += val;
3357                                         AdjustFractionalSeconds(fval, tm, fsec, SECS_PER_DAY);
3358                                         break;
3359                                 case 'T': /* ISO 8601 4.4.3.3 Alternative Format / Basic */
3360                                 case '\0':
3361                                         if (ISO8601IntegerWidth(fieldstart) == 8 && !havefield)
3362                                         {
3363                                                 tm->tm_year += val / 10000;
3364                                                 tm->tm_mon  += (val / 100) % 100;
3365                                                 tm->tm_mday += val % 100;
3366                                                 AdjustFractionalSeconds(fval, tm, fsec, SECS_PER_DAY);
3367                                                 if (unit == '\0')
3368                                                         return 0;
3369                                                 datepart = false;
3370                                                 havefield = false;
3371                                                 continue;
3372                                         }
3373                                         /* Else fall through to extended alternative format */
3374                                 case '-': /* ISO 8601 4.4.3.3 Alternative Format, Extended */
3375                                         if (havefield)
3376                                                 return DTERR_BAD_FORMAT;
3377
3378                                         tm->tm_year += val;
3379                                         tm->tm_mon  += (fval * 12);
3380                                         if (unit == '\0')
3381                                                 return 0;
3382                                         if (unit == 'T')
3383                                         {
3384                                                 datepart = false;
3385                                                 havefield = false;
3386                                                 continue;
3387                                         }
3388
3389                                         dterr = ParseISO8601Number(str, &str, &val, &fval);
3390                                         if (dterr)
3391                                                 return dterr;
3392                                         tm->tm_mon  += val;
3393                                         AdjustFractionalDays(fval, tm, fsec, DAYS_PER_MONTH);
3394                                         if (*str == '\0')
3395                                                 return 0;
3396                                         if (*str == 'T')
3397                                         {
3398                                                 datepart = false;
3399                                                 havefield = false;
3400                                                 continue;
3401                                         }
3402                                         if (*str != '-')
3403                                                 return DTERR_BAD_FORMAT;
3404                                         str++;
3405                                         
3406                                         dterr = ParseISO8601Number(str, &str, &val, &fval);
3407                                         if (dterr)
3408                                                 return dterr;
3409                                         tm->tm_mday += val;
3410                                         AdjustFractionalSeconds(fval, tm, fsec, SECS_PER_DAY);
3411                                         if (*str == '\0')
3412                                                 return 0;
3413                                         if (*str == 'T')
3414                                         {
3415                                                 datepart = false;
3416                                                 havefield = false;
3417                                                 continue;
3418                                         }
3419                                         return DTERR_BAD_FORMAT;
3420                                 default:
3421                                         /* not a valid date unit suffix */
3422                                         return DTERR_BAD_FORMAT;
3423                         }
3424                 }
3425                 else
3426                 {
3427                         switch (unit) /* after T: H M S */
3428                         {
3429                                 case 'H':
3430                                         tm->tm_hour += val;
3431                                         AdjustFractionalSeconds(fval, tm, fsec, SECS_PER_HOUR);
3432                                         break;
3433                                 case 'M':
3434                                         tm->tm_min += val;
3435                                         AdjustFractionalSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3436                                         break;
3437                                 case 'S':
3438                                         tm->tm_sec += val;
3439                                         AdjustFractionalSeconds(fval, tm, fsec, 1);
3440                                         break;
3441                                 case '\0': /* ISO 8601 4.4.3.3 Alternative Format */
3442                                     if (ISO8601IntegerWidth(fieldstart) == 6 && !havefield)
3443                                         {
3444                                                 tm->tm_hour += val / 10000;
3445                                                 tm->tm_min  += (val / 100) % 100;
3446                                                 tm->tm_sec  += val % 100;
3447                                                 AdjustFractionalSeconds(fval, tm, fsec, 1);
3448                                                 return 0;
3449                                         }
3450                                         /* Else fall through to extended alternative format */
3451                                 case ':': /* ISO 8601 4.4.3.3 Alternative Format, Extended */
3452                                         if (havefield)
3453                                                 return DTERR_BAD_FORMAT;
3454
3455                                         tm->tm_hour += val;
3456                                         AdjustFractionalSeconds(fval, tm, fsec, SECS_PER_HOUR);
3457                                         if (unit == '\0')
3458                                                 return 0;
3459                                         
3460                                         dterr = ParseISO8601Number(str, &str, &val, &fval);
3461                                         if (dterr)
3462                                                 return dterr;
3463                                         tm->tm_min  += val;
3464                                         AdjustFractionalSeconds(fval, tm, fsec, SECS_PER_MINUTE);
3465                                         if (*str == '\0')
3466                                                 return 0;
3467                                         if (*str != ':')
3468                                                 return DTERR_BAD_FORMAT;
3469                                         str++;
3470                                         
3471                                         dterr = ParseISO8601Number(str, &str, &val, &fval);
3472                                         if (dterr)
3473                                                 return dterr;
3474                                         tm->tm_sec  += val;
3475                                         AdjustFractionalSeconds(fval, tm, fsec, 1);
3476                                         if (*str == '\0')
3477                                                 return 0;
3478                                         return DTERR_BAD_FORMAT;
3479
3480                                 default:
3481                                         /* not a valid time unit suffix */
3482                                         return DTERR_BAD_FORMAT;
3483                         }
3484                 }
3485
3486                 havefield = true;
3487         }
3488
3489         return 0;
3490 }
3491
3492
3493 /* DecodeUnits()
3494  * Decode text string using lookup table.
3495  * This routine supports time interval decoding
3496  * (hence, it need not recognize timezone names).
3497  */
3498 int
3499 DecodeUnits(int field, char *lowtoken, int *val)
3500 {
3501         int                     type;
3502         const datetkn *tp;
3503
3504         tp = deltacache[field];
3505         if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3506         {
3507                 tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
3508         }
3509         if (tp == NULL)
3510         {
3511                 type = UNKNOWN_FIELD;
3512                 *val = 0;
3513         }
3514         else
3515         {
3516                 deltacache[field] = tp;
3517                 type = tp->type;
3518                 if (type == TZ || type == DTZ)
3519                         *val = FROMVAL(tp);
3520                 else
3521                         *val = tp->value;
3522         }
3523
3524         return type;
3525 }       /* DecodeUnits() */
3526
3527 /*
3528  * Report an error detected by one of the datetime input processing routines.
3529  *
3530  * dterr is the error code, str is the original input string, datatype is
3531  * the name of the datatype we were trying to accept.
3532  *
3533  * Note: it might seem useless to distinguish DTERR_INTERVAL_OVERFLOW and
3534  * DTERR_TZDISP_OVERFLOW from DTERR_FIELD_OVERFLOW, but SQL99 mandates three
3535  * separate SQLSTATE codes, so ...
3536  */
3537 void
3538 DateTimeParseError(int dterr, const char *str, const char *datatype)
3539 {
3540         switch (dterr)
3541         {
3542                 case DTERR_FIELD_OVERFLOW:
3543                         ereport(ERROR,
3544                                         (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3545                                          errmsg("date/time field value out of range: \"%s\"",
3546                                                         str)));
3547                         break;
3548                 case DTERR_MD_FIELD_OVERFLOW:
3549                         /* <nanny>same as above, but add hint about DateStyle</nanny> */
3550                         ereport(ERROR,
3551                                         (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3552                                          errmsg("date/time field value out of range: \"%s\"",
3553                                                         str),
3554                         errhint("Perhaps you need a different \"datestyle\" setting.")));
3555                         break;
3556                 case DTERR_INTERVAL_OVERFLOW:
3557                         ereport(ERROR,
3558                                         (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
3559                                          errmsg("interval field value out of range: \"%s\"",
3560                                                         str)));
3561                         break;
3562                 case DTERR_TZDISP_OVERFLOW:
3563                         ereport(ERROR,
3564                                         (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
3565                                          errmsg("time zone displacement out of range: \"%s\"",
3566                                                         str)));
3567                         break;
3568                 case DTERR_BAD_FORMAT:
3569                 default:
3570                         ereport(ERROR,
3571                                         (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
3572                                          errmsg("invalid input syntax for type %s: \"%s\"",
3573                                                         datatype, str)));
3574                         break;
3575         }
3576 }
3577
3578 /* datebsearch()
3579  * Binary search -- from Knuth (6.2.1) Algorithm B.  Special case like this
3580  * is WAY faster than the generic bsearch().
3581  */
3582 static const datetkn *
3583 datebsearch(const char *key, const datetkn *base, int nel)
3584 {
3585         const datetkn *last = base + nel - 1,
3586                            *position;
3587         int                     result;
3588
3589         while (last >= base)
3590         {
3591                 position = base + ((last - base) >> 1);
3592                 result = key[0] - position->token[0];
3593                 if (result == 0)
3594                 {
3595                         result = strncmp(key, position->token, TOKMAXLEN);
3596                         if (result == 0)
3597                                 return position;
3598                 }
3599                 if (result < 0)
3600                         last = position - 1;
3601                 else
3602                         base = position + 1;
3603         }
3604         return NULL;
3605 }
3606
3607 /* EncodeTimezone()
3608  *              Append representation of a numeric timezone offset to str.
3609  */
3610 static void
3611 EncodeTimezone(char *str, int tz, int style)
3612 {
3613         int                     hour,
3614                                 min,
3615                                 sec;
3616
3617         sec = abs(tz);
3618         min = sec / SECS_PER_MINUTE;
3619         sec -= min * SECS_PER_MINUTE;
3620         hour = min / MINS_PER_HOUR;
3621         min -= hour * MINS_PER_HOUR;
3622
3623         str += strlen(str);
3624         /* TZ is negated compared to sign we wish to display ... */
3625         *str++ = (tz <= 0 ? '+' : '-');
3626
3627         if (sec != 0)
3628                 sprintf(str, "%02d:%02d:%02d", hour, min, sec);
3629         else if (min != 0 || style == USE_XSD_DATES)
3630                 sprintf(str, "%02d:%02d", hour, min);
3631         else
3632                 sprintf(str, "%02d", hour);
3633 }
3634
3635 /* EncodeDateOnly()
3636  * Encode date as local time.
3637  */
3638 int
3639 EncodeDateOnly(struct pg_tm * tm, int style, char *str)
3640 {
3641         if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
3642                 return -1;
3643
3644         switch (style)
3645         {
3646                 case USE_ISO_DATES:
3647                 case USE_XSD_DATES:
3648                         /* compatible with ISO date formats */
3649                         if (tm->tm_year > 0)
3650                                 sprintf(str, "%04d-%02d-%02d",
3651                                                 tm->tm_year, tm->tm_mon, tm->tm_mday);
3652                         else
3653                                 sprintf(str, "%04d-%02d-%02d %s",
3654                                                 -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
3655                         break;
3656
3657                 case USE_SQL_DATES:
3658                         /* compatible with Oracle/Ingres date formats */
3659                         if (DateOrder == DATEORDER_DMY)
3660                                 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3661                         else
3662                                 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3663                         if (tm->tm_year > 0)
3664                                 sprintf(str + 5, "/%04d", tm->tm_year);
3665                         else
3666                                 sprintf(str + 5, "/%04d %s", -(tm->tm_year - 1), "BC");
3667                         break;
3668
3669                 case USE_GERMAN_DATES:
3670                         /* German-style date format */
3671                         sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3672                         if (tm->tm_year > 0)
3673                                 sprintf(str + 5, ".%04d", tm->tm_year);
3674                         else
3675                                 sprintf(str + 5, ".%04d %s", -(tm->tm_year - 1), "BC");
3676                         break;
3677
3678                 case USE_POSTGRES_DATES:
3679                 default:
3680                         /* traditional date-only style for Postgres */
3681                         if (DateOrder == DATEORDER_DMY)
3682                                 sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
3683                         else
3684                                 sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
3685                         if (tm->tm_year > 0)
3686                                 sprintf(str + 5, "-%04d", tm->tm_year);
3687                         else
3688                                 sprintf(str + 5, "-%04d %s", -(tm->tm_year - 1), "BC");
3689                         break;
3690         }
3691
3692         return TRUE;
3693 }       /* EncodeDateOnly() */
3694
3695
3696 /* EncodeTimeOnly()
3697  * Encode time fields only.
3698  */
3699 int
3700 EncodeTimeOnly(struct pg_tm * tm, fsec_t fsec, int *tzp, int style, char *str)
3701 {
3702         if (tm->tm_hour < 0 || tm->tm_hour > HOURS_PER_DAY)
3703                 return -1;
3704
3705         sprintf(str, "%02d:%02d", tm->tm_hour, tm->tm_min);
3706
3707         /*
3708          * Print fractional seconds if any.  The fractional field widths here
3709          * should be equal to the larger of MAX_TIME_PRECISION and
3710          * MAX_TIMESTAMP_PRECISION.
3711          */
3712         if (fsec != 0)
3713         {
3714 #ifdef HAVE_INT64_TIMESTAMP
3715                 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3716 #else
3717                 sprintf(str + strlen(str), ":%013.10f", tm->tm_sec + fsec);
3718 #endif
3719                 TrimTrailingZeros(str);
3720         }
3721         else
3722                 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3723
3724         if (tzp != NULL)
3725                 EncodeTimezone(str, *tzp, style);
3726
3727         return TRUE;
3728 }       /* EncodeTimeOnly() */
3729
3730
3731 /* EncodeDateTime()
3732  * Encode date and time interpreted as local time.
3733  * Support several date styles:
3734  *      Postgres - day mon hh:mm:ss yyyy tz
3735  *      SQL - mm/dd/yyyy hh:mm:ss.ss tz
3736  *      ISO - yyyy-mm-dd hh:mm:ss+/-tz
3737  *      German - dd.mm.yyyy hh:mm:ss tz
3738  *      XSD - yyyy-mm-ddThh:mm:ss.ss+/-tz
3739  * Variants (affects order of month and day for Postgres and SQL styles):
3740  *      US - mm/dd/yyyy
3741  *      European - dd/mm/yyyy
3742  */
3743 int
3744 EncodeDateTime(struct pg_tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, char *str)
3745 {
3746         int                     day;
3747
3748         /*
3749          * Why are we checking only the month field? Change this to an assert...
3750          * if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR) return -1;
3751          */
3752         Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3753
3754         switch (style)
3755         {
3756                 case USE_ISO_DATES:
3757                 case USE_XSD_DATES:
3758                         /* Compatible with ISO-8601 date formats */
3759
3760                         if (style == USE_ISO_DATES)
3761                                 sprintf(str, "%04d-%02d-%02d %02d:%02d",
3762                                                 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3763                                                 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3764                         else
3765                                 sprintf(str, "%04d-%02d-%02dT%02d:%02d",
3766                                                 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3767                                                 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3768
3769
3770                         /*
3771                          * Print fractional seconds if any.  The field widths here should
3772                          * be at least equal to MAX_TIMESTAMP_PRECISION.
3773                          *
3774                          * In float mode, don't print fractional seconds before 1 AD,
3775                          * since it's unlikely there's any precision left ...
3776                          */
3777 #ifdef HAVE_INT64_TIMESTAMP
3778                         if (fsec != 0)
3779                         {
3780                                 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3781                                 TrimTrailingZeros(str);
3782                         }
3783 #else
3784                         if (fsec != 0 && tm->tm_year > 0)
3785                         {
3786                                 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3787                                 TrimTrailingZeros(str);
3788                         }
3789 #endif
3790                         else
3791                                 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3792
3793                         /*
3794                          * tzp == NULL indicates that we don't want *any* time zone info
3795                          * in the output string. *tzn != NULL indicates that we have alpha
3796                          * time zone info available. tm_isdst != -1 indicates that we have
3797                          * a valid time zone translation.
3798                          */
3799                         if (tzp != NULL && tm->tm_isdst >= 0)
3800                                 EncodeTimezone(str, *tzp, style);
3801
3802                         if (tm->tm_year <= 0)
3803                                 sprintf(str + strlen(str), " BC");
3804                         break;
3805
3806                 case USE_SQL_DATES:
3807                         /* Compatible with Oracle/Ingres date formats */
3808
3809                         if (DateOrder == DATEORDER_DMY)
3810                                 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3811                         else
3812                                 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3813
3814                         sprintf(str + 5, "/%04d %02d:%02d",
3815                                         (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3816                                         tm->tm_hour, tm->tm_min);
3817
3818                         /*
3819                          * Print fractional seconds if any.  The field widths here should
3820                          * be at least equal to MAX_TIMESTAMP_PRECISION.
3821                          *
3822                          * In float mode, don't print fractional seconds before 1 AD,
3823                          * since it's unlikely there's any precision left ...
3824                          */
3825 #ifdef HAVE_INT64_TIMESTAMP
3826                         if (fsec != 0)
3827                         {
3828                                 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3829                                 TrimTrailingZeros(str);
3830                         }
3831 #else
3832                         if (fsec != 0 && tm->tm_year > 0)
3833                         {
3834                                 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3835                                 TrimTrailingZeros(str);
3836                         }
3837 #endif
3838                         else
3839                                 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3840
3841                         if (tzp != NULL && tm->tm_isdst >= 0)
3842                         {
3843                                 if (*tzn != NULL)
3844                                         sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3845                                 else
3846                                         EncodeTimezone(str, *tzp, style);
3847                         }
3848
3849                         if (tm->tm_year <= 0)
3850                                 sprintf(str + strlen(str), " BC");
3851                         break;
3852
3853                 case USE_GERMAN_DATES:
3854                         /* German variant on European style */
3855
3856                         sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3857
3858                         sprintf(str + 5, ".%04d %02d:%02d",
3859                                         (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3860                                         tm->tm_hour, tm->tm_min);
3861
3862                         /*
3863                          * Print fractional seconds if any.  The field widths here should
3864                          * be at least equal to MAX_TIMESTAMP_PRECISION.
3865                          *
3866                          * In float mode, don't print fractional seconds before 1 AD,
3867                          * since it's unlikely there's any precision left ...
3868                          */
3869 #ifdef HAVE_INT64_TIMESTAMP
3870                         if (fsec != 0)
3871                         {
3872                                 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3873                                 TrimTrailingZeros(str);
3874                         }
3875 #else
3876                         if (fsec != 0 && tm->tm_year > 0)
3877                         {
3878                                 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3879                                 TrimTrailingZeros(str);
3880                         }
3881 #endif
3882                         else
3883                                 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3884
3885                         if (tzp != NULL && tm->tm_isdst >= 0)
3886                         {
3887                                 if (*tzn != NULL)
3888                                         sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3889                                 else
3890                                         EncodeTimezone(str, *tzp, style);
3891                         }
3892
3893                         if (tm->tm_year <= 0)
3894                                 sprintf(str + strlen(str), " BC");
3895                         break;
3896
3897                 case USE_POSTGRES_DATES:
3898                 default:
3899                         /* Backward-compatible with traditional Postgres abstime dates */
3900
3901                         day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3902                         tm->tm_wday = j2day(day);
3903
3904                         strncpy(str, days[tm->tm_wday], 3);
3905                         strcpy(str + 3, " ");
3906
3907                         if (DateOrder == DATEORDER_DMY)
3908                                 sprintf(str + 4, "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
3909                         else
3910                                 sprintf(str + 4, "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);
3911
3912                         sprintf(str + 10, " %02d:%02d", tm->tm_hour, tm->tm_min);
3913
3914                         /*
3915                          * Print fractional seconds if any.  The field widths here should
3916                          * be at least equal to MAX_TIMESTAMP_PRECISION.
3917                          *
3918                          * In float mode, don't print fractional seconds before 1 AD,
3919                          * since it's unlikely there's any precision left ...
3920                          */
3921 #ifdef HAVE_INT64_TIMESTAMP
3922                         if (fsec != 0)
3923                         {
3924                                 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3925                                 TrimTrailingZeros(str);
3926                         }
3927 #else
3928                         if (fsec != 0 && tm->tm_year > 0)
3929                         {
3930                                 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3931                                 TrimTrailingZeros(str);
3932                         }
3933 #endif
3934                         else
3935                                 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3936
3937                         sprintf(str + strlen(str), " %04d",
3938                                         (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1));
3939
3940                         if (tzp != NULL && tm->tm_isdst >= 0)
3941                         {
3942                                 if (*tzn != NULL)
3943                                         sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3944                                 else
3945                                 {
3946                                         /*
3947                                          * We have a time zone, but no string version. Use the
3948                                          * numeric form, but be sure to include a leading space to
3949                                          * avoid formatting something which would be rejected by
3950                                          * the date/time parser later. - thomas 2001-10-19
3951                                          */
3952                                         sprintf(str + strlen(str), " ");
3953                                         EncodeTimezone(str, *tzp, style);
3954                                 }
3955                         }
3956
3957                         if (tm->tm_year <= 0)
3958                                 sprintf(str + strlen(str), " BC");
3959                         break;
3960         }
3961
3962         return TRUE;
3963 }
3964
3965
3966 /*
3967  * Helper functions to avoid duplicated code in EncodeInterval.
3968  *
3969  * Append sections and fractional seconds (if any) at *cp.
3970  * Note that any sign is stripped from the input seconds values.
3971  */
3972 static void
3973 AppendSeconds(char *cp, int sec, fsec_t fsec, bool fillzeros)
3974 {
3975         if (fsec == 0)
3976         {
3977                 sprintf(cp, fillzeros ? "%02d" : "%d", abs(sec));
3978         }
3979         else
3980         {
3981 #ifdef HAVE_INT64_TIMESTAMP
3982                 sprintf(cp, fillzeros ? "%02d.%06d" : "%d.%06d", abs(sec), Abs(fsec));
3983 #else
3984                 sprintf(cp, fillzeros ? "%012.9f" : "%.9f", fabs(sec + fsec));
3985 #endif
3986                 TrimTrailingZeros(cp);
3987         }
3988 }
3989
3990 /* Append an ISO8601 field, but only if value isn't zero */
3991 static char *
3992 AddISO8601IntervalPart(char *cp, int value, char units)
3993 {
3994         if (value == 0)
3995                 return cp;
3996         sprintf(cp, "%d%c", value, units);
3997         return cp + strlen(cp);
3998 }
3999
4000
4001 /* EncodeInterval()
4002  * Interpret time structure as a delta time and convert to string.
4003  *
4004  * Support "traditional Postgres" and ISO-8601 styles.
4005  * Actually, afaik ISO does not address time interval formatting,
4006  *      but this looks similar to the spec for absolute date/time.
4007  * - thomas 1998-04-30
4008  *
4009  * Actually, afaik, ISO 8601 does specify formats for "time
4010  * intervals...[of the]...format with time-unit designators", which
4011  * are pretty ugly.  The format looks something like
4012  *     P1Y1M1DT1H1M1.12345S
4013  * but useful for exchanging data with computers instead of humans.
4014  * - ron 2003-07-14
4015  *
4016  * And ISO's SQL 2008 standard specifies standards for
4017  * "year-month literal"s (that look like '2-3') and
4018  * "day-time literal"s (that look like ('4 5:6:7')
4019  */
4020 int
4021 EncodeInterval(struct pg_tm * tm, fsec_t fsec, int style, char *str)
4022 {
4023         char       *cp = str;
4024         int                     year = tm->tm_year;
4025         int                     mon  = tm->tm_mon;
4026         int                     mday = tm->tm_mday;
4027         int                     hour = tm->tm_hour;
4028         int                     min  = tm->tm_min;
4029         int                     sec  = tm->tm_sec;
4030         bool            is_before = FALSE;
4031         bool            is_nonzero = FALSE;
4032
4033         /*
4034          * The sign of year and month are guaranteed to match, since they are
4035          * stored internally as "month". But we'll need to check for is_before and
4036          * is_nonzero when determining the signs of day and hour/minute/seconds
4037          * fields.
4038          */
4039         switch (style)
4040         {
4041                 /* SQL Standard interval format */
4042                 case INTSTYLE_SQL_STANDARD:
4043                         {
4044                                 bool has_negative = year < 0 || mon  < 0 ||
4045                                                                         mday < 0 || hour < 0 ||
4046                                                                         min  < 0 || sec  < 0 || fsec < 0;
4047                                 bool has_positive = year > 0 || mon  > 0 ||
4048                                                                         mday > 0 || hour > 0 ||
4049                                                                         min  > 0 || sec  > 0 || fsec > 0;
4050                                 bool has_year_month = year != 0 || mon  != 0;
4051                                 bool has_day_time   = mday != 0 || hour != 0 ||
4052                                                                           min  != 0 || sec  != 0 || fsec != 0;
4053                                 bool has_day        = mday != 0;
4054                                 bool sql_standard_value = !(has_negative && has_positive) &&
4055                                                                                   !(has_year_month && has_day_time);
4056
4057                                 /*
4058                                  * SQL Standard wants only 1 "<sign>" preceding the whole
4059                                  * interval ... but can't do that if mixed signs.
4060                                  */
4061                                 if (has_negative && sql_standard_value)
4062                                 {
4063                                         *cp++ = '-';
4064                                         year = -year;
4065                                         mon  = -mon;
4066                                         mday = -mday;
4067                                         hour = -hour;
4068                                         min  = -min;
4069                                         sec  = -sec;
4070                                         fsec = -fsec;
4071                                 }
4072
4073                                 if (!has_negative && !has_positive)
4074                                 {
4075                                         sprintf(cp, "0");
4076                                 }
4077                                 else if (!sql_standard_value)
4078                                 {
4079                                         /*
4080                                          * For non sql-standard interval values,
4081                                          * force outputting the signs to avoid
4082                                          * ambiguities with intervals with mixed
4083                                          * sign components.
4084                                          */
4085                                         char year_sign = (year < 0 || mon < 0) ? '-' : '+';
4086                                         char day_sign = (mday < 0) ? '-' : '+';
4087                                         char sec_sign = (hour < 0 || min < 0 || sec < 0 || fsec < 0) ? '-' : '+';
4088
4089                                         sprintf(cp, "%c%d-%d %c%d %c%d:%02d:",
4090                                                         year_sign, abs(year), abs(mon),
4091                                                         day_sign, abs(mday),
4092                                                         sec_sign, abs(hour), abs(min));
4093                                         cp += strlen(cp);
4094                                         AppendSeconds(cp, sec, fsec, true);
4095                                 }
4096                                 else if (has_year_month)
4097                                 {
4098                                         sprintf(cp, "%d-%d", year, mon);
4099                                 }
4100                                 else if (has_day)
4101                                 {
4102                                         sprintf(cp, "%d %d:%02d:", mday, hour, min);
4103                                         cp += strlen(cp);
4104                                         AppendSeconds(cp, sec, fsec, true);
4105                                 }
4106                                 else
4107                                 {
4108                                         sprintf(cp, "%d:%02d:", hour, min);
4109                                         cp += strlen(cp);
4110                                         AppendSeconds(cp, sec, fsec, true);
4111                                 }
4112                         }
4113                         break;
4114
4115                 /* ISO 8601 "time-intervals by duration only" */
4116                 case INTSTYLE_ISO_8601:
4117                         /* special-case zero to avoid printing nothing */
4118                         if (year == 0 && mon == 0 && mday == 0 &&
4119                             hour == 0 && min == 0 && sec  == 0 && fsec == 0)
4120                         {
4121                                 sprintf(cp, "PT0S");
4122                                 break;
4123                         }
4124                         *cp++ = 'P';
4125                         cp = AddISO8601IntervalPart(cp, year, 'Y');
4126                         cp = AddISO8601IntervalPart(cp, mon , 'M');
4127                         cp = AddISO8601IntervalPart(cp, mday, 'D');
4128                         if (hour != 0 || min != 0 || sec != 0 || fsec != 0)
4129                                 *cp++ = 'T';
4130                         cp = AddISO8601IntervalPart(cp, hour, 'H');
4131                         cp = AddISO8601IntervalPart(cp, min , 'M');
4132                         if (sec != 0 || fsec != 0)
4133                         {
4134                                 if (sec < 0 || fsec < 0)
4135                                         *cp++ = '-';
4136                                 AppendSeconds(cp, sec, fsec, false);
4137                                 cp += strlen(cp);
4138                                 *cp++ = 'S';
4139                                 *cp++ = '\0';
4140                         }
4141                         break;
4142
4143                 /* Compatible with postgresql < 8.4 when DateStyle = 'iso' */
4144                 case INTSTYLE_POSTGRES:
4145                         if (tm->tm_year != 0)
4146                         {
4147                                 sprintf(cp, "%d year%s",
4148                                                 tm->tm_year, (tm->tm_year != 1) ? "s" : "");
4149                                 cp += strlen(cp);
4150                                 is_before = (tm->tm_year < 0);
4151                                 is_nonzero = TRUE;
4152                         }
4153
4154                         if (tm->tm_mon != 0)
4155                         {
4156                                 sprintf(cp, "%s%s%d mon%s", is_nonzero ? " " : "",
4157                                                 (is_before && tm->tm_mon > 0) ? "+" : "",
4158                                                 tm->tm_mon, (tm->tm_mon != 1) ? "s" : "");
4159                                 cp += strlen(cp);
4160                                 is_before = (tm->tm_mon < 0);
4161                                 is_nonzero = TRUE;
4162                         }
4163
4164                         if (tm->tm_mday != 0)
4165                         {
4166                                 sprintf(cp, "%s%s%d day%s", is_nonzero ? " " : "",
4167                                                 (is_before && tm->tm_mday > 0) ? "+" : "",
4168                                                 tm->tm_mday, (tm->tm_mday != 1) ? "s" : "");
4169                                 cp += strlen(cp);
4170                                 is_before = (tm->tm_mday < 0);
4171                                 is_nonzero = TRUE;
4172                         }
4173
4174                         if (!is_nonzero || tm->tm_hour != 0 || tm->tm_min != 0 ||
4175                                 tm->tm_sec != 0 || fsec != 0)
4176                         {
4177                                 int                     minus = (tm->tm_hour < 0 || tm->tm_min < 0 ||
4178                                                                          tm->tm_sec < 0 || fsec < 0);
4179
4180                                 sprintf(cp, "%s%s%02d:%02d:", is_nonzero ? " " : "",
4181                                                 (minus ? "-" : (is_before ? "+" : "")),
4182                                                 abs(tm->tm_hour), abs(tm->tm_min));
4183                                 cp += strlen(cp);
4184                                 AppendSeconds(cp, tm->tm_sec, fsec, true);
4185                                 cp += strlen(cp);
4186                                 is_nonzero = TRUE;
4187                         }
4188                         /* identically zero? then put in a unitless zero... */
4189                         if (!is_nonzero)
4190                         {
4191                                 strcat(cp, "0");
4192                                 cp += strlen(cp);
4193                         }
4194                         break;
4195
4196                 /* Compatible with postgresql < 8.4 when DateStyle != 'iso' */
4197                 case INTSTYLE_POSTGRES_VERBOSE:
4198                 default:
4199                         strcpy(cp, "@ ");
4200                         cp += strlen(cp);
4201
4202                         if (tm->tm_year != 0)
4203                         {
4204                                 int                     year = tm->tm_year;
4205
4206                                 if (tm->tm_year < 0)
4207                                         year = -year;
4208
4209                                 sprintf(cp, "%d year%s", year,
4210                                                 (year != 1) ? "s" : "");
4211                                 cp += strlen(cp);
4212                                 is_before = (tm->tm_year < 0);
4213                                 is_nonzero = TRUE;
4214                         }
4215
4216                         if (tm->tm_mon != 0)
4217                         {
4218                                 int                     mon = tm->tm_mon;
4219
4220                                 if (is_before || (!is_nonzero && tm->tm_mon < 0))
4221                                         mon = -mon;
4222
4223                                 sprintf(cp, "%s%d mon%s", is_nonzero ? " " : "", mon,
4224                                                 (mon != 1) ? "s" : "");
4225                                 cp += strlen(cp);
4226                                 if (!is_nonzero)
4227                                         is_before = (tm->tm_mon < 0);
4228                                 is_nonzero = TRUE;
4229                         }
4230
4231                         if (tm->tm_mday != 0)
4232                         {
4233                                 int                     day = tm->tm_mday;
4234
4235                                 if (is_before || (!is_nonzero && tm->tm_mday < 0))
4236                                         day = -day;
4237
4238                                 sprintf(cp, "%s%d day%s", is_nonzero ? " " : "", day,
4239                                                 (day != 1) ? "s" : "");
4240                                 cp += strlen(cp);
4241                                 if (!is_nonzero)
4242                                         is_before = (tm->tm_mday < 0);
4243                                 is_nonzero = TRUE;
4244                         }
4245                         if (tm->tm_hour != 0)
4246                         {
4247                                 int                     hour = tm->tm_hour;
4248
4249                                 if (is_before || (!is_nonzero && tm->tm_hour < 0))
4250                                         hour = -hour;
4251
4252                                 sprintf(cp, "%s%d hour%s", is_nonzero ? " " : "", hour,
4253                                                 (hour != 1) ? "s" : "");
4254                                 cp += strlen(cp);
4255                                 if (!is_nonzero)
4256                                         is_before = (tm->tm_hour < 0);
4257                                 is_nonzero = TRUE;
4258                         }
4259
4260                         if (tm->tm_min != 0)
4261                         {
4262                                 int                     min = tm->tm_min;
4263
4264                                 if (is_before || (!is_nonzero && tm->tm_min < 0))
4265                                         min = -min;
4266
4267                                 sprintf(cp, "%s%d min%s", is_nonzero ? " " : "", min,
4268                                                 (min != 1) ? "s" : "");
4269                                 cp += strlen(cp);
4270                                 if (!is_nonzero)
4271                                         is_before = (tm->tm_min < 0);
4272                                 is_nonzero = TRUE;
4273                         }
4274
4275                         /* fractional seconds? */
4276                         if (fsec != 0)
4277                         {
4278                                 fsec_t          sec;
4279
4280 #ifdef HAVE_INT64_TIMESTAMP
4281                                 sec = fsec;
4282                                 if (is_before || (!is_nonzero && tm->tm_sec < 0))
4283                                 {
4284                                         tm->tm_sec = -tm->tm_sec;
4285                                         sec = -sec;
4286                                         is_before = TRUE;
4287                                 }
4288                                 else if (!is_nonzero && tm->tm_sec == 0 && fsec < 0)
4289                                 {
4290                                         sec = -sec;
4291                                         is_before = TRUE;
4292                                 }
4293                                 sprintf(cp, "%s%d.%02d secs", is_nonzero ? " " : "",
4294                                                 tm->tm_sec, abs((int) rint(sec / 10000.0)));
4295                                 cp += strlen(cp);
4296 #else
4297                                 fsec += tm->tm_sec;
4298                                 sec = fsec;
4299                                 if (is_before || (!is_nonzero && fsec < 0))
4300                                         sec = -sec;
4301
4302                                 sprintf(cp, "%s%.2f secs", is_nonzero ? " " : "", sec);
4303                                 cp += strlen(cp);
4304                                 if (!is_nonzero)
4305                                         is_before = (fsec < 0);
4306 #endif
4307                                 is_nonzero = TRUE;
4308                         }
4309                         /* otherwise, integer seconds only? */
4310                         else if (tm->tm_sec != 0)
4311                         {
4312                                 int                     sec = tm->tm_sec;
4313
4314                                 if (is_before || (!is_nonzero && tm->tm_sec < 0))
4315                                         sec = -sec;
4316
4317                                 sprintf(cp, "%s%d sec%s", is_nonzero ? " " : "", sec,
4318                                                 (sec != 1) ? "s" : "");
4319                                 cp += strlen(cp);
4320                                 if (!is_nonzero)
4321                                         is_before = (tm->tm_sec < 0);
4322                                 is_nonzero = TRUE;
4323                         }
4324                         /* identically zero? then put in a unitless zero... */
4325                         if (!is_nonzero)
4326                         {
4327                                 strcat(cp, "0");
4328                                 cp += strlen(cp);
4329                         }
4330                         if (is_before)
4331                         {
4332                                 strcat(cp, " ago");
4333                                 cp += strlen(cp);
4334                         }
4335                         break;
4336         }
4337
4338         return 0;
4339 }       /* EncodeInterval() */
4340
4341
4342 /*
4343  * We've been burnt by stupid errors in the ordering of the datetkn tables
4344  * once too often.      Arrange to check them during postmaster start.
4345  */
4346 static bool
4347 CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
4348 {
4349         bool            ok = true;
4350         int                     i;
4351
4352         for (i = 1; i < nel; i++)
4353         {
4354                 if (strncmp(base[i - 1].token, base[i].token, TOKMAXLEN) >= 0)
4355                 {
4356                         elog(LOG, "ordering error in %s table: \"%.*s\" >= \"%.*s\"",
4357                                  tablename,
4358                                  TOKMAXLEN, base[i - 1].token,
4359                                  TOKMAXLEN, base[i].token);
4360                         ok = false;
4361                 }
4362         }
4363         return ok;
4364 }
4365
4366 bool
4367 CheckDateTokenTables(void)
4368 {
4369         bool            ok = true;
4370
4371         Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
4372         Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
4373
4374         ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
4375         ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
4376         return ok;
4377 }
4378
4379 /*
4380  * This function gets called during timezone config file load or reload
4381  * to create the final array of timezone tokens.  The argument array
4382  * is already sorted in name order.  This data is in a temporary memory
4383  * context and must be copied to somewhere permanent.
4384  */
4385 void
4386 InstallTimeZoneAbbrevs(tzEntry *abbrevs, int n)
4387 {
4388         datetkn    *newtbl;
4389         int                     i;
4390
4391         /*
4392          * Copy the data into TopMemoryContext and convert to datetkn format.
4393          */
4394         newtbl = (datetkn *) MemoryContextAlloc(TopMemoryContext,
4395                                                                                         n * sizeof(datetkn));
4396         for (i = 0; i < n; i++)
4397         {
4398                 strncpy(newtbl[i].token, abbrevs[i].abbrev, TOKMAXLEN);
4399                 newtbl[i].type = abbrevs[i].is_dst ? DTZ : TZ;
4400                 TOVAL(&newtbl[i], abbrevs[i].offset / 60);
4401         }
4402
4403         /* Check the ordering, if testing */
4404         Assert(CheckDateTokenTable("timezone offset", newtbl, n));
4405
4406         /* Now safe to replace existing table (if any) */
4407         if (timezonetktbl)
4408                 pfree(timezonetktbl);
4409         timezonetktbl = newtbl;
4410         sztimezonetktbl = n;
4411
4412         /* clear date cache in case it contains any stale timezone names */
4413         for (i = 0; i < MAXDATEFIELDS; i++)
4414                 datecache[i] = NULL;
4415 }
4416
4417 /*
4418  * This set-returning function reads all the available time zone abbreviations
4419  * and returns a set of (abbrev, utc_offset, is_dst).
4420  */
4421 Datum
4422 pg_timezone_abbrevs(PG_FUNCTION_ARGS)
4423 {
4424         FuncCallContext *funcctx;
4425         int                *pindex;
4426         Datum           result;
4427         HeapTuple       tuple;
4428         Datum           values[3];
4429         bool            nulls[3];
4430         char            buffer[TOKMAXLEN + 1];
4431         unsigned char *p;
4432         struct pg_tm tm;
4433         Interval   *resInterval;
4434
4435         /* stuff done only on the first call of the function */
4436         if (SRF_IS_FIRSTCALL())
4437         {
4438                 TupleDesc       tupdesc;
4439                 MemoryContext oldcontext;
4440
4441                 /* create a function context for cross-call persistence */
4442                 funcctx = SRF_FIRSTCALL_INIT();
4443
4444                 /*
4445                  * switch to memory context appropriate for multiple function calls
4446                  */
4447                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4448
4449                 /* allocate memory for user context */
4450                 pindex = (int *) palloc(sizeof(int));
4451                 *pindex = 0;
4452                 funcctx->user_fctx = (void *) pindex;
4453
4454                 /*
4455                  * build tupdesc for result tuples. This must match this function's
4456                  * pg_proc entry!
4457                  */
4458                 tupdesc = CreateTemplateTupleDesc(3, false);
4459                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "abbrev",
4460                                                    TEXTOID, -1, 0);
4461                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "utc_offset",
4462                                                    INTERVALOID, -1, 0);
4463                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_dst",
4464                                                    BOOLOID, -1, 0);
4465
4466                 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4467                 MemoryContextSwitchTo(oldcontext);
4468         }
4469
4470         /* stuff done on every call of the function */
4471         funcctx = SRF_PERCALL_SETUP();
4472         pindex = (int *) funcctx->user_fctx;
4473
4474         if (*pindex >= sztimezonetktbl)
4475                 SRF_RETURN_DONE(funcctx);
4476
4477         MemSet(nulls, 0, sizeof(nulls));
4478
4479         /*
4480          * Convert name to text, using upcasing conversion that is the inverse of
4481          * what ParseDateTime() uses.
4482          */
4483         strncpy(buffer, timezonetktbl[*pindex].token, TOKMAXLEN);
4484         buffer[TOKMAXLEN] = '\0';       /* may not be null-terminated */
4485         for (p = (unsigned char *) buffer; *p; p++)
4486                 *p = pg_toupper(*p);
4487
4488         values[0] = CStringGetTextDatum(buffer);
4489
4490         MemSet(&tm, 0, sizeof(struct pg_tm));
4491         tm.tm_min = (-1) * FROMVAL(&timezonetktbl[*pindex]);
4492         resInterval = (Interval *) palloc(sizeof(Interval));
4493         tm2interval(&tm, 0, resInterval);
4494         values[1] = IntervalPGetDatum(resInterval);
4495
4496         Assert(timezonetktbl[*pindex].type == DTZ ||
4497                    timezonetktbl[*pindex].type == TZ);
4498         values[2] = BoolGetDatum(timezonetktbl[*pindex].type == DTZ);
4499
4500         (*pindex)++;
4501
4502         tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4503         result = HeapTupleGetDatum(tuple);
4504
4505         SRF_RETURN_NEXT(funcctx, result);
4506 }
4507
4508 /*
4509  * This set-returning function reads all the available full time zones
4510  * and returns a set of (name, abbrev, utc_offset, is_dst).
4511  */
4512 Datum
4513 pg_timezone_names(PG_FUNCTION_ARGS)
4514 {
4515         MemoryContext oldcontext;
4516         FuncCallContext *funcctx;
4517         pg_tzenum  *tzenum;
4518         pg_tz      *tz;
4519         Datum           result;
4520         HeapTuple       tuple;
4521         Datum           values[4];
4522         bool            nulls[4];
4523         int                     tzoff;
4524         struct pg_tm tm;
4525         fsec_t          fsec;
4526         char       *tzn;
4527         Interval   *resInterval;
4528         struct pg_tm itm;
4529
4530         /* stuff done only on the first call of the function */
4531         if (SRF_IS_FIRSTCALL())
4532         {
4533                 TupleDesc       tupdesc;
4534
4535                 /* create a function context for cross-call persistence */
4536                 funcctx = SRF_FIRSTCALL_INIT();
4537
4538                 /*
4539                  * switch to memory context appropriate for multiple function calls
4540                  */
4541                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4542
4543                 /* initialize timezone scanning code */
4544                 tzenum = pg_tzenumerate_start();
4545                 funcctx->user_fctx = (void *) tzenum;
4546
4547                 /*
4548                  * build tupdesc for result tuples. This must match this function's
4549                  * pg_proc entry!
4550                  */
4551                 tupdesc = CreateTemplateTupleDesc(4, false);
4552                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
4553                                                    TEXTOID, -1, 0);
4554                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "abbrev",
4555                                                    TEXTOID, -1, 0);
4556                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "utc_offset",
4557                                                    INTERVALOID, -1, 0);
4558                 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_dst",
4559                                                    BOOLOID, -1, 0);
4560
4561                 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
4562                 MemoryContextSwitchTo(oldcontext);
4563         }
4564
4565         /* stuff done on every call of the function */
4566         funcctx = SRF_PERCALL_SETUP();
4567         tzenum = (pg_tzenum *) funcctx->user_fctx;
4568
4569         /* search for another zone to display */
4570         for (;;)
4571         {
4572                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4573                 tz = pg_tzenumerate_next(tzenum);
4574                 MemoryContextSwitchTo(oldcontext);
4575
4576                 if (!tz)
4577                 {
4578                         pg_tzenumerate_end(tzenum);
4579                         funcctx->user_fctx = NULL;
4580                         SRF_RETURN_DONE(funcctx);
4581                 }
4582
4583                 /* Convert now() to local time in this zone */
4584                 if (timestamp2tm(GetCurrentTransactionStartTimestamp(),
4585                                                  &tzoff, &tm, &fsec, &tzn, tz) != 0)
4586                         continue;                       /* ignore if conversion fails */
4587
4588                 /* Ignore zic's rather silly "Factory" time zone */
4589                 if (tzn && strcmp(tzn, "Local time zone must be set--see zic manual page") == 0)
4590                         continue;
4591
4592                 /* Found a displayable zone */
4593                 break;
4594         }
4595
4596         MemSet(nulls, 0, sizeof(nulls));
4597
4598         values[0] = CStringGetTextDatum(pg_get_timezone_name(tz));
4599         values[1] = CStringGetTextDatum(tzn ? tzn : "");
4600
4601         MemSet(&itm, 0, sizeof(struct pg_tm));
4602         itm.tm_sec = -tzoff;
4603         resInterval = (Interval *) palloc(sizeof(Interval));
4604         tm2interval(&itm, 0, resInterval);
4605         values[2] = IntervalPGetDatum(resInterval);
4606
4607         values[3] = BoolGetDatum(tm.tm_isdst > 0);
4608
4609         tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4610         result = HeapTupleGetDatum(tuple);
4611
4612         SRF_RETURN_NEXT(funcctx, result);
4613 }