]> granicus.if.org Git - postgresql/blob - src/backend/utils/adt/datetime.c
Reject year zero during datetime input, except when it's a 2-digit year
[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.187 2008/02/25 23:36:28 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/heapam.h"
23 #include "access/xact.h"
24 #include "catalog/pg_type.h"
25 #include "funcapi.h"
26 #include "miscadmin.h"
27 #include "utils/builtins.h"
28 #include "utils/datetime.h"
29 #include "utils/memutils.h"
30 #include "utils/tzparser.h"
31
32
33 static int DecodeNumber(int flen, char *field, bool haveTextMonth,
34                          int fmask, int *tmask,
35                          struct pg_tm * tm, fsec_t *fsec, bool *is2digits);
36 static int DecodeNumberField(int len, char *str,
37                                   int fmask, int *tmask,
38                                   struct pg_tm * tm, fsec_t *fsec, bool *is2digits);
39 static int DecodeTime(char *str, int fmask, int *tmask,
40                    struct pg_tm * tm, fsec_t *fsec);
41 static int      DecodeTimezone(char *str, int *tzp);
42 static const datetkn *datebsearch(const char *key, const datetkn *base, int nel);
43 static int      DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
44                                            struct pg_tm * tm);
45 static int      ValidateDate(int fmask, bool is2digits, bool bc,
46                                                  struct pg_tm * tm);
47 static void TrimTrailingZeros(char *str);
48
49
50 const int       day_tab[2][13] =
51 {
52         {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
53         {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}
54 };
55
56 char       *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
57 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
58
59 char       *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
60 "Thursday", "Friday", "Saturday", NULL};
61
62
63 /*****************************************************************************
64  *       PRIVATE ROUTINES                                                                                                                *
65  *****************************************************************************/
66
67 /*
68  * Definitions for squeezing values into "value"
69  * We set aside a high bit for a sign, and scale the timezone offsets
70  * in minutes by a factor of 15 (so can represent quarter-hour increments).
71  */
72 #define ABS_SIGNBIT             ((char) 0200)
73 #define VALMASK                 ((char) 0177)
74 #define POS(n)                  (n)
75 #define NEG(n)                  ((n)|ABS_SIGNBIT)
76 #define SIGNEDCHAR(c)   ((c)&ABS_SIGNBIT? -((c)&VALMASK): (c))
77 #define FROMVAL(tp)             (-SIGNEDCHAR((tp)->value) * 15) /* uncompress */
78 #define TOVAL(tp, v)    ((tp)->value = ((v) < 0? NEG((-(v))/15): POS(v)/15))
79
80 /*
81  * datetktbl holds date/time keywords.
82  *
83  * Note that this table must be strictly alphabetically ordered to allow an
84  * O(ln(N)) search algorithm to be used.
85  *
86  * The text field is NOT guaranteed to be NULL-terminated.
87  *
88  * To keep this table reasonably small, we divide the lexval for TZ and DTZ
89  * entries by 15 (so they are on 15 minute boundaries) and truncate the text
90  * field at TOKMAXLEN characters.
91  * Formerly, we divided by 10 rather than 15 but there are a few time zones
92  * which are 30 or 45 minutes away from an even hour, most are on an hour
93  * boundary, and none on other boundaries.
94  *
95  * The static table contains no TZ or DTZ entries, rather those are loaded
96  * from configuration files and stored in timezonetktbl, which has the same
97  * format as the static datetktbl.
98  */
99 static datetkn *timezonetktbl = NULL;
100
101 static int      sztimezonetktbl = 0;
102
103 static const datetkn datetktbl[] = {
104 /*      text, token, lexval */
105         {EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
106         {"abstime", IGNORE_DTF, 0}, /* for pre-v6.1 "Invalid Abstime" */
107         {DA_D, ADBC, AD},                       /* "ad" for years > 0 */
108         {"allballs", RESERV, DTK_ZULU},         /* 00:00:00 */
109         {"am", AMPM, AM},
110         {"apr", MONTH, 4},
111         {"april", MONTH, 4},
112         {"at", IGNORE_DTF, 0},          /* "at" (throwaway) */
113         {"aug", MONTH, 8},
114         {"august", MONTH, 8},
115         {DB_C, ADBC, BC},                       /* "bc" for years <= 0 */
116         {DCURRENT, RESERV, DTK_CURRENT},        /* "current" is always now */
117         {"d", UNITS, DTK_DAY},          /* "day of month" for ISO input */
118         {"dec", MONTH, 12},
119         {"december", MONTH, 12},
120         {"dow", RESERV, DTK_DOW},       /* day of week */
121         {"doy", RESERV, DTK_DOY},       /* day of year */
122         {"dst", DTZMOD, 6},
123         {EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
124         {"feb", MONTH, 2},
125         {"february", MONTH, 2},
126         {"fri", DOW, 5},
127         {"friday", DOW, 5},
128         {"h", UNITS, DTK_HOUR},         /* "hour" */
129         {LATE, RESERV, DTK_LATE},       /* "infinity" reserved for "late time" */
130         {INVALID, RESERV, DTK_INVALID},         /* "invalid" reserved for bad time */
131         {"isodow", RESERV, DTK_ISODOW},         /* ISO day of week, Sunday == 7 */
132         {"isoyear", UNITS, DTK_ISOYEAR},        /* year in terms of the ISO week date */
133         {"j", UNITS, DTK_JULIAN},
134         {"jan", MONTH, 1},
135         {"january", MONTH, 1},
136         {"jd", UNITS, DTK_JULIAN},
137         {"jul", MONTH, 7},
138         {"julian", UNITS, DTK_JULIAN},
139         {"july", MONTH, 7},
140         {"jun", MONTH, 6},
141         {"june", MONTH, 6},
142         {"m", UNITS, DTK_MONTH},        /* "month" for ISO input */
143         {"mar", MONTH, 3},
144         {"march", MONTH, 3},
145         {"may", MONTH, 5},
146         {"mm", UNITS, DTK_MINUTE},      /* "minute" for ISO input */
147         {"mon", DOW, 1},
148         {"monday", DOW, 1},
149         {"nov", MONTH, 11},
150         {"november", MONTH, 11},
151         {NOW, RESERV, DTK_NOW},         /* current transaction time */
152         {"oct", MONTH, 10},
153         {"october", MONTH, 10},
154         {"on", IGNORE_DTF, 0},          /* "on" (throwaway) */
155         {"pm", AMPM, PM},
156         {"s", UNITS, DTK_SECOND},       /* "seconds" for ISO input */
157         {"sat", DOW, 6},
158         {"saturday", DOW, 6},
159         {"sep", MONTH, 9},
160         {"sept", MONTH, 9},
161         {"september", MONTH, 9},
162         {"sun", DOW, 0},
163         {"sunday", DOW, 0},
164         {"t", ISOTIME, DTK_TIME},       /* Filler for ISO time fields */
165         {"thu", DOW, 4},
166         {"thur", DOW, 4},
167         {"thurs", DOW, 4},
168         {"thursday", DOW, 4},
169         {TODAY, RESERV, DTK_TODAY}, /* midnight */
170         {TOMORROW, RESERV, DTK_TOMORROW},       /* tomorrow midnight */
171         {"tue", DOW, 2},
172         {"tues", DOW, 2},
173         {"tuesday", DOW, 2},
174         {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
175         {"wed", DOW, 3},
176         {"wednesday", DOW, 3},
177         {"weds", DOW, 3},
178         {"y", UNITS, DTK_YEAR},         /* "year" for ISO input */
179         {YESTERDAY, RESERV, DTK_YESTERDAY}      /* yesterday midnight */
180 };
181
182 static int      szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];
183
184 static datetkn deltatktbl[] = {
185         /* text, token, lexval */
186         {"@", IGNORE_DTF, 0},           /* postgres relative prefix */
187         {DAGO, AGO, 0},                         /* "ago" indicates negative time offset */
188         {"c", UNITS, DTK_CENTURY},      /* "century" relative */
189         {"cent", UNITS, DTK_CENTURY},           /* "century" relative */
190         {"centuries", UNITS, DTK_CENTURY},      /* "centuries" relative */
191         {DCENTURY, UNITS, DTK_CENTURY},         /* "century" relative */
192         {"d", UNITS, DTK_DAY},          /* "day" relative */
193         {DDAY, UNITS, DTK_DAY},         /* "day" relative */
194         {"days", UNITS, DTK_DAY},       /* "days" relative */
195         {"dec", UNITS, DTK_DECADE}, /* "decade" relative */
196         {DDECADE, UNITS, DTK_DECADE},           /* "decade" relative */
197         {"decades", UNITS, DTK_DECADE},         /* "decades" relative */
198         {"decs", UNITS, DTK_DECADE},    /* "decades" relative */
199         {"h", UNITS, DTK_HOUR},         /* "hour" relative */
200         {DHOUR, UNITS, DTK_HOUR},       /* "hour" relative */
201         {"hours", UNITS, DTK_HOUR}, /* "hours" relative */
202         {"hr", UNITS, DTK_HOUR},        /* "hour" relative */
203         {"hrs", UNITS, DTK_HOUR},       /* "hours" relative */
204         {INVALID, RESERV, DTK_INVALID},         /* reserved for invalid time */
205         {"m", UNITS, DTK_MINUTE},       /* "minute" relative */
206         {"microsecon", UNITS, DTK_MICROSEC},            /* "microsecond" relative */
207         {"mil", UNITS, DTK_MILLENNIUM},         /* "millennium" relative */
208         {"millennia", UNITS, DTK_MILLENNIUM},           /* "millennia" relative */
209         {DMILLENNIUM, UNITS, DTK_MILLENNIUM},           /* "millennium" relative */
210         {"millisecon", UNITS, DTK_MILLISEC},            /* relative */
211         {"mils", UNITS, DTK_MILLENNIUM},        /* "millennia" relative */
212         {"min", UNITS, DTK_MINUTE}, /* "minute" relative */
213         {"mins", UNITS, DTK_MINUTE},    /* "minutes" relative */
214         {DMINUTE, UNITS, DTK_MINUTE},           /* "minute" relative */
215         {"minutes", UNITS, DTK_MINUTE},         /* "minutes" relative */
216         {"mon", UNITS, DTK_MONTH},      /* "months" relative */
217         {"mons", UNITS, DTK_MONTH}, /* "months" relative */
218         {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
219         {"months", UNITS, DTK_MONTH},
220         {"ms", UNITS, DTK_MILLISEC},
221         {"msec", UNITS, DTK_MILLISEC},
222         {DMILLISEC, UNITS, DTK_MILLISEC},
223         {"mseconds", UNITS, DTK_MILLISEC},
224         {"msecs", UNITS, DTK_MILLISEC},
225         {"qtr", UNITS, DTK_QUARTER},    /* "quarter" relative */
226         {DQUARTER, UNITS, DTK_QUARTER},         /* "quarter" relative */
227         {"reltime", IGNORE_DTF, 0}, /* pre-v6.1 "Undefined Reltime" */
228         {"s", UNITS, DTK_SECOND},
229         {"sec", UNITS, DTK_SECOND},
230         {DSECOND, UNITS, DTK_SECOND},
231         {"seconds", UNITS, DTK_SECOND},
232         {"secs", UNITS, DTK_SECOND},
233         {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
234         {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
235         {"timezone_m", UNITS, DTK_TZ_MINUTE},           /* timezone minutes units */
236         {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
237         {"us", UNITS, DTK_MICROSEC},    /* "microsecond" relative */
238         {"usec", UNITS, DTK_MICROSEC},          /* "microsecond" relative */
239         {DMICROSEC, UNITS, DTK_MICROSEC},       /* "microsecond" relative */
240         {"useconds", UNITS, DTK_MICROSEC},      /* "microseconds" relative */
241         {"usecs", UNITS, DTK_MICROSEC},         /* "microseconds" relative */
242         {"w", UNITS, DTK_WEEK},         /* "week" relative */
243         {DWEEK, UNITS, DTK_WEEK},       /* "week" relative */
244         {"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
245         {"y", UNITS, DTK_YEAR},         /* "year" relative */
246         {DYEAR, UNITS, DTK_YEAR},       /* "year" relative */
247         {"years", UNITS, DTK_YEAR}, /* "years" relative */
248         {"yr", UNITS, DTK_YEAR},        /* "year" relative */
249         {"yrs", UNITS, DTK_YEAR}        /* "years" relative */
250 };
251
252 static int      szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];
253
254 static const datetkn *datecache[MAXDATEFIELDS] = {NULL};
255
256 static const datetkn *deltacache[MAXDATEFIELDS] = {NULL};
257
258
259 /*
260  * Calendar time to Julian date conversions.
261  * Julian date is commonly used in astronomical applications,
262  *      since it is numerically accurate and computationally simple.
263  * The algorithms here will accurately convert between Julian day
264  *      and calendar date for all non-negative Julian days
265  *      (i.e. from Nov 24, -4713 on).
266  *
267  * These routines will be used by other date/time packages
268  * - thomas 97/02/25
269  *
270  * Rewritten to eliminate overflow problems. This now allows the
271  * routines to work correctly for all Julian day counts from
272  * 0 to 2147483647      (Nov 24, -4713 to Jun 3, 5874898) assuming
273  * a 32-bit integer. Longer types should also work to the limits
274  * of their precision.
275  */
276
277 int
278 date2j(int y, int m, int d)
279 {
280         int                     julian;
281         int                     century;
282
283         if (m > 2)
284         {
285                 m += 1;
286                 y += 4800;
287         }
288         else
289         {
290                 m += 13;
291                 y += 4799;
292         }
293
294         century = y / 100;
295         julian = y * 365 - 32167;
296         julian += y / 4 - century + century / 4;
297         julian += 7834 * m / 256 + d;
298
299         return julian;
300 }       /* date2j() */
301
302 void
303 j2date(int jd, int *year, int *month, int *day)
304 {
305         unsigned int julian;
306         unsigned int quad;
307         unsigned int extra;
308         int                     y;
309
310         julian = jd;
311         julian += 32044;
312         quad = julian / 146097;
313         extra = (julian - quad * 146097) * 4 + 3;
314         julian += 60 + quad * 3 + extra / 146097;
315         quad = julian / 1461;
316         julian -= quad * 1461;
317         y = julian * 4 / 1461;
318         julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
319                 + 123;
320         y += quad * 4;
321         *year = y - 4800;
322         quad = julian * 2141 / 65536;
323         *day = julian - 7834 * quad / 256;
324         *month = (quad + 10) % 12 + 1;
325
326         return;
327 }       /* j2date() */
328
329
330 /*
331  * j2day - convert Julian date to day-of-week (0..6 == Sun..Sat)
332  *
333  * Note: various places use the locution j2day(date - 1) to produce a
334  * result according to the convention 0..6 = Mon..Sun.  This is a bit of
335  * a crock, but will work as long as the computation here is just a modulo.
336  */
337 int
338 j2day(int date)
339 {
340         unsigned int day;
341
342         day = date;
343
344         day += 1;
345         day %= 7;
346
347         return (int) day;
348 }       /* j2day() */
349
350
351 /*
352  * GetCurrentDateTime()
353  *
354  * Get the transaction start time ("now()") broken down as a struct pg_tm.
355  */
356 void
357 GetCurrentDateTime(struct pg_tm * tm)
358 {
359         int                     tz;
360         fsec_t          fsec;
361
362         timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, &fsec,
363                                  NULL, NULL);
364         /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
365 }
366
367 /*
368  * GetCurrentTimeUsec()
369  *
370  * Get the transaction start time ("now()") broken down as a struct pg_tm,
371  * including fractional seconds and timezone offset.
372  */
373 void
374 GetCurrentTimeUsec(struct pg_tm * tm, fsec_t *fsec, int *tzp)
375 {
376         int                     tz;
377
378         timestamp2tm(GetCurrentTransactionStartTimestamp(), &tz, tm, fsec,
379                                  NULL, NULL);
380         /* Note: don't pass NULL tzp to timestamp2tm; affects behavior */
381         if (tzp != NULL)
382                 *tzp = tz;
383 }
384
385
386 /* TrimTrailingZeros()
387  * ... resulting from printing numbers with full precision.
388  */
389 static void
390 TrimTrailingZeros(char *str)
391 {
392         int                     len = strlen(str);
393
394 #if 0
395         /* chop off trailing one to cope with interval rounding */
396         if (strcmp(str + len - 4, "0001") == 0)
397         {
398                 len -= 4;
399                 *(str + len) = '\0';
400         }
401 #endif
402
403         /* chop off trailing zeros... but leave at least 2 fractional digits */
404         while (*(str + len - 1) == '0' && *(str + len - 3) != '.')
405         {
406                 len--;
407                 *(str + len) = '\0';
408         }
409 }
410
411 /* ParseDateTime()
412  *      Break string into tokens based on a date/time context.
413  *      Returns 0 if successful, DTERR code if bogus input detected.
414  *
415  * timestr - the input string
416  * workbuf - workspace for field string storage. This must be
417  *       larger than the largest legal input for this datetime type --
418  *       some additional space will be needed to NUL terminate fields.
419  * buflen - the size of workbuf
420  * field[] - pointers to field strings are returned in this array
421  * ftype[] - field type indicators are returned in this array
422  * maxfields - dimensions of the above two arrays
423  * *numfields - set to the actual number of fields detected
424  *
425  * The fields extracted from the input are stored as separate,
426  * null-terminated strings in the workspace at workbuf. Any text is
427  * converted to lower case.
428  *
429  * Several field types are assigned:
430  *      DTK_NUMBER - digits and (possibly) a decimal point
431  *      DTK_DATE - digits and two delimiters, or digits and text
432  *      DTK_TIME - digits, colon delimiters, and possibly a decimal point
433  *      DTK_STRING - text (no digits or punctuation)
434  *      DTK_SPECIAL - leading "+" or "-" followed by text
435  *      DTK_TZ - leading "+" or "-" followed by digits (also eats ':' or '.')
436  *
437  * Note that some field types can hold unexpected items:
438  *      DTK_NUMBER can hold date fields (yy.ddd)
439  *      DTK_STRING can hold months (January) and time zones (PST)
440  *      DTK_DATE can hold time zone names (America/New_York, GMT-8)
441  */
442 int
443 ParseDateTime(const char *timestr, char *workbuf, size_t buflen,
444                           char **field, int *ftype, int maxfields, int *numfields)
445 {
446         int                     nf = 0;
447         const char *cp = timestr;
448         char       *bufp = workbuf;
449         const char *bufend = workbuf + buflen;
450
451         /*
452          * Set the character pointed-to by "bufptr" to "newchar", and increment
453          * "bufptr". "end" gives the end of the buffer -- we return an error if
454          * there is no space left to append a character to the buffer. Note that
455          * "bufptr" is evaluated twice.
456          */
457 #define APPEND_CHAR(bufptr, end, newchar)               \
458         do                                                                                      \
459         {                                                                                       \
460                 if (((bufptr) + 1) >= (end))                    \
461                         return DTERR_BAD_FORMAT;                        \
462                 *(bufptr)++ = newchar;                                  \
463         } while (0)
464
465         /* outer loop through fields */
466         while (*cp != '\0')
467         {
468                 /* Ignore spaces between fields */
469                 if (isspace((unsigned char) *cp))
470                 {
471                         cp++;
472                         continue;
473                 }
474
475                 /* Record start of current field */
476                 if (nf >= maxfields)
477                         return DTERR_BAD_FORMAT;
478                 field[nf] = bufp;
479
480                 /* leading digit? then date or time */
481                 if (isdigit((unsigned char) *cp))
482                 {
483                         APPEND_CHAR(bufp, bufend, *cp++);
484                         while (isdigit((unsigned char) *cp))
485                                 APPEND_CHAR(bufp, bufend, *cp++);
486
487                         /* time field? */
488                         if (*cp == ':')
489                         {
490                                 ftype[nf] = DTK_TIME;
491                                 APPEND_CHAR(bufp, bufend, *cp++);
492                                 while (isdigit((unsigned char) *cp) ||
493                                            (*cp == ':') || (*cp == '.'))
494                                         APPEND_CHAR(bufp, bufend, *cp++);
495                         }
496                         /* date field? allow embedded text month */
497                         else if (*cp == '-' || *cp == '/' || *cp == '.')
498                         {
499                                 /* save delimiting character to use later */
500                                 char            delim = *cp;
501
502                                 APPEND_CHAR(bufp, bufend, *cp++);
503                                 /* second field is all digits? then no embedded text month */
504                                 if (isdigit((unsigned char) *cp))
505                                 {
506                                         ftype[nf] = ((delim == '.') ? DTK_NUMBER : DTK_DATE);
507                                         while (isdigit((unsigned char) *cp))
508                                                 APPEND_CHAR(bufp, bufend, *cp++);
509
510                                         /*
511                                          * insist that the delimiters match to get a three-field
512                                          * date.
513                                          */
514                                         if (*cp == delim)
515                                         {
516                                                 ftype[nf] = DTK_DATE;
517                                                 APPEND_CHAR(bufp, bufend, *cp++);
518                                                 while (isdigit((unsigned char) *cp) || *cp == delim)
519                                                         APPEND_CHAR(bufp, bufend, *cp++);
520                                         }
521                                 }
522                                 else
523                                 {
524                                         ftype[nf] = DTK_DATE;
525                                         while (isalnum((unsigned char) *cp) || *cp == delim)
526                                                 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
527                                 }
528                         }
529
530                         /*
531                          * otherwise, number only and will determine year, month, day, or
532                          * concatenated fields later...
533                          */
534                         else
535                                 ftype[nf] = DTK_NUMBER;
536                 }
537                 /* Leading decimal point? Then fractional seconds... */
538                 else if (*cp == '.')
539                 {
540                         APPEND_CHAR(bufp, bufend, *cp++);
541                         while (isdigit((unsigned char) *cp))
542                                 APPEND_CHAR(bufp, bufend, *cp++);
543
544                         ftype[nf] = DTK_NUMBER;
545                 }
546
547                 /*
548                  * text? then date string, month, day of week, special, or timezone
549                  */
550                 else if (isalpha((unsigned char) *cp))
551                 {
552                         bool            is_date;
553
554                         ftype[nf] = DTK_STRING;
555                         APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
556                         while (isalpha((unsigned char) *cp))
557                                 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
558
559                         /*
560                          * Dates can have embedded '-', '/', or '.' separators.  It could
561                          * also be a timezone name containing embedded '/', '+', '-', '_',
562                          * or ':' (but '_' or ':' can't be the first punctuation). If the
563                          * next character is a digit or '+', we need to check whether what
564                          * we have so far is a recognized non-timezone keyword --- if so,
565                          * don't believe that this is the start of a timezone.
566                          */
567                         is_date = false;
568                         if (*cp == '-' || *cp == '/' || *cp == '.')
569                                 is_date = true;
570                         else if (*cp == '+' || isdigit((unsigned char) *cp))
571                         {
572                                 *bufp = '\0';   /* null-terminate current field value */
573                                 /* we need search only the core token table, not TZ names */
574                                 if (datebsearch(field[nf], datetktbl, szdatetktbl) == NULL)
575                                         is_date = true;
576                         }
577                         if (is_date)
578                         {
579                                 ftype[nf] = DTK_DATE;
580                                 do
581                                 {
582                                         APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
583                                 } while (*cp == '+' || *cp == '-' ||
584                                                  *cp == '/' || *cp == '_' ||
585                                                  *cp == '.' || *cp == ':' ||
586                                                  isalnum((unsigned char) *cp));
587                         }
588                 }
589                 /* sign? then special or numeric timezone */
590                 else if (*cp == '+' || *cp == '-')
591                 {
592                         APPEND_CHAR(bufp, bufend, *cp++);
593                         /* soak up leading whitespace */
594                         while (isspace((unsigned char) *cp))
595                                 cp++;
596                         /* numeric timezone? */
597                         if (isdigit((unsigned char) *cp))
598                         {
599                                 ftype[nf] = DTK_TZ;
600                                 APPEND_CHAR(bufp, bufend, *cp++);
601                                 while (isdigit((unsigned char) *cp) ||
602                                            *cp == ':' || *cp == '.')
603                                         APPEND_CHAR(bufp, bufend, *cp++);
604                         }
605                         /* special? */
606                         else if (isalpha((unsigned char) *cp))
607                         {
608                                 ftype[nf] = DTK_SPECIAL;
609                                 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
610                                 while (isalpha((unsigned char) *cp))
611                                         APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
612                         }
613                         /* otherwise something wrong... */
614                         else
615                                 return DTERR_BAD_FORMAT;
616                 }
617                 /* ignore other punctuation but use as delimiter */
618                 else if (ispunct((unsigned char) *cp))
619                 {
620                         cp++;
621                         continue;
622                 }
623                 /* otherwise, something is not right... */
624                 else
625                         return DTERR_BAD_FORMAT;
626
627                 /* force in a delimiter after each field */
628                 *bufp++ = '\0';
629                 nf++;
630         }
631
632         *numfields = nf;
633
634         return 0;
635 }
636
637
638 /* DecodeDateTime()
639  * Interpret previously parsed fields for general date and time.
640  * Return 0 if full date, 1 if only time, and negative DTERR code if problems.
641  * (Currently, all callers treat 1 as an error return too.)
642  *
643  *              External format(s):
644  *                              "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
645  *                              "Fri Feb-7-1997 15:23:27"
646  *                              "Feb-7-1997 15:23:27"
647  *                              "2-7-1997 15:23:27"
648  *                              "1997-2-7 15:23:27"
649  *                              "1997.038 15:23:27"             (day of year 1-366)
650  *              Also supports input in compact time:
651  *                              "970207 152327"
652  *                              "97038 152327"
653  *                              "20011225T040506.789-07"
654  *
655  * Use the system-provided functions to get the current time zone
656  * if not specified in the input string.
657  *
658  * If the date is outside the range of pg_time_t (in practice that could only
659  * happen if pg_time_t is just 32 bits), then assume UTC time zone - thomas
660  * 1997-05-27
661  */
662 int
663 DecodeDateTime(char **field, int *ftype, int nf,
664                            int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
665 {
666         int                     fmask = 0,
667                                 tmask,
668                                 type;
669         int                     ptype = 0;              /* "prefix type" for ISO y2001m02d04 format */
670         int                     i;
671         int                     val;
672         int                     dterr;
673         int                     mer = HR24;
674         bool            haveTextMonth = FALSE;
675         bool            is2digits = FALSE;
676         bool            bc = FALSE;
677         pg_tz      *namedTz = NULL;
678
679         /*
680          * We'll insist on at least all of the date fields, but initialize the
681          * remaining fields in case they are not set later...
682          */
683         *dtype = DTK_DATE;
684         tm->tm_hour = 0;
685         tm->tm_min = 0;
686         tm->tm_sec = 0;
687         *fsec = 0;
688         /* don't know daylight savings time status apriori */
689         tm->tm_isdst = -1;
690         if (tzp != NULL)
691                 *tzp = 0;
692
693         for (i = 0; i < nf; i++)
694         {
695                 switch (ftype[i])
696                 {
697                         case DTK_DATE:
698                                 /***
699                                  * Integral julian day with attached time zone?
700                                  * All other forms with JD will be separated into
701                                  * distinct fields, so we handle just this case here.
702                                  ***/
703                                 if (ptype == DTK_JULIAN)
704                                 {
705                                         char       *cp;
706                                         int                     val;
707
708                                         if (tzp == NULL)
709                                                 return DTERR_BAD_FORMAT;
710
711                                         errno = 0;
712                                         val = strtol(field[i], &cp, 10);
713                                         if (errno == ERANGE)
714                                                 return DTERR_FIELD_OVERFLOW;
715
716                                         j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
717                                         /* Get the time zone from the end of the string */
718                                         dterr = DecodeTimezone(cp, tzp);
719                                         if (dterr)
720                                                 return dterr;
721
722                                         tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
723                                         ptype = 0;
724                                         break;
725                                 }
726                                 /***
727                                  * Already have a date? Then this might be a time zone name
728                                  * with embedded punctuation (e.g. "America/New_York") or a
729                                  * run-together time with trailing time zone (e.g. hhmmss-zz).
730                                  * - thomas 2001-12-25
731                                  *
732                                  * We consider it a time zone if we already have month & day.
733                                  * This is to allow the form "mmm dd hhmmss tz year", which
734                                  * we've historically accepted.
735                                  ***/
736                                 else if (ptype != 0 ||
737                                                  ((fmask & (DTK_M(MONTH) | DTK_M(DAY))) ==
738                                                   (DTK_M(MONTH) | DTK_M(DAY))))
739                                 {
740                                         /* No time zone accepted? Then quit... */
741                                         if (tzp == NULL)
742                                                 return DTERR_BAD_FORMAT;
743
744                                         if (isdigit((unsigned char) *field[i]) || ptype != 0)
745                                         {
746                                                 char       *cp;
747
748                                                 if (ptype != 0)
749                                                 {
750                                                         /* Sanity check; should not fail this test */
751                                                         if (ptype != DTK_TIME)
752                                                                 return DTERR_BAD_FORMAT;
753                                                         ptype = 0;
754                                                 }
755
756                                                 /*
757                                                  * Starts with a digit but we already have a time
758                                                  * field? Then we are in trouble with a date and time
759                                                  * already...
760                                                  */
761                                                 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
762                                                         return DTERR_BAD_FORMAT;
763
764                                                 if ((cp = strchr(field[i], '-')) == NULL)
765                                                         return DTERR_BAD_FORMAT;
766
767                                                 /* Get the time zone from the end of the string */
768                                                 dterr = DecodeTimezone(cp, tzp);
769                                                 if (dterr)
770                                                         return dterr;
771                                                 *cp = '\0';
772
773                                                 /*
774                                                  * Then read the rest of the field as a concatenated
775                                                  * time
776                                                  */
777                                                 dterr = DecodeNumberField(strlen(field[i]), field[i],
778                                                                                                   fmask,
779                                                                                                   &tmask, tm,
780                                                                                                   fsec, &is2digits);
781                                                 if (dterr < 0)
782                                                         return dterr;
783
784                                                 /*
785                                                  * modify tmask after returning from
786                                                  * DecodeNumberField()
787                                                  */
788                                                 tmask |= DTK_M(TZ);
789                                         }
790                                         else
791                                         {
792                                                 namedTz = pg_tzset(field[i]);
793                                                 if (!namedTz)
794                                                 {
795                                                         /*
796                                                          * We should return an error code instead of
797                                                          * ereport'ing directly, but then there is no way
798                                                          * to report the bad time zone name.
799                                                          */
800                                                         ereport(ERROR,
801                                                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
802                                                                          errmsg("time zone \"%s\" not recognized",
803                                                                                         field[i])));
804                                                 }
805                                                 /* we'll apply the zone setting below */
806                                                 tmask = DTK_M(TZ);
807                                         }
808                                 }
809                                 else
810                                 {
811                                         dterr = DecodeDate(field[i], fmask,
812                                                                            &tmask, &is2digits, tm);
813                                         if (dterr)
814                                                 return dterr;
815                                 }
816                                 break;
817
818                         case DTK_TIME:
819                                 dterr = DecodeTime(field[i], fmask, &tmask, tm, fsec);
820                                 if (dterr)
821                                         return dterr;
822
823                                 /*
824                                  * Check upper limit on hours; other limits checked in
825                                  * DecodeTime()
826                                  */
827                                 /* test for > 24:00:00 */
828                                 if (tm->tm_hour > 24 ||
829                                         (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0)))
830                                         return DTERR_FIELD_OVERFLOW;
831                                 break;
832
833                         case DTK_TZ:
834                                 {
835                                         int                     tz;
836
837                                         if (tzp == NULL)
838                                                 return DTERR_BAD_FORMAT;
839
840                                         dterr = DecodeTimezone(field[i], &tz);
841                                         if (dterr)
842                                                 return dterr;
843                                         *tzp = tz;
844                                         tmask = DTK_M(TZ);
845                                 }
846                                 break;
847
848                         case DTK_NUMBER:
849
850                                 /*
851                                  * Was this an "ISO date" with embedded field labels? An
852                                  * example is "y2001m02d04" - thomas 2001-02-04
853                                  */
854                                 if (ptype != 0)
855                                 {
856                                         char       *cp;
857                                         int                     val;
858
859                                         errno = 0;
860                                         val = strtol(field[i], &cp, 10);
861                                         if (errno == ERANGE)
862                                                 return DTERR_FIELD_OVERFLOW;
863
864                                         /*
865                                          * only a few kinds are allowed to have an embedded
866                                          * decimal
867                                          */
868                                         if (*cp == '.')
869                                                 switch (ptype)
870                                                 {
871                                                         case DTK_JULIAN:
872                                                         case DTK_TIME:
873                                                         case DTK_SECOND:
874                                                                 break;
875                                                         default:
876                                                                 return DTERR_BAD_FORMAT;
877                                                                 break;
878                                                 }
879                                         else if (*cp != '\0')
880                                                 return DTERR_BAD_FORMAT;
881
882                                         switch (ptype)
883                                         {
884                                                 case DTK_YEAR:
885                                                         tm->tm_year = val;
886                                                         tmask = DTK_M(YEAR);
887                                                         break;
888
889                                                 case DTK_MONTH:
890
891                                                         /*
892                                                          * already have a month and hour? then assume
893                                                          * minutes
894                                                          */
895                                                         if ((fmask & DTK_M(MONTH)) != 0 &&
896                                                                 (fmask & DTK_M(HOUR)) != 0)
897                                                         {
898                                                                 tm->tm_min = val;
899                                                                 tmask = DTK_M(MINUTE);
900                                                         }
901                                                         else
902                                                         {
903                                                                 tm->tm_mon = val;
904                                                                 tmask = DTK_M(MONTH);
905                                                         }
906                                                         break;
907
908                                                 case DTK_DAY:
909                                                         tm->tm_mday = val;
910                                                         tmask = DTK_M(DAY);
911                                                         break;
912
913                                                 case DTK_HOUR:
914                                                         tm->tm_hour = val;
915                                                         tmask = DTK_M(HOUR);
916                                                         break;
917
918                                                 case DTK_MINUTE:
919                                                         tm->tm_min = val;
920                                                         tmask = DTK_M(MINUTE);
921                                                         break;
922
923                                                 case DTK_SECOND:
924                                                         tm->tm_sec = val;
925                                                         tmask = DTK_M(SECOND);
926                                                         if (*cp == '.')
927                                                         {
928                                                                 double          frac;
929
930                                                                 frac = strtod(cp, &cp);
931                                                                 if (*cp != '\0')
932                                                                         return DTERR_BAD_FORMAT;
933 #ifdef HAVE_INT64_TIMESTAMP
934                                                                 *fsec = rint(frac * 1000000);
935 #else
936                                                                 *fsec = frac;
937 #endif
938                                                                 tmask = DTK_ALL_SECS_M;
939                                                         }
940                                                         break;
941
942                                                 case DTK_TZ:
943                                                         tmask = DTK_M(TZ);
944                                                         dterr = DecodeTimezone(field[i], tzp);
945                                                         if (dterr)
946                                                                 return dterr;
947                                                         break;
948
949                                                 case DTK_JULIAN:
950                                                         /***
951                                                          * previous field was a label for "julian date"?
952                                                          ***/
953                                                         tmask = DTK_DATE_M;
954                                                         j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
955                                                         /* fractional Julian Day? */
956                                                         if (*cp == '.')
957                                                         {
958                                                                 double          time;
959
960                                                                 time = strtod(cp, &cp);
961                                                                 if (*cp != '\0')
962                                                                         return DTERR_BAD_FORMAT;
963
964                                                                 tmask |= DTK_TIME_M;
965 #ifdef HAVE_INT64_TIMESTAMP
966                                                                 dt2time(time * USECS_PER_DAY,
967                                                                                 &tm->tm_hour, &tm->tm_min,
968                                                                                 &tm->tm_sec, fsec);
969 #else
970                                                                 dt2time(time * SECS_PER_DAY, &tm->tm_hour,
971                                                                                 &tm->tm_min, &tm->tm_sec, fsec);
972 #endif
973                                                         }
974                                                         break;
975
976                                                 case DTK_TIME:
977                                                         /* previous field was "t" for ISO time */
978                                                         dterr = DecodeNumberField(strlen(field[i]), field[i],
979                                                                                                           (fmask | DTK_DATE_M),
980                                                                                                           &tmask, tm,
981                                                                                                           fsec, &is2digits);
982                                                         if (dterr < 0)
983                                                                 return dterr;
984                                                         if (tmask != DTK_TIME_M)
985                                                                 return DTERR_BAD_FORMAT;
986                                                         break;
987
988                                                 default:
989                                                         return DTERR_BAD_FORMAT;
990                                                         break;
991                                         }
992
993                                         ptype = 0;
994                                         *dtype = DTK_DATE;
995                                 }
996                                 else
997                                 {
998                                         char       *cp;
999                                         int                     flen;
1000
1001                                         flen = strlen(field[i]);
1002                                         cp = strchr(field[i], '.');
1003
1004                                         /* Embedded decimal and no date yet? */
1005                                         if (cp != NULL && !(fmask & DTK_DATE_M))
1006                                         {
1007                                                 dterr = DecodeDate(field[i], fmask,
1008                                                                                    &tmask, &is2digits, tm);
1009                                                 if (dterr)
1010                                                         return dterr;
1011                                         }
1012                                         /* embedded decimal and several digits before? */
1013                                         else if (cp != NULL && flen - strlen(cp) > 2)
1014                                         {
1015                                                 /*
1016                                                  * Interpret as a concatenated date or time Set the
1017                                                  * type field to allow decoding other fields later.
1018                                                  * Example: 20011223 or 040506
1019                                                  */
1020                                                 dterr = DecodeNumberField(flen, field[i], fmask,
1021                                                                                                   &tmask, tm,
1022                                                                                                   fsec, &is2digits);
1023                                                 if (dterr < 0)
1024                                                         return dterr;
1025                                         }
1026                                         else if (flen > 4)
1027                                         {
1028                                                 dterr = DecodeNumberField(flen, field[i], fmask,
1029                                                                                                   &tmask, tm,
1030                                                                                                   fsec, &is2digits);
1031                                                 if (dterr < 0)
1032                                                         return dterr;
1033                                         }
1034                                         /* otherwise it is a single date/time field... */
1035                                         else
1036                                         {
1037                                                 dterr = DecodeNumber(flen, field[i],
1038                                                                                          haveTextMonth, fmask,
1039                                                                                          &tmask, tm,
1040                                                                                          fsec, &is2digits);
1041                                                 if (dterr)
1042                                                         return dterr;
1043                                         }
1044                                 }
1045                                 break;
1046
1047                         case DTK_STRING:
1048                         case DTK_SPECIAL:
1049                                 type = DecodeSpecial(i, field[i], &val);
1050                                 if (type == IGNORE_DTF)
1051                                         continue;
1052
1053                                 tmask = DTK_M(type);
1054                                 switch (type)
1055                                 {
1056                                         case RESERV:
1057                                                 switch (val)
1058                                                 {
1059                                                         case DTK_CURRENT:
1060                                                                 ereport(ERROR,
1061                                                                          (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1062                                                                           errmsg("date/time value \"current\" is no longer supported")));
1063
1064                                                                 return DTERR_BAD_FORMAT;
1065                                                                 break;
1066
1067                                                         case DTK_NOW:
1068                                                                 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1069                                                                 *dtype = DTK_DATE;
1070                                                                 GetCurrentTimeUsec(tm, fsec, tzp);
1071                                                                 break;
1072
1073                                                         case DTK_YESTERDAY:
1074                                                                 tmask = DTK_DATE_M;
1075                                                                 *dtype = DTK_DATE;
1076                                                                 GetCurrentDateTime(tm);
1077                                                                 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - 1,
1078                                                                         &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1079                                                                 tm->tm_hour = 0;
1080                                                                 tm->tm_min = 0;
1081                                                                 tm->tm_sec = 0;
1082                                                                 break;
1083
1084                                                         case DTK_TODAY:
1085                                                                 tmask = DTK_DATE_M;
1086                                                                 *dtype = DTK_DATE;
1087                                                                 GetCurrentDateTime(tm);
1088                                                                 tm->tm_hour = 0;
1089                                                                 tm->tm_min = 0;
1090                                                                 tm->tm_sec = 0;
1091                                                                 break;
1092
1093                                                         case DTK_TOMORROW:
1094                                                                 tmask = DTK_DATE_M;
1095                                                                 *dtype = DTK_DATE;
1096                                                                 GetCurrentDateTime(tm);
1097                                                                 j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1,
1098                                                                         &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1099                                                                 tm->tm_hour = 0;
1100                                                                 tm->tm_min = 0;
1101                                                                 tm->tm_sec = 0;
1102                                                                 break;
1103
1104                                                         case DTK_ZULU:
1105                                                                 tmask = (DTK_TIME_M | DTK_M(TZ));
1106                                                                 *dtype = DTK_DATE;
1107                                                                 tm->tm_hour = 0;
1108                                                                 tm->tm_min = 0;
1109                                                                 tm->tm_sec = 0;
1110                                                                 if (tzp != NULL)
1111                                                                         *tzp = 0;
1112                                                                 break;
1113
1114                                                         default:
1115                                                                 *dtype = val;
1116                                                 }
1117
1118                                                 break;
1119
1120                                         case MONTH:
1121
1122                                                 /*
1123                                                  * already have a (numeric) month? then see if we can
1124                                                  * substitute...
1125                                                  */
1126                                                 if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
1127                                                         !(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 &&
1128                                                         tm->tm_mon <= 31)
1129                                                 {
1130                                                         tm->tm_mday = tm->tm_mon;
1131                                                         tmask = DTK_M(DAY);
1132                                                 }
1133                                                 haveTextMonth = TRUE;
1134                                                 tm->tm_mon = val;
1135                                                 break;
1136
1137                                         case DTZMOD:
1138
1139                                                 /*
1140                                                  * daylight savings time modifier (solves "MET DST"
1141                                                  * syntax)
1142                                                  */
1143                                                 tmask |= DTK_M(DTZ);
1144                                                 tm->tm_isdst = 1;
1145                                                 if (tzp == NULL)
1146                                                         return DTERR_BAD_FORMAT;
1147                                                 *tzp += val * MINS_PER_HOUR;
1148                                                 break;
1149
1150                                         case DTZ:
1151
1152                                                 /*
1153                                                  * set mask for TZ here _or_ check for DTZ later when
1154                                                  * getting default timezone
1155                                                  */
1156                                                 tmask |= DTK_M(TZ);
1157                                                 tm->tm_isdst = 1;
1158                                                 if (tzp == NULL)
1159                                                         return DTERR_BAD_FORMAT;
1160                                                 *tzp = val * MINS_PER_HOUR;
1161                                                 break;
1162
1163                                         case TZ:
1164                                                 tm->tm_isdst = 0;
1165                                                 if (tzp == NULL)
1166                                                         return DTERR_BAD_FORMAT;
1167                                                 *tzp = val * MINS_PER_HOUR;
1168                                                 break;
1169
1170                                         case IGNORE_DTF:
1171                                                 break;
1172
1173                                         case AMPM:
1174                                                 mer = val;
1175                                                 break;
1176
1177                                         case ADBC:
1178                                                 bc = (val == BC);
1179                                                 break;
1180
1181                                         case DOW:
1182                                                 tm->tm_wday = val;
1183                                                 break;
1184
1185                                         case UNITS:
1186                                                 tmask = 0;
1187                                                 ptype = val;
1188                                                 break;
1189
1190                                         case ISOTIME:
1191
1192                                                 /*
1193                                                  * This is a filler field "t" indicating that the next
1194                                                  * field is time. Try to verify that this is sensible.
1195                                                  */
1196                                                 tmask = 0;
1197
1198                                                 /* No preceding date? Then quit... */
1199                                                 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1200                                                         return DTERR_BAD_FORMAT;
1201
1202                                                 /***
1203                                                  * We will need one of the following fields:
1204                                                  *      DTK_NUMBER should be hhmmss.fff
1205                                                  *      DTK_TIME should be hh:mm:ss.fff
1206                                                  *      DTK_DATE should be hhmmss-zz
1207                                                  ***/
1208                                                 if (i >= nf - 1 ||
1209                                                         (ftype[i + 1] != DTK_NUMBER &&
1210                                                          ftype[i + 1] != DTK_TIME &&
1211                                                          ftype[i + 1] != DTK_DATE))
1212                                                         return DTERR_BAD_FORMAT;
1213
1214                                                 ptype = val;
1215                                                 break;
1216
1217                                         case UNKNOWN_FIELD:
1218
1219                                                 /*
1220                                                  * Before giving up and declaring error, check to see
1221                                                  * if it is an all-alpha timezone name.
1222                                                  */
1223                                                 namedTz = pg_tzset(field[i]);
1224                                                 if (!namedTz)
1225                                                         return DTERR_BAD_FORMAT;
1226                                                 /* we'll apply the zone setting below */
1227                                                 tmask = DTK_M(TZ);
1228                                                 break;
1229
1230                                         default:
1231                                                 return DTERR_BAD_FORMAT;
1232                                 }
1233                                 break;
1234
1235                         default:
1236                                 return DTERR_BAD_FORMAT;
1237                 }
1238
1239                 if (tmask & fmask)
1240                         return DTERR_BAD_FORMAT;
1241                 fmask |= tmask;
1242         }                               /* end loop over fields */
1243
1244         /* do final checking/adjustment of Y/M/D fields */
1245         dterr = ValidateDate(fmask, is2digits, bc, tm);
1246         if (dterr)
1247                 return dterr;
1248
1249         /* handle AM/PM */
1250         if (mer != HR24 && tm->tm_hour > 12)
1251                 return DTERR_FIELD_OVERFLOW;
1252         if (mer == AM && tm->tm_hour == 12)
1253                 tm->tm_hour = 0;
1254         else if (mer == PM && tm->tm_hour != 12)
1255                 tm->tm_hour += 12;
1256
1257         /* do additional checking for full date specs... */
1258         if (*dtype == DTK_DATE)
1259         {
1260                 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1261                 {
1262                         if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1263                                 return 1;
1264                         return DTERR_BAD_FORMAT;
1265                 }
1266
1267                 /*
1268                  * If we had a full timezone spec, compute the offset (we could not do
1269                  * it before, because we need the date to resolve DST status).
1270                  */
1271                 if (namedTz != NULL)
1272                 {
1273                         /* daylight savings time modifier disallowed with full TZ */
1274                         if (fmask & DTK_M(DTZMOD))
1275                                 return DTERR_BAD_FORMAT;
1276
1277                         *tzp = DetermineTimeZoneOffset(tm, namedTz);
1278                 }
1279
1280                 /* timezone not specified? then find local timezone if possible */
1281                 if (tzp != NULL && !(fmask & DTK_M(TZ)))
1282                 {
1283                         /*
1284                          * daylight savings time modifier but no standard timezone? then
1285                          * error
1286                          */
1287                         if (fmask & DTK_M(DTZMOD))
1288                                 return DTERR_BAD_FORMAT;
1289
1290                         *tzp = DetermineTimeZoneOffset(tm, session_timezone);
1291                 }
1292         }
1293
1294         return 0;
1295 }
1296
1297
1298 /* DetermineTimeZoneOffset()
1299  *
1300  * Given a struct pg_tm in which tm_year, tm_mon, tm_mday, tm_hour, tm_min, and
1301  * tm_sec fields are set, attempt to determine the applicable time zone
1302  * (ie, regular or daylight-savings time) at that time.  Set the struct pg_tm's
1303  * tm_isdst field accordingly, and return the actual timezone offset.
1304  *
1305  * Note: it might seem that we should use mktime() for this, but bitter
1306  * experience teaches otherwise.  This code is much faster than most versions
1307  * of mktime(), anyway.
1308  */
1309 int
1310 DetermineTimeZoneOffset(struct pg_tm * tm, pg_tz *tzp)
1311 {
1312         int                     date,
1313                                 sec;
1314         pg_time_t       day,
1315                                 mytime,
1316                                 prevtime,
1317                                 boundary,
1318                                 beforetime,
1319                                 aftertime;
1320         long int        before_gmtoff,
1321                                 after_gmtoff;
1322         int                     before_isdst,
1323                                 after_isdst;
1324         int                     res;
1325
1326         if (tzp == session_timezone && HasCTZSet)
1327         {
1328                 tm->tm_isdst = 0;               /* for lack of a better idea */
1329                 return CTimeZone;
1330         }
1331
1332         /*
1333          * First, generate the pg_time_t value corresponding to the given
1334          * y/m/d/h/m/s taken as GMT time.  If this overflows, punt and decide the
1335          * timezone is GMT.  (We only need to worry about overflow on machines
1336          * where pg_time_t is 32 bits.)
1337          */
1338         if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
1339                 goto overflow;
1340         date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - UNIX_EPOCH_JDATE;
1341
1342         day = ((pg_time_t) date) * SECS_PER_DAY;
1343         if (day / SECS_PER_DAY != date)
1344                 goto overflow;
1345         sec = tm->tm_sec + (tm->tm_min + tm->tm_hour * MINS_PER_HOUR) * SECS_PER_MINUTE;
1346         mytime = day + sec;
1347         /* since sec >= 0, overflow could only be from +day to -mytime */
1348         if (mytime < 0 && day > 0)
1349                 goto overflow;
1350
1351         /*
1352          * Find the DST time boundary just before or following the target time. We
1353          * assume that all zones have GMT offsets less than 24 hours, and that DST
1354          * boundaries can't be closer together than 48 hours, so backing up 24
1355          * hours and finding the "next" boundary will work.
1356          */
1357         prevtime = mytime - SECS_PER_DAY;
1358         if (mytime < 0 && prevtime > 0)
1359                 goto overflow;
1360
1361         res = pg_next_dst_boundary(&prevtime,
1362                                                            &before_gmtoff, &before_isdst,
1363                                                            &boundary,
1364                                                            &after_gmtoff, &after_isdst,
1365                                                            tzp);
1366         if (res < 0)
1367                 goto overflow;                  /* failure? */
1368
1369         if (res == 0)
1370         {
1371                 /* Non-DST zone, life is simple */
1372                 tm->tm_isdst = before_isdst;
1373                 return -(int) before_gmtoff;
1374         }
1375
1376         /*
1377          * Form the candidate pg_time_t values with local-time adjustment
1378          */
1379         beforetime = mytime - before_gmtoff;
1380         if ((before_gmtoff > 0 &&
1381                  mytime < 0 && beforetime > 0) ||
1382                 (before_gmtoff <= 0 &&
1383                  mytime > 0 && beforetime < 0))
1384                 goto overflow;
1385         aftertime = mytime - after_gmtoff;
1386         if ((after_gmtoff > 0 &&
1387                  mytime < 0 && aftertime > 0) ||
1388                 (after_gmtoff <= 0 &&
1389                  mytime > 0 && aftertime < 0))
1390                 goto overflow;
1391
1392         /*
1393          * If both before or both after the boundary time, we know what to do
1394          */
1395         if (beforetime <= boundary && aftertime < boundary)
1396         {
1397                 tm->tm_isdst = before_isdst;
1398                 return -(int) before_gmtoff;
1399         }
1400         if (beforetime > boundary && aftertime >= boundary)
1401         {
1402                 tm->tm_isdst = after_isdst;
1403                 return -(int) after_gmtoff;
1404         }
1405
1406         /*
1407          * It's an invalid or ambiguous time due to timezone transition. Prefer
1408          * the standard-time interpretation.
1409          */
1410         if (after_isdst == 0)
1411         {
1412                 tm->tm_isdst = after_isdst;
1413                 return -(int) after_gmtoff;
1414         }
1415         tm->tm_isdst = before_isdst;
1416         return -(int) before_gmtoff;
1417
1418 overflow:
1419         /* Given date is out of range, so assume UTC */
1420         tm->tm_isdst = 0;
1421         return 0;
1422 }
1423
1424
1425 /* DecodeTimeOnly()
1426  * Interpret parsed string as time fields only.
1427  * Returns 0 if successful, DTERR code if bogus input detected.
1428  *
1429  * Note that support for time zone is here for
1430  * SQL92 TIME WITH TIME ZONE, but it reveals
1431  * bogosity with SQL92 date/time standards, since
1432  * we must infer a time zone from current time.
1433  * - thomas 2000-03-10
1434  * Allow specifying date to get a better time zone,
1435  * if time zones are allowed. - thomas 2001-12-26
1436  */
1437 int
1438 DecodeTimeOnly(char **field, int *ftype, int nf,
1439                            int *dtype, struct pg_tm * tm, fsec_t *fsec, int *tzp)
1440 {
1441         int                     fmask = 0,
1442                                 tmask,
1443                                 type;
1444         int                     ptype = 0;              /* "prefix type" for ISO h04mm05s06 format */
1445         int                     i;
1446         int                     val;
1447         int                     dterr;
1448         bool            is2digits = FALSE;
1449         bool            bc = FALSE;
1450         int                     mer = HR24;
1451         pg_tz      *namedTz = NULL;
1452
1453         *dtype = DTK_TIME;
1454         tm->tm_hour = 0;
1455         tm->tm_min = 0;
1456         tm->tm_sec = 0;
1457         *fsec = 0;
1458         /* don't know daylight savings time status apriori */
1459         tm->tm_isdst = -1;
1460
1461         if (tzp != NULL)
1462                 *tzp = 0;
1463
1464         for (i = 0; i < nf; i++)
1465         {
1466                 switch (ftype[i])
1467                 {
1468                         case DTK_DATE:
1469
1470                                 /*
1471                                  * Time zone not allowed? Then should not accept dates or time
1472                                  * zones no matter what else!
1473                                  */
1474                                 if (tzp == NULL)
1475                                         return DTERR_BAD_FORMAT;
1476
1477                                 /* Under limited circumstances, we will accept a date... */
1478                                 if (i == 0 && nf >= 2 &&
1479                                         (ftype[nf - 1] == DTK_DATE || ftype[1] == DTK_TIME))
1480                                 {
1481                                         dterr = DecodeDate(field[i], fmask,
1482                                                                            &tmask, &is2digits, tm);
1483                                         if (dterr)
1484                                                 return dterr;
1485                                 }
1486                                 /* otherwise, this is a time and/or time zone */
1487                                 else
1488                                 {
1489                                         if (isdigit((unsigned char) *field[i]))
1490                                         {
1491                                                 char       *cp;
1492
1493                                                 /*
1494                                                  * Starts with a digit but we already have a time
1495                                                  * field? Then we are in trouble with time already...
1496                                                  */
1497                                                 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1498                                                         return DTERR_BAD_FORMAT;
1499
1500                                                 /*
1501                                                  * Should not get here and fail. Sanity check only...
1502                                                  */
1503                                                 if ((cp = strchr(field[i], '-')) == NULL)
1504                                                         return DTERR_BAD_FORMAT;
1505
1506                                                 /* Get the time zone from the end of the string */
1507                                                 dterr = DecodeTimezone(cp, tzp);
1508                                                 if (dterr)
1509                                                         return dterr;
1510                                                 *cp = '\0';
1511
1512                                                 /*
1513                                                  * Then read the rest of the field as a concatenated
1514                                                  * time
1515                                                  */
1516                                                 dterr = DecodeNumberField(strlen(field[i]), field[i],
1517                                                                                                   (fmask | DTK_DATE_M),
1518                                                                                                   &tmask, tm,
1519                                                                                                   fsec, &is2digits);
1520                                                 if (dterr < 0)
1521                                                         return dterr;
1522                                                 ftype[i] = dterr;
1523
1524                                                 tmask |= DTK_M(TZ);
1525                                         }
1526                                         else
1527                                         {
1528                                                 namedTz = pg_tzset(field[i]);
1529                                                 if (!namedTz)
1530                                                 {
1531                                                         /*
1532                                                          * We should return an error code instead of
1533                                                          * ereport'ing directly, but then there is no way
1534                                                          * to report the bad time zone name.
1535                                                          */
1536                                                         ereport(ERROR,
1537                                                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1538                                                                          errmsg("time zone \"%s\" not recognized",
1539                                                                                         field[i])));
1540                                                 }
1541                                                 /* we'll apply the zone setting below */
1542                                                 ftype[i] = DTK_TZ;
1543                                                 tmask = DTK_M(TZ);
1544                                         }
1545                                 }
1546                                 break;
1547
1548                         case DTK_TIME:
1549                                 dterr = DecodeTime(field[i], (fmask | DTK_DATE_M),
1550                                                                    &tmask, tm, fsec);
1551                                 if (dterr)
1552                                         return dterr;
1553                                 break;
1554
1555                         case DTK_TZ:
1556                                 {
1557                                         int                     tz;
1558
1559                                         if (tzp == NULL)
1560                                                 return DTERR_BAD_FORMAT;
1561
1562                                         dterr = DecodeTimezone(field[i], &tz);
1563                                         if (dterr)
1564                                                 return dterr;
1565                                         *tzp = tz;
1566                                         tmask = DTK_M(TZ);
1567                                 }
1568                                 break;
1569
1570                         case DTK_NUMBER:
1571
1572                                 /*
1573                                  * Was this an "ISO time" with embedded field labels? An
1574                                  * example is "h04m05s06" - thomas 2001-02-04
1575                                  */
1576                                 if (ptype != 0)
1577                                 {
1578                                         char       *cp;
1579                                         int                     val;
1580
1581                                         /* Only accept a date under limited circumstances */
1582                                         switch (ptype)
1583                                         {
1584                                                 case DTK_JULIAN:
1585                                                 case DTK_YEAR:
1586                                                 case DTK_MONTH:
1587                                                 case DTK_DAY:
1588                                                         if (tzp == NULL)
1589                                                                 return DTERR_BAD_FORMAT;
1590                                                 default:
1591                                                         break;
1592                                         }
1593
1594                                         errno = 0;
1595                                         val = strtol(field[i], &cp, 10);
1596                                         if (errno == ERANGE)
1597                                                 return DTERR_FIELD_OVERFLOW;
1598
1599                                         /*
1600                                          * only a few kinds are allowed to have an embedded
1601                                          * decimal
1602                                          */
1603                                         if (*cp == '.')
1604                                                 switch (ptype)
1605                                                 {
1606                                                         case DTK_JULIAN:
1607                                                         case DTK_TIME:
1608                                                         case DTK_SECOND:
1609                                                                 break;
1610                                                         default:
1611                                                                 return DTERR_BAD_FORMAT;
1612                                                                 break;
1613                                                 }
1614                                         else if (*cp != '\0')
1615                                                 return DTERR_BAD_FORMAT;
1616
1617                                         switch (ptype)
1618                                         {
1619                                                 case DTK_YEAR:
1620                                                         tm->tm_year = val;
1621                                                         tmask = DTK_M(YEAR);
1622                                                         break;
1623
1624                                                 case DTK_MONTH:
1625
1626                                                         /*
1627                                                          * already have a month and hour? then assume
1628                                                          * minutes
1629                                                          */
1630                                                         if ((fmask & DTK_M(MONTH)) != 0 &&
1631                                                                 (fmask & DTK_M(HOUR)) != 0)
1632                                                         {
1633                                                                 tm->tm_min = val;
1634                                                                 tmask = DTK_M(MINUTE);
1635                                                         }
1636                                                         else
1637                                                         {
1638                                                                 tm->tm_mon = val;
1639                                                                 tmask = DTK_M(MONTH);
1640                                                         }
1641                                                         break;
1642
1643                                                 case DTK_DAY:
1644                                                         tm->tm_mday = val;
1645                                                         tmask = DTK_M(DAY);
1646                                                         break;
1647
1648                                                 case DTK_HOUR:
1649                                                         tm->tm_hour = val;
1650                                                         tmask = DTK_M(HOUR);
1651                                                         break;
1652
1653                                                 case DTK_MINUTE:
1654                                                         tm->tm_min = val;
1655                                                         tmask = DTK_M(MINUTE);
1656                                                         break;
1657
1658                                                 case DTK_SECOND:
1659                                                         tm->tm_sec = val;
1660                                                         tmask = DTK_M(SECOND);
1661                                                         if (*cp == '.')
1662                                                         {
1663                                                                 double          frac;
1664
1665                                                                 frac = strtod(cp, &cp);
1666                                                                 if (*cp != '\0')
1667                                                                         return DTERR_BAD_FORMAT;
1668 #ifdef HAVE_INT64_TIMESTAMP
1669                                                                 *fsec = rint(frac * 1000000);
1670 #else
1671                                                                 *fsec = frac;
1672 #endif
1673                                                                 tmask = DTK_ALL_SECS_M;
1674                                                         }
1675                                                         break;
1676
1677                                                 case DTK_TZ:
1678                                                         tmask = DTK_M(TZ);
1679                                                         dterr = DecodeTimezone(field[i], tzp);
1680                                                         if (dterr)
1681                                                                 return dterr;
1682                                                         break;
1683
1684                                                 case DTK_JULIAN:
1685                                                         /***
1686                                                          * previous field was a label for "julian date"?
1687                                                          ***/
1688                                                         tmask = DTK_DATE_M;
1689                                                         j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1690                                                         if (*cp == '.')
1691                                                         {
1692                                                                 double          time;
1693
1694                                                                 time = strtod(cp, &cp);
1695                                                                 if (*cp != '\0')
1696                                                                         return DTERR_BAD_FORMAT;
1697
1698                                                                 tmask |= DTK_TIME_M;
1699 #ifdef HAVE_INT64_TIMESTAMP
1700                                                                 dt2time(time * USECS_PER_DAY,
1701                                                                 &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1702 #else
1703                                                                 dt2time(time * SECS_PER_DAY,
1704                                                                 &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1705 #endif
1706                                                         }
1707                                                         break;
1708
1709                                                 case DTK_TIME:
1710                                                         /* previous field was "t" for ISO time */
1711                                                         dterr = DecodeNumberField(strlen(field[i]), field[i],
1712                                                                                                           (fmask | DTK_DATE_M),
1713                                                                                                           &tmask, tm,
1714                                                                                                           fsec, &is2digits);
1715                                                         if (dterr < 0)
1716                                                                 return dterr;
1717                                                         ftype[i] = dterr;
1718
1719                                                         if (tmask != DTK_TIME_M)
1720                                                                 return DTERR_BAD_FORMAT;
1721                                                         break;
1722
1723                                                 default:
1724                                                         return DTERR_BAD_FORMAT;
1725                                                         break;
1726                                         }
1727
1728                                         ptype = 0;
1729                                         *dtype = DTK_DATE;
1730                                 }
1731                                 else
1732                                 {
1733                                         char       *cp;
1734                                         int                     flen;
1735
1736                                         flen = strlen(field[i]);
1737                                         cp = strchr(field[i], '.');
1738
1739                                         /* Embedded decimal? */
1740                                         if (cp != NULL)
1741                                         {
1742                                                 /*
1743                                                  * Under limited circumstances, we will accept a
1744                                                  * date...
1745                                                  */
1746                                                 if (i == 0 && nf >= 2 && ftype[nf - 1] == DTK_DATE)
1747                                                 {
1748                                                         dterr = DecodeDate(field[i], fmask,
1749                                                                                            &tmask, &is2digits, tm);
1750                                                         if (dterr)
1751                                                                 return dterr;
1752                                                 }
1753                                                 /* embedded decimal and several digits before? */
1754                                                 else if (flen - strlen(cp) > 2)
1755                                                 {
1756                                                         /*
1757                                                          * Interpret as a concatenated date or time Set
1758                                                          * the type field to allow decoding other fields
1759                                                          * later. Example: 20011223 or 040506
1760                                                          */
1761                                                         dterr = DecodeNumberField(flen, field[i],
1762                                                                                                           (fmask | DTK_DATE_M),
1763                                                                                                           &tmask, tm,
1764                                                                                                           fsec, &is2digits);
1765                                                         if (dterr < 0)
1766                                                                 return dterr;
1767                                                         ftype[i] = dterr;
1768                                                 }
1769                                                 else
1770                                                         return DTERR_BAD_FORMAT;
1771                                         }
1772                                         else if (flen > 4)
1773                                         {
1774                                                 dterr = DecodeNumberField(flen, field[i],
1775                                                                                                   (fmask | DTK_DATE_M),
1776                                                                                                   &tmask, tm,
1777                                                                                                   fsec, &is2digits);
1778                                                 if (dterr < 0)
1779                                                         return dterr;
1780                                                 ftype[i] = dterr;
1781                                         }
1782                                         /* otherwise it is a single date/time field... */
1783                                         else
1784                                         {
1785                                                 dterr = DecodeNumber(flen, field[i],
1786                                                                                          FALSE,
1787                                                                                          (fmask | DTK_DATE_M),
1788                                                                                          &tmask, tm,
1789                                                                                          fsec, &is2digits);
1790                                                 if (dterr)
1791                                                         return dterr;
1792                                         }
1793                                 }
1794                                 break;
1795
1796                         case DTK_STRING:
1797                         case DTK_SPECIAL:
1798                                 type = DecodeSpecial(i, field[i], &val);
1799                                 if (type == IGNORE_DTF)
1800                                         continue;
1801
1802                                 tmask = DTK_M(type);
1803                                 switch (type)
1804                                 {
1805                                         case RESERV:
1806                                                 switch (val)
1807                                                 {
1808                                                         case DTK_CURRENT:
1809                                                                 ereport(ERROR,
1810                                                                          (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1811                                                                           errmsg("date/time value \"current\" is no longer supported")));
1812                                                                 return DTERR_BAD_FORMAT;
1813                                                                 break;
1814
1815                                                         case DTK_NOW:
1816                                                                 tmask = DTK_TIME_M;
1817                                                                 *dtype = DTK_TIME;
1818                                                                 GetCurrentTimeUsec(tm, fsec, NULL);
1819                                                                 break;
1820
1821                                                         case DTK_ZULU:
1822                                                                 tmask = (DTK_TIME_M | DTK_M(TZ));
1823                                                                 *dtype = DTK_TIME;
1824                                                                 tm->tm_hour = 0;
1825                                                                 tm->tm_min = 0;
1826                                                                 tm->tm_sec = 0;
1827                                                                 tm->tm_isdst = 0;
1828                                                                 break;
1829
1830                                                         default:
1831                                                                 return DTERR_BAD_FORMAT;
1832                                                 }
1833
1834                                                 break;
1835
1836                                         case DTZMOD:
1837
1838                                                 /*
1839                                                  * daylight savings time modifier (solves "MET DST"
1840                                                  * syntax)
1841                                                  */
1842                                                 tmask |= DTK_M(DTZ);
1843                                                 tm->tm_isdst = 1;
1844                                                 if (tzp == NULL)
1845                                                         return DTERR_BAD_FORMAT;
1846                                                 *tzp += val * MINS_PER_HOUR;
1847                                                 break;
1848
1849                                         case DTZ:
1850
1851                                                 /*
1852                                                  * set mask for TZ here _or_ check for DTZ later when
1853                                                  * getting default timezone
1854                                                  */
1855                                                 tmask |= DTK_M(TZ);
1856                                                 tm->tm_isdst = 1;
1857                                                 if (tzp == NULL)
1858                                                         return DTERR_BAD_FORMAT;
1859                                                 *tzp = val * MINS_PER_HOUR;
1860                                                 ftype[i] = DTK_TZ;
1861                                                 break;
1862
1863                                         case TZ:
1864                                                 tm->tm_isdst = 0;
1865                                                 if (tzp == NULL)
1866                                                         return DTERR_BAD_FORMAT;
1867                                                 *tzp = val * MINS_PER_HOUR;
1868                                                 ftype[i] = DTK_TZ;
1869                                                 break;
1870
1871                                         case IGNORE_DTF:
1872                                                 break;
1873
1874                                         case AMPM:
1875                                                 mer = val;
1876                                                 break;
1877
1878                                         case ADBC:
1879                                                 bc = (val == BC);
1880                                                 break;
1881
1882                                         case UNITS:
1883                                                 tmask = 0;
1884                                                 ptype = val;
1885                                                 break;
1886
1887                                         case ISOTIME:
1888                                                 tmask = 0;
1889
1890                                                 /***
1891                                                  * We will need one of the following fields:
1892                                                  *      DTK_NUMBER should be hhmmss.fff
1893                                                  *      DTK_TIME should be hh:mm:ss.fff
1894                                                  *      DTK_DATE should be hhmmss-zz
1895                                                  ***/
1896                                                 if (i >= nf - 1 ||
1897                                                         (ftype[i + 1] != DTK_NUMBER &&
1898                                                          ftype[i + 1] != DTK_TIME &&
1899                                                          ftype[i + 1] != DTK_DATE))
1900                                                         return DTERR_BAD_FORMAT;
1901
1902                                                 ptype = val;
1903                                                 break;
1904
1905                                         case UNKNOWN_FIELD:
1906
1907                                                 /*
1908                                                  * Before giving up and declaring error, check to see
1909                                                  * if it is an all-alpha timezone name.
1910                                                  */
1911                                                 namedTz = pg_tzset(field[i]);
1912                                                 if (!namedTz)
1913                                                         return DTERR_BAD_FORMAT;
1914                                                 /* we'll apply the zone setting below */
1915                                                 tmask = DTK_M(TZ);
1916                                                 break;
1917
1918                                         default:
1919                                                 return DTERR_BAD_FORMAT;
1920                                 }
1921                                 break;
1922
1923                         default:
1924                                 return DTERR_BAD_FORMAT;
1925                 }
1926
1927                 if (tmask & fmask)
1928                         return DTERR_BAD_FORMAT;
1929                 fmask |= tmask;
1930         }                               /* end loop over fields */
1931
1932         /* do final checking/adjustment of Y/M/D fields */
1933         dterr = ValidateDate(fmask, is2digits, bc, tm);
1934         if (dterr)
1935                 return dterr;
1936
1937         /* handle AM/PM */
1938         if (mer != HR24 && tm->tm_hour > 12)
1939                 return DTERR_FIELD_OVERFLOW;
1940         if (mer == AM && tm->tm_hour == 12)
1941                 tm->tm_hour = 0;
1942         else if (mer == PM && tm->tm_hour != 12)
1943                 tm->tm_hour += 12;
1944
1945         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
1946                 tm->tm_sec < 0 || tm->tm_sec > 60 || tm->tm_hour > 24 ||
1947         /* test for > 24:00:00 */
1948 #ifdef HAVE_INT64_TIMESTAMP
1949                 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0 ||
1950                                                            *fsec > INT64CONST(0))) ||
1951                 *fsec < INT64CONST(0) || *fsec >= USECS_PER_SEC
1952 #else
1953                 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0 ||
1954                                                            *fsec > 0)) ||
1955                 *fsec < 0 || *fsec >= 1
1956 #endif
1957                 )
1958                 return DTERR_FIELD_OVERFLOW;
1959
1960         if ((fmask & DTK_TIME_M) != DTK_TIME_M)
1961                 return DTERR_BAD_FORMAT;
1962
1963         /*
1964          * If we had a full timezone spec, compute the offset (we could not do it
1965          * before, because we may need the date to resolve DST status).
1966          */
1967         if (namedTz != NULL)
1968         {
1969                 long int        gmtoff;
1970
1971                 /* daylight savings time modifier disallowed with full TZ */
1972                 if (fmask & DTK_M(DTZMOD))
1973                         return DTERR_BAD_FORMAT;
1974
1975                 /* if non-DST zone, we do not need to know the date */
1976                 if (pg_get_timezone_offset(namedTz, &gmtoff))
1977                 {
1978                         *tzp = -(int) gmtoff;
1979                 }
1980                 else
1981                 {
1982                         /* a date has to be specified */
1983                         if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1984                                 return DTERR_BAD_FORMAT;
1985                         *tzp = DetermineTimeZoneOffset(tm, namedTz);
1986                 }
1987         }
1988
1989         /* timezone not specified? then find local timezone if possible */
1990         if (tzp != NULL && !(fmask & DTK_M(TZ)))
1991         {
1992                 struct pg_tm tt,
1993                                    *tmp = &tt;
1994
1995                 /*
1996                  * daylight savings time modifier but no standard timezone? then error
1997                  */
1998                 if (fmask & DTK_M(DTZMOD))
1999                         return DTERR_BAD_FORMAT;
2000
2001                 if ((fmask & DTK_DATE_M) == 0)
2002                         GetCurrentDateTime(tmp);
2003                 else
2004                 {
2005                         tmp->tm_year = tm->tm_year;
2006                         tmp->tm_mon = tm->tm_mon;
2007                         tmp->tm_mday = tm->tm_mday;
2008                 }
2009                 tmp->tm_hour = tm->tm_hour;
2010                 tmp->tm_min = tm->tm_min;
2011                 tmp->tm_sec = tm->tm_sec;
2012                 *tzp = DetermineTimeZoneOffset(tmp, session_timezone);
2013                 tm->tm_isdst = tmp->tm_isdst;
2014         }
2015
2016         return 0;
2017 }
2018
2019 /* DecodeDate()
2020  * Decode date string which includes delimiters.
2021  * Return 0 if okay, a DTERR code if not.
2022  *
2023  *      str: field to be parsed
2024  *      fmask: bitmask for field types already seen
2025  *      *tmask: receives bitmask for fields found here
2026  *      *is2digits: set to TRUE if we find 2-digit year
2027  *      *tm: field values are stored into appropriate members of this struct
2028  */
2029 static int
2030 DecodeDate(char *str, int fmask, int *tmask, bool *is2digits,
2031                    struct pg_tm * tm)
2032 {
2033         fsec_t          fsec;
2034         int                     nf = 0;
2035         int                     i,
2036                                 len;
2037         int                     dterr;
2038         bool            haveTextMonth = FALSE;
2039         int                     type,
2040                                 val,
2041                                 dmask = 0;
2042         char       *field[MAXDATEFIELDS];
2043
2044         *tmask = 0;
2045
2046         /* parse this string... */
2047         while (*str != '\0' && nf < MAXDATEFIELDS)
2048         {
2049                 /* skip field separators */
2050                 while (!isalnum((unsigned char) *str))
2051                         str++;
2052
2053                 field[nf] = str;
2054                 if (isdigit((unsigned char) *str))
2055                 {
2056                         while (isdigit((unsigned char) *str))
2057                                 str++;
2058                 }
2059                 else if (isalpha((unsigned char) *str))
2060                 {
2061                         while (isalpha((unsigned char) *str))
2062                                 str++;
2063                 }
2064
2065                 /* Just get rid of any non-digit, non-alpha characters... */
2066                 if (*str != '\0')
2067                         *str++ = '\0';
2068                 nf++;
2069         }
2070
2071         /* look first for text fields, since that will be unambiguous month */
2072         for (i = 0; i < nf; i++)
2073         {
2074                 if (isalpha((unsigned char) *field[i]))
2075                 {
2076                         type = DecodeSpecial(i, field[i], &val);
2077                         if (type == IGNORE_DTF)
2078                                 continue;
2079
2080                         dmask = DTK_M(type);
2081                         switch (type)
2082                         {
2083                                 case MONTH:
2084                                         tm->tm_mon = val;
2085                                         haveTextMonth = TRUE;
2086                                         break;
2087
2088                                 default:
2089                                         return DTERR_BAD_FORMAT;
2090                         }
2091                         if (fmask & dmask)
2092                                 return DTERR_BAD_FORMAT;
2093
2094                         fmask |= dmask;
2095                         *tmask |= dmask;
2096
2097                         /* mark this field as being completed */
2098                         field[i] = NULL;
2099                 }
2100         }
2101
2102         /* now pick up remaining numeric fields */
2103         for (i = 0; i < nf; i++)
2104         {
2105                 if (field[i] == NULL)
2106                         continue;
2107
2108                 if ((len = strlen(field[i])) <= 0)
2109                         return DTERR_BAD_FORMAT;
2110
2111                 dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2112                                                          &dmask, tm,
2113                                                          &fsec, is2digits);
2114                 if (dterr)
2115                         return dterr;
2116
2117                 if (fmask & dmask)
2118                         return DTERR_BAD_FORMAT;
2119
2120                 fmask |= dmask;
2121                 *tmask |= dmask;
2122         }
2123
2124         if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
2125                 return DTERR_BAD_FORMAT;
2126
2127         /* validation of the field values must wait until ValidateDate() */
2128
2129         return 0;
2130 }
2131
2132 /* ValidateDate()
2133  * Check valid year/month/day values, handle BC and DOY cases
2134  * Return 0 if okay, a DTERR code if not.
2135  */
2136 static int
2137 ValidateDate(int fmask, bool is2digits, bool bc, struct pg_tm * tm)
2138 {
2139         if (fmask & DTK_M(YEAR))
2140         {
2141                 if (bc)
2142                 {
2143                         /* there is no year zero in AD/BC notation */
2144                         if (tm->tm_year <= 0)
2145                                 return DTERR_FIELD_OVERFLOW;
2146                         /* internally, we represent 1 BC as year zero, 2 BC as -1, etc */
2147                         tm->tm_year = -(tm->tm_year - 1);
2148                 }
2149                 else if (is2digits)
2150                 {
2151                         /* allow 2-digit input for 1970-2069 AD; 00 is allowed */
2152                         if (tm->tm_year < 0)                            /* just paranoia */
2153                                 return DTERR_FIELD_OVERFLOW;
2154                         if (tm->tm_year < 70)
2155                                 tm->tm_year += 2000;
2156                         else if (tm->tm_year < 100)
2157                                 tm->tm_year += 1900;
2158                 }
2159                 else
2160                 {
2161                         /* there is no year zero in AD/BC notation */
2162                         if (tm->tm_year <= 0)
2163                                 return DTERR_FIELD_OVERFLOW;
2164                 }
2165         }
2166
2167         /* now that we have correct year, decode DOY */
2168         if (fmask & DTK_M(DOY))
2169         {
2170                 j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
2171                            &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2172         }
2173
2174         /* check for valid month */
2175         if (fmask & DTK_M(MONTH))
2176         {
2177                 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
2178                         return DTERR_MD_FIELD_OVERFLOW;
2179         }
2180
2181         /* minimal check for valid day */
2182         if (fmask & DTK_M(DAY))
2183         {
2184                 if (tm->tm_mday < 1 || tm->tm_mday > 31)
2185                         return DTERR_MD_FIELD_OVERFLOW;
2186         }
2187
2188         if ((fmask & DTK_DATE_M) == DTK_DATE_M)
2189         {
2190                 /*
2191                  * Check for valid day of month, now that we know for sure the month
2192                  * and year.  Note we don't use MD_FIELD_OVERFLOW here, since it seems
2193                  * unlikely that "Feb 29" is a YMD-order error.
2194                  */
2195                 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2196                         return DTERR_FIELD_OVERFLOW;
2197         }
2198
2199         return 0;
2200 }
2201
2202
2203 /* DecodeTime()
2204  * Decode time string which includes delimiters.
2205  * Return 0 if okay, a DTERR code if not.
2206  *
2207  * Only check the lower limit on hours, since this same code can be
2208  * used to represent time spans.
2209  */
2210 static int
2211 DecodeTime(char *str, int fmask, int *tmask, struct pg_tm * tm, fsec_t *fsec)
2212 {
2213         char       *cp;
2214
2215         *tmask = DTK_TIME_M;
2216
2217         errno = 0;
2218         tm->tm_hour = strtol(str, &cp, 10);
2219         if (errno == ERANGE)
2220                 return DTERR_FIELD_OVERFLOW;
2221         if (*cp != ':')
2222                 return DTERR_BAD_FORMAT;
2223         str = cp + 1;
2224         errno = 0;
2225         tm->tm_min = strtol(str, &cp, 10);
2226         if (errno == ERANGE)
2227                 return DTERR_FIELD_OVERFLOW;
2228         if (*cp == '\0')
2229         {
2230                 tm->tm_sec = 0;
2231                 *fsec = 0;
2232         }
2233         else if (*cp != ':')
2234                 return DTERR_BAD_FORMAT;
2235         else
2236         {
2237                 str = cp + 1;
2238                 errno = 0;
2239                 tm->tm_sec = strtol(str, &cp, 10);
2240                 if (errno == ERANGE)
2241                         return DTERR_FIELD_OVERFLOW;
2242                 if (*cp == '\0')
2243                         *fsec = 0;
2244                 else if (*cp == '.')
2245                 {
2246                         double          frac;
2247
2248                         str = cp;
2249                         frac = strtod(str, &cp);
2250                         if (*cp != '\0')
2251                                 return DTERR_BAD_FORMAT;
2252 #ifdef HAVE_INT64_TIMESTAMP
2253                         *fsec = rint(frac * 1000000);
2254 #else
2255                         *fsec = frac;
2256 #endif
2257                 }
2258                 else
2259                         return DTERR_BAD_FORMAT;
2260         }
2261
2262         /* do a sanity check */
2263 #ifdef HAVE_INT64_TIMESTAMP
2264         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2265                 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < INT64CONST(0) ||
2266                 *fsec >= USECS_PER_SEC)
2267                 return DTERR_FIELD_OVERFLOW;
2268 #else
2269         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
2270                 tm->tm_sec < 0 || tm->tm_sec > 60 || *fsec < 0 || *fsec >= 1)
2271                 return DTERR_FIELD_OVERFLOW;
2272 #endif
2273
2274         return 0;
2275 }
2276
2277
2278 /* DecodeNumber()
2279  * Interpret plain numeric field as a date value in context.
2280  * Return 0 if okay, a DTERR code if not.
2281  */
2282 static int
2283 DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask,
2284                          int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2285 {
2286         int                     val;
2287         char       *cp;
2288         int                     dterr;
2289
2290         *tmask = 0;
2291
2292         errno = 0;
2293         val = strtol(str, &cp, 10);
2294         if (errno == ERANGE)
2295                 return DTERR_FIELD_OVERFLOW;
2296         if (cp == str)
2297                 return DTERR_BAD_FORMAT;
2298
2299         if (*cp == '.')
2300         {
2301                 double          frac;
2302
2303                 /*
2304                  * More than two digits before decimal point? Then could be a date or
2305                  * a run-together time: 2001.360 20011225 040506.789
2306                  */
2307                 if (cp - str > 2)
2308                 {
2309                         dterr = DecodeNumberField(flen, str,
2310                                                                           (fmask | DTK_DATE_M),
2311                                                                           tmask, tm,
2312                                                                           fsec, is2digits);
2313                         if (dterr < 0)
2314                                 return dterr;
2315                         return 0;
2316                 }
2317
2318                 frac = strtod(cp, &cp);
2319                 if (*cp != '\0')
2320                         return DTERR_BAD_FORMAT;
2321 #ifdef HAVE_INT64_TIMESTAMP
2322                 *fsec = rint(frac * 1000000);
2323 #else
2324                 *fsec = frac;
2325 #endif
2326         }
2327         else if (*cp != '\0')
2328                 return DTERR_BAD_FORMAT;
2329
2330         /* Special case for day of year */
2331         if (flen == 3 && (fmask & DTK_DATE_M) == DTK_M(YEAR) && val >= 1 &&
2332                 val <= 366)
2333         {
2334                 *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2335                 tm->tm_yday = val;
2336                 /* tm_mon and tm_mday can't actually be set yet ... */
2337                 return 0;
2338         }
2339
2340         /* Switch based on what we have so far */
2341         switch (fmask & DTK_DATE_M)
2342         {
2343                 case 0:
2344
2345                         /*
2346                          * Nothing so far; make a decision about what we think the input
2347                          * is.  There used to be lots of heuristics here, but the
2348                          * consensus now is to be paranoid.  It *must* be either
2349                          * YYYY-MM-DD (with a more-than-two-digit year field), or the
2350                          * field order defined by DateOrder.
2351                          */
2352                         if (flen >= 3 || DateOrder == DATEORDER_YMD)
2353                         {
2354                                 *tmask = DTK_M(YEAR);
2355                                 tm->tm_year = val;
2356                         }
2357                         else if (DateOrder == DATEORDER_DMY)
2358                         {
2359                                 *tmask = DTK_M(DAY);
2360                                 tm->tm_mday = val;
2361                         }
2362                         else
2363                         {
2364                                 *tmask = DTK_M(MONTH);
2365                                 tm->tm_mon = val;
2366                         }
2367                         break;
2368
2369                 case (DTK_M(YEAR)):
2370                         /* Must be at second field of YY-MM-DD */
2371                         *tmask = DTK_M(MONTH);
2372                         tm->tm_mon = val;
2373                         break;
2374
2375                 case (DTK_M(MONTH)):
2376                         if (haveTextMonth)
2377                         {
2378                                 /*
2379                                  * We are at the first numeric field of a date that included a
2380                                  * textual month name.  We want to support the variants
2381                                  * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2382                                  * inputs.      We will also accept MON-DD-YY or DD-MON-YY in
2383                                  * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2384                                  */
2385                                 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2386                                 {
2387                                         *tmask = DTK_M(YEAR);
2388                                         tm->tm_year = val;
2389                                 }
2390                                 else
2391                                 {
2392                                         *tmask = DTK_M(DAY);
2393                                         tm->tm_mday = val;
2394                                 }
2395                         }
2396                         else
2397                         {
2398                                 /* Must be at second field of MM-DD-YY */
2399                                 *tmask = DTK_M(DAY);
2400                                 tm->tm_mday = val;
2401                         }
2402                         break;
2403
2404                 case (DTK_M(YEAR) | DTK_M(MONTH)):
2405                         if (haveTextMonth)
2406                         {
2407                                 /* Need to accept DD-MON-YYYY even in YMD mode */
2408                                 if (flen >= 3 && *is2digits)
2409                                 {
2410                                         /* Guess that first numeric field is day was wrong */
2411                                         *tmask = DTK_M(DAY);            /* YEAR is already set */
2412                                         tm->tm_mday = tm->tm_year;
2413                                         tm->tm_year = val;
2414                                         *is2digits = FALSE;
2415                                 }
2416                                 else
2417                                 {
2418                                         *tmask = DTK_M(DAY);
2419                                         tm->tm_mday = val;
2420                                 }
2421                         }
2422                         else
2423                         {
2424                                 /* Must be at third field of YY-MM-DD */
2425                                 *tmask = DTK_M(DAY);
2426                                 tm->tm_mday = val;
2427                         }
2428                         break;
2429
2430                 case (DTK_M(DAY)):
2431                         /* Must be at second field of DD-MM-YY */
2432                         *tmask = DTK_M(MONTH);
2433                         tm->tm_mon = val;
2434                         break;
2435
2436                 case (DTK_M(MONTH) | DTK_M(DAY)):
2437                         /* Must be at third field of DD-MM-YY or MM-DD-YY */
2438                         *tmask = DTK_M(YEAR);
2439                         tm->tm_year = val;
2440                         break;
2441
2442                 case (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY)):
2443                         /* we have all the date, so it must be a time field */
2444                         dterr = DecodeNumberField(flen, str, fmask,
2445                                                                           tmask, tm,
2446                                                                           fsec, is2digits);
2447                         if (dterr < 0)
2448                                 return dterr;
2449                         return 0;
2450
2451                 default:
2452                         /* Anything else is bogus input */
2453                         return DTERR_BAD_FORMAT;
2454         }
2455
2456         /*
2457          * When processing a year field, mark it for adjustment if it's only one
2458          * or two digits.
2459          */
2460         if (*tmask == DTK_M(YEAR))
2461                 *is2digits = (flen <= 2);
2462
2463         return 0;
2464 }
2465
2466
2467 /* DecodeNumberField()
2468  * Interpret numeric string as a concatenated date or time field.
2469  * Return a DTK token (>= 0) if successful, a DTERR code (< 0) if not.
2470  *
2471  * Use the context of previously decoded fields to help with
2472  * the interpretation.
2473  */
2474 static int
2475 DecodeNumberField(int len, char *str, int fmask,
2476                                 int *tmask, struct pg_tm * tm, fsec_t *fsec, bool *is2digits)
2477 {
2478         char       *cp;
2479
2480         /*
2481          * Have a decimal point? Then this is a date or something with a seconds
2482          * field...
2483          */
2484         if ((cp = strchr(str, '.')) != NULL)
2485         {
2486                 double          frac;
2487
2488                 frac = strtod(cp, NULL);
2489 #ifdef HAVE_INT64_TIMESTAMP
2490                 *fsec = rint(frac * 1000000);
2491 #else
2492                 *fsec = frac;
2493 #endif
2494                 *cp = '\0';
2495                 len = strlen(str);
2496         }
2497         /* No decimal point and no complete date yet? */
2498         else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2499         {
2500                 /* yyyymmdd? */
2501                 if (len == 8)
2502                 {
2503                         *tmask = DTK_DATE_M;
2504
2505                         tm->tm_mday = atoi(str + 6);
2506                         *(str + 6) = '\0';
2507                         tm->tm_mon = atoi(str + 4);
2508                         *(str + 4) = '\0';
2509                         tm->tm_year = atoi(str + 0);
2510
2511                         return DTK_DATE;
2512                 }
2513                 /* yymmdd? */
2514                 else if (len == 6)
2515                 {
2516                         *tmask = DTK_DATE_M;
2517                         tm->tm_mday = atoi(str + 4);
2518                         *(str + 4) = '\0';
2519                         tm->tm_mon = atoi(str + 2);
2520                         *(str + 2) = '\0';
2521                         tm->tm_year = atoi(str + 0);
2522                         *is2digits = TRUE;
2523
2524                         return DTK_DATE;
2525                 }
2526         }
2527
2528         /* not all time fields are specified? */
2529         if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2530         {
2531                 /* hhmmss */
2532                 if (len == 6)
2533                 {
2534                         *tmask = DTK_TIME_M;
2535                         tm->tm_sec = atoi(str + 4);
2536                         *(str + 4) = '\0';
2537                         tm->tm_min = atoi(str + 2);
2538                         *(str + 2) = '\0';
2539                         tm->tm_hour = atoi(str + 0);
2540
2541                         return DTK_TIME;
2542                 }
2543                 /* hhmm? */
2544                 else if (len == 4)
2545                 {
2546                         *tmask = DTK_TIME_M;
2547                         tm->tm_sec = 0;
2548                         tm->tm_min = atoi(str + 2);
2549                         *(str + 2) = '\0';
2550                         tm->tm_hour = atoi(str + 0);
2551
2552                         return DTK_TIME;
2553                 }
2554         }
2555
2556         return DTERR_BAD_FORMAT;
2557 }
2558
2559
2560 /* DecodeTimezone()
2561  * Interpret string as a numeric timezone.
2562  *
2563  * Return 0 if okay (and set *tzp), a DTERR code if not okay.
2564  *
2565  * NB: this must *not* ereport on failure; see commands/variable.c.
2566  *
2567  * Note: we allow timezone offsets up to 13:59.  There are places that
2568  * use +1300 summer time.
2569  */
2570 static int
2571 DecodeTimezone(char *str, int *tzp)
2572 {
2573         int                     tz;
2574         int                     hr,
2575                                 min,
2576                                 sec = 0;
2577         char       *cp;
2578
2579         /* leading character must be "+" or "-" */
2580         if (*str != '+' && *str != '-')
2581                 return DTERR_BAD_FORMAT;
2582
2583         errno = 0;
2584         hr = strtol(str + 1, &cp, 10);
2585         if (errno == ERANGE)
2586                 return DTERR_TZDISP_OVERFLOW;
2587
2588         /* explicit delimiter? */
2589         if (*cp == ':')
2590         {
2591                 errno = 0;
2592                 min = strtol(cp + 1, &cp, 10);
2593                 if (errno == ERANGE)
2594                         return DTERR_TZDISP_OVERFLOW;
2595                 if (*cp == ':')
2596                 {
2597                         errno = 0;
2598                         sec = strtol(cp + 1, &cp, 10);
2599                         if (errno == ERANGE)
2600                                 return DTERR_TZDISP_OVERFLOW;
2601                 }
2602         }
2603         /* otherwise, might have run things together... */
2604         else if (*cp == '\0' && strlen(str) > 3)
2605         {
2606                 min = hr % 100;
2607                 hr = hr / 100;
2608                 /* we could, but don't, support a run-together hhmmss format */
2609         }
2610         else
2611                 min = 0;
2612
2613         if (hr < 0 || hr > 14)
2614                 return DTERR_TZDISP_OVERFLOW;
2615         if (min < 0 || min >= 60)
2616                 return DTERR_TZDISP_OVERFLOW;
2617         if (sec < 0 || sec >= 60)
2618                 return DTERR_TZDISP_OVERFLOW;
2619
2620         tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
2621         if (*str == '-')
2622                 tz = -tz;
2623
2624         *tzp = -tz;
2625
2626         if (*cp != '\0')
2627                 return DTERR_BAD_FORMAT;
2628
2629         return 0;
2630 }
2631
2632 /* DecodeSpecial()
2633  * Decode text string using lookup table.
2634  *
2635  * Implement a cache lookup since it is likely that dates
2636  *      will be related in format.
2637  *
2638  * NB: this must *not* ereport on failure;
2639  * see commands/variable.c.
2640  */
2641 int
2642 DecodeSpecial(int field, char *lowtoken, int *val)
2643 {
2644         int                     type;
2645         const datetkn *tp;
2646
2647         tp = datecache[field];
2648         if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
2649         {
2650                 tp = datebsearch(lowtoken, timezonetktbl, sztimezonetktbl);
2651                 if (tp == NULL)
2652                         tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
2653         }
2654         if (tp == NULL)
2655         {
2656                 type = UNKNOWN_FIELD;
2657                 *val = 0;
2658         }
2659         else
2660         {
2661                 datecache[field] = tp;
2662                 type = tp->type;
2663                 switch (type)
2664                 {
2665                         case TZ:
2666                         case DTZ:
2667                         case DTZMOD:
2668                                 *val = FROMVAL(tp);
2669                                 break;
2670
2671                         default:
2672                                 *val = tp->value;
2673                                 break;
2674                 }
2675         }
2676
2677         return type;
2678 }
2679
2680
2681 /* DecodeInterval()
2682  * Interpret previously parsed fields for general time interval.
2683  * Returns 0 if successful, DTERR code if bogus input detected.
2684  *
2685  * Allow "date" field DTK_DATE since this could be just
2686  *      an unsigned floating point number. - thomas 1997-11-16
2687  *
2688  * Allow ISO-style time span, with implicit units on number of days
2689  *      preceding an hh:mm:ss field. - thomas 1998-04-30
2690  */
2691 int
2692 DecodeInterval(char **field, int *ftype, int nf, int *dtype, struct pg_tm * tm, fsec_t *fsec)
2693 {
2694         bool            is_before = FALSE;
2695         char       *cp;
2696         int                     fmask = 0,
2697                                 tmask,
2698                                 type;
2699         int                     i;
2700         int                     dterr;
2701         int                     val;
2702         double          fval;
2703
2704         *dtype = DTK_DELTA;
2705
2706         type = IGNORE_DTF;
2707         tm->tm_year = 0;
2708         tm->tm_mon = 0;
2709         tm->tm_mday = 0;
2710         tm->tm_hour = 0;
2711         tm->tm_min = 0;
2712         tm->tm_sec = 0;
2713         *fsec = 0;
2714
2715         /* read through list backwards to pick up units before values */
2716         for (i = nf - 1; i >= 0; i--)
2717         {
2718                 switch (ftype[i])
2719                 {
2720                         case DTK_TIME:
2721                                 dterr = DecodeTime(field[i], fmask, &tmask, tm, fsec);
2722                                 if (dterr)
2723                                         return dterr;
2724                                 type = DTK_DAY;
2725                                 break;
2726
2727                         case DTK_TZ:
2728
2729                                 /*
2730                                  * Timezone is a token with a leading sign character and
2731                                  * otherwise the same as a non-signed time field
2732                                  */
2733                                 Assert(*field[i] == '-' || *field[i] == '+');
2734
2735                                 /*
2736                                  * A single signed number ends up here, but will be rejected
2737                                  * by DecodeTime(). So, work this out to drop through to
2738                                  * DTK_NUMBER, which *can* tolerate this.
2739                                  */
2740                                 cp = field[i] + 1;
2741                                 while (*cp != '\0' && *cp != ':' && *cp != '.')
2742                                         cp++;
2743                                 if (*cp == ':' &&
2744                                         DecodeTime(field[i] + 1, fmask, &tmask, tm, fsec) == 0)
2745                                 {
2746                                         if (*field[i] == '-')
2747                                         {
2748                                                 /* flip the sign on all fields */
2749                                                 tm->tm_hour = -tm->tm_hour;
2750                                                 tm->tm_min = -tm->tm_min;
2751                                                 tm->tm_sec = -tm->tm_sec;
2752                                                 *fsec = -(*fsec);
2753                                         }
2754
2755                                         /*
2756                                          * Set the next type to be a day, if units are not
2757                                          * specified. This handles the case of '1 +02:03' since we
2758                                          * are reading right to left.
2759                                          */
2760                                         type = DTK_DAY;
2761                                         tmask = DTK_M(TZ);
2762                                         break;
2763                                 }
2764                                 else if (type == IGNORE_DTF)
2765                                 {
2766                                         if (*cp == '.')
2767                                         {
2768                                                 /*
2769                                                  * Got a decimal point? Then assume some sort of
2770                                                  * seconds specification
2771                                                  */
2772                                                 type = DTK_SECOND;
2773                                         }
2774                                         else if (*cp == '\0')
2775                                         {
2776                                                 /*
2777                                                  * Only a signed integer? Then must assume a
2778                                                  * timezone-like usage
2779                                                  */
2780                                                 type = DTK_HOUR;
2781                                         }
2782                                 }
2783                                 /* DROP THROUGH */
2784
2785                         case DTK_DATE:
2786                         case DTK_NUMBER:
2787                                 errno = 0;
2788                                 val = strtol(field[i], &cp, 10);
2789                                 if (errno == ERANGE)
2790                                         return DTERR_FIELD_OVERFLOW;
2791
2792                                 if (type == IGNORE_DTF)
2793                                         type = DTK_SECOND;
2794
2795                                 if (*cp == '.')
2796                                 {
2797                                         fval = strtod(cp, &cp);
2798                                         if (*cp != '\0')
2799                                                 return DTERR_BAD_FORMAT;
2800
2801                                         if (*field[i] == '-')
2802                                                 fval = -fval;
2803                                 }
2804                                 else if (*cp == '\0')
2805                                         fval = 0;
2806                                 else
2807                                         return DTERR_BAD_FORMAT;
2808
2809                                 tmask = 0;              /* DTK_M(type); */
2810
2811                                 switch (type)
2812                                 {
2813                                         case DTK_MICROSEC:
2814 #ifdef HAVE_INT64_TIMESTAMP
2815                                                 *fsec += val + fval;
2816 #else
2817                                                 *fsec += (val + fval) * 1e-6;
2818 #endif
2819                                                 tmask = DTK_M(MICROSECOND);
2820                                                 break;
2821
2822                                         case DTK_MILLISEC:
2823 #ifdef HAVE_INT64_TIMESTAMP
2824                                                 *fsec += (val + fval) * 1000;
2825 #else
2826                                                 *fsec += (val + fval) * 1e-3;
2827 #endif
2828                                                 tmask = DTK_M(MILLISECOND);
2829                                                 break;
2830
2831                                         case DTK_SECOND:
2832                                                 tm->tm_sec += val;
2833 #ifdef HAVE_INT64_TIMESTAMP
2834                                                 *fsec += fval * 1000000;
2835 #else
2836                                                 *fsec += fval;
2837 #endif
2838
2839                                                 /*
2840                                                  * If any subseconds were specified, consider this
2841                                                  * microsecond and millisecond input as well.
2842                                                  */
2843                                                 if (fval == 0)
2844                                                         tmask = DTK_M(SECOND);
2845                                                 else
2846                                                         tmask = DTK_ALL_SECS_M;
2847                                                 break;
2848
2849                                         case DTK_MINUTE:
2850                                                 tm->tm_min += val;
2851                                                 if (fval != 0)
2852                                                 {
2853                                                         int                     sec;
2854
2855                                                         fval *= SECS_PER_MINUTE;
2856                                                         sec = fval;
2857                                                         tm->tm_sec += sec;
2858 #ifdef HAVE_INT64_TIMESTAMP
2859                                                         *fsec += (fval - sec) * 1000000;
2860 #else
2861                                                         *fsec += fval - sec;
2862 #endif
2863                                                 }
2864                                                 tmask = DTK_M(MINUTE);
2865                                                 break;
2866
2867                                         case DTK_HOUR:
2868                                                 tm->tm_hour += val;
2869                                                 if (fval != 0)
2870                                                 {
2871                                                         int                     sec;
2872
2873                                                         fval *= SECS_PER_HOUR;
2874                                                         sec = fval;
2875                                                         tm->tm_sec += sec;
2876 #ifdef HAVE_INT64_TIMESTAMP
2877                                                         *fsec += (fval - sec) * 1000000;
2878 #else
2879                                                         *fsec += fval - sec;
2880 #endif
2881                                                 }
2882                                                 tmask = DTK_M(HOUR);
2883                                                 break;
2884
2885                                         case DTK_DAY:
2886                                                 tm->tm_mday += val;
2887                                                 if (fval != 0)
2888                                                 {
2889                                                         int                     sec;
2890
2891                                                         fval *= SECS_PER_DAY;
2892                                                         sec = fval;
2893                                                         tm->tm_sec += sec;
2894 #ifdef HAVE_INT64_TIMESTAMP
2895                                                         *fsec += (fval - sec) * 1000000;
2896 #else
2897                                                         *fsec += fval - sec;
2898 #endif
2899                                                 }
2900                                                 tmask = (fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY);
2901                                                 break;
2902
2903                                         case DTK_WEEK:
2904                                                 tm->tm_mday += val * 7;
2905                                                 if (fval != 0)
2906                                                 {
2907                                                         int                     extra_days;
2908
2909                                                         fval *= 7;
2910                                                         extra_days = (int32) fval;
2911                                                         tm->tm_mday += extra_days;
2912                                                         fval -= extra_days;
2913                                                         if (fval != 0)
2914                                                         {
2915                                                                 int                     sec;
2916
2917                                                                 fval *= SECS_PER_DAY;
2918                                                                 sec = fval;
2919                                                                 tm->tm_sec += sec;
2920 #ifdef HAVE_INT64_TIMESTAMP
2921                                                                 *fsec += (fval - sec) * 1000000;
2922 #else
2923                                                                 *fsec += fval - sec;
2924 #endif
2925                                                         }
2926                                                 }
2927                                                 tmask = (fmask & DTK_M(DAY)) ? 0 : DTK_M(DAY);
2928                                                 break;
2929
2930                                         case DTK_MONTH:
2931                                                 tm->tm_mon += val;
2932                                                 if (fval != 0)
2933                                                 {
2934                                                         int                     day;
2935
2936                                                         fval *= DAYS_PER_MONTH;
2937                                                         day = fval;
2938                                                         tm->tm_mday += day;
2939                                                         fval -= day;
2940                                                         if (fval != 0)
2941                                                         {
2942                                                                 int                     sec;
2943
2944                                                                 fval *= SECS_PER_DAY;
2945                                                                 sec = fval;
2946                                                                 tm->tm_sec += sec;
2947 #ifdef HAVE_INT64_TIMESTAMP
2948                                                                 *fsec += (fval - sec) * 1000000;
2949 #else
2950                                                                 *fsec += fval - sec;
2951 #endif
2952                                                         }
2953                                                 }
2954                                                 tmask = DTK_M(MONTH);
2955                                                 break;
2956
2957                                         case DTK_YEAR:
2958                                                 tm->tm_year += val;
2959                                                 if (fval != 0)
2960                                                         tm->tm_mon += fval * MONTHS_PER_YEAR;
2961                                                 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2962                                                 break;
2963
2964                                         case DTK_DECADE:
2965                                                 tm->tm_year += val * 10;
2966                                                 if (fval != 0)
2967                                                         tm->tm_mon += fval * MONTHS_PER_YEAR * 10;
2968                                                 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2969                                                 break;
2970
2971                                         case DTK_CENTURY:
2972                                                 tm->tm_year += val * 100;
2973                                                 if (fval != 0)
2974                                                         tm->tm_mon += fval * MONTHS_PER_YEAR * 100;
2975                                                 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2976                                                 break;
2977
2978                                         case DTK_MILLENNIUM:
2979                                                 tm->tm_year += val * 1000;
2980                                                 if (fval != 0)
2981                                                         tm->tm_mon += fval * MONTHS_PER_YEAR * 1000;
2982                                                 tmask = (fmask & DTK_M(YEAR)) ? 0 : DTK_M(YEAR);
2983                                                 break;
2984
2985                                         default:
2986                                                 return DTERR_BAD_FORMAT;
2987                                 }
2988                                 break;
2989
2990                         case DTK_STRING:
2991                         case DTK_SPECIAL:
2992                                 type = DecodeUnits(i, field[i], &val);
2993                                 if (type == IGNORE_DTF)
2994                                         continue;
2995
2996                                 tmask = 0;              /* DTK_M(type); */
2997                                 switch (type)
2998                                 {
2999                                         case UNITS:
3000                                                 type = val;
3001                                                 break;
3002
3003                                         case AGO:
3004                                                 is_before = TRUE;
3005                                                 type = val;
3006                                                 break;
3007
3008                                         case RESERV:
3009                                                 tmask = (DTK_DATE_M || DTK_TIME_M);
3010                                                 *dtype = val;
3011                                                 break;
3012
3013                                         default:
3014                                                 return DTERR_BAD_FORMAT;
3015                                 }
3016                                 break;
3017
3018                         default:
3019                                 return DTERR_BAD_FORMAT;
3020                 }
3021
3022                 if (tmask & fmask)
3023                         return DTERR_BAD_FORMAT;
3024                 fmask |= tmask;
3025         }
3026
3027         if (*fsec != 0)
3028         {
3029                 int                     sec;
3030
3031 #ifdef HAVE_INT64_TIMESTAMP
3032                 sec = *fsec / USECS_PER_SEC;
3033                 *fsec -= sec * USECS_PER_SEC;
3034 #else
3035                 TMODULO(*fsec, sec, 1.0);
3036 #endif
3037                 tm->tm_sec += sec;
3038         }
3039
3040         if (is_before)
3041         {
3042                 *fsec = -(*fsec);
3043                 tm->tm_sec = -tm->tm_sec;
3044                 tm->tm_min = -tm->tm_min;
3045                 tm->tm_hour = -tm->tm_hour;
3046                 tm->tm_mday = -tm->tm_mday;
3047                 tm->tm_mon = -tm->tm_mon;
3048                 tm->tm_year = -tm->tm_year;
3049         }
3050
3051         /* ensure that at least one time field has been found */
3052         if (fmask == 0)
3053                 return DTERR_BAD_FORMAT;
3054
3055         return 0;
3056 }
3057
3058
3059 /* DecodeUnits()
3060  * Decode text string using lookup table.
3061  * This routine supports time interval decoding
3062  * (hence, it need not recognize timezone names).
3063  */
3064 int
3065 DecodeUnits(int field, char *lowtoken, int *val)
3066 {
3067         int                     type;
3068         const datetkn *tp;
3069
3070         tp = deltacache[field];
3071         if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3072         {
3073                 tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
3074         }
3075         if (tp == NULL)
3076         {
3077                 type = UNKNOWN_FIELD;
3078                 *val = 0;
3079         }
3080         else
3081         {
3082                 deltacache[field] = tp;
3083                 type = tp->type;
3084                 if (type == TZ || type == DTZ)
3085                         *val = FROMVAL(tp);
3086                 else
3087                         *val = tp->value;
3088         }
3089
3090         return type;
3091 }       /* DecodeUnits() */
3092
3093 /*
3094  * Report an error detected by one of the datetime input processing routines.
3095  *
3096  * dterr is the error code, str is the original input string, datatype is
3097  * the name of the datatype we were trying to accept.
3098  *
3099  * Note: it might seem useless to distinguish DTERR_INTERVAL_OVERFLOW and
3100  * DTERR_TZDISP_OVERFLOW from DTERR_FIELD_OVERFLOW, but SQL99 mandates three
3101  * separate SQLSTATE codes, so ...
3102  */
3103 void
3104 DateTimeParseError(int dterr, const char *str, const char *datatype)
3105 {
3106         switch (dterr)
3107         {
3108                 case DTERR_FIELD_OVERFLOW:
3109                         ereport(ERROR,
3110                                         (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3111                                          errmsg("date/time field value out of range: \"%s\"",
3112                                                         str)));
3113                         break;
3114                 case DTERR_MD_FIELD_OVERFLOW:
3115                         /* <nanny>same as above, but add hint about DateStyle</nanny> */
3116                         ereport(ERROR,
3117                                         (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
3118                                          errmsg("date/time field value out of range: \"%s\"",
3119                                                         str),
3120                         errhint("Perhaps you need a different \"datestyle\" setting.")));
3121                         break;
3122                 case DTERR_INTERVAL_OVERFLOW:
3123                         ereport(ERROR,
3124                                         (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
3125                                          errmsg("interval field value out of range: \"%s\"",
3126                                                         str)));
3127                         break;
3128                 case DTERR_TZDISP_OVERFLOW:
3129                         ereport(ERROR,
3130                                         (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
3131                                          errmsg("time zone displacement out of range: \"%s\"",
3132                                                         str)));
3133                         break;
3134                 case DTERR_BAD_FORMAT:
3135                 default:
3136                         ereport(ERROR,
3137                                         (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
3138                                          errmsg("invalid input syntax for type %s: \"%s\"",
3139                                                         datatype, str)));
3140                         break;
3141         }
3142 }
3143
3144 /* datebsearch()
3145  * Binary search -- from Knuth (6.2.1) Algorithm B.  Special case like this
3146  * is WAY faster than the generic bsearch().
3147  */
3148 static const datetkn *
3149 datebsearch(const char *key, const datetkn *base, int nel)
3150 {
3151         const datetkn *last = base + nel - 1,
3152                            *position;
3153         int                     result;
3154
3155         while (last >= base)
3156         {
3157                 position = base + ((last - base) >> 1);
3158                 result = key[0] - position->token[0];
3159                 if (result == 0)
3160                 {
3161                         result = strncmp(key, position->token, TOKMAXLEN);
3162                         if (result == 0)
3163                                 return position;
3164                 }
3165                 if (result < 0)
3166                         last = position - 1;
3167                 else
3168                         base = position + 1;
3169         }
3170         return NULL;
3171 }
3172
3173 /* EncodeTimezone()
3174  *              Append representation of a numeric timezone offset to str.
3175  */
3176 static void
3177 EncodeTimezone(char *str, int tz, int style)
3178 {
3179         int                     hour,
3180                                 min,
3181                                 sec;
3182
3183         sec = abs(tz);
3184         min = sec / SECS_PER_MINUTE;
3185         sec -= min * SECS_PER_MINUTE;
3186         hour = min / MINS_PER_HOUR;
3187         min -= hour * MINS_PER_HOUR;
3188
3189         str += strlen(str);
3190         /* TZ is negated compared to sign we wish to display ... */
3191         *str++ = (tz <= 0 ? '+' : '-');
3192
3193         if (sec != 0)
3194                 sprintf(str, "%02d:%02d:%02d", hour, min, sec);
3195         else if (min != 0 || style == USE_XSD_DATES)
3196                 sprintf(str, "%02d:%02d", hour, min);
3197         else
3198                 sprintf(str, "%02d", hour);
3199 }
3200
3201 /* EncodeDateOnly()
3202  * Encode date as local time.
3203  */
3204 int
3205 EncodeDateOnly(struct pg_tm * tm, int style, char *str)
3206 {
3207         if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
3208                 return -1;
3209
3210         switch (style)
3211         {
3212                 case USE_ISO_DATES:
3213                 case USE_XSD_DATES:
3214                         /* compatible with ISO date formats */
3215                         if (tm->tm_year > 0)
3216                                 sprintf(str, "%04d-%02d-%02d",
3217                                                 tm->tm_year, tm->tm_mon, tm->tm_mday);
3218                         else
3219                                 sprintf(str, "%04d-%02d-%02d %s",
3220                                                 -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
3221                         break;
3222
3223                 case USE_SQL_DATES:
3224                         /* compatible with Oracle/Ingres date formats */
3225                         if (DateOrder == DATEORDER_DMY)
3226                                 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3227                         else
3228                                 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3229                         if (tm->tm_year > 0)
3230                                 sprintf(str + 5, "/%04d", tm->tm_year);
3231                         else
3232                                 sprintf(str + 5, "/%04d %s", -(tm->tm_year - 1), "BC");
3233                         break;
3234
3235                 case USE_GERMAN_DATES:
3236                         /* German-style date format */
3237                         sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3238                         if (tm->tm_year > 0)
3239                                 sprintf(str + 5, ".%04d", tm->tm_year);
3240                         else
3241                                 sprintf(str + 5, ".%04d %s", -(tm->tm_year - 1), "BC");
3242                         break;
3243
3244                 case USE_POSTGRES_DATES:
3245                 default:
3246                         /* traditional date-only style for Postgres */
3247                         if (DateOrder == DATEORDER_DMY)
3248                                 sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
3249                         else
3250                                 sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
3251                         if (tm->tm_year > 0)
3252                                 sprintf(str + 5, "-%04d", tm->tm_year);
3253                         else
3254                                 sprintf(str + 5, "-%04d %s", -(tm->tm_year - 1), "BC");
3255                         break;
3256         }
3257
3258         return TRUE;
3259 }       /* EncodeDateOnly() */
3260
3261
3262 /* EncodeTimeOnly()
3263  * Encode time fields only.
3264  */
3265 int
3266 EncodeTimeOnly(struct pg_tm * tm, fsec_t fsec, int *tzp, int style, char *str)
3267 {
3268         if (tm->tm_hour < 0 || tm->tm_hour > HOURS_PER_DAY)
3269                 return -1;
3270
3271         sprintf(str, "%02d:%02d", tm->tm_hour, tm->tm_min);
3272
3273         /*
3274          * Print fractional seconds if any.  The fractional field widths here
3275          * should be equal to the larger of MAX_TIME_PRECISION and
3276          * MAX_TIMESTAMP_PRECISION.
3277          */
3278         if (fsec != 0)
3279         {
3280 #ifdef HAVE_INT64_TIMESTAMP
3281                 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3282 #else
3283                 sprintf(str + strlen(str), ":%013.10f", tm->tm_sec + fsec);
3284 #endif
3285                 TrimTrailingZeros(str);
3286         }
3287         else
3288                 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3289
3290         if (tzp != NULL)
3291                 EncodeTimezone(str, *tzp, style);
3292
3293         return TRUE;
3294 }       /* EncodeTimeOnly() */
3295
3296
3297 /* EncodeDateTime()
3298  * Encode date and time interpreted as local time.
3299  * Support several date styles:
3300  *      Postgres - day mon hh:mm:ss yyyy tz
3301  *      SQL - mm/dd/yyyy hh:mm:ss.ss tz
3302  *      ISO - yyyy-mm-dd hh:mm:ss+/-tz
3303  *      German - dd.mm.yyyy hh:mm:ss tz
3304  *      XSD - yyyy-mm-ddThh:mm:ss.ss+/-tz
3305  * Variants (affects order of month and day for Postgres and SQL styles):
3306  *      US - mm/dd/yyyy
3307  *      European - dd/mm/yyyy
3308  */
3309 int
3310 EncodeDateTime(struct pg_tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, char *str)
3311 {
3312         int                     day;
3313
3314         /*
3315          * Why are we checking only the month field? Change this to an assert...
3316          * if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR) return -1;
3317          */
3318         Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
3319
3320         switch (style)
3321         {
3322                 case USE_ISO_DATES:
3323                 case USE_XSD_DATES:
3324                         /* Compatible with ISO-8601 date formats */
3325
3326                         if (style == USE_ISO_DATES)
3327                                 sprintf(str, "%04d-%02d-%02d %02d:%02d",
3328                                                 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3329                                                 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3330                         else
3331                                 sprintf(str, "%04d-%02d-%02dT%02d:%02d",
3332                                                 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3333                                                 tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
3334
3335
3336                         /*
3337                          * Print fractional seconds if any.  The field widths here should
3338                          * be at least equal to MAX_TIMESTAMP_PRECISION.
3339                          *
3340                          * In float mode, don't print fractional seconds before 1 AD,
3341                          * since it's unlikely there's any precision left ...
3342                          */
3343 #ifdef HAVE_INT64_TIMESTAMP
3344                         if (fsec != 0)
3345                         {
3346                                 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3347                                 TrimTrailingZeros(str);
3348                         }
3349 #else
3350                         if (fsec != 0 && tm->tm_year > 0)
3351                         {
3352                                 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3353                                 TrimTrailingZeros(str);
3354                         }
3355 #endif
3356                         else
3357                                 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3358
3359                         /*
3360                          * tzp == NULL indicates that we don't want *any* time zone info
3361                          * in the output string. *tzn != NULL indicates that we have alpha
3362                          * time zone info available. tm_isdst != -1 indicates that we have
3363                          * a valid time zone translation.
3364                          */
3365                         if (tzp != NULL && tm->tm_isdst >= 0)
3366                                 EncodeTimezone(str, *tzp, style);
3367
3368                         if (tm->tm_year <= 0)
3369                                 sprintf(str + strlen(str), " BC");
3370                         break;
3371
3372                 case USE_SQL_DATES:
3373                         /* Compatible with Oracle/Ingres date formats */
3374
3375                         if (DateOrder == DATEORDER_DMY)
3376                                 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
3377                         else
3378                                 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
3379
3380                         sprintf(str + 5, "/%04d %02d:%02d",
3381                                         (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3382                                         tm->tm_hour, tm->tm_min);
3383
3384                         /*
3385                          * Print fractional seconds if any.  The field widths here should
3386                          * be at least equal to MAX_TIMESTAMP_PRECISION.
3387                          *
3388                          * In float mode, don't print fractional seconds before 1 AD,
3389                          * since it's unlikely there's any precision left ...
3390                          */
3391 #ifdef HAVE_INT64_TIMESTAMP
3392                         if (fsec != 0)
3393                         {
3394                                 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3395                                 TrimTrailingZeros(str);
3396                         }
3397 #else
3398                         if (fsec != 0 && tm->tm_year > 0)
3399                         {
3400                                 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3401                                 TrimTrailingZeros(str);
3402                         }
3403 #endif
3404                         else
3405                                 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3406
3407                         if (tzp != NULL && tm->tm_isdst >= 0)
3408                         {
3409                                 if (*tzn != NULL)
3410                                         sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3411                                 else
3412                                         EncodeTimezone(str, *tzp, style);
3413                         }
3414
3415                         if (tm->tm_year <= 0)
3416                                 sprintf(str + strlen(str), " BC");
3417                         break;
3418
3419                 case USE_GERMAN_DATES:
3420                         /* German variant on European style */
3421
3422                         sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
3423
3424                         sprintf(str + 5, ".%04d %02d:%02d",
3425                                         (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
3426                                         tm->tm_hour, tm->tm_min);
3427
3428                         /*
3429                          * Print fractional seconds if any.  The field widths here should
3430                          * be at least equal to MAX_TIMESTAMP_PRECISION.
3431                          *
3432                          * In float mode, don't print fractional seconds before 1 AD,
3433                          * since it's unlikely there's any precision left ...
3434                          */
3435 #ifdef HAVE_INT64_TIMESTAMP
3436                         if (fsec != 0)
3437                         {
3438                                 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3439                                 TrimTrailingZeros(str);
3440                         }
3441 #else
3442                         if (fsec != 0 && tm->tm_year > 0)
3443                         {
3444                                 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3445                                 TrimTrailingZeros(str);
3446                         }
3447 #endif
3448                         else
3449                                 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3450
3451                         if (tzp != NULL && tm->tm_isdst >= 0)
3452                         {
3453                                 if (*tzn != NULL)
3454                                         sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3455                                 else
3456                                         EncodeTimezone(str, *tzp, style);
3457                         }
3458
3459                         if (tm->tm_year <= 0)
3460                                 sprintf(str + strlen(str), " BC");
3461                         break;
3462
3463                 case USE_POSTGRES_DATES:
3464                 default:
3465                         /* Backward-compatible with traditional Postgres abstime dates */
3466
3467                         day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3468                         tm->tm_wday = j2day(day);
3469
3470                         strncpy(str, days[tm->tm_wday], 3);
3471                         strcpy(str + 3, " ");
3472
3473                         if (DateOrder == DATEORDER_DMY)
3474                                 sprintf(str + 4, "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
3475                         else
3476                                 sprintf(str + 4, "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);
3477
3478                         sprintf(str + 10, " %02d:%02d", tm->tm_hour, tm->tm_min);
3479
3480                         /*
3481                          * Print fractional seconds if any.  The field widths here should
3482                          * be at least equal to MAX_TIMESTAMP_PRECISION.
3483                          *
3484                          * In float mode, don't print fractional seconds before 1 AD,
3485                          * since it's unlikely there's any precision left ...
3486                          */
3487 #ifdef HAVE_INT64_TIMESTAMP
3488                         if (fsec != 0)
3489                         {
3490                                 sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
3491                                 TrimTrailingZeros(str);
3492                         }
3493 #else
3494                         if (fsec != 0 && tm->tm_year > 0)
3495                         {
3496                                 sprintf(str + strlen(str), ":%09.6f", tm->tm_sec + fsec);
3497                                 TrimTrailingZeros(str);
3498                         }
3499 #endif
3500                         else
3501                                 sprintf(str + strlen(str), ":%02d", tm->tm_sec);
3502
3503                         sprintf(str + strlen(str), " %04d",
3504                                         (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1));
3505
3506                         if (tzp != NULL && tm->tm_isdst >= 0)
3507                         {
3508                                 if (*tzn != NULL)
3509                                         sprintf(str + strlen(str), " %.*s", MAXTZLEN, *tzn);
3510                                 else
3511                                 {
3512                                         /*
3513                                          * We have a time zone, but no string version. Use the
3514                                          * numeric form, but be sure to include a leading space to
3515                                          * avoid formatting something which would be rejected by
3516                                          * the date/time parser later. - thomas 2001-10-19
3517                                          */
3518                                         sprintf(str + strlen(str), " ");
3519                                         EncodeTimezone(str, *tzp, style);
3520                                 }
3521                         }
3522
3523                         if (tm->tm_year <= 0)
3524                                 sprintf(str + strlen(str), " BC");
3525                         break;
3526         }
3527
3528         return TRUE;
3529 }
3530
3531
3532 /* EncodeInterval()
3533  * Interpret time structure as a delta time and convert to string.
3534  *
3535  * Support "traditional Postgres" and ISO-8601 styles.
3536  * Actually, afaik ISO does not address time interval formatting,
3537  *      but this looks similar to the spec for absolute date/time.
3538  * - thomas 1998-04-30
3539  */
3540 int
3541 EncodeInterval(struct pg_tm * tm, fsec_t fsec, int style, char *str)
3542 {
3543         bool            is_before = FALSE;
3544         bool            is_nonzero = FALSE;
3545         char       *cp = str;
3546
3547         /*
3548          * The sign of year and month are guaranteed to match, since they are
3549          * stored internally as "month". But we'll need to check for is_before and
3550          * is_nonzero when determining the signs of hour/minute/seconds fields.
3551          */
3552         switch (style)
3553         {
3554                         /* compatible with ISO date formats */
3555                 case USE_ISO_DATES:
3556                         if (tm->tm_year != 0)
3557                         {
3558                                 sprintf(cp, "%d year%s",
3559                                                 tm->tm_year, (tm->tm_year != 1) ? "s" : "");
3560                                 cp += strlen(cp);
3561                                 is_before = (tm->tm_year < 0);
3562                                 is_nonzero = TRUE;
3563                         }
3564
3565                         if (tm->tm_mon != 0)
3566                         {
3567                                 sprintf(cp, "%s%s%d mon%s", is_nonzero ? " " : "",
3568                                                 (is_before && tm->tm_mon > 0) ? "+" : "",
3569                                                 tm->tm_mon, (tm->tm_mon != 1) ? "s" : "");
3570                                 cp += strlen(cp);
3571                                 is_before = (tm->tm_mon < 0);
3572                                 is_nonzero = TRUE;
3573                         }
3574
3575                         if (tm->tm_mday != 0)
3576                         {
3577                                 sprintf(cp, "%s%s%d day%s", is_nonzero ? " " : "",
3578                                                 (is_before && tm->tm_mday > 0) ? "+" : "",
3579                                                 tm->tm_mday, (tm->tm_mday != 1) ? "s" : "");
3580                                 cp += strlen(cp);
3581                                 is_before = (tm->tm_mday < 0);
3582                                 is_nonzero = TRUE;
3583                         }
3584
3585                         if (!is_nonzero || tm->tm_hour != 0 || tm->tm_min != 0 ||
3586                                 tm->tm_sec != 0 || fsec != 0)
3587                         {
3588                                 int                     minus = (tm->tm_hour < 0 || tm->tm_min < 0 ||
3589                                                                          tm->tm_sec < 0 || fsec < 0);
3590
3591                                 sprintf(cp, "%s%s%02d:%02d", is_nonzero ? " " : "",
3592                                                 (minus ? "-" : (is_before ? "+" : "")),
3593                                                 abs(tm->tm_hour), abs(tm->tm_min));
3594                                 cp += strlen(cp);
3595                                 /* Mark as "non-zero" since the fields are now filled in */
3596                                 is_nonzero = TRUE;
3597
3598                                 /* need fractional seconds? */
3599                                 if (fsec != 0)
3600                                 {
3601 #ifdef HAVE_INT64_TIMESTAMP
3602                                         sprintf(cp, ":%02d", abs(tm->tm_sec));
3603                                         cp += strlen(cp);
3604                                         sprintf(cp, ".%06d", Abs(fsec));
3605 #else
3606                                         fsec += tm->tm_sec;
3607                                         sprintf(cp, ":%012.9f", fabs(fsec));
3608 #endif
3609                                         TrimTrailingZeros(cp);
3610                                         cp += strlen(cp);
3611                                 }
3612                                 else
3613                                 {
3614                                         sprintf(cp, ":%02d", abs(tm->tm_sec));
3615                                         cp += strlen(cp);
3616                                 }
3617                         }
3618                         break;
3619
3620                 case USE_POSTGRES_DATES:
3621                 default:
3622                         strcpy(cp, "@ ");
3623                         cp += strlen(cp);
3624
3625                         if (tm->tm_year != 0)
3626                         {
3627                                 int                     year = tm->tm_year;
3628
3629                                 if (tm->tm_year < 0)
3630                                         year = -year;
3631
3632                                 sprintf(cp, "%d year%s", year,
3633                                                 (year != 1) ? "s" : "");
3634                                 cp += strlen(cp);
3635                                 is_before = (tm->tm_year < 0);
3636                                 is_nonzero = TRUE;
3637                         }
3638
3639                         if (tm->tm_mon != 0)
3640                         {
3641                                 int                     mon = tm->tm_mon;
3642
3643                                 if (is_before || (!is_nonzero && tm->tm_mon < 0))
3644                                         mon = -mon;
3645
3646                                 sprintf(cp, "%s%d mon%s", is_nonzero ? " " : "", mon,
3647                                                 (mon != 1) ? "s" : "");
3648                                 cp += strlen(cp);
3649                                 if (!is_nonzero)
3650                                         is_before = (tm->tm_mon < 0);
3651                                 is_nonzero = TRUE;
3652                         }
3653
3654                         if (tm->tm_mday != 0)
3655                         {
3656                                 int                     day = tm->tm_mday;
3657
3658                                 if (is_before || (!is_nonzero && tm->tm_mday < 0))
3659                                         day = -day;
3660
3661                                 sprintf(cp, "%s%d day%s", is_nonzero ? " " : "", day,
3662                                                 (day != 1) ? "s" : "");
3663                                 cp += strlen(cp);
3664                                 if (!is_nonzero)
3665                                         is_before = (tm->tm_mday < 0);
3666                                 is_nonzero = TRUE;
3667                         }
3668                         if (tm->tm_hour != 0)
3669                         {
3670                                 int                     hour = tm->tm_hour;
3671
3672                                 if (is_before || (!is_nonzero && tm->tm_hour < 0))
3673                                         hour = -hour;
3674
3675                                 sprintf(cp, "%s%d hour%s", is_nonzero ? " " : "", hour,
3676                                                 (hour != 1) ? "s" : "");
3677                                 cp += strlen(cp);
3678                                 if (!is_nonzero)
3679                                         is_before = (tm->tm_hour < 0);
3680                                 is_nonzero = TRUE;
3681                         }
3682
3683                         if (tm->tm_min != 0)
3684                         {
3685                                 int                     min = tm->tm_min;
3686
3687                                 if (is_before || (!is_nonzero && tm->tm_min < 0))
3688                                         min = -min;
3689
3690                                 sprintf(cp, "%s%d min%s", is_nonzero ? " " : "", min,
3691                                                 (min != 1) ? "s" : "");
3692                                 cp += strlen(cp);
3693                                 if (!is_nonzero)
3694                                         is_before = (tm->tm_min < 0);
3695                                 is_nonzero = TRUE;
3696                         }
3697
3698                         /* fractional seconds? */
3699                         if (fsec != 0)
3700                         {
3701                                 fsec_t          sec;
3702
3703 #ifdef HAVE_INT64_TIMESTAMP
3704                                 sec = fsec;
3705                                 if (is_before || (!is_nonzero && tm->tm_sec < 0))
3706                                 {
3707                                         tm->tm_sec = -tm->tm_sec;
3708                                         sec = -sec;
3709                                         is_before = TRUE;
3710                                 }
3711                                 else if (!is_nonzero && tm->tm_sec == 0 && fsec < 0)
3712                                 {
3713                                         sec = -sec;
3714                                         is_before = TRUE;
3715                                 }
3716                                 sprintf(cp, "%s%d.%02d secs", is_nonzero ? " " : "",
3717                                                 tm->tm_sec, ((int) sec) / 10000);
3718                                 cp += strlen(cp);
3719 #else
3720                                 fsec += tm->tm_sec;
3721                                 sec = fsec;
3722                                 if (is_before || (!is_nonzero && fsec < 0))
3723                                         sec = -sec;
3724
3725                                 sprintf(cp, "%s%.2f secs", is_nonzero ? " " : "", sec);
3726                                 cp += strlen(cp);
3727                                 if (!is_nonzero)
3728                                         is_before = (fsec < 0);
3729 #endif
3730                                 is_nonzero = TRUE;
3731                         }
3732                         /* otherwise, integer seconds only? */
3733                         else if (tm->tm_sec != 0)
3734                         {
3735                                 int                     sec = tm->tm_sec;
3736
3737                                 if (is_before || (!is_nonzero && tm->tm_sec < 0))
3738                                         sec = -sec;
3739
3740                                 sprintf(cp, "%s%d sec%s", is_nonzero ? " " : "", sec,
3741                                                 (sec != 1) ? "s" : "");
3742                                 cp += strlen(cp);
3743                                 if (!is_nonzero)
3744                                         is_before = (tm->tm_sec < 0);
3745                                 is_nonzero = TRUE;
3746                         }
3747                         break;
3748         }
3749
3750         /* identically zero? then put in a unitless zero... */
3751         if (!is_nonzero)
3752         {
3753                 strcat(cp, "0");
3754                 cp += strlen(cp);
3755         }
3756
3757         if (is_before && (style != USE_ISO_DATES))
3758         {
3759                 strcat(cp, " ago");
3760                 cp += strlen(cp);
3761         }
3762
3763         return 0;
3764 }       /* EncodeInterval() */
3765
3766
3767 /*
3768  * We've been burnt by stupid errors in the ordering of the datetkn tables
3769  * once too often.      Arrange to check them during postmaster start.
3770  */
3771 static bool
3772 CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
3773 {
3774         bool            ok = true;
3775         int                     i;
3776
3777         for (i = 1; i < nel; i++)
3778         {
3779                 if (strncmp(base[i - 1].token, base[i].token, TOKMAXLEN) >= 0)
3780                 {
3781                         elog(LOG, "ordering error in %s table: \"%.*s\" >= \"%.*s\"",
3782                                  tablename,
3783                                  TOKMAXLEN, base[i - 1].token,
3784                                  TOKMAXLEN, base[i].token);
3785                         ok = false;
3786                 }
3787         }
3788         return ok;
3789 }
3790
3791 bool
3792 CheckDateTokenTables(void)
3793 {
3794         bool            ok = true;
3795
3796         Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
3797         Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
3798
3799         ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
3800         ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
3801         return ok;
3802 }
3803
3804 /*
3805  * This function gets called during timezone config file load or reload
3806  * to create the final array of timezone tokens.  The argument array
3807  * is already sorted in name order.  This data is in a temporary memory
3808  * context and must be copied to somewhere permanent.
3809  */
3810 void
3811 InstallTimeZoneAbbrevs(tzEntry *abbrevs, int n)
3812 {
3813         datetkn    *newtbl;
3814         int                     i;
3815
3816         /*
3817          * Copy the data into TopMemoryContext and convert to datetkn format.
3818          */
3819         newtbl = (datetkn *) MemoryContextAlloc(TopMemoryContext,
3820                                                                                         n * sizeof(datetkn));
3821         for (i = 0; i < n; i++)
3822         {
3823                 strncpy(newtbl[i].token, abbrevs[i].abbrev, TOKMAXLEN);
3824                 newtbl[i].type = abbrevs[i].is_dst ? DTZ : TZ;
3825                 TOVAL(&newtbl[i], abbrevs[i].offset / 60);
3826         }
3827
3828         /* Check the ordering, if testing */
3829         Assert(CheckDateTokenTable("timezone offset", newtbl, n));
3830
3831         /* Now safe to replace existing table (if any) */
3832         if (timezonetktbl)
3833                 pfree(timezonetktbl);
3834         timezonetktbl = newtbl;
3835         sztimezonetktbl = n;
3836
3837         /* clear date cache in case it contains any stale timezone names */
3838         for (i = 0; i < MAXDATEFIELDS; i++)
3839                 datecache[i] = NULL;
3840 }
3841
3842 /*
3843  * This set-returning function reads all the available time zone abbreviations
3844  * and returns a set of (abbrev, utc_offset, is_dst).
3845  */
3846 Datum
3847 pg_timezone_abbrevs(PG_FUNCTION_ARGS)
3848 {
3849         FuncCallContext *funcctx;
3850         int                *pindex;
3851         Datum           result;
3852         HeapTuple       tuple;
3853         Datum           values[3];
3854         bool            nulls[3];
3855         char            buffer[TOKMAXLEN + 1];
3856         unsigned char *p;
3857         struct pg_tm tm;
3858         Interval   *resInterval;
3859
3860         /* stuff done only on the first call of the function */
3861         if (SRF_IS_FIRSTCALL())
3862         {
3863                 TupleDesc       tupdesc;
3864                 MemoryContext oldcontext;
3865
3866                 /* create a function context for cross-call persistence */
3867                 funcctx = SRF_FIRSTCALL_INIT();
3868
3869                 /*
3870                  * switch to memory context appropriate for multiple function calls
3871                  */
3872                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
3873
3874                 /* allocate memory for user context */
3875                 pindex = (int *) palloc(sizeof(int));
3876                 *pindex = 0;
3877                 funcctx->user_fctx = (void *) pindex;
3878
3879                 /*
3880                  * build tupdesc for result tuples. This must match this function's
3881                  * pg_proc entry!
3882                  */
3883                 tupdesc = CreateTemplateTupleDesc(3, false);
3884                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "abbrev",
3885                                                    TEXTOID, -1, 0);
3886                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "utc_offset",
3887                                                    INTERVALOID, -1, 0);
3888                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "is_dst",
3889                                                    BOOLOID, -1, 0);
3890
3891                 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
3892                 MemoryContextSwitchTo(oldcontext);
3893         }
3894
3895         /* stuff done on every call of the function */
3896         funcctx = SRF_PERCALL_SETUP();
3897         pindex = (int *) funcctx->user_fctx;
3898
3899         if (*pindex >= sztimezonetktbl)
3900                 SRF_RETURN_DONE(funcctx);
3901
3902         MemSet(nulls, 0, sizeof(nulls));
3903
3904         /*
3905          * Convert name to text, using upcasing conversion that is the inverse of
3906          * what ParseDateTime() uses.
3907          */
3908         strncpy(buffer, timezonetktbl[*pindex].token, TOKMAXLEN);
3909         buffer[TOKMAXLEN] = '\0';       /* may not be null-terminated */
3910         for (p = (unsigned char *) buffer; *p; p++)
3911                 *p = pg_toupper(*p);
3912
3913         values[0] = DirectFunctionCall1(textin, CStringGetDatum(buffer));
3914
3915         MemSet(&tm, 0, sizeof(struct pg_tm));
3916         tm.tm_min = (-1) * FROMVAL(&timezonetktbl[*pindex]);
3917         resInterval = (Interval *) palloc(sizeof(Interval));
3918         tm2interval(&tm, 0, resInterval);
3919         values[1] = IntervalPGetDatum(resInterval);
3920
3921         Assert(timezonetktbl[*pindex].type == DTZ ||
3922                    timezonetktbl[*pindex].type == TZ);
3923         values[2] = BoolGetDatum(timezonetktbl[*pindex].type == DTZ);
3924
3925         (*pindex)++;
3926
3927         tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
3928         result = HeapTupleGetDatum(tuple);
3929
3930         SRF_RETURN_NEXT(funcctx, result);
3931 }
3932
3933 /*
3934  * This set-returning function reads all the available full time zones
3935  * and returns a set of (name, abbrev, utc_offset, is_dst).
3936  */
3937 Datum
3938 pg_timezone_names(PG_FUNCTION_ARGS)
3939 {
3940         MemoryContext oldcontext;
3941         FuncCallContext *funcctx;
3942         pg_tzenum  *tzenum;
3943         pg_tz      *tz;
3944         Datum           result;
3945         HeapTuple       tuple;
3946         Datum           values[4];
3947         bool            nulls[4];
3948         int                     tzoff;
3949         struct pg_tm tm;
3950         fsec_t          fsec;
3951         char       *tzn;
3952         Interval   *resInterval;
3953         struct pg_tm itm;
3954
3955         /* stuff done only on the first call of the function */
3956         if (SRF_IS_FIRSTCALL())
3957         {
3958                 TupleDesc       tupdesc;
3959
3960                 /* create a function context for cross-call persistence */
3961                 funcctx = SRF_FIRSTCALL_INIT();
3962
3963                 /*
3964                  * switch to memory context appropriate for multiple function calls
3965                  */
3966                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
3967
3968                 /* initialize timezone scanning code */
3969                 tzenum = pg_tzenumerate_start();
3970                 funcctx->user_fctx = (void *) tzenum;
3971
3972                 /*
3973                  * build tupdesc for result tuples. This must match this function's
3974                  * pg_proc entry!
3975                  */
3976                 tupdesc = CreateTemplateTupleDesc(4, false);
3977                 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
3978                                                    TEXTOID, -1, 0);
3979                 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "abbrev",
3980                                                    TEXTOID, -1, 0);
3981                 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "utc_offset",
3982                                                    INTERVALOID, -1, 0);
3983                 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "is_dst",
3984                                                    BOOLOID, -1, 0);
3985
3986                 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
3987                 MemoryContextSwitchTo(oldcontext);
3988         }
3989
3990         /* stuff done on every call of the function */
3991         funcctx = SRF_PERCALL_SETUP();
3992         tzenum = (pg_tzenum *) funcctx->user_fctx;
3993
3994         /* search for another zone to display */
3995         for (;;)
3996         {
3997                 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
3998                 tz = pg_tzenumerate_next(tzenum);
3999                 MemoryContextSwitchTo(oldcontext);
4000
4001                 if (!tz)
4002                 {
4003                         pg_tzenumerate_end(tzenum);
4004                         funcctx->user_fctx = NULL;
4005                         SRF_RETURN_DONE(funcctx);
4006                 }
4007
4008                 /* Convert now() to local time in this zone */
4009                 if (timestamp2tm(GetCurrentTransactionStartTimestamp(),
4010                                                  &tzoff, &tm, &fsec, &tzn, tz) != 0)
4011                         continue;                       /* ignore if conversion fails */
4012
4013                 /* Ignore zic's rather silly "Factory" time zone */
4014                 if (tzn && strcmp(tzn, "Local time zone must be set--see zic manual page") == 0)
4015                         continue;
4016
4017                 /* Found a displayable zone */
4018                 break;
4019         }
4020
4021         MemSet(nulls, 0, sizeof(nulls));
4022
4023         values[0] = DirectFunctionCall1(textin,
4024                                                                   CStringGetDatum(pg_get_timezone_name(tz)));
4025
4026         values[1] = DirectFunctionCall1(textin,
4027                                                                         CStringGetDatum(tzn ? tzn : ""));
4028
4029         MemSet(&itm, 0, sizeof(struct pg_tm));
4030         itm.tm_sec = -tzoff;
4031         resInterval = (Interval *) palloc(sizeof(Interval));
4032         tm2interval(&itm, 0, resInterval);
4033         values[2] = IntervalPGetDatum(resInterval);
4034
4035         values[3] = BoolGetDatum(tm.tm_isdst > 0);
4036
4037         tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
4038         result = HeapTupleGetDatum(tuple);
4039
4040         SRF_RETURN_NEXT(funcctx, result);
4041 }