OSDN Git Service

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