PostgreSQL Source Code  git master
dt_common.c
Go to the documentation of this file.
1 /* src/interfaces/ecpg/pgtypeslib/dt_common.c */
2 
3 #include "postgres_fe.h"
4 
5 #include <time.h>
6 #include <ctype.h>
7 #include <math.h>
8 
9 #include "common/string.h"
10 #include "dt.h"
11 #include "pgtypes_timestamp.h"
12 #include "pgtypeslib_extern.h"
13 
14 const int day_tab[2][13] = {
15  {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
16 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}};
17 
18 typedef long AbsoluteTime;
19 
20 static const datetkn datetktbl[] = {
21 /* text, token, lexval */
22  {EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
23  {"acsst", DTZ, 37800}, /* Cent. Australia */
24  {"acst", DTZ, -14400}, /* Atlantic/Porto Acre */
25  {"act", TZ, -18000}, /* Atlantic/Porto Acre */
26  {DA_D, ADBC, AD}, /* "ad" for years >= 0 */
27  {"adt", DTZ, -10800}, /* Atlantic Daylight Time */
28  {"aesst", DTZ, 39600}, /* E. Australia */
29  {"aest", TZ, 36000}, /* Australia Eastern Std Time */
30  {"aft", TZ, 16200}, /* Kabul */
31  {"ahst", TZ, -36000}, /* Alaska-Hawaii Std Time */
32  {"akdt", DTZ, -28800}, /* Alaska Daylight Time */
33  {"akst", DTZ, -32400}, /* Alaska Standard Time */
34  {"allballs", RESERV, DTK_ZULU}, /* 00:00:00 */
35  {"almst", TZ, 25200}, /* Almaty Savings Time */
36  {"almt", TZ, 21600}, /* Almaty Time */
37  {"am", AMPM, AM},
38  {"amst", DTZ, 18000}, /* Armenia Summer Time (Yerevan) */
39 #if 0
40  {"amst", DTZ, -10800}, /* Porto Velho */
41 #endif
42  {"amt", TZ, 14400}, /* Armenia Time (Yerevan) */
43  {"anast", DTZ, 46800}, /* Anadyr Summer Time (Russia) */
44  {"anat", TZ, 43200}, /* Anadyr Time (Russia) */
45  {"apr", MONTH, 4},
46  {"april", MONTH, 4},
47 #if 0
48  aqtst
49  aqtt
50  arst
51 #endif
52  {"art", TZ, -10800}, /* Argentina Time */
53 #if 0
54  ashst
55  ast /* Atlantic Standard Time, Arabia Standard
56  * Time, Acre Standard Time */
57 #endif
58  {"ast", TZ, -14400}, /* Atlantic Std Time (Canada) */
59  {"at", IGNORE_DTF, 0}, /* "at" (throwaway) */
60  {"aug", MONTH, 8},
61  {"august", MONTH, 8},
62  {"awsst", DTZ, 32400}, /* W. Australia */
63  {"awst", TZ, 28800}, /* W. Australia */
64  {"awt", DTZ, -10800},
65  {"azost", DTZ, 0}, /* Azores Summer Time */
66  {"azot", TZ, -3600}, /* Azores Time */
67  {"azst", DTZ, 18000}, /* Azerbaijan Summer Time */
68  {"azt", TZ, 14400}, /* Azerbaijan Time */
69  {DB_C, ADBC, BC}, /* "bc" for years < 0 */
70  {"bdst", TZ, 7200}, /* British Double Summer Time */
71  {"bdt", TZ, 21600}, /* Dacca */
72  {"bnt", TZ, 28800}, /* Brunei Darussalam Time */
73  {"bort", TZ, 28800}, /* Borneo Time (Indonesia) */
74 #if 0
75  bortst
76  bost
77 #endif
78  {"bot", TZ, -14400}, /* Bolivia Time */
79  {"bra", TZ, -10800}, /* Brazil Time */
80 #if 0
81  brst
82  brt
83 #endif
84  {"bst", DTZ, 3600}, /* British Summer Time */
85 #if 0
86  {"bst", TZ, -10800}, /* Brazil Standard Time */
87  {"bst", DTZ, -39600}, /* Bering Summer Time */
88 #endif
89  {"bt", TZ, 10800}, /* Baghdad Time */
90  {"btt", TZ, 21600}, /* Bhutan Time */
91  {"cadt", DTZ, 37800}, /* Central Australian DST */
92  {"cast", TZ, 34200}, /* Central Australian ST */
93  {"cat", TZ, -36000}, /* Central Alaska Time */
94  {"cct", TZ, 28800}, /* China Coast Time */
95 #if 0
96  {"cct", TZ, 23400}, /* Indian Cocos (Island) Time */
97 #endif
98  {"cdt", DTZ, -18000}, /* Central Daylight Time */
99  {"cest", DTZ, 7200}, /* Central European Dayl.Time */
100  {"cet", TZ, 3600}, /* Central European Time */
101  {"cetdst", DTZ, 7200}, /* Central European Dayl.Time */
102  {"chadt", DTZ, 49500}, /* Chatham Island Daylight Time (13:45) */
103  {"chast", TZ, 45900}, /* Chatham Island Time (12:45) */
104 #if 0
105  ckhst
106 #endif
107  {"ckt", TZ, 43200}, /* Cook Islands Time */
108  {"clst", DTZ, -10800}, /* Chile Summer Time */
109  {"clt", TZ, -14400}, /* Chile Time */
110 #if 0
111  cost
112 #endif
113  {"cot", TZ, -18000}, /* Columbia Time */
114  {"cst", TZ, -21600}, /* Central Standard Time */
115 #if 0
116  cvst
117 #endif
118  {"cvt", TZ, 25200}, /* Christmas Island Time (Indian Ocean) */
119  {"cxt", TZ, 25200}, /* Christmas Island Time (Indian Ocean) */
120  {"d", UNITS, DTK_DAY}, /* "day of month" for ISO input */
121  {"davt", TZ, 25200}, /* Davis Time (Antarctica) */
122  {"ddut", TZ, 36000}, /* Dumont-d'Urville Time (Antarctica) */
123  {"dec", MONTH, 12},
124  {"december", MONTH, 12},
125  {"dnt", TZ, 3600}, /* Dansk Normal Tid */
126  {"dow", UNITS, DTK_DOW}, /* day of week */
127  {"doy", UNITS, DTK_DOY}, /* day of year */
128  {"dst", DTZMOD, SECS_PER_HOUR},
129 #if 0
130  {"dusst", DTZ, 21600}, /* Dushanbe Summer Time */
131 #endif
132  {"easst", DTZ, -18000}, /* Easter Island Summer Time */
133  {"east", TZ, -21600}, /* Easter Island Time */
134  {"eat", TZ, 10800}, /* East Africa Time */
135 #if 0
136  {"east", DTZ, 14400}, /* Indian Antananarivo Savings Time */
137  {"eat", TZ, 10800}, /* Indian Antananarivo Time */
138  {"ect", TZ, -14400}, /* Eastern Caribbean Time */
139  {"ect", TZ, -18000}, /* Ecuador Time */
140 #endif
141  {"edt", DTZ, -14400}, /* Eastern Daylight Time */
142  {"eest", DTZ, 10800}, /* Eastern Europe Summer Time */
143  {"eet", TZ, 7200}, /* East. Europe, USSR Zone 1 */
144  {"eetdst", DTZ, 10800}, /* Eastern Europe Daylight Time */
145  {"egst", DTZ, 0}, /* East Greenland Summer Time */
146  {"egt", TZ, -3600}, /* East Greenland Time */
147 #if 0
148  ehdt
149 #endif
150  {EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
151  {"est", TZ, -18000}, /* Eastern Standard Time */
152  {"feb", MONTH, 2},
153  {"february", MONTH, 2},
154  {"fjst", DTZ, -46800}, /* Fiji Summer Time (13 hour offset!) */
155  {"fjt", TZ, -43200}, /* Fiji Time */
156  {"fkst", DTZ, -10800}, /* Falkland Islands Summer Time */
157  {"fkt", TZ, -7200}, /* Falkland Islands Time */
158 #if 0
159  fnst
160  fnt
161 #endif
162  {"fri", DOW, 5},
163  {"friday", DOW, 5},
164  {"fst", TZ, 3600}, /* French Summer Time */
165  {"fwt", DTZ, 7200}, /* French Winter Time */
166  {"galt", TZ, -21600}, /* Galapagos Time */
167  {"gamt", TZ, -32400}, /* Gambier Time */
168  {"gest", DTZ, 18000}, /* Georgia Summer Time */
169  {"get", TZ, 14400}, /* Georgia Time */
170  {"gft", TZ, -10800}, /* French Guiana Time */
171 #if 0
172  ghst
173 #endif
174  {"gilt", TZ, 43200}, /* Gilbert Islands Time */
175  {"gmt", TZ, 0}, /* Greenwich Mean Time */
176  {"gst", TZ, 36000}, /* Guam Std Time, USSR Zone 9 */
177  {"gyt", TZ, -14400}, /* Guyana Time */
178  {"h", UNITS, DTK_HOUR}, /* "hour" */
179 #if 0
180  hadt
181  hast
182 #endif
183  {"hdt", DTZ, -32400}, /* Hawaii/Alaska Daylight Time */
184 #if 0
185  hkst
186 #endif
187  {"hkt", TZ, 28800}, /* Hong Kong Time */
188 #if 0
189  {"hmt", TZ, 10800}, /* Hellas ? ? */
190  hovst
191  hovt
192 #endif
193  {"hst", TZ, -36000}, /* Hawaii Std Time */
194 #if 0
195  hwt
196 #endif
197  {"ict", TZ, 25200}, /* Indochina Time */
198  {"idle", TZ, 43200}, /* Intl. Date Line, East */
199  {"idlw", TZ, -43200}, /* Intl. Date Line, West */
200 #if 0
201  idt /* Israeli, Iran, Indian Daylight Time */
202 #endif
203  {LATE, RESERV, DTK_LATE}, /* "infinity" reserved for "late time" */
204  {"iot", TZ, 18000}, /* Indian Chagos Time */
205  {"irkst", DTZ, 32400}, /* Irkutsk Summer Time */
206  {"irkt", TZ, 28800}, /* Irkutsk Time */
207  {"irt", TZ, 12600}, /* Iran Time */
208  {"isodow", UNITS, DTK_ISODOW}, /* ISO day of week, Sunday == 7 */
209 #if 0
210  isst
211 #endif
212  {"ist", TZ, 7200}, /* Israel */
213  {"it", TZ, 12600}, /* Iran Time */
214  {"j", UNITS, DTK_JULIAN},
215  {"jan", MONTH, 1},
216  {"january", MONTH, 1},
217  {"javt", TZ, 25200}, /* Java Time (07:00? see JT) */
218  {"jayt", TZ, 32400}, /* Jayapura Time (Indonesia) */
219  {"jd", UNITS, DTK_JULIAN},
220  {"jst", TZ, 32400}, /* Japan Std Time,USSR Zone 8 */
221  {"jt", TZ, 27000}, /* Java Time (07:30? see JAVT) */
222  {"jul", MONTH, 7},
223  {"julian", UNITS, DTK_JULIAN},
224  {"july", MONTH, 7},
225  {"jun", MONTH, 6},
226  {"june", MONTH, 6},
227  {"kdt", DTZ, 36000}, /* Korea Daylight Time */
228  {"kgst", DTZ, 21600}, /* Kyrgyzstan Summer Time */
229  {"kgt", TZ, 18000}, /* Kyrgyzstan Time */
230  {"kost", TZ, 43200}, /* Kosrae Time */
231  {"krast", DTZ, 25200}, /* Krasnoyarsk Summer Time */
232  {"krat", TZ, 28800}, /* Krasnoyarsk Standard Time */
233  {"kst", TZ, 32400}, /* Korea Standard Time */
234  {"lhdt", DTZ, 39600}, /* Lord Howe Daylight Time, Australia */
235  {"lhst", TZ, 37800}, /* Lord Howe Standard Time, Australia */
236  {"ligt", TZ, 36000}, /* From Melbourne, Australia */
237  {"lint", TZ, 50400}, /* Line Islands Time (Kiribati; +14 hours!) */
238  {"lkt", TZ, 21600}, /* Lanka Time */
239  {"m", UNITS, DTK_MONTH}, /* "month" for ISO input */
240  {"magst", DTZ, 43200}, /* Magadan Summer Time */
241  {"magt", TZ, 39600}, /* Magadan Time */
242  {"mar", MONTH, 3},
243  {"march", MONTH, 3},
244  {"mart", TZ, -34200}, /* Marquesas Time */
245  {"mawt", TZ, 21600}, /* Mawson, Antarctica */
246  {"may", MONTH, 5},
247  {"mdt", DTZ, -21600}, /* Mountain Daylight Time */
248  {"mest", DTZ, 7200}, /* Middle Europe Summer Time */
249  {"met", TZ, 3600}, /* Middle Europe Time */
250  {"metdst", DTZ, 7200}, /* Middle Europe Daylight Time */
251  {"mewt", TZ, 3600}, /* Middle Europe Winter Time */
252  {"mez", TZ, 3600}, /* Middle Europe Zone */
253  {"mht", TZ, 43200}, /* Kwajalein */
254  {"mm", UNITS, DTK_MINUTE}, /* "minute" for ISO input */
255  {"mmt", TZ, 23400}, /* Myannar Time */
256  {"mon", DOW, 1},
257  {"monday", DOW, 1},
258 #if 0
259  most
260 #endif
261  {"mpt", TZ, 36000}, /* North Mariana Islands Time */
262  {"msd", DTZ, 14400}, /* Moscow Summer Time */
263  {"msk", TZ, 10800}, /* Moscow Time */
264  {"mst", TZ, -25200}, /* Mountain Standard Time */
265  {"mt", TZ, 30600}, /* Moluccas Time */
266  {"mut", TZ, 14400}, /* Mauritius Island Time */
267  {"mvt", TZ, 18000}, /* Maldives Island Time */
268  {"myt", TZ, 28800}, /* Malaysia Time */
269 #if 0
270  ncst
271 #endif
272  {"nct", TZ, 39600}, /* New Caledonia Time */
273  {"ndt", DTZ, -9000}, /* Nfld. Daylight Time */
274  {"nft", TZ, -12600}, /* Newfoundland Standard Time */
275  {"nor", TZ, 3600}, /* Norway Standard Time */
276  {"nov", MONTH, 11},
277  {"november", MONTH, 11},
278  {"novst", DTZ, 25200}, /* Novosibirsk Summer Time */
279  {"novt", TZ, 21600}, /* Novosibirsk Standard Time */
280  {NOW, RESERV, DTK_NOW}, /* current transaction time */
281  {"npt", TZ, 20700}, /* Nepal Standard Time (GMT-5:45) */
282  {"nst", TZ, -12600}, /* Nfld. Standard Time */
283  {"nt", TZ, -39600}, /* Nome Time */
284  {"nut", TZ, -39600}, /* Niue Time */
285  {"nzdt", DTZ, 46800}, /* New Zealand Daylight Time */
286  {"nzst", TZ, 43200}, /* New Zealand Standard Time */
287  {"nzt", TZ, 43200}, /* New Zealand Time */
288  {"oct", MONTH, 10},
289  {"october", MONTH, 10},
290  {"omsst", DTZ, 25200}, /* Omsk Summer Time */
291  {"omst", TZ, 21600}, /* Omsk Time */
292  {"on", IGNORE_DTF, 0}, /* "on" (throwaway) */
293  {"pdt", DTZ, -25200}, /* Pacific Daylight Time */
294 #if 0
295  pest
296 #endif
297  {"pet", TZ, -18000}, /* Peru Time */
298  {"petst", DTZ, 46800}, /* Petropavlovsk-Kamchatski Summer Time */
299  {"pett", TZ, 43200}, /* Petropavlovsk-Kamchatski Time */
300  {"pgt", TZ, 36000}, /* Papua New Guinea Time */
301  {"phot", TZ, 46800}, /* Phoenix Islands (Kiribati) Time */
302 #if 0
303  phst
304 #endif
305  {"pht", TZ, 28800}, /* Philippine Time */
306  {"pkt", TZ, 18000}, /* Pakistan Time */
307  {"pm", AMPM, PM},
308  {"pmdt", DTZ, -7200}, /* Pierre & Miquelon Daylight Time */
309 #if 0
310  pmst
311 #endif
312  {"pont", TZ, 39600}, /* Ponape Time (Micronesia) */
313  {"pst", TZ, -28800}, /* Pacific Standard Time */
314  {"pwt", TZ, 32400}, /* Palau Time */
315  {"pyst", DTZ, -10800}, /* Paraguay Summer Time */
316  {"pyt", TZ, -14400}, /* Paraguay Time */
317  {"ret", DTZ, 14400}, /* Reunion Island Time */
318  {"s", UNITS, DTK_SECOND}, /* "seconds" for ISO input */
319  {"sadt", DTZ, 37800}, /* S. Australian Dayl. Time */
320 #if 0
321  samst
322  samt
323 #endif
324  {"sast", TZ, 34200}, /* South Australian Std Time */
325  {"sat", DOW, 6},
326  {"saturday", DOW, 6},
327 #if 0
328  sbt
329 #endif
330  {"sct", DTZ, 14400}, /* Mahe Island Time */
331  {"sep", MONTH, 9},
332  {"sept", MONTH, 9},
333  {"september", MONTH, 9},
334  {"set", TZ, -3600}, /* Seychelles Time ?? */
335 #if 0
336  sgt
337 #endif
338  {"sst", DTZ, 7200}, /* Swedish Summer Time */
339  {"sun", DOW, 0},
340  {"sunday", DOW, 0},
341  {"swt", TZ, 3600}, /* Swedish Winter Time */
342 #if 0
343  syot
344 #endif
345  {"t", ISOTIME, DTK_TIME}, /* Filler for ISO time fields */
346  {"tft", TZ, 18000}, /* Kerguelen Time */
347  {"that", TZ, -36000}, /* Tahiti Time */
348  {"thu", DOW, 4},
349  {"thur", DOW, 4},
350  {"thurs", DOW, 4},
351  {"thursday", DOW, 4},
352  {"tjt", TZ, 18000}, /* Tajikistan Time */
353  {"tkt", TZ, -36000}, /* Tokelau Time */
354  {"tmt", TZ, 18000}, /* Turkmenistan Time */
355  {TODAY, RESERV, DTK_TODAY}, /* midnight */
356  {TOMORROW, RESERV, DTK_TOMORROW}, /* tomorrow midnight */
357 #if 0
358  tost
359 #endif
360  {"tot", TZ, 46800}, /* Tonga Time */
361 #if 0
362  tpt
363 #endif
364  {"truk", TZ, 36000}, /* Truk Time */
365  {"tue", DOW, 2},
366  {"tues", DOW, 2},
367  {"tuesday", DOW, 2},
368  {"tvt", TZ, 43200}, /* Tuvalu Time */
369 #if 0
370  uct
371 #endif
372  {"ulast", DTZ, 32400}, /* Ulan Bator Summer Time */
373  {"ulat", TZ, 28800}, /* Ulan Bator Time */
374  {"ut", TZ, 0},
375  {"utc", TZ, 0},
376  {"uyst", DTZ, -7200}, /* Uruguay Summer Time */
377  {"uyt", TZ, -10800}, /* Uruguay Time */
378  {"uzst", DTZ, 21600}, /* Uzbekistan Summer Time */
379  {"uzt", TZ, 18000}, /* Uzbekistan Time */
380  {"vet", TZ, -14400}, /* Venezuela Time */
381  {"vlast", DTZ, 39600}, /* Vladivostok Summer Time */
382  {"vlat", TZ, 36000}, /* Vladivostok Time */
383 #if 0
384  vust
385 #endif
386  {"vut", TZ, 39600}, /* Vanuata Time */
387  {"wadt", DTZ, 28800}, /* West Australian DST */
388  {"wakt", TZ, 43200}, /* Wake Time */
389 #if 0
390  warst
391 #endif
392  {"wast", TZ, 25200}, /* West Australian Std Time */
393  {"wat", TZ, -3600}, /* West Africa Time */
394  {"wdt", DTZ, 32400}, /* West Australian DST */
395  {"wed", DOW, 3},
396  {"wednesday", DOW, 3},
397  {"weds", DOW, 3},
398  {"west", DTZ, 3600}, /* Western Europe Summer Time */
399  {"wet", TZ, 0}, /* Western Europe */
400  {"wetdst", DTZ, 3600}, /* Western Europe Daylight Savings Time */
401  {"wft", TZ, 43200}, /* Wallis and Futuna Time */
402  {"wgst", DTZ, -7200}, /* West Greenland Summer Time */
403  {"wgt", TZ, -10800}, /* West Greenland Time */
404  {"wst", TZ, 28800}, /* West Australian Standard Time */
405  {"y", UNITS, DTK_YEAR}, /* "year" for ISO input */
406  {"yakst", DTZ, 36000}, /* Yakutsk Summer Time */
407  {"yakt", TZ, 32400}, /* Yakutsk Time */
408  {"yapt", TZ, 36000}, /* Yap Time (Micronesia) */
409  {"ydt", DTZ, -28800}, /* Yukon Daylight Time */
410  {"yekst", DTZ, 21600}, /* Yekaterinburg Summer Time */
411  {"yekt", TZ, 18000}, /* Yekaterinburg Time */
412  {YESTERDAY, RESERV, DTK_YESTERDAY}, /* yesterday midnight */
413  {"yst", TZ, -32400}, /* Yukon Standard Time */
414  {"z", TZ, 0}, /* time zone tag per ISO-8601 */
415  {"zp4", TZ, -14400}, /* UTC +4 hours. */
416  {"zp5", TZ, -18000}, /* UTC +5 hours. */
417  {"zp6", TZ, -21600}, /* UTC +6 hours. */
418  {ZULU, TZ, 0}, /* UTC */
419 };
420 
421 static const datetkn deltatktbl[] = {
422  /* text, token, lexval */
423  {"@", IGNORE_DTF, 0}, /* postgres relative prefix */
424  {DAGO, AGO, 0}, /* "ago" indicates negative time offset */
425  {"c", UNITS, DTK_CENTURY}, /* "century" relative */
426  {"cent", UNITS, DTK_CENTURY}, /* "century" relative */
427  {"centuries", UNITS, DTK_CENTURY}, /* "centuries" relative */
428  {DCENTURY, UNITS, DTK_CENTURY}, /* "century" relative */
429  {"d", UNITS, DTK_DAY}, /* "day" relative */
430  {DDAY, UNITS, DTK_DAY}, /* "day" relative */
431  {"days", UNITS, DTK_DAY}, /* "days" relative */
432  {"dec", UNITS, DTK_DECADE}, /* "decade" relative */
433  {DDECADE, UNITS, DTK_DECADE}, /* "decade" relative */
434  {"decades", UNITS, DTK_DECADE}, /* "decades" relative */
435  {"decs", UNITS, DTK_DECADE}, /* "decades" relative */
436  {"h", UNITS, DTK_HOUR}, /* "hour" relative */
437  {DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */
438  {"hours", UNITS, DTK_HOUR}, /* "hours" relative */
439  {"hr", UNITS, DTK_HOUR}, /* "hour" relative */
440  {"hrs", UNITS, DTK_HOUR}, /* "hours" relative */
441  {"m", UNITS, DTK_MINUTE}, /* "minute" relative */
442  {"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
443  {"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
444  {"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
445  {DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
446  {"millisecon", UNITS, DTK_MILLISEC}, /* relative */
447  {"mils", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
448  {"min", UNITS, DTK_MINUTE}, /* "minute" relative */
449  {"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */
450  {DMINUTE, UNITS, DTK_MINUTE}, /* "minute" relative */
451  {"minutes", UNITS, DTK_MINUTE}, /* "minutes" relative */
452  {"mon", UNITS, DTK_MONTH}, /* "months" relative */
453  {"mons", UNITS, DTK_MONTH}, /* "months" relative */
454  {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
455  {"months", UNITS, DTK_MONTH},
456  {"ms", UNITS, DTK_MILLISEC},
457  {"msec", UNITS, DTK_MILLISEC},
458  {DMILLISEC, UNITS, DTK_MILLISEC},
459  {"mseconds", UNITS, DTK_MILLISEC},
460  {"msecs", UNITS, DTK_MILLISEC},
461  {"qtr", UNITS, DTK_QUARTER}, /* "quarter" relative */
462  {DQUARTER, UNITS, DTK_QUARTER}, /* "quarter" relative */
463  {"s", UNITS, DTK_SECOND},
464  {"sec", UNITS, DTK_SECOND},
465  {DSECOND, UNITS, DTK_SECOND},
466  {"seconds", UNITS, DTK_SECOND},
467  {"secs", UNITS, DTK_SECOND},
468  {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
469  {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
470  {"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */
471  {"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
472  {"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
473  {DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */
474  {"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
475  {"usecs", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
476  {"w", UNITS, DTK_WEEK}, /* "week" relative */
477  {DWEEK, UNITS, DTK_WEEK}, /* "week" relative */
478  {"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
479  {"y", UNITS, DTK_YEAR}, /* "year" relative */
480  {DYEAR, UNITS, DTK_YEAR}, /* "year" relative */
481  {"years", UNITS, DTK_YEAR}, /* "years" relative */
482  {"yr", UNITS, DTK_YEAR}, /* "year" relative */
483  {"yrs", UNITS, DTK_YEAR}, /* "years" relative */
484 };
485 
486 static const unsigned int szdatetktbl = lengthof(datetktbl);
487 static const unsigned int szdeltatktbl = lengthof(deltatktbl);
488 
489 static const datetkn *datecache[MAXDATEFIELDS] = {NULL};
490 
491 static const datetkn *deltacache[MAXDATEFIELDS] = {NULL};
492 
493 char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
494 
495 char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", NULL};
496 
497 char *pgtypes_date_weekdays_short[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL};
498 
499 char *pgtypes_date_months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", NULL};
500 
501 static const datetkn *
502 datebsearch(const char *key, const datetkn *base, unsigned int nel)
503 {
504  if (nel > 0)
505  {
506  const datetkn *last = base + nel - 1,
507  *position;
508  int result;
509 
510  while (last >= base)
511  {
512  position = base + ((last - base) >> 1);
513  /* precheck the first character for a bit of extra speed */
514  result = (int) key[0] - (int) position->token[0];
515  if (result == 0)
516  {
517  /* use strncmp so that we match truncated tokens */
518  result = strncmp(key, position->token, TOKMAXLEN);
519  if (result == 0)
520  return position;
521  }
522  if (result < 0)
523  last = position - 1;
524  else
525  base = position + 1;
526  }
527  }
528  return NULL;
529 }
530 
531 /* DecodeUnits()
532  * Decode text string using lookup table.
533  * This routine supports time interval decoding.
534  */
535 int
536 DecodeUnits(int field, char *lowtoken, int *val)
537 {
538  int type;
539  const datetkn *tp;
540 
541  /* use strncmp so that we match truncated tokens */
542  if (deltacache[field] != NULL &&
543  strncmp(lowtoken, deltacache[field]->token, TOKMAXLEN) == 0)
544  tp = deltacache[field];
545  else
546  tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
547  deltacache[field] = tp;
548  if (tp == NULL)
549  {
550  type = UNKNOWN_FIELD;
551  *val = 0;
552  }
553  else
554  {
555  type = tp->type;
556  *val = tp->value;
557  }
558 
559  return type;
560 } /* DecodeUnits() */
561 
562 /*
563  * Calendar time to Julian date conversions.
564  * Julian date is commonly used in astronomical applications,
565  * since it is numerically accurate and computationally simple.
566  * The algorithms here will accurately convert between Julian day
567  * and calendar date for all non-negative Julian days
568  * (i.e. from Nov 24, -4713 on).
569  *
570  * These routines will be used by other date/time packages
571  * - thomas 97/02/25
572  *
573  * Rewritten to eliminate overflow problems. This now allows the
574  * routines to work correctly for all Julian day counts from
575  * 0 to 2147483647 (Nov 24, -4713 to Jun 3, 5874898) assuming
576  * a 32-bit integer. Longer types should also work to the limits
577  * of their precision.
578  */
579 
580 int
581 date2j(int y, int m, int d)
582 {
583  int julian;
584  int century;
585 
586  if (m > 2)
587  {
588  m += 1;
589  y += 4800;
590  }
591  else
592  {
593  m += 13;
594  y += 4799;
595  }
596 
597  century = y / 100;
598  julian = y * 365 - 32167;
599  julian += y / 4 - century + century / 4;
600  julian += 7834 * m / 256 + d;
601 
602  return julian;
603 } /* date2j() */
604 
605 void
606 j2date(int jd, int *year, int *month, int *day)
607 {
608  unsigned int julian;
609  unsigned int quad;
610  unsigned int extra;
611  int y;
612 
613  julian = jd;
614  julian += 32044;
615  quad = julian / 146097;
616  extra = (julian - quad * 146097) * 4 + 3;
617  julian += 60 + quad * 3 + extra / 146097;
618  quad = julian / 1461;
619  julian -= quad * 1461;
620  y = julian * 4 / 1461;
621  julian = ((y != 0) ? (julian + 305) % 365 : (julian + 306) % 366) + 123;
622  y += quad * 4;
623  *year = y - 4800;
624  quad = julian * 2141 / 65536;
625  *day = julian - 7834 * quad / 256;
626  *month = (quad + 10) % 12 + 1;
627 } /* j2date() */
628 
629 /* DecodeSpecial()
630  * Decode text string using lookup table.
631  * Implement a cache lookup since it is likely that dates
632  * will be related in format.
633  */
634 static int
635 DecodeSpecial(int field, char *lowtoken, int *val)
636 {
637  int type;
638  const datetkn *tp;
639 
640  /* use strncmp so that we match truncated tokens */
641  if (datecache[field] != NULL &&
642  strncmp(lowtoken, datecache[field]->token, TOKMAXLEN) == 0)
643  tp = datecache[field];
644  else
645  {
646  tp = NULL;
647  if (!tp)
648  tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
649  }
650  datecache[field] = tp;
651  if (tp == NULL)
652  {
653  type = UNKNOWN_FIELD;
654  *val = 0;
655  }
656  else
657  {
658  type = tp->type;
659  *val = tp->value;
660  }
661 
662  return type;
663 } /* DecodeSpecial() */
664 
665 /* EncodeDateOnly()
666  * Encode date as local time.
667  */
668 void
669 EncodeDateOnly(struct tm *tm, int style, char *str, bool EuroDates)
670 {
671  Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
672 
673  switch (style)
674  {
675  case USE_ISO_DATES:
676  /* compatible with ISO date formats */
677  if (tm->tm_year > 0)
678  sprintf(str, "%04d-%02d-%02d",
679  tm->tm_year, tm->tm_mon, tm->tm_mday);
680  else
681  sprintf(str, "%04d-%02d-%02d %s",
682  -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
683  break;
684 
685  case USE_SQL_DATES:
686  /* compatible with Oracle/Ingres date formats */
687  if (EuroDates)
688  sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
689  else
690  sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
691  if (tm->tm_year > 0)
692  sprintf(str + 5, "/%04d", tm->tm_year);
693  else
694  sprintf(str + 5, "/%04d %s", -(tm->tm_year - 1), "BC");
695  break;
696 
697  case USE_GERMAN_DATES:
698  /* German-style date format */
699  sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
700  if (tm->tm_year > 0)
701  sprintf(str + 5, ".%04d", tm->tm_year);
702  else
703  sprintf(str + 5, ".%04d %s", -(tm->tm_year - 1), "BC");
704  break;
705 
706  case USE_POSTGRES_DATES:
707  default:
708  /* traditional date-only style for Postgres */
709  if (EuroDates)
710  sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
711  else
712  sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
713  if (tm->tm_year > 0)
714  sprintf(str + 5, "-%04d", tm->tm_year);
715  else
716  sprintf(str + 5, "-%04d %s", -(tm->tm_year - 1), "BC");
717  break;
718  }
719 }
720 
721 void
723 {
724  int len = strlen(str);
725 
726  /* chop off trailing zeros... but leave at least 2 fractional digits */
727  while (*(str + len - 1) == '0' && *(str + len - 3) != '.')
728  {
729  len--;
730  *(str + len) = '\0';
731  }
732 }
733 
734 /* EncodeDateTime()
735  * Encode date and time interpreted as local time.
736  *
737  * tm and fsec are the value to encode, print_tz determines whether to include
738  * a time zone (the difference between timestamp and timestamptz types), tz is
739  * the numeric time zone offset, tzn is the textual time zone, which if
740  * specified will be used instead of tz by some styles, style is the date
741  * style, str is where to write the output.
742  *
743  * Supported date styles:
744  * Postgres - day mon hh:mm:ss yyyy tz
745  * SQL - mm/dd/yyyy hh:mm:ss.ss tz
746  * ISO - yyyy-mm-dd hh:mm:ss+/-tz
747  * German - dd.mm.yyyy hh:mm:ss tz
748  * Variants (affects order of month and day for Postgres and SQL styles):
749  * US - mm/dd/yyyy
750  * European - dd/mm/yyyy
751  */
752 void
753 EncodeDateTime(struct tm *tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str, bool EuroDates)
754 {
755  int day,
756  hour,
757  min;
758 
759  /*
760  * Negative tm_isdst means we have no valid time zone translation.
761  */
762  if (tm->tm_isdst < 0)
763  print_tz = false;
764 
765  switch (style)
766  {
767  case USE_ISO_DATES:
768  /* Compatible with ISO-8601 date formats */
769 
770  sprintf(str, "%04d-%02d-%02d %02d:%02d",
771  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
772  tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
773 
774  /*
775  * Print fractional seconds if any. The field widths here should
776  * be at least equal to MAX_TIMESTAMP_PRECISION.
777  */
778  if (fsec != 0)
779  {
780  sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
781  TrimTrailingZeros(str);
782  }
783  else
784  sprintf(str + strlen(str), ":%02d", tm->tm_sec);
785 
786  if (tm->tm_year <= 0)
787  sprintf(str + strlen(str), " BC");
788 
789  if (print_tz)
790  {
791  hour = -(tz / SECS_PER_HOUR);
792  min = (abs(tz) / MINS_PER_HOUR) % MINS_PER_HOUR;
793  if (min != 0)
794  sprintf(str + strlen(str), "%+03d:%02d", hour, min);
795  else
796  sprintf(str + strlen(str), "%+03d", hour);
797  }
798  break;
799 
800  case USE_SQL_DATES:
801  /* Compatible with Oracle/Ingres date formats */
802 
803  if (EuroDates)
804  sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
805  else
806  sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
807 
808  sprintf(str + 5, "/%04d %02d:%02d",
809  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
810  tm->tm_hour, tm->tm_min);
811 
812  /*
813  * Print fractional seconds if any. The field widths here should
814  * be at least equal to MAX_TIMESTAMP_PRECISION.
815  */
816  if (fsec != 0)
817  {
818  sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
819  TrimTrailingZeros(str);
820  }
821  else
822  sprintf(str + strlen(str), ":%02d", tm->tm_sec);
823 
824  if (tm->tm_year <= 0)
825  sprintf(str + strlen(str), " BC");
826 
827  /*
828  * Note: the uses of %.*s in this function would be risky if the
829  * timezone names ever contain non-ASCII characters. However, all
830  * TZ abbreviations in the IANA database are plain ASCII.
831  */
832 
833  if (print_tz)
834  {
835  if (tzn)
836  sprintf(str + strlen(str), " %.*s", MAXTZLEN, tzn);
837  else
838  {
839  hour = -(tz / SECS_PER_HOUR);
840  min = (abs(tz) / MINS_PER_HOUR) % MINS_PER_HOUR;
841  if (min != 0)
842  sprintf(str + strlen(str), "%+03d:%02d", hour, min);
843  else
844  sprintf(str + strlen(str), "%+03d", hour);
845  }
846  }
847  break;
848 
849  case USE_GERMAN_DATES:
850  /* German variant on European style */
851 
852  sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
853 
854  sprintf(str + 5, ".%04d %02d:%02d",
855  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1),
856  tm->tm_hour, tm->tm_min);
857 
858  /*
859  * Print fractional seconds if any. The field widths here should
860  * be at least equal to MAX_TIMESTAMP_PRECISION.
861  */
862  if (fsec != 0)
863  {
864  sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
865  TrimTrailingZeros(str);
866  }
867  else
868  sprintf(str + strlen(str), ":%02d", tm->tm_sec);
869 
870  if (tm->tm_year <= 0)
871  sprintf(str + strlen(str), " BC");
872 
873  if (print_tz)
874  {
875  if (tzn)
876  sprintf(str + strlen(str), " %.*s", MAXTZLEN, tzn);
877  else
878  {
879  hour = -(tz / SECS_PER_HOUR);
880  min = (abs(tz) / MINS_PER_HOUR) % MINS_PER_HOUR;
881  if (min != 0)
882  sprintf(str + strlen(str), "%+03d:%02d", hour, min);
883  else
884  sprintf(str + strlen(str), "%+03d", hour);
885  }
886  }
887  break;
888 
889  case USE_POSTGRES_DATES:
890  default:
891  /* Backward-compatible with traditional Postgres abstime dates */
892 
893  day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
894  tm->tm_wday = (int) ((day + date2j(2000, 1, 1) + 1) % 7);
895 
896  memcpy(str, days[tm->tm_wday], 3);
897  strcpy(str + 3, " ");
898 
899  if (EuroDates)
900  sprintf(str + 4, "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
901  else
902  sprintf(str + 4, "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);
903 
904  sprintf(str + 10, " %02d:%02d", tm->tm_hour, tm->tm_min);
905 
906  /*
907  * Print fractional seconds if any. The field widths here should
908  * be at least equal to MAX_TIMESTAMP_PRECISION.
909  */
910  if (fsec != 0)
911  {
912  sprintf(str + strlen(str), ":%02d.%06d", tm->tm_sec, fsec);
913  TrimTrailingZeros(str);
914  }
915  else
916  sprintf(str + strlen(str), ":%02d", tm->tm_sec);
917 
918  sprintf(str + strlen(str), " %04d",
919  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1));
920  if (tm->tm_year <= 0)
921  sprintf(str + strlen(str), " BC");
922 
923  if (print_tz)
924  {
925  if (tzn)
926  sprintf(str + strlen(str), " %.*s", MAXTZLEN, tzn);
927  else
928  {
929  /*
930  * We have a time zone, but no string version. Use the
931  * numeric form, but be sure to include a leading space to
932  * avoid formatting something which would be rejected by
933  * the date/time parser later. - thomas 2001-10-19
934  */
935  hour = -(tz / SECS_PER_HOUR);
936  min = (abs(tz) / MINS_PER_HOUR) % MINS_PER_HOUR;
937  if (min != 0)
938  sprintf(str + strlen(str), " %+03d:%02d", hour, min);
939  else
940  sprintf(str + strlen(str), " %+03d", hour);
941  }
942  }
943  break;
944  }
945 }
946 
947 int
949 {
950  struct tm *t0;
951  time_t epoch = 0;
952 
953  t0 = gmtime(&epoch);
954 
955  if (t0)
956  {
957  tm->tm_year = t0->tm_year + 1900;
958  tm->tm_mon = t0->tm_mon + 1;
959  tm->tm_mday = t0->tm_mday;
960  tm->tm_hour = t0->tm_hour;
961  tm->tm_min = t0->tm_min;
962  tm->tm_sec = t0->tm_sec;
963 
964  return 0;
965  }
966 
967  return -1;
968 } /* GetEpochTime() */
969 
970 static void
971 abstime2tm(AbsoluteTime _time, int *tzp, struct tm *tm, char **tzn)
972 {
973  time_t time = (time_t) _time;
974  struct tm *tx;
975 
976  errno = 0;
977  if (tzp != NULL)
978  tx = localtime((time_t *) &time);
979  else
980  tx = gmtime((time_t *) &time);
981 
982  if (!tx)
983  {
984  errno = PGTYPES_TS_BAD_TIMESTAMP;
985  return;
986  }
987 
988  tm->tm_year = tx->tm_year + 1900;
989  tm->tm_mon = tx->tm_mon + 1;
990  tm->tm_mday = tx->tm_mday;
991  tm->tm_hour = tx->tm_hour;
992  tm->tm_min = tx->tm_min;
993  tm->tm_sec = tx->tm_sec;
994  tm->tm_isdst = tx->tm_isdst;
995 
996 #if defined(HAVE_STRUCT_TM_TM_ZONE)
997  tm->tm_gmtoff = tx->tm_gmtoff;
998  tm->tm_zone = tx->tm_zone;
999 
1000  if (tzp != NULL)
1001  {
1002  /*
1003  * We have a brute force time zone per SQL99? Then use it without
1004  * change since we have already rotated to the time zone.
1005  */
1006  *tzp = -tm->tm_gmtoff; /* tm_gmtoff is Sun/DEC-ism */
1007 
1008  /*
1009  * FreeBSD man pages indicate that this should work - tgl 97/04/23
1010  */
1011  if (tzn != NULL)
1012  {
1013  /*
1014  * Copy no more than MAXTZLEN bytes of timezone to tzn, in case it
1015  * contains an error message, which doesn't fit in the buffer
1016  */
1017  StrNCpy(*tzn, tm->tm_zone, MAXTZLEN + 1);
1018  if (strlen(tm->tm_zone) > MAXTZLEN)
1019  tm->tm_isdst = -1;
1020  }
1021  }
1022  else
1023  tm->tm_isdst = -1;
1024 #elif defined(HAVE_INT_TIMEZONE)
1025  if (tzp != NULL)
1026  {
1027  *tzp = (tm->tm_isdst > 0) ? TIMEZONE_GLOBAL - SECS_PER_HOUR : TIMEZONE_GLOBAL;
1028 
1029  if (tzn != NULL)
1030  {
1031  /*
1032  * Copy no more than MAXTZLEN bytes of timezone to tzn, in case it
1033  * contains an error message, which doesn't fit in the buffer
1034  */
1035  StrNCpy(*tzn, TZNAME_GLOBAL[tm->tm_isdst], MAXTZLEN + 1);
1036  if (strlen(TZNAME_GLOBAL[tm->tm_isdst]) > MAXTZLEN)
1037  tm->tm_isdst = -1;
1038  }
1039  }
1040  else
1041  tm->tm_isdst = -1;
1042 #else /* not (HAVE_STRUCT_TM_TM_ZONE || HAVE_INT_TIMEZONE) */
1043  if (tzp != NULL)
1044  {
1045  /* default to UTC */
1046  *tzp = 0;
1047  if (tzn != NULL)
1048  *tzn = NULL;
1049  }
1050  else
1051  tm->tm_isdst = -1;
1052 #endif
1053 }
1054 
1055 void
1057 {
1058  int tz;
1059 
1060  abstime2tm(time(NULL), &tz, tm, NULL);
1061 }
1062 
1063 void
1064 dt2time(double jd, int *hour, int *min, int *sec, fsec_t *fsec)
1065 {
1066  int64 time;
1067 
1068  time = jd;
1069  *hour = time / USECS_PER_HOUR;
1070  time -= (*hour) * USECS_PER_HOUR;
1071  *min = time / USECS_PER_MINUTE;
1072  time -= (*min) * USECS_PER_MINUTE;
1073  *sec = time / USECS_PER_SEC;
1074  *fsec = time - (*sec * USECS_PER_SEC);
1075 } /* dt2time() */
1076 
1077 
1078 
1079 /* DecodeNumberField()
1080  * Interpret numeric string as a concatenated date or time field.
1081  * Use the context of previously decoded fields to help with
1082  * the interpretation.
1083  */
1084 static int
1085 DecodeNumberField(int len, char *str, int fmask,
1086  int *tmask, struct tm *tm, fsec_t *fsec, bool *is2digits)
1087 {
1088  char *cp;
1089 
1090  /*
1091  * Have a decimal point? Then this is a date or something with a seconds
1092  * field...
1093  */
1094  if ((cp = strchr(str, '.')) != NULL)
1095  {
1096  char fstr[7];
1097  int i;
1098 
1099  cp++;
1100 
1101  /*
1102  * OK, we have at most six digits to care about. Let's construct a
1103  * string with those digits, zero-padded on the right, and then do the
1104  * conversion to an integer.
1105  *
1106  * XXX This truncates the seventh digit, unlike rounding it as the
1107  * backend does.
1108  */
1109  for (i = 0; i < 6; i++)
1110  fstr[i] = *cp != '\0' ? *cp++ : '0';
1111  fstr[i] = '\0';
1112  *fsec = strtoint(fstr, NULL, 10);
1113  *cp = '\0';
1114  len = strlen(str);
1115  }
1116  /* No decimal point and no complete date yet? */
1117  else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1118  {
1119  /* yyyymmdd? */
1120  if (len == 8)
1121  {
1122  *tmask = DTK_DATE_M;
1123 
1124  tm->tm_mday = atoi(str + 6);
1125  *(str + 6) = '\0';
1126  tm->tm_mon = atoi(str + 4);
1127  *(str + 4) = '\0';
1128  tm->tm_year = atoi(str + 0);
1129 
1130  return DTK_DATE;
1131  }
1132  /* yymmdd? */
1133  else if (len == 6)
1134  {
1135  *tmask = DTK_DATE_M;
1136  tm->tm_mday = atoi(str + 4);
1137  *(str + 4) = '\0';
1138  tm->tm_mon = atoi(str + 2);
1139  *(str + 2) = '\0';
1140  tm->tm_year = atoi(str + 0);
1141  *is2digits = true;
1142 
1143  return DTK_DATE;
1144  }
1145  /* yyddd? */
1146  else if (len == 5)
1147  {
1148  *tmask = DTK_DATE_M;
1149  tm->tm_mday = atoi(str + 2);
1150  *(str + 2) = '\0';
1151  tm->tm_mon = 1;
1152  tm->tm_year = atoi(str + 0);
1153  *is2digits = true;
1154 
1155  return DTK_DATE;
1156  }
1157  }
1158 
1159  /* not all time fields are specified? */
1160  if ((fmask & DTK_TIME_M) != DTK_TIME_M)
1161  {
1162  /* hhmmss */
1163  if (len == 6)
1164  {
1165  *tmask = DTK_TIME_M;
1166  tm->tm_sec = atoi(str + 4);
1167  *(str + 4) = '\0';
1168  tm->tm_min = atoi(str + 2);
1169  *(str + 2) = '\0';
1170  tm->tm_hour = atoi(str + 0);
1171 
1172  return DTK_TIME;
1173  }
1174  /* hhmm? */
1175  else if (len == 4)
1176  {
1177  *tmask = DTK_TIME_M;
1178  tm->tm_sec = 0;
1179  tm->tm_min = atoi(str + 2);
1180  *(str + 2) = '\0';
1181  tm->tm_hour = atoi(str + 0);
1182 
1183  return DTK_TIME;
1184  }
1185  }
1186 
1187  return -1;
1188 } /* DecodeNumberField() */
1189 
1190 
1191 /* DecodeNumber()
1192  * Interpret plain numeric field as a date value in context.
1193  */
1194 static int
1195 DecodeNumber(int flen, char *str, int fmask,
1196  int *tmask, struct tm *tm, fsec_t *fsec, bool *is2digits, bool EuroDates)
1197 {
1198  int val;
1199  char *cp;
1200 
1201  *tmask = 0;
1202 
1203  val = strtoint(str, &cp, 10);
1204  if (cp == str)
1205  return -1;
1206 
1207  if (*cp == '.')
1208  {
1209  /*
1210  * More than two digits? Then could be a date or a run-together time:
1211  * 2001.360 20011225 040506.789
1212  */
1213  if (cp - str > 2)
1214  return DecodeNumberField(flen, str, (fmask | DTK_DATE_M),
1215  tmask, tm, fsec, is2digits);
1216 
1217  *fsec = strtod(cp, &cp);
1218  if (*cp != '\0')
1219  return -1;
1220  }
1221  else if (*cp != '\0')
1222  return -1;
1223 
1224  /* Special case day of year? */
1225  if (flen == 3 && (fmask & DTK_M(YEAR)) && val >= 1 && val <= 366)
1226  {
1227  *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
1228  tm->tm_yday = val;
1229  j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
1230  &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1231  }
1232 
1233  /***
1234  * Enough digits to be unequivocal year? Used to test for 4 digits or
1235  * more, but we now test first for a three-digit doy so anything
1236  * bigger than two digits had better be an explicit year.
1237  * - thomas 1999-01-09
1238  * Back to requiring a 4 digit year. We accept a two digit
1239  * year farther down. - thomas 2000-03-28
1240  ***/
1241  else if (flen >= 4)
1242  {
1243  *tmask = DTK_M(YEAR);
1244 
1245  /* already have a year? then see if we can substitute... */
1246  if ((fmask & DTK_M(YEAR)) && !(fmask & DTK_M(DAY)) &&
1247  tm->tm_year >= 1 && tm->tm_year <= 31)
1248  {
1249  tm->tm_mday = tm->tm_year;
1250  *tmask = DTK_M(DAY);
1251  }
1252 
1253  tm->tm_year = val;
1254  }
1255 
1256  /* already have year? then could be month */
1257  else if ((fmask & DTK_M(YEAR)) && !(fmask & DTK_M(MONTH)) && val >= 1 && val <= MONTHS_PER_YEAR)
1258  {
1259  *tmask = DTK_M(MONTH);
1260  tm->tm_mon = val;
1261  }
1262  /* no year and EuroDates enabled? then could be day */
1263  else if ((EuroDates || (fmask & DTK_M(MONTH))) &&
1264  !(fmask & DTK_M(YEAR)) && !(fmask & DTK_M(DAY)) &&
1265  val >= 1 && val <= 31)
1266  {
1267  *tmask = DTK_M(DAY);
1268  tm->tm_mday = val;
1269  }
1270  else if (!(fmask & DTK_M(MONTH)) && val >= 1 && val <= MONTHS_PER_YEAR)
1271  {
1272  *tmask = DTK_M(MONTH);
1273  tm->tm_mon = val;
1274  }
1275  else if (!(fmask & DTK_M(DAY)) && val >= 1 && val <= 31)
1276  {
1277  *tmask = DTK_M(DAY);
1278  tm->tm_mday = val;
1279  }
1280 
1281  /*
1282  * Check for 2 or 4 or more digits, but currently we reach here only if
1283  * two digits. - thomas 2000-03-28
1284  */
1285  else if (!(fmask & DTK_M(YEAR)) && (flen >= 4 || flen == 2))
1286  {
1287  *tmask = DTK_M(YEAR);
1288  tm->tm_year = val;
1289 
1290  /* adjust ONLY if exactly two digits... */
1291  *is2digits = (flen == 2);
1292  }
1293  else
1294  return -1;
1295 
1296  return 0;
1297 } /* DecodeNumber() */
1298 
1299 /* DecodeDate()
1300  * Decode date string which includes delimiters.
1301  * Insist on a complete set of fields.
1302  */
1303 static int
1304 DecodeDate(char *str, int fmask, int *tmask, struct tm *tm, bool EuroDates)
1305 {
1306  fsec_t fsec;
1307 
1308  int nf = 0;
1309  int i,
1310  len;
1311  bool bc = false;
1312  bool is2digits = false;
1313  int type,
1314  val,
1315  dmask = 0;
1316  char *field[MAXDATEFIELDS];
1317 
1318  /* parse this string... */
1319  while (*str != '\0' && nf < MAXDATEFIELDS)
1320  {
1321  /* skip field separators */
1322  while (!isalnum((unsigned char) *str))
1323  str++;
1324 
1325  field[nf] = str;
1326  if (isdigit((unsigned char) *str))
1327  {
1328  while (isdigit((unsigned char) *str))
1329  str++;
1330  }
1331  else if (isalpha((unsigned char) *str))
1332  {
1333  while (isalpha((unsigned char) *str))
1334  str++;
1335  }
1336 
1337  /* Just get rid of any non-digit, non-alpha characters... */
1338  if (*str != '\0')
1339  *str++ = '\0';
1340  nf++;
1341  }
1342 
1343 #if 0
1344  /* don't allow too many fields */
1345  if (nf > 3)
1346  return -1;
1347 #endif
1348 
1349  *tmask = 0;
1350 
1351  /* look first for text fields, since that will be unambiguous month */
1352  for (i = 0; i < nf; i++)
1353  {
1354  if (isalpha((unsigned char) *field[i]))
1355  {
1356  type = DecodeSpecial(i, field[i], &val);
1357  if (type == IGNORE_DTF)
1358  continue;
1359 
1360  dmask = DTK_M(type);
1361  switch (type)
1362  {
1363  case MONTH:
1364  tm->tm_mon = val;
1365  break;
1366 
1367  case ADBC:
1368  bc = (val == BC);
1369  break;
1370 
1371  default:
1372  return -1;
1373  }
1374  if (fmask & dmask)
1375  return -1;
1376 
1377  fmask |= dmask;
1378  *tmask |= dmask;
1379 
1380  /* mark this field as being completed */
1381  field[i] = NULL;
1382  }
1383  }
1384 
1385  /* now pick up remaining numeric fields */
1386  for (i = 0; i < nf; i++)
1387  {
1388  if (field[i] == NULL)
1389  continue;
1390 
1391  if ((len = strlen(field[i])) <= 0)
1392  return -1;
1393 
1394  if (DecodeNumber(len, field[i], fmask, &dmask, tm, &fsec, &is2digits, EuroDates) != 0)
1395  return -1;
1396 
1397  if (fmask & dmask)
1398  return -1;
1399 
1400  fmask |= dmask;
1401  *tmask |= dmask;
1402  }
1403 
1404  if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
1405  return -1;
1406 
1407  /* there is no year zero in AD/BC notation; i.e. "1 BC" == year 0 */
1408  if (bc)
1409  {
1410  if (tm->tm_year > 0)
1411  tm->tm_year = -(tm->tm_year - 1);
1412  else
1413  return -1;
1414  }
1415  else if (is2digits)
1416  {
1417  if (tm->tm_year < 70)
1418  tm->tm_year += 2000;
1419  else if (tm->tm_year < 100)
1420  tm->tm_year += 1900;
1421  }
1422 
1423  return 0;
1424 } /* DecodeDate() */
1425 
1426 
1427 /* DecodeTime()
1428  * Decode time string which includes delimiters.
1429  * Only check the lower limit on hours, since this same code
1430  * can be used to represent time spans.
1431  */
1432 int
1433 DecodeTime(char *str, int *tmask, struct tm *tm, fsec_t *fsec)
1434 {
1435  char *cp;
1436 
1437  *tmask = DTK_TIME_M;
1438 
1439  tm->tm_hour = strtoint(str, &cp, 10);
1440  if (*cp != ':')
1441  return -1;
1442  str = cp + 1;
1443  tm->tm_min = strtoint(str, &cp, 10);
1444  if (*cp == '\0')
1445  {
1446  tm->tm_sec = 0;
1447  *fsec = 0;
1448  }
1449  else if (*cp != ':')
1450  return -1;
1451  else
1452  {
1453  str = cp + 1;
1454  tm->tm_sec = strtoint(str, &cp, 10);
1455  if (*cp == '\0')
1456  *fsec = 0;
1457  else if (*cp == '.')
1458  {
1459  char fstr[7];
1460  int i;
1461 
1462  cp++;
1463 
1464  /*
1465  * OK, we have at most six digits to care about. Let's construct a
1466  * string with those digits, zero-padded on the right, and then do
1467  * the conversion to an integer.
1468  *
1469  * XXX This truncates the seventh digit, unlike rounding it as the
1470  * backend does.
1471  */
1472  for (i = 0; i < 6; i++)
1473  fstr[i] = *cp != '\0' ? *cp++ : '0';
1474  fstr[i] = '\0';
1475  *fsec = strtoint(fstr, &cp, 10);
1476  if (*cp != '\0')
1477  return -1;
1478  }
1479  else
1480  return -1;
1481  }
1482 
1483  /* do a sanity check */
1484  if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_min > 59 ||
1485  tm->tm_sec < 0 || tm->tm_sec > 59 || *fsec >= USECS_PER_SEC)
1486  return -1;
1487 
1488  return 0;
1489 } /* DecodeTime() */
1490 
1491 /* DecodeTimezone()
1492  * Interpret string as a numeric timezone.
1493  *
1494  * Note: we allow timezone offsets up to 13:59. There are places that
1495  * use +1300 summer time.
1496  */
1497 static int
1498 DecodeTimezone(char *str, int *tzp)
1499 {
1500  int tz;
1501  int hr,
1502  min;
1503  char *cp;
1504  int len;
1505 
1506  /* assume leading character is "+" or "-" */
1507  hr = strtoint(str + 1, &cp, 10);
1508 
1509  /* explicit delimiter? */
1510  if (*cp == ':')
1511  min = strtoint(cp + 1, &cp, 10);
1512  /* otherwise, might have run things together... */
1513  else if (*cp == '\0' && (len = strlen(str)) > 3)
1514  {
1515  min = strtoint(str + len - 2, &cp, 10);
1516  if (min < 0 || min >= 60)
1517  return -1;
1518 
1519  *(str + len - 2) = '\0';
1520  hr = strtoint(str + 1, &cp, 10);
1521  if (hr < 0 || hr > 13)
1522  return -1;
1523  }
1524  else
1525  min = 0;
1526 
1527  tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE;
1528  if (*str == '-')
1529  tz = -tz;
1530 
1531  *tzp = -tz;
1532  return *cp != '\0';
1533 } /* DecodeTimezone() */
1534 
1535 
1536 /* DecodePosixTimezone()
1537  * Interpret string as a POSIX-compatible timezone:
1538  * PST-hh:mm
1539  * PST+h
1540  * - thomas 2000-03-15
1541  */
1542 static int
1543 DecodePosixTimezone(char *str, int *tzp)
1544 {
1545  int val,
1546  tz;
1547  int type;
1548  char *cp;
1549  char delim;
1550 
1551  cp = str;
1552  while (*cp != '\0' && isalpha((unsigned char) *cp))
1553  cp++;
1554 
1555  if (DecodeTimezone(cp, &tz) != 0)
1556  return -1;
1557 
1558  delim = *cp;
1559  *cp = '\0';
1560  type = DecodeSpecial(MAXDATEFIELDS - 1, str, &val);
1561  *cp = delim;
1562 
1563  switch (type)
1564  {
1565  case DTZ:
1566  case TZ:
1567  *tzp = -(val + tz);
1568  break;
1569 
1570  default:
1571  return -1;
1572  }
1573 
1574  return 0;
1575 } /* DecodePosixTimezone() */
1576 
1577 /* ParseDateTime()
1578  * Break string into tokens based on a date/time context.
1579  * Several field types are assigned:
1580  * DTK_NUMBER - digits and (possibly) a decimal point
1581  * DTK_DATE - digits and two delimiters, or digits and text
1582  * DTK_TIME - digits, colon delimiters, and possibly a decimal point
1583  * DTK_STRING - text (no digits)
1584  * DTK_SPECIAL - leading "+" or "-" followed by text
1585  * DTK_TZ - leading "+" or "-" followed by digits
1586  * Note that some field types can hold unexpected items:
1587  * DTK_NUMBER can hold date fields (yy.ddd)
1588  * DTK_STRING can hold months (January) and time zones (PST)
1589  * DTK_DATE can hold Posix time zones (GMT-8)
1590  *
1591  * The "lowstr" work buffer must have at least strlen(timestr) + MAXDATEFIELDS
1592  * bytes of space. On output, field[] entries will point into it.
1593  * The field[] and ftype[] arrays must have at least MAXDATEFIELDS entries.
1594  */
1595 int
1596 ParseDateTime(char *timestr, char *lowstr,
1597  char **field, int *ftype, int *numfields, char **endstr)
1598 {
1599  int nf = 0;
1600  char *lp = lowstr;
1601 
1602  *endstr = timestr;
1603  /* outer loop through fields */
1604  while (*(*endstr) != '\0')
1605  {
1606  /* Record start of current field */
1607  if (nf >= MAXDATEFIELDS)
1608  return -1;
1609  field[nf] = lp;
1610 
1611  /* leading digit? then date or time */
1612  if (isdigit((unsigned char) *(*endstr)))
1613  {
1614  *lp++ = *(*endstr)++;
1615  while (isdigit((unsigned char) *(*endstr)))
1616  *lp++ = *(*endstr)++;
1617 
1618  /* time field? */
1619  if (*(*endstr) == ':')
1620  {
1621  ftype[nf] = DTK_TIME;
1622  *lp++ = *(*endstr)++;
1623  while (isdigit((unsigned char) *(*endstr)) ||
1624  (*(*endstr) == ':') || (*(*endstr) == '.'))
1625  *lp++ = *(*endstr)++;
1626  }
1627  /* date field? allow embedded text month */
1628  else if (*(*endstr) == '-' || *(*endstr) == '/' || *(*endstr) == '.')
1629  {
1630  /* save delimiting character to use later */
1631  char *dp = (*endstr);
1632 
1633  *lp++ = *(*endstr)++;
1634  /* second field is all digits? then no embedded text month */
1635  if (isdigit((unsigned char) *(*endstr)))
1636  {
1637  ftype[nf] = (*dp == '.') ? DTK_NUMBER : DTK_DATE;
1638  while (isdigit((unsigned char) *(*endstr)))
1639  *lp++ = *(*endstr)++;
1640 
1641  /*
1642  * insist that the delimiters match to get a three-field
1643  * date.
1644  */
1645  if (*(*endstr) == *dp)
1646  {
1647  ftype[nf] = DTK_DATE;
1648  *lp++ = *(*endstr)++;
1649  while (isdigit((unsigned char) *(*endstr)) || (*(*endstr) == *dp))
1650  *lp++ = *(*endstr)++;
1651  }
1652  }
1653  else
1654  {
1655  ftype[nf] = DTK_DATE;
1656  while (isalnum((unsigned char) *(*endstr)) || (*(*endstr) == *dp))
1657  *lp++ = pg_tolower((unsigned char) *(*endstr)++);
1658  }
1659  }
1660 
1661  /*
1662  * otherwise, number only and will determine year, month, day, or
1663  * concatenated fields later...
1664  */
1665  else
1666  ftype[nf] = DTK_NUMBER;
1667  }
1668  /* Leading decimal point? Then fractional seconds... */
1669  else if (*(*endstr) == '.')
1670  {
1671  *lp++ = *(*endstr)++;
1672  while (isdigit((unsigned char) *(*endstr)))
1673  *lp++ = *(*endstr)++;
1674 
1675  ftype[nf] = DTK_NUMBER;
1676  }
1677 
1678  /*
1679  * text? then date string, month, day of week, special, or timezone
1680  */
1681  else if (isalpha((unsigned char) *(*endstr)))
1682  {
1683  ftype[nf] = DTK_STRING;
1684  *lp++ = pg_tolower((unsigned char) *(*endstr)++);
1685  while (isalpha((unsigned char) *(*endstr)))
1686  *lp++ = pg_tolower((unsigned char) *(*endstr)++);
1687 
1688  /*
1689  * Full date string with leading text month? Could also be a POSIX
1690  * time zone...
1691  */
1692  if (*(*endstr) == '-' || *(*endstr) == '/' || *(*endstr) == '.')
1693  {
1694  char *dp = (*endstr);
1695 
1696  ftype[nf] = DTK_DATE;
1697  *lp++ = *(*endstr)++;
1698  while (isdigit((unsigned char) *(*endstr)) || *(*endstr) == *dp)
1699  *lp++ = *(*endstr)++;
1700  }
1701  }
1702  /* skip leading spaces */
1703  else if (isspace((unsigned char) *(*endstr)))
1704  {
1705  (*endstr)++;
1706  continue;
1707  }
1708  /* sign? then special or numeric timezone */
1709  else if (*(*endstr) == '+' || *(*endstr) == '-')
1710  {
1711  *lp++ = *(*endstr)++;
1712  /* soak up leading whitespace */
1713  while (isspace((unsigned char) *(*endstr)))
1714  (*endstr)++;
1715  /* numeric timezone? */
1716  if (isdigit((unsigned char) *(*endstr)))
1717  {
1718  ftype[nf] = DTK_TZ;
1719  *lp++ = *(*endstr)++;
1720  while (isdigit((unsigned char) *(*endstr)) ||
1721  (*(*endstr) == ':') || (*(*endstr) == '.'))
1722  *lp++ = *(*endstr)++;
1723  }
1724  /* special? */
1725  else if (isalpha((unsigned char) *(*endstr)))
1726  {
1727  ftype[nf] = DTK_SPECIAL;
1728  *lp++ = pg_tolower((unsigned char) *(*endstr)++);
1729  while (isalpha((unsigned char) *(*endstr)))
1730  *lp++ = pg_tolower((unsigned char) *(*endstr)++);
1731  }
1732  /* otherwise something wrong... */
1733  else
1734  return -1;
1735  }
1736  /* ignore punctuation but use as delimiter */
1737  else if (ispunct((unsigned char) *(*endstr)))
1738  {
1739  (*endstr)++;
1740  continue;
1741 
1742  }
1743  /* otherwise, something is not right... */
1744  else
1745  return -1;
1746 
1747  /* force in a delimiter after each field */
1748  *lp++ = '\0';
1749  nf++;
1750  }
1751 
1752  *numfields = nf;
1753 
1754  return 0;
1755 } /* ParseDateTime() */
1756 
1757 
1758 /* DecodeDateTime()
1759  * Interpret previously parsed fields for general date and time.
1760  * Return 0 if full date, 1 if only time, and -1 if problems.
1761  * External format(s):
1762  * "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
1763  * "Fri Feb-7-1997 15:23:27"
1764  * "Feb-7-1997 15:23:27"
1765  * "2-7-1997 15:23:27"
1766  * "1997-2-7 15:23:27"
1767  * "1997.038 15:23:27" (day of year 1-366)
1768  * Also supports input in compact time:
1769  * "970207 152327"
1770  * "97038 152327"
1771  * "20011225T040506.789-07"
1772  *
1773  * Use the system-provided functions to get the current time zone
1774  * if not specified in the input string.
1775  * If the date is outside the time_t system-supported time range,
1776  * then assume UTC time zone. - thomas 1997-05-27
1777  */
1778 int
1779 DecodeDateTime(char **field, int *ftype, int nf,
1780  int *dtype, struct tm *tm, fsec_t *fsec, bool EuroDates)
1781 {
1782  int fmask = 0,
1783  tmask,
1784  type;
1785  int ptype = 0; /* "prefix type" for ISO y2001m02d04 format */
1786  int i;
1787  int val;
1788  int mer = HR24;
1789  bool haveTextMonth = false;
1790  bool is2digits = false;
1791  bool bc = false;
1792  int t = 0;
1793  int *tzp = &t;
1794 
1795  /***
1796  * We'll insist on at least all of the date fields, but initialize the
1797  * remaining fields in case they are not set later...
1798  ***/
1799  *dtype = DTK_DATE;
1800  tm->tm_hour = 0;
1801  tm->tm_min = 0;
1802  tm->tm_sec = 0;
1803  *fsec = 0;
1804  /* don't know daylight savings time status apriori */
1805  tm->tm_isdst = -1;
1806  if (tzp != NULL)
1807  *tzp = 0;
1808 
1809  for (i = 0; i < nf; i++)
1810  {
1811  switch (ftype[i])
1812  {
1813  case DTK_DATE:
1814  /***
1815  * Integral julian day with attached time zone?
1816  * All other forms with JD will be separated into
1817  * distinct fields, so we handle just this case here.
1818  ***/
1819  if (ptype == DTK_JULIAN)
1820  {
1821  char *cp;
1822  int val;
1823 
1824  if (tzp == NULL)
1825  return -1;
1826 
1827  val = strtoint(field[i], &cp, 10);
1828  if (*cp != '-')
1829  return -1;
1830 
1831  j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1832  /* Get the time zone from the end of the string */
1833  if (DecodeTimezone(cp, tzp) != 0)
1834  return -1;
1835 
1836  tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
1837  ptype = 0;
1838  break;
1839  }
1840  /***
1841  * Already have a date? Then this might be a POSIX time
1842  * zone with an embedded dash (e.g. "PST-3" == "EST") or
1843  * a run-together time with trailing time zone (e.g. hhmmss-zz).
1844  * - thomas 2001-12-25
1845  ***/
1846  else if (((fmask & DTK_DATE_M) == DTK_DATE_M)
1847  || (ptype != 0))
1848  {
1849  /* No time zone accepted? Then quit... */
1850  if (tzp == NULL)
1851  return -1;
1852 
1853  if (isdigit((unsigned char) *field[i]) || ptype != 0)
1854  {
1855  char *cp;
1856 
1857  if (ptype != 0)
1858  {
1859  /* Sanity check; should not fail this test */
1860  if (ptype != DTK_TIME)
1861  return -1;
1862  ptype = 0;
1863  }
1864 
1865  /*
1866  * Starts with a digit but we already have a time
1867  * field? Then we are in trouble with a date and time
1868  * already...
1869  */
1870  if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1871  return -1;
1872 
1873  if ((cp = strchr(field[i], '-')) == NULL)
1874  return -1;
1875 
1876  /* Get the time zone from the end of the string */
1877  if (DecodeTimezone(cp, tzp) != 0)
1878  return -1;
1879  *cp = '\0';
1880 
1881  /*
1882  * Then read the rest of the field as a concatenated
1883  * time
1884  */
1885  if ((ftype[i] = DecodeNumberField(strlen(field[i]), field[i], fmask,
1886  &tmask, tm, fsec, &is2digits)) < 0)
1887  return -1;
1888 
1889  /*
1890  * modify tmask after returning from
1891  * DecodeNumberField()
1892  */
1893  tmask |= DTK_M(TZ);
1894  }
1895  else
1896  {
1897  if (DecodePosixTimezone(field[i], tzp) != 0)
1898  return -1;
1899 
1900  ftype[i] = DTK_TZ;
1901  tmask = DTK_M(TZ);
1902  }
1903  }
1904  else if (DecodeDate(field[i], fmask, &tmask, tm, EuroDates) != 0)
1905  return -1;
1906  break;
1907 
1908  case DTK_TIME:
1909  if (DecodeTime(field[i], &tmask, tm, fsec) != 0)
1910  return -1;
1911 
1912  /*
1913  * Check upper limit on hours; other limits checked in
1914  * DecodeTime()
1915  */
1916  /* test for > 24:00:00 */
1917  if (tm->tm_hour > 24 ||
1918  (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0)))
1919  return -1;
1920  break;
1921 
1922  case DTK_TZ:
1923  {
1924  int tz;
1925 
1926  if (tzp == NULL)
1927  return -1;
1928 
1929  if (DecodeTimezone(field[i], &tz) != 0)
1930  return -1;
1931 
1932  /*
1933  * Already have a time zone? Then maybe this is the second
1934  * field of a POSIX time: EST+3 (equivalent to PST)
1935  */
1936  if (i > 0 && (fmask & DTK_M(TZ)) != 0 &&
1937  ftype[i - 1] == DTK_TZ &&
1938  isalpha((unsigned char) *field[i - 1]))
1939  {
1940  *tzp -= tz;
1941  tmask = 0;
1942  }
1943  else
1944  {
1945  *tzp = tz;
1946  tmask = DTK_M(TZ);
1947  }
1948  }
1949  break;
1950 
1951  case DTK_NUMBER:
1952 
1953  /*
1954  * Was this an "ISO date" with embedded field labels? An
1955  * example is "y2001m02d04" - thomas 2001-02-04
1956  */
1957  if (ptype != 0)
1958  {
1959  char *cp;
1960  int val;
1961 
1962  val = strtoint(field[i], &cp, 10);
1963 
1964  /*
1965  * only a few kinds are allowed to have an embedded
1966  * decimal
1967  */
1968  if (*cp == '.')
1969  switch (ptype)
1970  {
1971  case DTK_JULIAN:
1972  case DTK_TIME:
1973  case DTK_SECOND:
1974  break;
1975  default:
1976  return 1;
1977  break;
1978  }
1979  else if (*cp != '\0')
1980  return -1;
1981 
1982  switch (ptype)
1983  {
1984  case DTK_YEAR:
1985  tm->tm_year = val;
1986  tmask = DTK_M(YEAR);
1987  break;
1988 
1989  case DTK_MONTH:
1990 
1991  /*
1992  * already have a month and hour? then assume
1993  * minutes
1994  */
1995  if ((fmask & DTK_M(MONTH)) != 0 &&
1996  (fmask & DTK_M(HOUR)) != 0)
1997  {
1998  tm->tm_min = val;
1999  tmask = DTK_M(MINUTE);
2000  }
2001  else
2002  {
2003  tm->tm_mon = val;
2004  tmask = DTK_M(MONTH);
2005  }
2006  break;
2007 
2008  case DTK_DAY:
2009  tm->tm_mday = val;
2010  tmask = DTK_M(DAY);
2011  break;
2012 
2013  case DTK_HOUR:
2014  tm->tm_hour = val;
2015  tmask = DTK_M(HOUR);
2016  break;
2017 
2018  case DTK_MINUTE:
2019  tm->tm_min = val;
2020  tmask = DTK_M(MINUTE);
2021  break;
2022 
2023  case DTK_SECOND:
2024  tm->tm_sec = val;
2025  tmask = DTK_M(SECOND);
2026  if (*cp == '.')
2027  {
2028  double frac;
2029 
2030  frac = strtod(cp, &cp);
2031  if (*cp != '\0')
2032  return -1;
2033  *fsec = frac * 1000000;
2034  }
2035  break;
2036 
2037  case DTK_TZ:
2038  tmask = DTK_M(TZ);
2039  if (DecodeTimezone(field[i], tzp) != 0)
2040  return -1;
2041  break;
2042 
2043  case DTK_JULIAN:
2044  /***
2045  * previous field was a label for "julian date"?
2046  ***/
2047  tmask = DTK_DATE_M;
2048  j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2049  /* fractional Julian Day? */
2050  if (*cp == '.')
2051  {
2052  double time;
2053 
2054  time = strtod(cp, &cp);
2055  if (*cp != '\0')
2056  return -1;
2057 
2058  tmask |= DTK_TIME_M;
2059  dt2time((time * USECS_PER_DAY), &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
2060  }
2061  break;
2062 
2063  case DTK_TIME:
2064  /* previous field was "t" for ISO time */
2065  if ((ftype[i] = DecodeNumberField(strlen(field[i]), field[i], (fmask | DTK_DATE_M),
2066  &tmask, tm, fsec, &is2digits)) < 0)
2067  return -1;
2068 
2069  if (tmask != DTK_TIME_M)
2070  return -1;
2071  break;
2072 
2073  default:
2074  return -1;
2075  break;
2076  }
2077 
2078  ptype = 0;
2079  *dtype = DTK_DATE;
2080  }
2081  else
2082  {
2083  char *cp;
2084  int flen;
2085 
2086  flen = strlen(field[i]);
2087  cp = strchr(field[i], '.');
2088 
2089  /* Embedded decimal and no date yet? */
2090  if (cp != NULL && !(fmask & DTK_DATE_M))
2091  {
2092  if (DecodeDate(field[i], fmask, &tmask, tm, EuroDates) != 0)
2093  return -1;
2094  }
2095  /* embedded decimal and several digits before? */
2096  else if (cp != NULL && flen - strlen(cp) > 2)
2097  {
2098  /*
2099  * Interpret as a concatenated date or time Set the
2100  * type field to allow decoding other fields later.
2101  * Example: 20011223 or 040506
2102  */
2103  if ((ftype[i] = DecodeNumberField(flen, field[i], fmask,
2104  &tmask, tm, fsec, &is2digits)) < 0)
2105  return -1;
2106  }
2107  else if (flen > 4)
2108  {
2109  if ((ftype[i] = DecodeNumberField(flen, field[i], fmask,
2110  &tmask, tm, fsec, &is2digits)) < 0)
2111  return -1;
2112  }
2113  /* otherwise it is a single date/time field... */
2114  else if (DecodeNumber(flen, field[i], fmask,
2115  &tmask, tm, fsec, &is2digits, EuroDates) != 0)
2116  return -1;
2117  }
2118  break;
2119 
2120  case DTK_STRING:
2121  case DTK_SPECIAL:
2122  type = DecodeSpecial(i, field[i], &val);
2123  if (type == IGNORE_DTF)
2124  continue;
2125 
2126  tmask = DTK_M(type);
2127  switch (type)
2128  {
2129  case RESERV:
2130  switch (val)
2131  {
2132  case DTK_NOW:
2133  tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
2134  *dtype = DTK_DATE;
2135  GetCurrentDateTime(tm);
2136  break;
2137 
2138  case DTK_YESTERDAY:
2139  tmask = DTK_DATE_M;
2140  *dtype = DTK_DATE;
2141  GetCurrentDateTime(tm);
2142  j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - 1,
2143  &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2144  tm->tm_hour = 0;
2145  tm->tm_min = 0;
2146  tm->tm_sec = 0;
2147  break;
2148 
2149  case DTK_TODAY:
2150  tmask = DTK_DATE_M;
2151  *dtype = DTK_DATE;
2152  GetCurrentDateTime(tm);
2153  tm->tm_hour = 0;
2154  tm->tm_min = 0;
2155  tm->tm_sec = 0;
2156  break;
2157 
2158  case DTK_TOMORROW:
2159  tmask = DTK_DATE_M;
2160  *dtype = DTK_DATE;
2161  GetCurrentDateTime(tm);
2162  j2date(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1,
2163  &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2164  tm->tm_hour = 0;
2165  tm->tm_min = 0;
2166  tm->tm_sec = 0;
2167  break;
2168 
2169  case DTK_ZULU:
2170  tmask = (DTK_TIME_M | DTK_M(TZ));
2171  *dtype = DTK_DATE;
2172  tm->tm_hour = 0;
2173  tm->tm_min = 0;
2174  tm->tm_sec = 0;
2175  if (tzp != NULL)
2176  *tzp = 0;
2177  break;
2178 
2179  default:
2180  *dtype = val;
2181  }
2182 
2183  break;
2184 
2185  case MONTH:
2186 
2187  /*
2188  * already have a (numeric) month? then see if we can
2189  * substitute...
2190  */
2191  if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
2192  !(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 && tm->tm_mon <= 31)
2193  {
2194  tm->tm_mday = tm->tm_mon;
2195  tmask = DTK_M(DAY);
2196  }
2197  haveTextMonth = true;
2198  tm->tm_mon = val;
2199  break;
2200 
2201  case DTZMOD:
2202 
2203  /*
2204  * daylight savings time modifier (solves "MET DST"
2205  * syntax)
2206  */
2207  tmask |= DTK_M(DTZ);
2208  tm->tm_isdst = 1;
2209  if (tzp == NULL)
2210  return -1;
2211  *tzp -= val;
2212  break;
2213 
2214  case DTZ:
2215 
2216  /*
2217  * set mask for TZ here _or_ check for DTZ later when
2218  * getting default timezone
2219  */
2220  tmask |= DTK_M(TZ);
2221  tm->tm_isdst = 1;
2222  if (tzp == NULL)
2223  return -1;
2224  *tzp = -val;
2225  ftype[i] = DTK_TZ;
2226  break;
2227 
2228  case TZ:
2229  tm->tm_isdst = 0;
2230  if (tzp == NULL)
2231  return -1;
2232  *tzp = -val;
2233  ftype[i] = DTK_TZ;
2234  break;
2235 
2236  case IGNORE_DTF:
2237  break;
2238 
2239  case AMPM:
2240  mer = val;
2241  break;
2242 
2243  case ADBC:
2244  bc = (val == BC);
2245  break;
2246 
2247  case DOW:
2248  tm->tm_wday = val;
2249  break;
2250 
2251  case UNITS:
2252  tmask = 0;
2253  ptype = val;
2254  break;
2255 
2256  case ISOTIME:
2257 
2258  /*
2259  * This is a filler field "t" indicating that the next
2260  * field is time. Try to verify that this is sensible.
2261  */
2262  tmask = 0;
2263 
2264  /* No preceding date? Then quit... */
2265  if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2266  return -1;
2267 
2268  /***
2269  * We will need one of the following fields:
2270  * DTK_NUMBER should be hhmmss.fff
2271  * DTK_TIME should be hh:mm:ss.fff
2272  * DTK_DATE should be hhmmss-zz
2273  ***/
2274  if (i >= nf - 1 ||
2275  (ftype[i + 1] != DTK_NUMBER &&
2276  ftype[i + 1] != DTK_TIME &&
2277  ftype[i + 1] != DTK_DATE))
2278  return -1;
2279 
2280  ptype = val;
2281  break;
2282 
2283  default:
2284  return -1;
2285  }
2286  break;
2287 
2288  default:
2289  return -1;
2290  }
2291 
2292  if (tmask & fmask)
2293  return -1;
2294  fmask |= tmask;
2295  }
2296 
2297  /* there is no year zero in AD/BC notation; i.e. "1 BC" == year 0 */
2298  if (bc)
2299  {
2300  if (tm->tm_year > 0)
2301  tm->tm_year = -(tm->tm_year - 1);
2302  else
2303  return -1;
2304  }
2305  else if (is2digits)
2306  {
2307  if (tm->tm_year < 70)
2308  tm->tm_year += 2000;
2309  else if (tm->tm_year < 100)
2310  tm->tm_year += 1900;
2311  }
2312 
2313  if (mer != HR24 && tm->tm_hour > 12)
2314  return -1;
2315  if (mer == AM && tm->tm_hour == 12)
2316  tm->tm_hour = 0;
2317  else if (mer == PM && tm->tm_hour != 12)
2318  tm->tm_hour += 12;
2319 
2320  /* do additional checking for full date specs... */
2321  if (*dtype == DTK_DATE)
2322  {
2323  if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2324  return ((fmask & DTK_TIME_M) == DTK_TIME_M) ? 1 : -1;
2325 
2326  /*
2327  * check for valid day of month, now that we know for sure the month
2328  * and year...
2329  */
2330  if (tm->tm_mday < 1 || tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2331  return -1;
2332 
2333  /*
2334  * backend tried to find local timezone here but we don't use the
2335  * result afterwards anyway so we only check for this error: daylight
2336  * savings time modifier but no standard timezone?
2337  */
2338  if ((fmask & DTK_DATE_M) == DTK_DATE_M && tzp != NULL && !(fmask & DTK_M(TZ)) && (fmask & DTK_M(DTZMOD)))
2339  return -1;
2340  }
2341 
2342  return 0;
2343 } /* DecodeDateTime() */
2344 
2345 /* Function works as follows:
2346  *
2347  *
2348  * */
2349 
2350 static char *
2351 find_end_token(char *str, char *fmt)
2352 {
2353  /*
2354  * str: here is28the day12the hour fmt: here is%dthe day%hthe hour
2355  *
2356  * we extract the 28, we read the percent sign and the type "d" then this
2357  * functions gets called as find_end_token("28the day12the hour", "the
2358  * day%hthehour")
2359  *
2360  * fmt points to "the day%hthehour", next_percent points to %hthehour and
2361  * we have to find a match for everything between these positions ("the
2362  * day"). We look for "the day" in str and know that the pattern we are
2363  * about to scan ends where this string starts (right after the "28")
2364  *
2365  * At the end, *fmt is '\0' and *str isn't. end_position then is
2366  * unchanged.
2367  */
2368  char *end_position = NULL;
2369  char *next_percent,
2370  *subst_location = NULL;
2371  int scan_offset = 0;
2372  char last_char;
2373 
2374  /* are we at the end? */
2375  if (!*fmt)
2376  {
2377  end_position = fmt;
2378  return end_position;
2379  }
2380 
2381  /* not at the end */
2382  while (fmt[scan_offset] == '%' && fmt[scan_offset + 1])
2383  {
2384  /*
2385  * there is no delimiter, skip to the next delimiter if we're reading
2386  * a number and then something that is not a number "9:15pm", we might
2387  * be able to recover with the strtol end pointer. Go for the next
2388  * percent sign
2389  */
2390  scan_offset += 2;
2391  }
2392  next_percent = strchr(fmt + scan_offset, '%');
2393  if (next_percent)
2394  {
2395  /*
2396  * we don't want to allocate extra memory, so we temporarily set the
2397  * '%' sign to '\0' and call strstr However since we allow whitespace
2398  * to float around everything, we have to shorten the pattern until we
2399  * reach a non-whitespace character
2400  */
2401 
2402  subst_location = next_percent;
2403  while (*(subst_location - 1) == ' ' && subst_location - 1 > fmt + scan_offset)
2404  subst_location--;
2405  last_char = *subst_location;
2406  *subst_location = '\0';
2407 
2408  /*
2409  * the haystack is the str and the needle is the original fmt but it
2410  * ends at the position where the next percent sign would be
2411  */
2412 
2413  /*
2414  * There is one special case. Imagine: str = " 2", fmt = "%d %...",
2415  * since we want to allow blanks as "dynamic" padding we have to
2416  * accept this. Now, we are called with a fmt of " %..." and look for
2417  * " " in str. We find it at the first position and never read the
2418  * 2...
2419  */
2420  while (*str == ' ')
2421  str++;
2422  end_position = strstr(str, fmt + scan_offset);
2423  *subst_location = last_char;
2424  }
2425  else
2426  {
2427  /*
2428  * there is no other percent sign. So everything up to the end has to
2429  * match.
2430  */
2431  end_position = str + strlen(str);
2432  }
2433  if (!end_position)
2434  {
2435  /*
2436  * maybe we have the following case:
2437  *
2438  * str = "4:15am" fmt = "%M:%S %p"
2439  *
2440  * at this place we could have
2441  *
2442  * str = "15am" fmt = " %p"
2443  *
2444  * and have set fmt to " " because overwrote the % sign with a NULL
2445  *
2446  * In this case where we would have to match a space but can't find
2447  * it, set end_position to the end of the string
2448  */
2449  if ((fmt + scan_offset)[0] == ' ' && fmt + scan_offset + 1 == subst_location)
2450  end_position = str + strlen(str);
2451  }
2452  return end_position;
2453 }
2454 
2455 static int
2456 pgtypes_defmt_scan(union un_fmt_comb *scan_val, int scan_type, char **pstr, char *pfmt)
2457 {
2458  /*
2459  * scan everything between pstr and pstr_end. This is not including the
2460  * last character so we might set it to '\0' for the parsing
2461  */
2462 
2463  char last_char;
2464  int err = 0;
2465  char *pstr_end;
2466  char *strtol_end = NULL;
2467 
2468  while (**pstr == ' ')
2469  pstr++;
2470  pstr_end = find_end_token(*pstr, pfmt);
2471  if (!pstr_end)
2472  {
2473  /* there was an error, no match */
2474  return 1;
2475  }
2476  last_char = *pstr_end;
2477  *pstr_end = '\0';
2478 
2479  switch (scan_type)
2480  {
2481  case PGTYPES_TYPE_UINT:
2482 
2483  /*
2484  * numbers may be blank-padded, this is the only deviation from
2485  * the fmt-string we accept
2486  */
2487  while (**pstr == ' ')
2488  (*pstr)++;
2489  errno = 0;
2490  scan_val->uint_val = (unsigned int) strtol(*pstr, &strtol_end, 10);
2491  if (errno)
2492  err = 1;
2493  break;
2495  while (**pstr == ' ')
2496  (*pstr)++;
2497  errno = 0;
2498  scan_val->luint_val = (unsigned long int) strtol(*pstr, &strtol_end, 10);
2499  if (errno)
2500  err = 1;
2501  break;
2503  scan_val->str_val = pgtypes_strdup(*pstr);
2504  if (scan_val->str_val == NULL)
2505  err = 1;
2506  break;
2507  }
2508  if (strtol_end && *strtol_end)
2509  *pstr = strtol_end;
2510  else
2511  *pstr = pstr_end;
2512  *pstr_end = last_char;
2513  return err;
2514 }
2515 
2516 /* XXX range checking */
2517 int
2519  int *year, int *month, int *day,
2520  int *hour, int *minute, int *second,
2521  int *tz)
2522 {
2523  union un_fmt_comb scan_val;
2524  int scan_type;
2525 
2526  char *pstr,
2527  *pfmt,
2528  *tmp;
2529  int err = 1;
2530  unsigned int j;
2531  struct tm tm;
2532 
2533  pfmt = fmt;
2534  pstr = *str;
2535 
2536  while (*pfmt)
2537  {
2538  err = 0;
2539  while (*pfmt == ' ')
2540  pfmt++;
2541  while (*pstr == ' ')
2542  pstr++;
2543  if (*pfmt != '%')
2544  {
2545  if (*pfmt == *pstr)
2546  {
2547  pfmt++;
2548  pstr++;
2549  }
2550  else
2551  {
2552  /* Error: no match */
2553  err = 1;
2554  return err;
2555  }
2556  continue;
2557  }
2558  /* here *pfmt equals '%' */
2559  pfmt++;
2560  switch (*pfmt)
2561  {
2562  case 'a':
2563  pfmt++;
2564 
2565  /*
2566  * we parse the day and see if it is a week day but we do not
2567  * check if the week day really matches the date
2568  */
2569  err = 1;
2570  j = 0;
2571  while (pgtypes_date_weekdays_short[j])
2572  {
2573  if (strncmp(pgtypes_date_weekdays_short[j], pstr,
2574  strlen(pgtypes_date_weekdays_short[j])) == 0)
2575  {
2576  /* found it */
2577  err = 0;
2578  pstr += strlen(pgtypes_date_weekdays_short[j]);
2579  break;
2580  }
2581  j++;
2582  }
2583  break;
2584  case 'A':
2585  /* see note above */
2586  pfmt++;
2587  err = 1;
2588  j = 0;
2589  while (days[j])
2590  {
2591  if (strncmp(days[j], pstr, strlen(days[j])) == 0)
2592  {
2593  /* found it */
2594  err = 0;
2595  pstr += strlen(days[j]);
2596  break;
2597  }
2598  j++;
2599  }
2600  break;
2601  case 'b':
2602  case 'h':
2603  pfmt++;
2604  err = 1;
2605  j = 0;
2606  while (months[j])
2607  {
2608  if (strncmp(months[j], pstr, strlen(months[j])) == 0)
2609  {
2610  /* found it */
2611  err = 0;
2612  pstr += strlen(months[j]);
2613  *month = j + 1;
2614  break;
2615  }
2616  j++;
2617  }
2618  break;
2619  case 'B':
2620  /* see note above */
2621  pfmt++;
2622  err = 1;
2623  j = 0;
2624  while (pgtypes_date_months[j])
2625  {
2626  if (strncmp(pgtypes_date_months[j], pstr, strlen(pgtypes_date_months[j])) == 0)
2627  {
2628  /* found it */
2629  err = 0;
2630  pstr += strlen(pgtypes_date_months[j]);
2631  *month = j + 1;
2632  break;
2633  }
2634  j++;
2635  }
2636  break;
2637  case 'c':
2638  /* XXX */
2639  break;
2640  case 'C':
2641  pfmt++;
2642  scan_type = PGTYPES_TYPE_UINT;
2643  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2644  *year = scan_val.uint_val * 100;
2645  break;
2646  case 'd':
2647  case 'e':
2648  pfmt++;
2649  scan_type = PGTYPES_TYPE_UINT;
2650  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2651  *day = scan_val.uint_val;
2652  break;
2653  case 'D':
2654 
2655  /*
2656  * we have to concatenate the strings in order to be able to
2657  * find the end of the substitution
2658  */
2659  pfmt++;
2660  tmp = pgtypes_alloc(strlen("%m/%d/%y") + strlen(pstr) + 1);
2661  strcpy(tmp, "%m/%d/%y");
2662  strcat(tmp, pfmt);
2663  err = PGTYPEStimestamp_defmt_scan(&pstr, tmp, d, year, month, day, hour, minute, second, tz);
2664  free(tmp);
2665  return err;
2666  case 'm':
2667  pfmt++;
2668  scan_type = PGTYPES_TYPE_UINT;
2669  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2670  *month = scan_val.uint_val;
2671  break;
2672  case 'y':
2673  case 'g': /* XXX difference to y (ISO) */
2674  pfmt++;
2675  scan_type = PGTYPES_TYPE_UINT;
2676  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2677  if (*year < 0)
2678  {
2679  /* not yet set */
2680  *year = scan_val.uint_val;
2681  }
2682  else
2683  *year += scan_val.uint_val;
2684  if (*year < 100)
2685  *year += 1900;
2686  break;
2687  case 'G':
2688  /* XXX difference to %V (ISO) */
2689  pfmt++;
2690  scan_type = PGTYPES_TYPE_UINT;
2691  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2692  *year = scan_val.uint_val;
2693  break;
2694  case 'H':
2695  case 'I':
2696  case 'k':
2697  case 'l':
2698  pfmt++;
2699  scan_type = PGTYPES_TYPE_UINT;
2700  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2701  *hour += scan_val.uint_val;
2702  break;
2703  case 'j':
2704  pfmt++;
2705  scan_type = PGTYPES_TYPE_UINT;
2706  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2707 
2708  /*
2709  * XXX what should we do with that? We could say that it's
2710  * sufficient if we have the year and the day within the year
2711  * to get at least a specific day.
2712  */
2713  break;
2714  case 'M':
2715  pfmt++;
2716  scan_type = PGTYPES_TYPE_UINT;
2717  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2718  *minute = scan_val.uint_val;
2719  break;
2720  case 'n':
2721  pfmt++;
2722  if (*pstr == '\n')
2723  pstr++;
2724  else
2725  err = 1;
2726  break;
2727  case 'p':
2728  err = 1;
2729  pfmt++;
2730  if (strncmp(pstr, "am", 2) == 0)
2731  {
2732  *hour += 0;
2733  err = 0;
2734  pstr += 2;
2735  }
2736  if (strncmp(pstr, "a.m.", 4) == 0)
2737  {
2738  *hour += 0;
2739  err = 0;
2740  pstr += 4;
2741  }
2742  if (strncmp(pstr, "pm", 2) == 0)
2743  {
2744  *hour += 12;
2745  err = 0;
2746  pstr += 2;
2747  }
2748  if (strncmp(pstr, "p.m.", 4) == 0)
2749  {
2750  *hour += 12;
2751  err = 0;
2752  pstr += 4;
2753  }
2754  break;
2755  case 'P':
2756  err = 1;
2757  pfmt++;
2758  if (strncmp(pstr, "AM", 2) == 0)
2759  {
2760  *hour += 0;
2761  err = 0;
2762  pstr += 2;
2763  }
2764  if (strncmp(pstr, "A.M.", 4) == 0)
2765  {
2766  *hour += 0;
2767  err = 0;
2768  pstr += 4;
2769  }
2770  if (strncmp(pstr, "PM", 2) == 0)
2771  {
2772  *hour += 12;
2773  err = 0;
2774  pstr += 2;
2775  }
2776  if (strncmp(pstr, "P.M.", 4) == 0)
2777  {
2778  *hour += 12;
2779  err = 0;
2780  pstr += 4;
2781  }
2782  break;
2783  case 'r':
2784  pfmt++;
2785  tmp = pgtypes_alloc(strlen("%I:%M:%S %p") + strlen(pstr) + 1);
2786  strcpy(tmp, "%I:%M:%S %p");
2787  strcat(tmp, pfmt);
2788  err = PGTYPEStimestamp_defmt_scan(&pstr, tmp, d, year, month, day, hour, minute, second, tz);
2789  free(tmp);
2790  return err;
2791  case 'R':
2792  pfmt++;
2793  tmp = pgtypes_alloc(strlen("%H:%M") + strlen(pstr) + 1);
2794  strcpy(tmp, "%H:%M");
2795  strcat(tmp, pfmt);
2796  err = PGTYPEStimestamp_defmt_scan(&pstr, tmp, d, year, month, day, hour, minute, second, tz);
2797  free(tmp);
2798  return err;
2799  case 's':
2800  pfmt++;
2801  scan_type = PGTYPES_TYPE_UINT_LONG;
2802  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2803  /* number of seconds in scan_val.luint_val */
2804  {
2805  struct tm *tms;
2806  time_t et = (time_t) scan_val.luint_val;
2807 
2808  tms = gmtime(&et);
2809 
2810  if (tms)
2811  {
2812  *year = tms->tm_year + 1900;
2813  *month = tms->tm_mon + 1;
2814  *day = tms->tm_mday;
2815  *hour = tms->tm_hour;
2816  *minute = tms->tm_min;
2817  *second = tms->tm_sec;
2818  }
2819  else
2820  err = 1;
2821  }
2822  break;
2823  case 'S':
2824  pfmt++;
2825  scan_type = PGTYPES_TYPE_UINT;
2826  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2827  *second = scan_val.uint_val;
2828  break;
2829  case 't':
2830  pfmt++;
2831  if (*pstr == '\t')
2832  pstr++;
2833  else
2834  err = 1;
2835  break;
2836  case 'T':
2837  pfmt++;
2838  tmp = pgtypes_alloc(strlen("%H:%M:%S") + strlen(pstr) + 1);
2839  strcpy(tmp, "%H:%M:%S");
2840  strcat(tmp, pfmt);
2841  err = PGTYPEStimestamp_defmt_scan(&pstr, tmp, d, year, month, day, hour, minute, second, tz);
2842  free(tmp);
2843  return err;
2844  case 'u':
2845  pfmt++;
2846  scan_type = PGTYPES_TYPE_UINT;
2847  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2848  if (scan_val.uint_val < 1 || scan_val.uint_val > 7)
2849  err = 1;
2850  break;
2851  case 'U':
2852  pfmt++;
2853  scan_type = PGTYPES_TYPE_UINT;
2854  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2855  if (scan_val.uint_val > 53)
2856  err = 1;
2857  break;
2858  case 'V':
2859  pfmt++;
2860  scan_type = PGTYPES_TYPE_UINT;
2861  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2862  if (scan_val.uint_val < 1 || scan_val.uint_val > 53)
2863  err = 1;
2864  break;
2865  case 'w':
2866  pfmt++;
2867  scan_type = PGTYPES_TYPE_UINT;
2868  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2869  if (scan_val.uint_val > 6)
2870  err = 1;
2871  break;
2872  case 'W':
2873  pfmt++;
2874  scan_type = PGTYPES_TYPE_UINT;
2875  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2876  if (scan_val.uint_val > 53)
2877  err = 1;
2878  break;
2879  case 'x':
2880  case 'X':
2881  /* XXX */
2882  break;
2883  case 'Y':
2884  pfmt++;
2885  scan_type = PGTYPES_TYPE_UINT;
2886  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2887  *year = scan_val.uint_val;
2888  break;
2889  case 'z':
2890  pfmt++;
2891  scan_type = PGTYPES_TYPE_STRING_MALLOCED;
2892  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2893  if (!err)
2894  {
2895  err = DecodeTimezone(scan_val.str_val, tz);
2896  free(scan_val.str_val);
2897  }
2898  break;
2899  case 'Z':
2900  pfmt++;
2901  scan_type = PGTYPES_TYPE_STRING_MALLOCED;
2902  err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2903  if (!err)
2904  {
2905  /*
2906  * XXX use DecodeSpecial instead? Do we need strcasecmp
2907  * here?
2908  */
2909  err = 1;
2910  for (j = 0; j < szdatetktbl; j++)
2911  {
2912  if ((datetktbl[j].type == TZ || datetktbl[j].type == DTZ) &&
2913  pg_strcasecmp(datetktbl[j].token,
2914  scan_val.str_val) == 0)
2915  {
2916  *tz = -datetktbl[j].value;
2917  err = 0;
2918  break;
2919  }
2920  }
2921  free(scan_val.str_val);
2922  }
2923  break;
2924  case '+':
2925  /* XXX */
2926  break;
2927  case '%':
2928  pfmt++;
2929  if (*pstr == '%')
2930  pstr++;
2931  else
2932  err = 1;
2933  break;
2934  default:
2935  err = 1;
2936  }
2937  }
2938  if (!err)
2939  {
2940  if (*second < 0)
2941  *second = 0;
2942  if (*minute < 0)
2943  *minute = 0;
2944  if (*hour < 0)
2945  *hour = 0;
2946  if (*day < 0)
2947  {
2948  err = 1;
2949  *day = 1;
2950  }
2951  if (*month < 0)
2952  {
2953  err = 1;
2954  *month = 1;
2955  }
2956  if (*year < 0)
2957  {
2958  err = 1;
2959  *year = 1970;
2960  }
2961 
2962  if (*second > 59)
2963  {
2964  err = 1;
2965  *second = 0;
2966  }
2967  if (*minute > 59)
2968  {
2969  err = 1;
2970  *minute = 0;
2971  }
2972  if (*hour > 24 || /* test for > 24:00:00 */
2973  (*hour == 24 && (*minute > 0 || *second > 0)))
2974  {
2975  err = 1;
2976  *hour = 0;
2977  }
2978  if (*month > MONTHS_PER_YEAR)
2979  {
2980  err = 1;
2981  *month = 1;
2982  }
2983  if (*day > day_tab[isleap(*year)][*month - 1])
2984  {
2985  *day = day_tab[isleap(*year)][*month - 1];
2986  err = 1;
2987  }
2988 
2989  tm.tm_sec = *second;
2990  tm.tm_min = *minute;
2991  tm.tm_hour = *hour;
2992  tm.tm_mday = *day;
2993  tm.tm_mon = *month;
2994  tm.tm_year = *year;
2995 
2996  tm2timestamp(&tm, 0, tz, d);
2997  }
2998  return err;
2999 }
3000 
3001 /* XXX: 1900 is compiled in as the base for years */
static int DecodeNumberField(int len, char *str, int fmask, int *tmask, struct tm *tm, fsec_t *fsec, bool *is2digits)
Definition: dt_common.c:1085
#define DYEAR
Definition: datetime.h:57
#define DTK_TZ_HOUR
Definition: datetime.h:178
static const datetkn datetktbl[]
Definition: dt_common.c:20
static char * find_end_token(char *str, char *fmt)
Definition: dt_common.c:2351
#define DTK_CENTURY
Definition: datetime.h:170
#define PM
Definition: datetime.h:73
#define DAY
Definition: datetime.h:94
#define UNITS
Definition: datetime.h:108
int GetEpochTime(struct tm *tm)
Definition: dt_common.c:948
#define DAGO
Definition: datetime.h:36
#define IGNORE_DTF
Definition: datetime.h:99
static const unsigned int szdatetktbl
Definition: dt_common.c:486
static const datetkn deltatktbl[]
Definition: dt_common.c:421
char * days[]
Definition: dt_common.c:495
unsigned long int luint_val
#define DWEEK
Definition: datetime.h:54
#define DTK_JULIAN
Definition: datetime.h:174
#define DTK_WEEK
Definition: datetime.h:165
#define DTK_YEAR
Definition: datetime.h:168
#define LATE
Definition: datetime.h:41
#define USECS_PER_SEC
Definition: timestamp.h:94
#define YEAR
Definition: datetime.h:93
int DecodeDateTime(char **field, int *ftype, int nf, int *dtype, struct tm *tm, fsec_t *fsec, bool EuroDates)
Definition: dt_common.c:1779
int64 timestamp
#define NOW
Definition: datetime.h:42
#define DTK_QUARTER
Definition: datetime.h:167
#define isleap(y)
Definition: datetime.h:271
#define TZNAME_GLOBAL
Definition: port.h:227
void GetCurrentDateTime(struct tm *tm)
Definition: dt_common.c:1056
#define TIMEZONE_GLOBAL
Definition: port.h:226
#define AGO
Definition: datetime.h:111
#define DTK_TIME_M
Definition: datetime.h:193
#define DTK_MILLENNIUM
Definition: datetime.h:171
#define PGTYPES_TYPE_UINT_LONG
unsigned char pg_tolower(unsigned char ch)
Definition: pgstrcasecmp.c:122
#define USECS_PER_MINUTE
Definition: timestamp.h:93
#define DTK_ISODOW
Definition: datetime.h:181
#define TZ
Definition: datetime.h:96
#define USE_SQL_DATES
Definition: miscadmin.h:215
#define UNKNOWN_FIELD
Definition: datetime.h:125
#define SECOND
Definition: datetime.h:103
int32 value
Definition: datetime.h:212
#define DTK_TODAY
Definition: datetime.h:156
#define DTK_TOMORROW
Definition: datetime.h:157
#define MAXTZLEN
Definition: miscadmin.h:241
#define ADBC
Definition: datetime.h:109
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define lengthof(array)
Definition: c.h:669
static int DecodeTimezone(char *str, int *tzp)
Definition: dt_common.c:1498
#define AD
Definition: datetime.h:76
#define EPOCH
Definition: datetime.h:38
int date2j(int y, int m, int d)
Definition: dt_common.c:581
#define DTK_DATE_M
Definition: datetime.h:192
#define MINS_PER_HOUR
Definition: timestamp.h:89
#define USE_ISO_DATES
Definition: miscadmin.h:214
#define TOMORROW
Definition: datetime.h:44
#define DHOUR
Definition: datetime.h:52
#define DA_D
Definition: datetime.h:61
static struct pg_tm tm
Definition: localtime.c:108
void j2date(int jd, int *year, int *month, int *day)
Definition: dt_common.c:606
#define DMILLISEC
Definition: datetime.h:49
#define DSECOND
Definition: datetime.h:50
#define DTK_MONTH
Definition: datetime.h:166
#define DTK_MILLISEC
Definition: datetime.h:172
#define MONTHS_PER_YEAR
Definition: timestamp.h:69
#define sprintf
Definition: port.h:194
char * pgtypes_strdup(const char *str)
Definition: common.c:20
#define DMICROSEC
Definition: datetime.h:48
#define DTK_DECADE
Definition: datetime.h:169
#define TODAY
Definition: datetime.h:43
#define PGTYPES_TYPE_UINT
#define DTK_TZ
Definition: datetime.h:147
#define ZULU
Definition: datetime.h:46
#define DTK_HOUR
Definition: datetime.h:163
#define DOW
Definition: datetime.h:107
#define AM
Definition: datetime.h:72
char * months[]
Definition: dt_common.c:493
static const datetkn * datecache[MAXDATEFIELDS]
Definition: dt_common.c:489
#define DTK_SECOND
Definition: datetime.h:161
#define DCENTURY
Definition: datetime.h:59
char * pgtypes_alloc(long size)
Definition: common.c:10
void EncodeDateOnly(struct tm *tm, int style, char *str, bool EuroDates)
Definition: dt_common.c:669
static const unsigned int szdeltatktbl
Definition: dt_common.c:487
static const datetkn * datebsearch(const char *key, const datetkn *base, unsigned int nel)
Definition: dt_common.c:502
void EncodeDateTime(struct tm *tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str, bool EuroDates)
Definition: dt_common.c:753
int PGTYPEStimestamp_defmt_scan(char **str, char *fmt, timestamp *d, int *year, int *month, int *day, int *hour, int *minute, int *second, int *tz)
Definition: dt_common.c:2518
#define DMILLENNIUM
Definition: datetime.h:60
#define SECS_PER_MINUTE
Definition: timestamp.h:88
#define DMINUTE
Definition: datetime.h:51
#define USECS_PER_HOUR
Definition: timestamp.h:92
#define USE_POSTGRES_DATES
Definition: miscadmin.h:213
int strtoint(const char *pg_restrict str, char **pg_restrict endptr, int base)
Definition: string.c:50
int32 fsec_t
Definition: timestamp.h:41
#define DTK_YESTERDAY
Definition: datetime.h:155
#define DTK_NUMBER
Definition: datetime.h:142
#define MINUTE
Definition: datetime.h:102
#define USECS_PER_DAY
Definition: timestamp.h:91
#define DTK_TZ_MINUTE
Definition: datetime.h:179
#define SECS_PER_HOUR
Definition: timestamp.h:87
#define MONTH
Definition: datetime.h:92
#define DTK_MINUTE
Definition: datetime.h:162
#define BC
Definition: datetime.h:77
int DecodeUnits(int field, char *lowtoken, int *val)
Definition: dt_common.c:536
char * pgtypes_date_weekdays_short[]
Definition: dt_common.c:497
#define DTK_DOW
Definition: datetime.h:176
#define DTK_LATE
Definition: datetime.h:152
#define DTK_MICROSEC
Definition: datetime.h:173
#define PGTYPES_TYPE_STRING_MALLOCED
const int day_tab[2][13]
Definition: dt_common.c:14
#define DMONTH
Definition: datetime.h:55
#define ISOTIME
Definition: datetime.h:116
#define DTK_TIME
Definition: datetime.h:146
#define DTK_DOY
Definition: datetime.h:177
#define YESTERDAY
Definition: datetime.h:45
#define free(a)
Definition: header.h:65
int tm2timestamp(struct pg_tm *tm, fsec_t fsec, int *tzp, Timestamp *result)
Definition: timestamp.c:1887
char type
Definition: datetime.h:211
static int DecodeSpecial(int field, char *lowtoken, int *val)
Definition: dt_common.c:635
#define Assert(condition)
Definition: c.h:739
#define StrNCpy(dst, src, len)
Definition: c.h:945
#define AMPM
Definition: datetime.h:100
#define DTIMEZONE
Definition: datetime.h:63
long AbsoluteTime
Definition: dt_common.c:18
#define DTK_EARLY
Definition: datetime.h:151
#define MAXDATEFIELDS
Definition: datetime.h:203
#define DTK_STRING
Definition: datetime.h:143
#define DTK_DAY
Definition: datetime.h:164
int DecodeTime(char *str, int *tmask, struct tm *tm, fsec_t *fsec)
Definition: dt_common.c:1433
#define RESERV
Definition: datetime.h:91
#define DDAY
Definition: datetime.h:53
#define DTZ
Definition: datetime.h:97
static int DecodeNumber(int flen, char *str, int fmask, int *tmask, struct tm *tm, fsec_t *fsec, bool *is2digits, bool EuroDates)
Definition: dt_common.c:1195
#define DTK_EPOCH
Definition: datetime.h:153
#define USE_GERMAN_DATES
Definition: miscadmin.h:216
#define DTK_NOW
Definition: datetime.h:154
static const unsigned __int64 epoch
Definition: gettimeofday.c:34
static int DecodePosixTimezone(char *str, int *tzp)
Definition: dt_common.c:1543
int i
#define TOKMAXLEN
Definition: datetime.h:205
#define DTK_M(t)
Definition: datetime.h:188
#define HOUR
Definition: datetime.h:101
void dt2time(double jd, int *hour, int *min, int *sec, fsec_t *fsec)
Definition: dt_common.c:1064
#define DTK_ZULU
Definition: datetime.h:158
#define DQUARTER
Definition: datetime.h:56
static const datetkn * deltacache[MAXDATEFIELDS]
Definition: dt_common.c:491
#define DTZMOD
Definition: datetime.h:123
static int DecodeDate(char *str, int fmask, int *tmask, struct tm *tm, bool EuroDates)
Definition: dt_common.c:1304
static void abstime2tm(AbsoluteTime _time, int *tzp, struct tm *tm, char **tzn)
Definition: dt_common.c:971
void TrimTrailingZeros(char *str)
Definition: dt_common.c:722
#define DOY
Definition: datetime.h:106
#define EARLY
Definition: datetime.h:40
char * pgtypes_date_months[]
Definition: dt_common.c:499
long val
Definition: informix.c:664
unsigned int uint_val
#define PGTYPES_TS_BAD_TIMESTAMP
Definition: pgtypes_error.h:15
#define DDECADE
Definition: datetime.h:58
#define DTK_DATE
Definition: datetime.h:145
int ParseDateTime(char *timestr, char *lowstr, char **field, int *ftype, int *numfields, char **endstr)
Definition: dt_common.c:1596
#define HR24
Definition: datetime.h:74
#define DTK_SPECIAL
Definition: datetime.h:150
static int pgtypes_defmt_scan(union un_fmt_comb *scan_val, int scan_type, char **pstr, char *pfmt)
Definition: dt_common.c:2456
#define DB_C
Definition: datetime.h:62