]> granicus.if.org Git - postgresql/blob - src/backend/utils/adt/date.c
Move Timestamp/Interval typedefs and basic macros into datatype/timestamp.h.
[postgresql] / src / backend / utils / adt / date.c
1 /*-------------------------------------------------------------------------
2  *
3  * date.c
4  *        implements DATE and TIME data types specified in SQL-92 standard
5  *
6  * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994-5, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/utils/adt/date.c
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include <ctype.h>
19 #include <limits.h>
20 #include <float.h>
21 #include <time.h>
22
23 #include "access/hash.h"
24 #include "libpq/pqformat.h"
25 #include "miscadmin.h"
26 #include "parser/scansup.h"
27 #include "utils/array.h"
28 #include "utils/builtins.h"
29 #include "utils/date.h"
30 #include "utils/datetime.h"
31 #include "utils/nabstime.h"
32
33 /*
34  * gcc's -ffast-math switch breaks routines that expect exact results from
35  * expressions like timeval / SECS_PER_HOUR, where timeval is double.
36  */
37 #ifdef __FAST_MATH__
38 #error -ffast-math is known to break this code
39 #endif
40
41
42 static void EncodeSpecialDate(DateADT dt, char *str);
43 static int      time2tm(TimeADT time, struct pg_tm * tm, fsec_t *fsec);
44 static int      timetz2tm(TimeTzADT *time, struct pg_tm * tm, fsec_t *fsec, int *tzp);
45 static int      tm2time(struct pg_tm * tm, fsec_t fsec, TimeADT *result);
46 static int      tm2timetz(struct pg_tm * tm, fsec_t fsec, int tz, TimeTzADT *result);
47 static void AdjustTimeForTypmod(TimeADT *time, int32 typmod);
48
49
50 /* common code for timetypmodin and timetztypmodin */
51 static int32
52 anytime_typmodin(bool istz, ArrayType *ta)
53 {
54         int32           typmod;
55         int32      *tl;
56         int                     n;
57
58         tl = ArrayGetIntegerTypmods(ta, &n);
59
60         /*
61          * we're not too tense about good error message here because grammar
62          * shouldn't allow wrong number of modifiers for TIME
63          */
64         if (n != 1)
65                 ereport(ERROR,
66                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
67                                  errmsg("invalid type modifier")));
68
69         if (*tl < 0)
70                 ereport(ERROR,
71                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
72                                  errmsg("TIME(%d)%s precision must not be negative",
73                                                 *tl, (istz ? " WITH TIME ZONE" : ""))));
74         if (*tl > MAX_TIME_PRECISION)
75         {
76                 ereport(WARNING,
77                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
78                                  errmsg("TIME(%d)%s precision reduced to maximum allowed, %d",
79                                                 *tl, (istz ? " WITH TIME ZONE" : ""),
80                                                 MAX_TIME_PRECISION)));
81                 typmod = MAX_TIME_PRECISION;
82         }
83         else
84                 typmod = *tl;
85
86         return typmod;
87 }
88
89 /* common code for timetypmodout and timetztypmodout */
90 static char *
91 anytime_typmodout(bool istz, int32 typmod)
92 {
93         char       *res = (char *) palloc(64);
94         const char *tz = istz ? " with time zone" : " without time zone";
95
96         if (typmod >= 0)
97                 snprintf(res, 64, "(%d)%s", (int) typmod, tz);
98         else
99                 snprintf(res, 64, "%s", tz);
100         return res;
101 }
102
103
104 /*****************************************************************************
105  *       Date ADT
106  *****************************************************************************/
107
108
109 /* date_in()
110  * Given date text string, convert to internal date format.
111  */
112 Datum
113 date_in(PG_FUNCTION_ARGS)
114 {
115         char       *str = PG_GETARG_CSTRING(0);
116         DateADT         date;
117         fsec_t          fsec;
118         struct pg_tm tt,
119                            *tm = &tt;
120         int                     tzp;
121         int                     dtype;
122         int                     nf;
123         int                     dterr;
124         char       *field[MAXDATEFIELDS];
125         int                     ftype[MAXDATEFIELDS];
126         char            workbuf[MAXDATELEN + 1];
127
128         dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
129                                                   field, ftype, MAXDATEFIELDS, &nf);
130         if (dterr == 0)
131                 dterr = DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tzp);
132         if (dterr != 0)
133                 DateTimeParseError(dterr, str, "date");
134
135         switch (dtype)
136         {
137                 case DTK_DATE:
138                         break;
139
140                 case DTK_CURRENT:
141                         ereport(ERROR,
142                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
143                           errmsg("date/time value \"current\" is no longer supported")));
144
145                         GetCurrentDateTime(tm);
146                         break;
147
148                 case DTK_EPOCH:
149                         GetEpochTime(tm);
150                         break;
151
152                 case DTK_LATE:
153                         DATE_NOEND(date);
154                         PG_RETURN_DATEADT(date);
155
156                 case DTK_EARLY:
157                         DATE_NOBEGIN(date);
158                         PG_RETURN_DATEADT(date);
159
160                 default:
161                         DateTimeParseError(DTERR_BAD_FORMAT, str, "date");
162                         break;
163         }
164
165         if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
166                 ereport(ERROR,
167                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
168                                  errmsg("date out of range: \"%s\"", str)));
169
170         date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - POSTGRES_EPOCH_JDATE;
171
172         PG_RETURN_DATEADT(date);
173 }
174
175 /* date_out()
176  * Given internal format date, convert to text string.
177  */
178 Datum
179 date_out(PG_FUNCTION_ARGS)
180 {
181         DateADT         date = PG_GETARG_DATEADT(0);
182         char       *result;
183         struct pg_tm tt,
184                            *tm = &tt;
185         char            buf[MAXDATELEN + 1];
186
187         if (DATE_NOT_FINITE(date))
188                 EncodeSpecialDate(date, buf);
189         else
190         {
191                 j2date(date + POSTGRES_EPOCH_JDATE,
192                            &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
193                 EncodeDateOnly(tm, DateStyle, buf);
194         }
195
196         result = pstrdup(buf);
197         PG_RETURN_CSTRING(result);
198 }
199
200 /*
201  *              date_recv                       - converts external binary format to date
202  */
203 Datum
204 date_recv(PG_FUNCTION_ARGS)
205 {
206         StringInfo      buf = (StringInfo) PG_GETARG_POINTER(0);
207         DateADT         result;
208
209         result = (DateADT) pq_getmsgint(buf, sizeof(DateADT));
210
211         /* Limit to the same range that date_in() accepts. */
212         if (DATE_NOT_FINITE(result))
213                  /* ok */ ;
214         else if (result < -POSTGRES_EPOCH_JDATE ||
215                          result >= JULIAN_MAX - POSTGRES_EPOCH_JDATE)
216                 ereport(ERROR,
217                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
218                                  errmsg("date out of range")));
219
220         PG_RETURN_DATEADT(result);
221 }
222
223 /*
224  *              date_send                       - converts date to binary format
225  */
226 Datum
227 date_send(PG_FUNCTION_ARGS)
228 {
229         DateADT         date = PG_GETARG_DATEADT(0);
230         StringInfoData buf;
231
232         pq_begintypsend(&buf);
233         pq_sendint(&buf, date, sizeof(date));
234         PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
235 }
236
237 /*
238  * Convert reserved date values to string.
239  */
240 static void
241 EncodeSpecialDate(DateADT dt, char *str)
242 {
243         if (DATE_IS_NOBEGIN(dt))
244                 strcpy(str, EARLY);
245         else if (DATE_IS_NOEND(dt))
246                 strcpy(str, LATE);
247         else    /* shouldn't happen */
248                 elog(ERROR, "invalid argument for EncodeSpecialDate");
249 }
250
251
252 /*
253  * Comparison functions for dates
254  */
255
256 Datum
257 date_eq(PG_FUNCTION_ARGS)
258 {
259         DateADT         dateVal1 = PG_GETARG_DATEADT(0);
260         DateADT         dateVal2 = PG_GETARG_DATEADT(1);
261
262         PG_RETURN_BOOL(dateVal1 == dateVal2);
263 }
264
265 Datum
266 date_ne(PG_FUNCTION_ARGS)
267 {
268         DateADT         dateVal1 = PG_GETARG_DATEADT(0);
269         DateADT         dateVal2 = PG_GETARG_DATEADT(1);
270
271         PG_RETURN_BOOL(dateVal1 != dateVal2);
272 }
273
274 Datum
275 date_lt(PG_FUNCTION_ARGS)
276 {
277         DateADT         dateVal1 = PG_GETARG_DATEADT(0);
278         DateADT         dateVal2 = PG_GETARG_DATEADT(1);
279
280         PG_RETURN_BOOL(dateVal1 < dateVal2);
281 }
282
283 Datum
284 date_le(PG_FUNCTION_ARGS)
285 {
286         DateADT         dateVal1 = PG_GETARG_DATEADT(0);
287         DateADT         dateVal2 = PG_GETARG_DATEADT(1);
288
289         PG_RETURN_BOOL(dateVal1 <= dateVal2);
290 }
291
292 Datum
293 date_gt(PG_FUNCTION_ARGS)
294 {
295         DateADT         dateVal1 = PG_GETARG_DATEADT(0);
296         DateADT         dateVal2 = PG_GETARG_DATEADT(1);
297
298         PG_RETURN_BOOL(dateVal1 > dateVal2);
299 }
300
301 Datum
302 date_ge(PG_FUNCTION_ARGS)
303 {
304         DateADT         dateVal1 = PG_GETARG_DATEADT(0);
305         DateADT         dateVal2 = PG_GETARG_DATEADT(1);
306
307         PG_RETURN_BOOL(dateVal1 >= dateVal2);
308 }
309
310 Datum
311 date_cmp(PG_FUNCTION_ARGS)
312 {
313         DateADT         dateVal1 = PG_GETARG_DATEADT(0);
314         DateADT         dateVal2 = PG_GETARG_DATEADT(1);
315
316         if (dateVal1 < dateVal2)
317                 PG_RETURN_INT32(-1);
318         else if (dateVal1 > dateVal2)
319                 PG_RETURN_INT32(1);
320         PG_RETURN_INT32(0);
321 }
322
323 Datum
324 date_finite(PG_FUNCTION_ARGS)
325 {
326         DateADT         date = PG_GETARG_DATEADT(0);
327
328         PG_RETURN_BOOL(!DATE_NOT_FINITE(date));
329 }
330
331 Datum
332 date_larger(PG_FUNCTION_ARGS)
333 {
334         DateADT         dateVal1 = PG_GETARG_DATEADT(0);
335         DateADT         dateVal2 = PG_GETARG_DATEADT(1);
336
337         PG_RETURN_DATEADT((dateVal1 > dateVal2) ? dateVal1 : dateVal2);
338 }
339
340 Datum
341 date_smaller(PG_FUNCTION_ARGS)
342 {
343         DateADT         dateVal1 = PG_GETARG_DATEADT(0);
344         DateADT         dateVal2 = PG_GETARG_DATEADT(1);
345
346         PG_RETURN_DATEADT((dateVal1 < dateVal2) ? dateVal1 : dateVal2);
347 }
348
349 /* Compute difference between two dates in days.
350  */
351 Datum
352 date_mi(PG_FUNCTION_ARGS)
353 {
354         DateADT         dateVal1 = PG_GETARG_DATEADT(0);
355         DateADT         dateVal2 = PG_GETARG_DATEADT(1);
356
357         if (DATE_NOT_FINITE(dateVal1) || DATE_NOT_FINITE(dateVal2))
358                 ereport(ERROR,
359                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
360                                  errmsg("cannot subtract infinite dates")));
361
362         PG_RETURN_INT32((int32) (dateVal1 - dateVal2));
363 }
364
365 /* Add a number of days to a date, giving a new date.
366  * Must handle both positive and negative numbers of days.
367  */
368 Datum
369 date_pli(PG_FUNCTION_ARGS)
370 {
371         DateADT         dateVal = PG_GETARG_DATEADT(0);
372         int32           days = PG_GETARG_INT32(1);
373
374         if (DATE_NOT_FINITE(dateVal))
375                 days = 0;                               /* can't change infinity */
376
377         PG_RETURN_DATEADT(dateVal + days);
378 }
379
380 /* Subtract a number of days from a date, giving a new date.
381  */
382 Datum
383 date_mii(PG_FUNCTION_ARGS)
384 {
385         DateADT         dateVal = PG_GETARG_DATEADT(0);
386         int32           days = PG_GETARG_INT32(1);
387
388         if (DATE_NOT_FINITE(dateVal))
389                 days = 0;                               /* can't change infinity */
390
391         PG_RETURN_DATEADT(dateVal - days);
392 }
393
394 /*
395  * Internal routines for promoting date to timestamp and timestamp with
396  * time zone
397  */
398
399 static Timestamp
400 date2timestamp(DateADT dateVal)
401 {
402         Timestamp       result;
403
404         if (DATE_IS_NOBEGIN(dateVal))
405                 TIMESTAMP_NOBEGIN(result);
406         else if (DATE_IS_NOEND(dateVal))
407                 TIMESTAMP_NOEND(result);
408         else
409         {
410 #ifdef HAVE_INT64_TIMESTAMP
411                 /* date is days since 2000, timestamp is microseconds since same... */
412                 result = dateVal * USECS_PER_DAY;
413                 /* Date's range is wider than timestamp's, so check for overflow */
414                 if (result / USECS_PER_DAY != dateVal)
415                         ereport(ERROR,
416                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
417                                          errmsg("date out of range for timestamp")));
418 #else
419                 /* date is days since 2000, timestamp is seconds since same... */
420                 result = dateVal * (double) SECS_PER_DAY;
421 #endif
422         }
423
424         return result;
425 }
426
427 static TimestampTz
428 date2timestamptz(DateADT dateVal)
429 {
430         TimestampTz result;
431         struct pg_tm tt,
432                            *tm = &tt;
433         int                     tz;
434
435         if (DATE_IS_NOBEGIN(dateVal))
436                 TIMESTAMP_NOBEGIN(result);
437         else if (DATE_IS_NOEND(dateVal))
438                 TIMESTAMP_NOEND(result);
439         else
440         {
441                 j2date(dateVal + POSTGRES_EPOCH_JDATE,
442                            &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
443                 tm->tm_hour = 0;
444                 tm->tm_min = 0;
445                 tm->tm_sec = 0;
446                 tz = DetermineTimeZoneOffset(tm, session_timezone);
447
448 #ifdef HAVE_INT64_TIMESTAMP
449                 result = dateVal * USECS_PER_DAY + tz * USECS_PER_SEC;
450                 /* Date's range is wider than timestamp's, so check for overflow */
451                 if ((result - tz * USECS_PER_SEC) / USECS_PER_DAY != dateVal)
452                         ereport(ERROR,
453                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
454                                          errmsg("date out of range for timestamp")));
455 #else
456                 result = dateVal * (double) SECS_PER_DAY + tz;
457 #endif
458         }
459
460         return result;
461 }
462
463 /*
464  * date2timestamp_no_overflow
465  *
466  * This is chartered to produce a double value that is numerically
467  * equivalent to the corresponding Timestamp value, if the date is in the
468  * valid range of Timestamps, but in any case not throw an overflow error.
469  * We can do this since the numerical range of double is greater than
470  * that of non-erroneous timestamps.  The results are currently only
471  * used for statistical estimation purposes.
472  */
473 double
474 date2timestamp_no_overflow(DateADT dateVal)
475 {
476         double          result;
477
478         if (DATE_IS_NOBEGIN(dateVal))
479                 result = -DBL_MAX;
480         else if (DATE_IS_NOEND(dateVal))
481                 result = DBL_MAX;
482         else
483         {
484 #ifdef HAVE_INT64_TIMESTAMP
485                 /* date is days since 2000, timestamp is microseconds since same... */
486                 result = dateVal * (double) USECS_PER_DAY;
487 #else
488                 /* date is days since 2000, timestamp is seconds since same... */
489                 result = dateVal * (double) SECS_PER_DAY;
490 #endif
491         }
492
493         return result;
494 }
495
496
497 /*
498  * Crosstype comparison functions for dates
499  */
500
501 Datum
502 date_eq_timestamp(PG_FUNCTION_ARGS)
503 {
504         DateADT         dateVal = PG_GETARG_DATEADT(0);
505         Timestamp       dt2 = PG_GETARG_TIMESTAMP(1);
506         Timestamp       dt1;
507
508         dt1 = date2timestamp(dateVal);
509
510         PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
511 }
512
513 Datum
514 date_ne_timestamp(PG_FUNCTION_ARGS)
515 {
516         DateADT         dateVal = PG_GETARG_DATEADT(0);
517         Timestamp       dt2 = PG_GETARG_TIMESTAMP(1);
518         Timestamp       dt1;
519
520         dt1 = date2timestamp(dateVal);
521
522         PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
523 }
524
525 Datum
526 date_lt_timestamp(PG_FUNCTION_ARGS)
527 {
528         DateADT         dateVal = PG_GETARG_DATEADT(0);
529         Timestamp       dt2 = PG_GETARG_TIMESTAMP(1);
530         Timestamp       dt1;
531
532         dt1 = date2timestamp(dateVal);
533
534         PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
535 }
536
537 Datum
538 date_gt_timestamp(PG_FUNCTION_ARGS)
539 {
540         DateADT         dateVal = PG_GETARG_DATEADT(0);
541         Timestamp       dt2 = PG_GETARG_TIMESTAMP(1);
542         Timestamp       dt1;
543
544         dt1 = date2timestamp(dateVal);
545
546         PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
547 }
548
549 Datum
550 date_le_timestamp(PG_FUNCTION_ARGS)
551 {
552         DateADT         dateVal = PG_GETARG_DATEADT(0);
553         Timestamp       dt2 = PG_GETARG_TIMESTAMP(1);
554         Timestamp       dt1;
555
556         dt1 = date2timestamp(dateVal);
557
558         PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) <= 0);
559 }
560
561 Datum
562 date_ge_timestamp(PG_FUNCTION_ARGS)
563 {
564         DateADT         dateVal = PG_GETARG_DATEADT(0);
565         Timestamp       dt2 = PG_GETARG_TIMESTAMP(1);
566         Timestamp       dt1;
567
568         dt1 = date2timestamp(dateVal);
569
570         PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) >= 0);
571 }
572
573 Datum
574 date_cmp_timestamp(PG_FUNCTION_ARGS)
575 {
576         DateADT         dateVal = PG_GETARG_DATEADT(0);
577         Timestamp       dt2 = PG_GETARG_TIMESTAMP(1);
578         Timestamp       dt1;
579
580         dt1 = date2timestamp(dateVal);
581
582         PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
583 }
584
585 Datum
586 date_eq_timestamptz(PG_FUNCTION_ARGS)
587 {
588         DateADT         dateVal = PG_GETARG_DATEADT(0);
589         TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
590         TimestampTz dt1;
591
592         dt1 = date2timestamptz(dateVal);
593
594         PG_RETURN_BOOL(timestamptz_cmp_internal(dt1, dt2) == 0);
595 }
596
597 Datum
598 date_ne_timestamptz(PG_FUNCTION_ARGS)
599 {
600         DateADT         dateVal = PG_GETARG_DATEADT(0);
601         TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
602         TimestampTz dt1;
603
604         dt1 = date2timestamptz(dateVal);
605
606         PG_RETURN_BOOL(timestamptz_cmp_internal(dt1, dt2) != 0);
607 }
608
609 Datum
610 date_lt_timestamptz(PG_FUNCTION_ARGS)
611 {
612         DateADT         dateVal = PG_GETARG_DATEADT(0);
613         TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
614         TimestampTz dt1;
615
616         dt1 = date2timestamptz(dateVal);
617
618         PG_RETURN_BOOL(timestamptz_cmp_internal(dt1, dt2) < 0);
619 }
620
621 Datum
622 date_gt_timestamptz(PG_FUNCTION_ARGS)
623 {
624         DateADT         dateVal = PG_GETARG_DATEADT(0);
625         TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
626         TimestampTz dt1;
627
628         dt1 = date2timestamptz(dateVal);
629
630         PG_RETURN_BOOL(timestamptz_cmp_internal(dt1, dt2) > 0);
631 }
632
633 Datum
634 date_le_timestamptz(PG_FUNCTION_ARGS)
635 {
636         DateADT         dateVal = PG_GETARG_DATEADT(0);
637         TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
638         TimestampTz dt1;
639
640         dt1 = date2timestamptz(dateVal);
641
642         PG_RETURN_BOOL(timestamptz_cmp_internal(dt1, dt2) <= 0);
643 }
644
645 Datum
646 date_ge_timestamptz(PG_FUNCTION_ARGS)
647 {
648         DateADT         dateVal = PG_GETARG_DATEADT(0);
649         TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
650         TimestampTz dt1;
651
652         dt1 = date2timestamptz(dateVal);
653
654         PG_RETURN_BOOL(timestamptz_cmp_internal(dt1, dt2) >= 0);
655 }
656
657 Datum
658 date_cmp_timestamptz(PG_FUNCTION_ARGS)
659 {
660         DateADT         dateVal = PG_GETARG_DATEADT(0);
661         TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
662         TimestampTz dt1;
663
664         dt1 = date2timestamptz(dateVal);
665
666         PG_RETURN_INT32(timestamptz_cmp_internal(dt1, dt2));
667 }
668
669 Datum
670 timestamp_eq_date(PG_FUNCTION_ARGS)
671 {
672         Timestamp       dt1 = PG_GETARG_TIMESTAMP(0);
673         DateADT         dateVal = PG_GETARG_DATEADT(1);
674         Timestamp       dt2;
675
676         dt2 = date2timestamp(dateVal);
677
678         PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
679 }
680
681 Datum
682 timestamp_ne_date(PG_FUNCTION_ARGS)
683 {
684         Timestamp       dt1 = PG_GETARG_TIMESTAMP(0);
685         DateADT         dateVal = PG_GETARG_DATEADT(1);
686         Timestamp       dt2;
687
688         dt2 = date2timestamp(dateVal);
689
690         PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
691 }
692
693 Datum
694 timestamp_lt_date(PG_FUNCTION_ARGS)
695 {
696         Timestamp       dt1 = PG_GETARG_TIMESTAMP(0);
697         DateADT         dateVal = PG_GETARG_DATEADT(1);
698         Timestamp       dt2;
699
700         dt2 = date2timestamp(dateVal);
701
702         PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
703 }
704
705 Datum
706 timestamp_gt_date(PG_FUNCTION_ARGS)
707 {
708         Timestamp       dt1 = PG_GETARG_TIMESTAMP(0);
709         DateADT         dateVal = PG_GETARG_DATEADT(1);
710         Timestamp       dt2;
711
712         dt2 = date2timestamp(dateVal);
713
714         PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
715 }
716
717 Datum
718 timestamp_le_date(PG_FUNCTION_ARGS)
719 {
720         Timestamp       dt1 = PG_GETARG_TIMESTAMP(0);
721         DateADT         dateVal = PG_GETARG_DATEADT(1);
722         Timestamp       dt2;
723
724         dt2 = date2timestamp(dateVal);
725
726         PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) <= 0);
727 }
728
729 Datum
730 timestamp_ge_date(PG_FUNCTION_ARGS)
731 {
732         Timestamp       dt1 = PG_GETARG_TIMESTAMP(0);
733         DateADT         dateVal = PG_GETARG_DATEADT(1);
734         Timestamp       dt2;
735
736         dt2 = date2timestamp(dateVal);
737
738         PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) >= 0);
739 }
740
741 Datum
742 timestamp_cmp_date(PG_FUNCTION_ARGS)
743 {
744         Timestamp       dt1 = PG_GETARG_TIMESTAMP(0);
745         DateADT         dateVal = PG_GETARG_DATEADT(1);
746         Timestamp       dt2;
747
748         dt2 = date2timestamp(dateVal);
749
750         PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
751 }
752
753 Datum
754 timestamptz_eq_date(PG_FUNCTION_ARGS)
755 {
756         TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
757         DateADT         dateVal = PG_GETARG_DATEADT(1);
758         TimestampTz dt2;
759
760         dt2 = date2timestamptz(dateVal);
761
762         PG_RETURN_BOOL(timestamptz_cmp_internal(dt1, dt2) == 0);
763 }
764
765 Datum
766 timestamptz_ne_date(PG_FUNCTION_ARGS)
767 {
768         TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
769         DateADT         dateVal = PG_GETARG_DATEADT(1);
770         TimestampTz dt2;
771
772         dt2 = date2timestamptz(dateVal);
773
774         PG_RETURN_BOOL(timestamptz_cmp_internal(dt1, dt2) != 0);
775 }
776
777 Datum
778 timestamptz_lt_date(PG_FUNCTION_ARGS)
779 {
780         TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
781         DateADT         dateVal = PG_GETARG_DATEADT(1);
782         TimestampTz dt2;
783
784         dt2 = date2timestamptz(dateVal);
785
786         PG_RETURN_BOOL(timestamptz_cmp_internal(dt1, dt2) < 0);
787 }
788
789 Datum
790 timestamptz_gt_date(PG_FUNCTION_ARGS)
791 {
792         TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
793         DateADT         dateVal = PG_GETARG_DATEADT(1);
794         TimestampTz dt2;
795
796         dt2 = date2timestamptz(dateVal);
797
798         PG_RETURN_BOOL(timestamptz_cmp_internal(dt1, dt2) > 0);
799 }
800
801 Datum
802 timestamptz_le_date(PG_FUNCTION_ARGS)
803 {
804         TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
805         DateADT         dateVal = PG_GETARG_DATEADT(1);
806         TimestampTz dt2;
807
808         dt2 = date2timestamptz(dateVal);
809
810         PG_RETURN_BOOL(timestamptz_cmp_internal(dt1, dt2) <= 0);
811 }
812
813 Datum
814 timestamptz_ge_date(PG_FUNCTION_ARGS)
815 {
816         TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
817         DateADT         dateVal = PG_GETARG_DATEADT(1);
818         TimestampTz dt2;
819
820         dt2 = date2timestamptz(dateVal);
821
822         PG_RETURN_BOOL(timestamptz_cmp_internal(dt1, dt2) >= 0);
823 }
824
825 Datum
826 timestamptz_cmp_date(PG_FUNCTION_ARGS)
827 {
828         TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
829         DateADT         dateVal = PG_GETARG_DATEADT(1);
830         TimestampTz dt2;
831
832         dt2 = date2timestamptz(dateVal);
833
834         PG_RETURN_INT32(timestamptz_cmp_internal(dt1, dt2));
835 }
836
837
838 /* Add an interval to a date, giving a new date.
839  * Must handle both positive and negative intervals.
840  *
841  * We implement this by promoting the date to timestamp (without time zone)
842  * and then using the timestamp plus interval function.
843  */
844 Datum
845 date_pl_interval(PG_FUNCTION_ARGS)
846 {
847         DateADT         dateVal = PG_GETARG_DATEADT(0);
848         Interval   *span = PG_GETARG_INTERVAL_P(1);
849         Timestamp       dateStamp;
850
851         dateStamp = date2timestamp(dateVal);
852
853         return DirectFunctionCall2(timestamp_pl_interval,
854                                                            TimestampGetDatum(dateStamp),
855                                                            PointerGetDatum(span));
856 }
857
858 /* Subtract an interval from a date, giving a new date.
859  * Must handle both positive and negative intervals.
860  *
861  * We implement this by promoting the date to timestamp (without time zone)
862  * and then using the timestamp minus interval function.
863  */
864 Datum
865 date_mi_interval(PG_FUNCTION_ARGS)
866 {
867         DateADT         dateVal = PG_GETARG_DATEADT(0);
868         Interval   *span = PG_GETARG_INTERVAL_P(1);
869         Timestamp       dateStamp;
870
871         dateStamp = date2timestamp(dateVal);
872
873         return DirectFunctionCall2(timestamp_mi_interval,
874                                                            TimestampGetDatum(dateStamp),
875                                                            PointerGetDatum(span));
876 }
877
878 /* date_timestamp()
879  * Convert date to timestamp data type.
880  */
881 Datum
882 date_timestamp(PG_FUNCTION_ARGS)
883 {
884         DateADT         dateVal = PG_GETARG_DATEADT(0);
885         Timestamp       result;
886
887         result = date2timestamp(dateVal);
888
889         PG_RETURN_TIMESTAMP(result);
890 }
891
892
893 /* timestamp_date()
894  * Convert timestamp to date data type.
895  */
896 Datum
897 timestamp_date(PG_FUNCTION_ARGS)
898 {
899         Timestamp       timestamp = PG_GETARG_TIMESTAMP(0);
900         DateADT         result;
901         struct pg_tm tt,
902                            *tm = &tt;
903         fsec_t          fsec;
904
905         if (TIMESTAMP_IS_NOBEGIN(timestamp))
906                 DATE_NOBEGIN(result);
907         else if (TIMESTAMP_IS_NOEND(timestamp))
908                 DATE_NOEND(result);
909         else
910         {
911                 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
912                         ereport(ERROR,
913                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
914                                          errmsg("timestamp out of range")));
915
916                 result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - POSTGRES_EPOCH_JDATE;
917         }
918
919         PG_RETURN_DATEADT(result);
920 }
921
922
923 /* date_timestamptz()
924  * Convert date to timestamp with time zone data type.
925  */
926 Datum
927 date_timestamptz(PG_FUNCTION_ARGS)
928 {
929         DateADT         dateVal = PG_GETARG_DATEADT(0);
930         TimestampTz result;
931
932         result = date2timestamptz(dateVal);
933
934         PG_RETURN_TIMESTAMP(result);
935 }
936
937
938 /* timestamptz_date()
939  * Convert timestamp with time zone to date data type.
940  */
941 Datum
942 timestamptz_date(PG_FUNCTION_ARGS)
943 {
944         TimestampTz timestamp = PG_GETARG_TIMESTAMP(0);
945         DateADT         result;
946         struct pg_tm tt,
947                            *tm = &tt;
948         fsec_t          fsec;
949         int                     tz;
950         char       *tzn;
951
952         if (TIMESTAMP_IS_NOBEGIN(timestamp))
953                 DATE_NOBEGIN(result);
954         else if (TIMESTAMP_IS_NOEND(timestamp))
955                 DATE_NOEND(result);
956         else
957         {
958                 if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
959                         ereport(ERROR,
960                                         (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
961                                          errmsg("timestamp out of range")));
962
963                 result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - POSTGRES_EPOCH_JDATE;
964         }
965
966         PG_RETURN_DATEADT(result);
967 }
968
969
970 /* abstime_date()
971  * Convert abstime to date data type.
972  */
973 Datum
974 abstime_date(PG_FUNCTION_ARGS)
975 {
976         AbsoluteTime abstime = PG_GETARG_ABSOLUTETIME(0);
977         DateADT         result;
978         struct pg_tm tt,
979                            *tm = &tt;
980         int                     tz;
981
982         switch (abstime)
983         {
984                 case INVALID_ABSTIME:
985                         ereport(ERROR,
986                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
987                                    errmsg("cannot convert reserved abstime value to date")));
988                         result = 0;                     /* keep compiler quiet */
989                         break;
990
991                 case NOSTART_ABSTIME:
992                         DATE_NOBEGIN(result);
993                         break;
994
995                 case NOEND_ABSTIME:
996                         DATE_NOEND(result);
997                         break;
998
999                 default:
1000                         abstime2tm(abstime, &tz, tm, NULL);
1001                         result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - POSTGRES_EPOCH_JDATE;
1002                         break;
1003         }
1004
1005         PG_RETURN_DATEADT(result);
1006 }
1007
1008
1009 /*****************************************************************************
1010  *       Time ADT
1011  *****************************************************************************/
1012
1013 Datum
1014 time_in(PG_FUNCTION_ARGS)
1015 {
1016         char       *str = PG_GETARG_CSTRING(0);
1017
1018 #ifdef NOT_USED
1019         Oid                     typelem = PG_GETARG_OID(1);
1020 #endif
1021         int32           typmod = PG_GETARG_INT32(2);
1022         TimeADT         result;
1023         fsec_t          fsec;
1024         struct pg_tm tt,
1025                            *tm = &tt;
1026         int                     tz;
1027         int                     nf;
1028         int                     dterr;
1029         char            workbuf[MAXDATELEN + 1];
1030         char       *field[MAXDATEFIELDS];
1031         int                     dtype;
1032         int                     ftype[MAXDATEFIELDS];
1033
1034         dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
1035                                                   field, ftype, MAXDATEFIELDS, &nf);
1036         if (dterr == 0)
1037                 dterr = DecodeTimeOnly(field, ftype, nf, &dtype, tm, &fsec, &tz);
1038         if (dterr != 0)
1039                 DateTimeParseError(dterr, str, "time");
1040
1041         tm2time(tm, fsec, &result);
1042         AdjustTimeForTypmod(&result, typmod);
1043
1044         PG_RETURN_TIMEADT(result);
1045 }
1046
1047 /* tm2time()
1048  * Convert a tm structure to a time data type.
1049  */
1050 static int
1051 tm2time(struct pg_tm * tm, fsec_t fsec, TimeADT *result)
1052 {
1053 #ifdef HAVE_INT64_TIMESTAMP
1054         *result = ((((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec)
1055                            * USECS_PER_SEC) + fsec;
1056 #else
1057         *result = ((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec + fsec;
1058 #endif
1059         return 0;
1060 }
1061
1062 /* time2tm()
1063  * Convert time data type to POSIX time structure.
1064  *
1065  * For dates within the range of pg_time_t, convert to the local time zone.
1066  * If out of this range, leave as UTC (in practice that could only happen
1067  * if pg_time_t is just 32 bits) - thomas 97/05/27
1068  */
1069 static int
1070 time2tm(TimeADT time, struct pg_tm * tm, fsec_t *fsec)
1071 {
1072 #ifdef HAVE_INT64_TIMESTAMP
1073         tm->tm_hour = time / USECS_PER_HOUR;
1074         time -= tm->tm_hour * USECS_PER_HOUR;
1075         tm->tm_min = time / USECS_PER_MINUTE;
1076         time -= tm->tm_min * USECS_PER_MINUTE;
1077         tm->tm_sec = time / USECS_PER_SEC;
1078         time -= tm->tm_sec * USECS_PER_SEC;
1079         *fsec = time;
1080 #else
1081         double          trem;
1082
1083 recalc:
1084         trem = time;
1085         TMODULO(trem, tm->tm_hour, (double) SECS_PER_HOUR);
1086         TMODULO(trem, tm->tm_min, (double) SECS_PER_MINUTE);
1087         TMODULO(trem, tm->tm_sec, 1.0);
1088         trem = TIMEROUND(trem);
1089         /* roundoff may need to propagate to higher-order fields */
1090         if (trem >= 1.0)
1091         {
1092                 time = ceil(time);
1093                 goto recalc;
1094         }
1095         *fsec = trem;
1096 #endif
1097
1098         return 0;
1099 }
1100
1101 Datum
1102 time_out(PG_FUNCTION_ARGS)
1103 {
1104         TimeADT         time = PG_GETARG_TIMEADT(0);
1105         char       *result;
1106         struct pg_tm tt,
1107                            *tm = &tt;
1108         fsec_t          fsec;
1109         char            buf[MAXDATELEN + 1];
1110
1111         time2tm(time, tm, &fsec);
1112         EncodeTimeOnly(tm, fsec, NULL, DateStyle, buf);
1113
1114         result = pstrdup(buf);
1115         PG_RETURN_CSTRING(result);
1116 }
1117
1118 /*
1119  *              time_recv                       - converts external binary format to time
1120  *
1121  * We make no attempt to provide compatibility between int and float
1122  * time representations ...
1123  */
1124 Datum
1125 time_recv(PG_FUNCTION_ARGS)
1126 {
1127         StringInfo      buf = (StringInfo) PG_GETARG_POINTER(0);
1128
1129 #ifdef NOT_USED
1130         Oid                     typelem = PG_GETARG_OID(1);
1131 #endif
1132         int32           typmod = PG_GETARG_INT32(2);
1133         TimeADT         result;
1134
1135 #ifdef HAVE_INT64_TIMESTAMP
1136         result = pq_getmsgint64(buf);
1137
1138         if (result < INT64CONST(0) || result > USECS_PER_DAY)
1139                 ereport(ERROR,
1140                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1141                                  errmsg("time out of range")));
1142 #else
1143         result = pq_getmsgfloat8(buf);
1144
1145         if (result < 0 || result > (double) SECS_PER_DAY)
1146                 ereport(ERROR,
1147                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1148                                  errmsg("time out of range")));
1149 #endif
1150
1151         AdjustTimeForTypmod(&result, typmod);
1152
1153         PG_RETURN_TIMEADT(result);
1154 }
1155
1156 /*
1157  *              time_send                       - converts time to binary format
1158  */
1159 Datum
1160 time_send(PG_FUNCTION_ARGS)
1161 {
1162         TimeADT         time = PG_GETARG_TIMEADT(0);
1163         StringInfoData buf;
1164
1165         pq_begintypsend(&buf);
1166 #ifdef HAVE_INT64_TIMESTAMP
1167         pq_sendint64(&buf, time);
1168 #else
1169         pq_sendfloat8(&buf, time);
1170 #endif
1171         PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
1172 }
1173
1174 Datum
1175 timetypmodin(PG_FUNCTION_ARGS)
1176 {
1177         ArrayType  *ta = PG_GETARG_ARRAYTYPE_P(0);
1178
1179         PG_RETURN_INT32(anytime_typmodin(false, ta));
1180 }
1181
1182 Datum
1183 timetypmodout(PG_FUNCTION_ARGS)
1184 {
1185         int32           typmod = PG_GETARG_INT32(0);
1186
1187         PG_RETURN_CSTRING(anytime_typmodout(false, typmod));
1188 }
1189
1190
1191 /* time_scale()
1192  * Adjust time type for specified scale factor.
1193  * Used by PostgreSQL type system to stuff columns.
1194  */
1195 Datum
1196 time_scale(PG_FUNCTION_ARGS)
1197 {
1198         TimeADT         time = PG_GETARG_TIMEADT(0);
1199         int32           typmod = PG_GETARG_INT32(1);
1200         TimeADT         result;
1201
1202         result = time;
1203         AdjustTimeForTypmod(&result, typmod);
1204
1205         PG_RETURN_TIMEADT(result);
1206 }
1207
1208 /* AdjustTimeForTypmod()
1209  * Force the precision of the time value to a specified value.
1210  * Uses *exactly* the same code as in AdjustTimestampForTypemod()
1211  * but we make a separate copy because those types do not
1212  * have a fundamental tie together but rather a coincidence of
1213  * implementation. - thomas
1214  */
1215 static void
1216 AdjustTimeForTypmod(TimeADT *time, int32 typmod)
1217 {
1218 #ifdef HAVE_INT64_TIMESTAMP
1219         static const int64 TimeScales[MAX_TIME_PRECISION + 1] = {
1220                 INT64CONST(1000000),
1221                 INT64CONST(100000),
1222                 INT64CONST(10000),
1223                 INT64CONST(1000),
1224                 INT64CONST(100),
1225                 INT64CONST(10),
1226                 INT64CONST(1)
1227         };
1228
1229         static const int64 TimeOffsets[MAX_TIME_PRECISION + 1] = {
1230                 INT64CONST(500000),
1231                 INT64CONST(50000),
1232                 INT64CONST(5000),
1233                 INT64CONST(500),
1234                 INT64CONST(50),
1235                 INT64CONST(5),
1236                 INT64CONST(0)
1237         };
1238 #else
1239         /* note MAX_TIME_PRECISION differs in this case */
1240         static const double TimeScales[MAX_TIME_PRECISION + 1] = {
1241                 1.0,
1242                 10.0,
1243                 100.0,
1244                 1000.0,
1245                 10000.0,
1246                 100000.0,
1247                 1000000.0,
1248                 10000000.0,
1249                 100000000.0,
1250                 1000000000.0,
1251                 10000000000.0
1252         };
1253 #endif
1254
1255         if (typmod >= 0 && typmod <= MAX_TIME_PRECISION)
1256         {
1257                 /*
1258                  * Note: this round-to-nearest code is not completely consistent about
1259                  * rounding values that are exactly halfway between integral values.
1260                  * On most platforms, rint() will implement round-to-nearest-even, but
1261                  * the integer code always rounds up (away from zero).  Is it worth
1262                  * trying to be consistent?
1263                  */
1264 #ifdef HAVE_INT64_TIMESTAMP
1265                 if (*time >= INT64CONST(0))
1266                         *time = ((*time + TimeOffsets[typmod]) / TimeScales[typmod]) *
1267                                 TimeScales[typmod];
1268                 else
1269                         *time = -((((-*time) + TimeOffsets[typmod]) / TimeScales[typmod]) *
1270                                           TimeScales[typmod]);
1271 #else
1272                 *time = rint((double) *time * TimeScales[typmod]) / TimeScales[typmod];
1273 #endif
1274         }
1275 }
1276
1277
1278 Datum
1279 time_eq(PG_FUNCTION_ARGS)
1280 {
1281         TimeADT         time1 = PG_GETARG_TIMEADT(0);
1282         TimeADT         time2 = PG_GETARG_TIMEADT(1);
1283
1284         PG_RETURN_BOOL(time1 == time2);
1285 }
1286
1287 Datum
1288 time_ne(PG_FUNCTION_ARGS)
1289 {
1290         TimeADT         time1 = PG_GETARG_TIMEADT(0);
1291         TimeADT         time2 = PG_GETARG_TIMEADT(1);
1292
1293         PG_RETURN_BOOL(time1 != time2);
1294 }
1295
1296 Datum
1297 time_lt(PG_FUNCTION_ARGS)
1298 {
1299         TimeADT         time1 = PG_GETARG_TIMEADT(0);
1300         TimeADT         time2 = PG_GETARG_TIMEADT(1);
1301
1302         PG_RETURN_BOOL(time1 < time2);
1303 }
1304
1305 Datum
1306 time_le(PG_FUNCTION_ARGS)
1307 {
1308         TimeADT         time1 = PG_GETARG_TIMEADT(0);
1309         TimeADT         time2 = PG_GETARG_TIMEADT(1);
1310
1311         PG_RETURN_BOOL(time1 <= time2);
1312 }
1313
1314 Datum
1315 time_gt(PG_FUNCTION_ARGS)
1316 {
1317         TimeADT         time1 = PG_GETARG_TIMEADT(0);
1318         TimeADT         time2 = PG_GETARG_TIMEADT(1);
1319
1320         PG_RETURN_BOOL(time1 > time2);
1321 }
1322
1323 Datum
1324 time_ge(PG_FUNCTION_ARGS)
1325 {
1326         TimeADT         time1 = PG_GETARG_TIMEADT(0);
1327         TimeADT         time2 = PG_GETARG_TIMEADT(1);
1328
1329         PG_RETURN_BOOL(time1 >= time2);
1330 }
1331
1332 Datum
1333 time_cmp(PG_FUNCTION_ARGS)
1334 {
1335         TimeADT         time1 = PG_GETARG_TIMEADT(0);
1336         TimeADT         time2 = PG_GETARG_TIMEADT(1);
1337
1338         if (time1 < time2)
1339                 PG_RETURN_INT32(-1);
1340         if (time1 > time2)
1341                 PG_RETURN_INT32(1);
1342         PG_RETURN_INT32(0);
1343 }
1344
1345 Datum
1346 time_hash(PG_FUNCTION_ARGS)
1347 {
1348         /* We can use either hashint8 or hashfloat8 directly */
1349 #ifdef HAVE_INT64_TIMESTAMP
1350         return hashint8(fcinfo);
1351 #else
1352         return hashfloat8(fcinfo);
1353 #endif
1354 }
1355
1356 Datum
1357 time_larger(PG_FUNCTION_ARGS)
1358 {
1359         TimeADT         time1 = PG_GETARG_TIMEADT(0);
1360         TimeADT         time2 = PG_GETARG_TIMEADT(1);
1361
1362         PG_RETURN_TIMEADT((time1 > time2) ? time1 : time2);
1363 }
1364
1365 Datum
1366 time_smaller(PG_FUNCTION_ARGS)
1367 {
1368         TimeADT         time1 = PG_GETARG_TIMEADT(0);
1369         TimeADT         time2 = PG_GETARG_TIMEADT(1);
1370
1371         PG_RETURN_TIMEADT((time1 < time2) ? time1 : time2);
1372 }
1373
1374 /* overlaps_time() --- implements the SQL92 OVERLAPS operator.
1375  *
1376  * Algorithm is per SQL92 spec.  This is much harder than you'd think
1377  * because the spec requires us to deliver a non-null answer in some cases
1378  * where some of the inputs are null.
1379  */
1380 Datum
1381 overlaps_time(PG_FUNCTION_ARGS)
1382 {
1383         /*
1384          * The arguments are TimeADT, but we leave them as generic Datums to avoid
1385          * dereferencing nulls (TimeADT is pass-by-reference!)
1386          */
1387         Datum           ts1 = PG_GETARG_DATUM(0);
1388         Datum           te1 = PG_GETARG_DATUM(1);
1389         Datum           ts2 = PG_GETARG_DATUM(2);
1390         Datum           te2 = PG_GETARG_DATUM(3);
1391         bool            ts1IsNull = PG_ARGISNULL(0);
1392         bool            te1IsNull = PG_ARGISNULL(1);
1393         bool            ts2IsNull = PG_ARGISNULL(2);
1394         bool            te2IsNull = PG_ARGISNULL(3);
1395
1396 #define TIMEADT_GT(t1,t2) \
1397         (DatumGetTimeADT(t1) > DatumGetTimeADT(t2))
1398 #define TIMEADT_LT(t1,t2) \
1399         (DatumGetTimeADT(t1) < DatumGetTimeADT(t2))
1400
1401         /*
1402          * If both endpoints of interval 1 are null, the result is null (unknown).
1403          * If just one endpoint is null, take ts1 as the non-null one. Otherwise,
1404          * take ts1 as the lesser endpoint.
1405          */
1406         if (ts1IsNull)
1407         {
1408                 if (te1IsNull)
1409                         PG_RETURN_NULL();
1410                 /* swap null for non-null */
1411                 ts1 = te1;
1412                 te1IsNull = true;
1413         }
1414         else if (!te1IsNull)
1415         {
1416                 if (TIMEADT_GT(ts1, te1))
1417                 {
1418                         Datum           tt = ts1;
1419
1420                         ts1 = te1;
1421                         te1 = tt;
1422                 }
1423         }
1424
1425         /* Likewise for interval 2. */
1426         if (ts2IsNull)
1427         {
1428                 if (te2IsNull)
1429                         PG_RETURN_NULL();
1430                 /* swap null for non-null */
1431                 ts2 = te2;
1432                 te2IsNull = true;
1433         }
1434         else if (!te2IsNull)
1435         {
1436                 if (TIMEADT_GT(ts2, te2))
1437                 {
1438                         Datum           tt = ts2;
1439
1440                         ts2 = te2;
1441                         te2 = tt;
1442                 }
1443         }
1444
1445         /*
1446          * At this point neither ts1 nor ts2 is null, so we can consider three
1447          * cases: ts1 > ts2, ts1 < ts2, ts1 = ts2
1448          */
1449         if (TIMEADT_GT(ts1, ts2))
1450         {
1451                 /*
1452                  * This case is ts1 < te2 OR te1 < te2, which may look redundant but
1453                  * in the presence of nulls it's not quite completely so.
1454                  */
1455                 if (te2IsNull)
1456                         PG_RETURN_NULL();
1457                 if (TIMEADT_LT(ts1, te2))
1458                         PG_RETURN_BOOL(true);
1459                 if (te1IsNull)
1460                         PG_RETURN_NULL();
1461
1462                 /*
1463                  * If te1 is not null then we had ts1 <= te1 above, and we just found
1464                  * ts1 >= te2, hence te1 >= te2.
1465                  */
1466                 PG_RETURN_BOOL(false);
1467         }
1468         else if (TIMEADT_LT(ts1, ts2))
1469         {
1470                 /* This case is ts2 < te1 OR te2 < te1 */
1471                 if (te1IsNull)
1472                         PG_RETURN_NULL();
1473                 if (TIMEADT_LT(ts2, te1))
1474                         PG_RETURN_BOOL(true);
1475                 if (te2IsNull)
1476                         PG_RETURN_NULL();
1477
1478                 /*
1479                  * If te2 is not null then we had ts2 <= te2 above, and we just found
1480                  * ts2 >= te1, hence te2 >= te1.
1481                  */
1482                 PG_RETURN_BOOL(false);
1483         }
1484         else
1485         {
1486                 /*
1487                  * For ts1 = ts2 the spec says te1 <> te2 OR te1 = te2, which is a
1488                  * rather silly way of saying "true if both are nonnull, else null".
1489                  */
1490                 if (te1IsNull || te2IsNull)
1491                         PG_RETURN_NULL();
1492                 PG_RETURN_BOOL(true);
1493         }
1494
1495 #undef TIMEADT_GT
1496 #undef TIMEADT_LT
1497 }
1498
1499 /* timestamp_time()
1500  * Convert timestamp to time data type.
1501  */
1502 Datum
1503 timestamp_time(PG_FUNCTION_ARGS)
1504 {
1505         Timestamp       timestamp = PG_GETARG_TIMESTAMP(0);
1506         TimeADT         result;
1507         struct pg_tm tt,
1508                            *tm = &tt;
1509         fsec_t          fsec;
1510
1511         if (TIMESTAMP_NOT_FINITE(timestamp))
1512                 PG_RETURN_NULL();
1513
1514         if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
1515                 ereport(ERROR,
1516                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1517                                  errmsg("timestamp out of range")));
1518
1519 #ifdef HAVE_INT64_TIMESTAMP
1520
1521         /*
1522          * Could also do this with time = (timestamp / USECS_PER_DAY *
1523          * USECS_PER_DAY) - timestamp;
1524          */
1525         result = ((((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec) *
1526                           USECS_PER_SEC) + fsec;
1527 #else
1528         result = ((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec + fsec;
1529 #endif
1530
1531         PG_RETURN_TIMEADT(result);
1532 }
1533
1534 /* timestamptz_time()
1535  * Convert timestamptz to time data type.
1536  */
1537 Datum
1538 timestamptz_time(PG_FUNCTION_ARGS)
1539 {
1540         TimestampTz timestamp = PG_GETARG_TIMESTAMP(0);
1541         TimeADT         result;
1542         struct pg_tm tt,
1543                            *tm = &tt;
1544         int                     tz;
1545         fsec_t          fsec;
1546         char       *tzn;
1547
1548         if (TIMESTAMP_NOT_FINITE(timestamp))
1549                 PG_RETURN_NULL();
1550
1551         if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
1552                 ereport(ERROR,
1553                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1554                                  errmsg("timestamp out of range")));
1555
1556 #ifdef HAVE_INT64_TIMESTAMP
1557
1558         /*
1559          * Could also do this with time = (timestamp / USECS_PER_DAY *
1560          * USECS_PER_DAY) - timestamp;
1561          */
1562         result = ((((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec) *
1563                           USECS_PER_SEC) + fsec;
1564 #else
1565         result = ((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec + fsec;
1566 #endif
1567
1568         PG_RETURN_TIMEADT(result);
1569 }
1570
1571 /* datetime_timestamp()
1572  * Convert date and time to timestamp data type.
1573  */
1574 Datum
1575 datetime_timestamp(PG_FUNCTION_ARGS)
1576 {
1577         DateADT         date = PG_GETARG_DATEADT(0);
1578         TimeADT         time = PG_GETARG_TIMEADT(1);
1579         Timestamp       result;
1580
1581         result = date2timestamp(date);
1582         if (!TIMESTAMP_NOT_FINITE(result))
1583                 result += time;
1584
1585         PG_RETURN_TIMESTAMP(result);
1586 }
1587
1588 /* time_interval()
1589  * Convert time to interval data type.
1590  */
1591 Datum
1592 time_interval(PG_FUNCTION_ARGS)
1593 {
1594         TimeADT         time = PG_GETARG_TIMEADT(0);
1595         Interval   *result;
1596
1597         result = (Interval *) palloc(sizeof(Interval));
1598
1599         result->time = time;
1600         result->day = 0;
1601         result->month = 0;
1602
1603         PG_RETURN_INTERVAL_P(result);
1604 }
1605
1606 /* interval_time()
1607  * Convert interval to time data type.
1608  *
1609  * This is defined as producing the fractional-day portion of the interval.
1610  * Therefore, we can just ignore the months field.      It is not real clear
1611  * what to do with negative intervals, but we choose to subtract the floor,
1612  * so that, say, '-2 hours' becomes '22:00:00'.
1613  */
1614 Datum
1615 interval_time(PG_FUNCTION_ARGS)
1616 {
1617         Interval   *span = PG_GETARG_INTERVAL_P(0);
1618         TimeADT         result;
1619
1620 #ifdef HAVE_INT64_TIMESTAMP
1621         int64           days;
1622
1623         result = span->time;
1624         if (result >= USECS_PER_DAY)
1625         {
1626                 days = result / USECS_PER_DAY;
1627                 result -= days * USECS_PER_DAY;
1628         }
1629         else if (result < 0)
1630         {
1631                 days = (-result + USECS_PER_DAY - 1) / USECS_PER_DAY;
1632                 result += days * USECS_PER_DAY;
1633         }
1634 #else
1635         result = span->time;
1636         if (result >= (double) SECS_PER_DAY || result < 0)
1637                 result -= floor(result / (double) SECS_PER_DAY) * (double) SECS_PER_DAY;
1638 #endif
1639
1640         PG_RETURN_TIMEADT(result);
1641 }
1642
1643 /* time_mi_time()
1644  * Subtract two times to produce an interval.
1645  */
1646 Datum
1647 time_mi_time(PG_FUNCTION_ARGS)
1648 {
1649         TimeADT         time1 = PG_GETARG_TIMEADT(0);
1650         TimeADT         time2 = PG_GETARG_TIMEADT(1);
1651         Interval   *result;
1652
1653         result = (Interval *) palloc(sizeof(Interval));
1654
1655         result->month = 0;
1656         result->day = 0;
1657         result->time = time1 - time2;
1658
1659         PG_RETURN_INTERVAL_P(result);
1660 }
1661
1662 /* time_pl_interval()
1663  * Add interval to time.
1664  */
1665 Datum
1666 time_pl_interval(PG_FUNCTION_ARGS)
1667 {
1668         TimeADT         time = PG_GETARG_TIMEADT(0);
1669         Interval   *span = PG_GETARG_INTERVAL_P(1);
1670         TimeADT         result;
1671
1672 #ifdef HAVE_INT64_TIMESTAMP
1673         result = time + span->time;
1674         result -= result / USECS_PER_DAY * USECS_PER_DAY;
1675         if (result < INT64CONST(0))
1676                 result += USECS_PER_DAY;
1677 #else
1678         TimeADT         time1;
1679
1680         result = time + span->time;
1681         TMODULO(result, time1, (double) SECS_PER_DAY);
1682         if (result < 0)
1683                 result += SECS_PER_DAY;
1684 #endif
1685
1686         PG_RETURN_TIMEADT(result);
1687 }
1688
1689 /* time_mi_interval()
1690  * Subtract interval from time.
1691  */
1692 Datum
1693 time_mi_interval(PG_FUNCTION_ARGS)
1694 {
1695         TimeADT         time = PG_GETARG_TIMEADT(0);
1696         Interval   *span = PG_GETARG_INTERVAL_P(1);
1697         TimeADT         result;
1698
1699 #ifdef HAVE_INT64_TIMESTAMP
1700         result = time - span->time;
1701         result -= result / USECS_PER_DAY * USECS_PER_DAY;
1702         if (result < INT64CONST(0))
1703                 result += USECS_PER_DAY;
1704 #else
1705         TimeADT         time1;
1706
1707         result = time - span->time;
1708         TMODULO(result, time1, (double) SECS_PER_DAY);
1709         if (result < 0)
1710                 result += SECS_PER_DAY;
1711 #endif
1712
1713         PG_RETURN_TIMEADT(result);
1714 }
1715
1716
1717 /* time_part()
1718  * Extract specified field from time type.
1719  */
1720 Datum
1721 time_part(PG_FUNCTION_ARGS)
1722 {
1723         text       *units = PG_GETARG_TEXT_PP(0);
1724         TimeADT         time = PG_GETARG_TIMEADT(1);
1725         float8          result;
1726         int                     type,
1727                                 val;
1728         char       *lowunits;
1729
1730         lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
1731                                                                                         VARSIZE_ANY_EXHDR(units),
1732                                                                                         false);
1733
1734         type = DecodeUnits(0, lowunits, &val);
1735         if (type == UNKNOWN_FIELD)
1736                 type = DecodeSpecial(0, lowunits, &val);
1737
1738         if (type == UNITS)
1739         {
1740                 fsec_t          fsec;
1741                 struct pg_tm tt,
1742                                    *tm = &tt;
1743
1744                 time2tm(time, tm, &fsec);
1745
1746                 switch (val)
1747                 {
1748                         case DTK_MICROSEC:
1749 #ifdef HAVE_INT64_TIMESTAMP
1750                                 result = tm->tm_sec * 1000000.0 + fsec;
1751 #else
1752                                 result = (tm->tm_sec + fsec) * 1000000;
1753 #endif
1754                                 break;
1755
1756                         case DTK_MILLISEC:
1757 #ifdef HAVE_INT64_TIMESTAMP
1758                                 result = tm->tm_sec * 1000.0 + fsec / 1000.0;
1759 #else
1760                                 result = (tm->tm_sec + fsec) * 1000;
1761 #endif
1762                                 break;
1763
1764                         case DTK_SECOND:
1765 #ifdef HAVE_INT64_TIMESTAMP
1766                                 result = tm->tm_sec + fsec / 1000000.0;
1767 #else
1768                                 result = tm->tm_sec + fsec;
1769 #endif
1770                                 break;
1771
1772                         case DTK_MINUTE:
1773                                 result = tm->tm_min;
1774                                 break;
1775
1776                         case DTK_HOUR:
1777                                 result = tm->tm_hour;
1778                                 break;
1779
1780                         case DTK_TZ:
1781                         case DTK_TZ_MINUTE:
1782                         case DTK_TZ_HOUR:
1783                         case DTK_DAY:
1784                         case DTK_MONTH:
1785                         case DTK_QUARTER:
1786                         case DTK_YEAR:
1787                         case DTK_DECADE:
1788                         case DTK_CENTURY:
1789                         case DTK_MILLENNIUM:
1790                         case DTK_ISOYEAR:
1791                         default:
1792                                 ereport(ERROR,
1793                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1794                                                  errmsg("\"time\" units \"%s\" not recognized",
1795                                                                 lowunits)));
1796                                 result = 0;
1797                 }
1798         }
1799         else if (type == RESERV && val == DTK_EPOCH)
1800         {
1801 #ifdef HAVE_INT64_TIMESTAMP
1802                 result = time / 1000000.0;
1803 #else
1804                 result = time;
1805 #endif
1806         }
1807         else
1808         {
1809                 ereport(ERROR,
1810                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1811                                  errmsg("\"time\" units \"%s\" not recognized",
1812                                                 lowunits)));
1813                 result = 0;
1814         }
1815
1816         PG_RETURN_FLOAT8(result);
1817 }
1818
1819
1820 /*****************************************************************************
1821  *       Time With Time Zone ADT
1822  *****************************************************************************/
1823
1824 /* tm2timetz()
1825  * Convert a tm structure to a time data type.
1826  */
1827 static int
1828 tm2timetz(struct pg_tm * tm, fsec_t fsec, int tz, TimeTzADT *result)
1829 {
1830 #ifdef HAVE_INT64_TIMESTAMP
1831         result->time = ((((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec) *
1832                                         USECS_PER_SEC) + fsec;
1833 #else
1834         result->time = ((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec + fsec;
1835 #endif
1836         result->zone = tz;
1837
1838         return 0;
1839 }
1840
1841 Datum
1842 timetz_in(PG_FUNCTION_ARGS)
1843 {
1844         char       *str = PG_GETARG_CSTRING(0);
1845
1846 #ifdef NOT_USED
1847         Oid                     typelem = PG_GETARG_OID(1);
1848 #endif
1849         int32           typmod = PG_GETARG_INT32(2);
1850         TimeTzADT  *result;
1851         fsec_t          fsec;
1852         struct pg_tm tt,
1853                            *tm = &tt;
1854         int                     tz;
1855         int                     nf;
1856         int                     dterr;
1857         char            workbuf[MAXDATELEN + 1];
1858         char       *field[MAXDATEFIELDS];
1859         int                     dtype;
1860         int                     ftype[MAXDATEFIELDS];
1861
1862         dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
1863                                                   field, ftype, MAXDATEFIELDS, &nf);
1864         if (dterr == 0)
1865                 dterr = DecodeTimeOnly(field, ftype, nf, &dtype, tm, &fsec, &tz);
1866         if (dterr != 0)
1867                 DateTimeParseError(dterr, str, "time with time zone");
1868
1869         result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
1870         tm2timetz(tm, fsec, tz, result);
1871         AdjustTimeForTypmod(&(result->time), typmod);
1872
1873         PG_RETURN_TIMETZADT_P(result);
1874 }
1875
1876 Datum
1877 timetz_out(PG_FUNCTION_ARGS)
1878 {
1879         TimeTzADT  *time = PG_GETARG_TIMETZADT_P(0);
1880         char       *result;
1881         struct pg_tm tt,
1882                            *tm = &tt;
1883         fsec_t          fsec;
1884         int                     tz;
1885         char            buf[MAXDATELEN + 1];
1886
1887         timetz2tm(time, tm, &fsec, &tz);
1888         EncodeTimeOnly(tm, fsec, &tz, DateStyle, buf);
1889
1890         result = pstrdup(buf);
1891         PG_RETURN_CSTRING(result);
1892 }
1893
1894 /*
1895  *              timetz_recv                     - converts external binary format to timetz
1896  */
1897 Datum
1898 timetz_recv(PG_FUNCTION_ARGS)
1899 {
1900         StringInfo      buf = (StringInfo) PG_GETARG_POINTER(0);
1901
1902 #ifdef NOT_USED
1903         Oid                     typelem = PG_GETARG_OID(1);
1904 #endif
1905         int32           typmod = PG_GETARG_INT32(2);
1906         TimeTzADT  *result;
1907
1908         result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
1909
1910 #ifdef HAVE_INT64_TIMESTAMP
1911         result->time = pq_getmsgint64(buf);
1912
1913         if (result->time < INT64CONST(0) || result->time > USECS_PER_DAY)
1914                 ereport(ERROR,
1915                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1916                                  errmsg("time out of range")));
1917 #else
1918         result->time = pq_getmsgfloat8(buf);
1919
1920         if (result->time < 0 || result->time > (double) SECS_PER_DAY)
1921                 ereport(ERROR,
1922                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1923                                  errmsg("time out of range")));
1924 #endif
1925
1926         result->zone = pq_getmsgint(buf, sizeof(result->zone));
1927
1928         /* we allow GMT displacements up to 14:59:59, cf DecodeTimezone() */
1929         if (result->zone <= -15 * SECS_PER_HOUR ||
1930                 result->zone >= 15 * SECS_PER_HOUR)
1931                 ereport(ERROR,
1932                                 (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
1933                                  errmsg("time zone displacement out of range")));
1934
1935         AdjustTimeForTypmod(&(result->time), typmod);
1936
1937         PG_RETURN_TIMETZADT_P(result);
1938 }
1939
1940 /*
1941  *              timetz_send                     - converts timetz to binary format
1942  */
1943 Datum
1944 timetz_send(PG_FUNCTION_ARGS)
1945 {
1946         TimeTzADT  *time = PG_GETARG_TIMETZADT_P(0);
1947         StringInfoData buf;
1948
1949         pq_begintypsend(&buf);
1950 #ifdef HAVE_INT64_TIMESTAMP
1951         pq_sendint64(&buf, time->time);
1952 #else
1953         pq_sendfloat8(&buf, time->time);
1954 #endif
1955         pq_sendint(&buf, time->zone, sizeof(time->zone));
1956         PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
1957 }
1958
1959 Datum
1960 timetztypmodin(PG_FUNCTION_ARGS)
1961 {
1962         ArrayType  *ta = PG_GETARG_ARRAYTYPE_P(0);
1963
1964         PG_RETURN_INT32(anytime_typmodin(true, ta));
1965 }
1966
1967 Datum
1968 timetztypmodout(PG_FUNCTION_ARGS)
1969 {
1970         int32           typmod = PG_GETARG_INT32(0);
1971
1972         PG_RETURN_CSTRING(anytime_typmodout(true, typmod));
1973 }
1974
1975
1976 /* timetz2tm()
1977  * Convert TIME WITH TIME ZONE data type to POSIX time structure.
1978  */
1979 static int
1980 timetz2tm(TimeTzADT *time, struct pg_tm * tm, fsec_t *fsec, int *tzp)
1981 {
1982         TimeOffset      trem = time->time;
1983
1984 #ifdef HAVE_INT64_TIMESTAMP
1985         tm->tm_hour = trem / USECS_PER_HOUR;
1986         trem -= tm->tm_hour * USECS_PER_HOUR;
1987         tm->tm_min = trem / USECS_PER_MINUTE;
1988         trem -= tm->tm_min * USECS_PER_MINUTE;
1989         tm->tm_sec = trem / USECS_PER_SEC;
1990         *fsec = trem - tm->tm_sec * USECS_PER_SEC;
1991 #else
1992 recalc:
1993         TMODULO(trem, tm->tm_hour, (double) SECS_PER_HOUR);
1994         TMODULO(trem, tm->tm_min, (double) SECS_PER_MINUTE);
1995         TMODULO(trem, tm->tm_sec, 1.0);
1996         trem = TIMEROUND(trem);
1997         /* roundoff may need to propagate to higher-order fields */
1998         if (trem >= 1.0)
1999         {
2000                 trem = ceil(time->time);
2001                 goto recalc;
2002         }
2003         *fsec = trem;
2004 #endif
2005
2006         if (tzp != NULL)
2007                 *tzp = time->zone;
2008
2009         return 0;
2010 }
2011
2012 /* timetz_scale()
2013  * Adjust time type for specified scale factor.
2014  * Used by PostgreSQL type system to stuff columns.
2015  */
2016 Datum
2017 timetz_scale(PG_FUNCTION_ARGS)
2018 {
2019         TimeTzADT  *time = PG_GETARG_TIMETZADT_P(0);
2020         int32           typmod = PG_GETARG_INT32(1);
2021         TimeTzADT  *result;
2022
2023         result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
2024
2025         result->time = time->time;
2026         result->zone = time->zone;
2027
2028         AdjustTimeForTypmod(&(result->time), typmod);
2029
2030         PG_RETURN_TIMETZADT_P(result);
2031 }
2032
2033
2034 static int
2035 timetz_cmp_internal(TimeTzADT *time1, TimeTzADT *time2)
2036 {
2037         TimeOffset      t1,
2038                                 t2;
2039
2040         /* Primary sort is by true (GMT-equivalent) time */
2041 #ifdef HAVE_INT64_TIMESTAMP
2042         t1 = time1->time + (time1->zone * USECS_PER_SEC);
2043         t2 = time2->time + (time2->zone * USECS_PER_SEC);
2044 #else
2045         t1 = time1->time + time1->zone;
2046         t2 = time2->time + time2->zone;
2047 #endif
2048
2049         if (t1 > t2)
2050                 return 1;
2051         if (t1 < t2)
2052                 return -1;
2053
2054         /*
2055          * If same GMT time, sort by timezone; we only want to say that two
2056          * timetz's are equal if both the time and zone parts are equal.
2057          */
2058         if (time1->zone > time2->zone)
2059                 return 1;
2060         if (time1->zone < time2->zone)
2061                 return -1;
2062
2063         return 0;
2064 }
2065
2066 Datum
2067 timetz_eq(PG_FUNCTION_ARGS)
2068 {
2069         TimeTzADT  *time1 = PG_GETARG_TIMETZADT_P(0);
2070         TimeTzADT  *time2 = PG_GETARG_TIMETZADT_P(1);
2071
2072         PG_RETURN_BOOL(timetz_cmp_internal(time1, time2) == 0);
2073 }
2074
2075 Datum
2076 timetz_ne(PG_FUNCTION_ARGS)
2077 {
2078         TimeTzADT  *time1 = PG_GETARG_TIMETZADT_P(0);
2079         TimeTzADT  *time2 = PG_GETARG_TIMETZADT_P(1);
2080
2081         PG_RETURN_BOOL(timetz_cmp_internal(time1, time2) != 0);
2082 }
2083
2084 Datum
2085 timetz_lt(PG_FUNCTION_ARGS)
2086 {
2087         TimeTzADT  *time1 = PG_GETARG_TIMETZADT_P(0);
2088         TimeTzADT  *time2 = PG_GETARG_TIMETZADT_P(1);
2089
2090         PG_RETURN_BOOL(timetz_cmp_internal(time1, time2) < 0);
2091 }
2092
2093 Datum
2094 timetz_le(PG_FUNCTION_ARGS)
2095 {
2096         TimeTzADT  *time1 = PG_GETARG_TIMETZADT_P(0);
2097         TimeTzADT  *time2 = PG_GETARG_TIMETZADT_P(1);
2098
2099         PG_RETURN_BOOL(timetz_cmp_internal(time1, time2) <= 0);
2100 }
2101
2102 Datum
2103 timetz_gt(PG_FUNCTION_ARGS)
2104 {
2105         TimeTzADT  *time1 = PG_GETARG_TIMETZADT_P(0);
2106         TimeTzADT  *time2 = PG_GETARG_TIMETZADT_P(1);
2107
2108         PG_RETURN_BOOL(timetz_cmp_internal(time1, time2) > 0);
2109 }
2110
2111 Datum
2112 timetz_ge(PG_FUNCTION_ARGS)
2113 {
2114         TimeTzADT  *time1 = PG_GETARG_TIMETZADT_P(0);
2115         TimeTzADT  *time2 = PG_GETARG_TIMETZADT_P(1);
2116
2117         PG_RETURN_BOOL(timetz_cmp_internal(time1, time2) >= 0);
2118 }
2119
2120 Datum
2121 timetz_cmp(PG_FUNCTION_ARGS)
2122 {
2123         TimeTzADT  *time1 = PG_GETARG_TIMETZADT_P(0);
2124         TimeTzADT  *time2 = PG_GETARG_TIMETZADT_P(1);
2125
2126         PG_RETURN_INT32(timetz_cmp_internal(time1, time2));
2127 }
2128
2129 Datum
2130 timetz_hash(PG_FUNCTION_ARGS)
2131 {
2132         TimeTzADT  *key = PG_GETARG_TIMETZADT_P(0);
2133         uint32          thash;
2134
2135         /*
2136          * To avoid any problems with padding bytes in the struct, we figure the
2137          * field hashes separately and XOR them.  This also provides a convenient
2138          * framework for dealing with the fact that the time field might be either
2139          * double or int64.
2140          */
2141 #ifdef HAVE_INT64_TIMESTAMP
2142         thash = DatumGetUInt32(DirectFunctionCall1(hashint8,
2143                                                                                            Int64GetDatumFast(key->time)));
2144 #else
2145         thash = DatumGetUInt32(DirectFunctionCall1(hashfloat8,
2146                                                                                          Float8GetDatumFast(key->time)));
2147 #endif
2148         thash ^= DatumGetUInt32(hash_uint32(key->zone));
2149         PG_RETURN_UINT32(thash);
2150 }
2151
2152 Datum
2153 timetz_larger(PG_FUNCTION_ARGS)
2154 {
2155         TimeTzADT  *time1 = PG_GETARG_TIMETZADT_P(0);
2156         TimeTzADT  *time2 = PG_GETARG_TIMETZADT_P(1);
2157         TimeTzADT  *result;
2158
2159         if (timetz_cmp_internal(time1, time2) > 0)
2160                 result = time1;
2161         else
2162                 result = time2;
2163         PG_RETURN_TIMETZADT_P(result);
2164 }
2165
2166 Datum
2167 timetz_smaller(PG_FUNCTION_ARGS)
2168 {
2169         TimeTzADT  *time1 = PG_GETARG_TIMETZADT_P(0);
2170         TimeTzADT  *time2 = PG_GETARG_TIMETZADT_P(1);
2171         TimeTzADT  *result;
2172
2173         if (timetz_cmp_internal(time1, time2) < 0)
2174                 result = time1;
2175         else
2176                 result = time2;
2177         PG_RETURN_TIMETZADT_P(result);
2178 }
2179
2180 /* timetz_pl_interval()
2181  * Add interval to timetz.
2182  */
2183 Datum
2184 timetz_pl_interval(PG_FUNCTION_ARGS)
2185 {
2186         TimeTzADT  *time = PG_GETARG_TIMETZADT_P(0);
2187         Interval   *span = PG_GETARG_INTERVAL_P(1);
2188         TimeTzADT  *result;
2189
2190 #ifndef HAVE_INT64_TIMESTAMP
2191         TimeTzADT       time1;
2192 #endif
2193
2194         result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
2195
2196 #ifdef HAVE_INT64_TIMESTAMP
2197         result->time = time->time + span->time;
2198         result->time -= result->time / USECS_PER_DAY * USECS_PER_DAY;
2199         if (result->time < INT64CONST(0))
2200                 result->time += USECS_PER_DAY;
2201 #else
2202         result->time = time->time + span->time;
2203         TMODULO(result->time, time1.time, (double) SECS_PER_DAY);
2204         if (result->time < 0)
2205                 result->time += SECS_PER_DAY;
2206 #endif
2207
2208         result->zone = time->zone;
2209
2210         PG_RETURN_TIMETZADT_P(result);
2211 }
2212
2213 /* timetz_mi_interval()
2214  * Subtract interval from timetz.
2215  */
2216 Datum
2217 timetz_mi_interval(PG_FUNCTION_ARGS)
2218 {
2219         TimeTzADT  *time = PG_GETARG_TIMETZADT_P(0);
2220         Interval   *span = PG_GETARG_INTERVAL_P(1);
2221         TimeTzADT  *result;
2222
2223 #ifndef HAVE_INT64_TIMESTAMP
2224         TimeTzADT       time1;
2225 #endif
2226
2227         result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
2228
2229 #ifdef HAVE_INT64_TIMESTAMP
2230         result->time = time->time - span->time;
2231         result->time -= result->time / USECS_PER_DAY * USECS_PER_DAY;
2232         if (result->time < INT64CONST(0))
2233                 result->time += USECS_PER_DAY;
2234 #else
2235         result->time = time->time - span->time;
2236         TMODULO(result->time, time1.time, (double) SECS_PER_DAY);
2237         if (result->time < 0)
2238                 result->time += SECS_PER_DAY;
2239 #endif
2240
2241         result->zone = time->zone;
2242
2243         PG_RETURN_TIMETZADT_P(result);
2244 }
2245
2246 /* overlaps_timetz() --- implements the SQL92 OVERLAPS operator.
2247  *
2248  * Algorithm is per SQL92 spec.  This is much harder than you'd think
2249  * because the spec requires us to deliver a non-null answer in some cases
2250  * where some of the inputs are null.
2251  */
2252 Datum
2253 overlaps_timetz(PG_FUNCTION_ARGS)
2254 {
2255         /*
2256          * The arguments are TimeTzADT *, but we leave them as generic Datums for
2257          * convenience of notation --- and to avoid dereferencing nulls.
2258          */
2259         Datum           ts1 = PG_GETARG_DATUM(0);
2260         Datum           te1 = PG_GETARG_DATUM(1);
2261         Datum           ts2 = PG_GETARG_DATUM(2);
2262         Datum           te2 = PG_GETARG_DATUM(3);
2263         bool            ts1IsNull = PG_ARGISNULL(0);
2264         bool            te1IsNull = PG_ARGISNULL(1);
2265         bool            ts2IsNull = PG_ARGISNULL(2);
2266         bool            te2IsNull = PG_ARGISNULL(3);
2267
2268 #define TIMETZ_GT(t1,t2) \
2269         DatumGetBool(DirectFunctionCall2(timetz_gt,t1,t2))
2270 #define TIMETZ_LT(t1,t2) \
2271         DatumGetBool(DirectFunctionCall2(timetz_lt,t1,t2))
2272
2273         /*
2274          * If both endpoints of interval 1 are null, the result is null (unknown).
2275          * If just one endpoint is null, take ts1 as the non-null one. Otherwise,
2276          * take ts1 as the lesser endpoint.
2277          */
2278         if (ts1IsNull)
2279         {
2280                 if (te1IsNull)
2281                         PG_RETURN_NULL();
2282                 /* swap null for non-null */
2283                 ts1 = te1;
2284                 te1IsNull = true;
2285         }
2286         else if (!te1IsNull)
2287         {
2288                 if (TIMETZ_GT(ts1, te1))
2289                 {
2290                         Datum           tt = ts1;
2291
2292                         ts1 = te1;
2293                         te1 = tt;
2294                 }
2295         }
2296
2297         /* Likewise for interval 2. */
2298         if (ts2IsNull)
2299         {
2300                 if (te2IsNull)
2301                         PG_RETURN_NULL();
2302                 /* swap null for non-null */
2303                 ts2 = te2;
2304                 te2IsNull = true;
2305         }
2306         else if (!te2IsNull)
2307         {
2308                 if (TIMETZ_GT(ts2, te2))
2309                 {
2310                         Datum           tt = ts2;
2311
2312                         ts2 = te2;
2313                         te2 = tt;
2314                 }
2315         }
2316
2317         /*
2318          * At this point neither ts1 nor ts2 is null, so we can consider three
2319          * cases: ts1 > ts2, ts1 < ts2, ts1 = ts2
2320          */
2321         if (TIMETZ_GT(ts1, ts2))
2322         {
2323                 /*
2324                  * This case is ts1 < te2 OR te1 < te2, which may look redundant but
2325                  * in the presence of nulls it's not quite completely so.
2326                  */
2327                 if (te2IsNull)
2328                         PG_RETURN_NULL();
2329                 if (TIMETZ_LT(ts1, te2))
2330                         PG_RETURN_BOOL(true);
2331                 if (te1IsNull)
2332                         PG_RETURN_NULL();
2333
2334                 /*
2335                  * If te1 is not null then we had ts1 <= te1 above, and we just found
2336                  * ts1 >= te2, hence te1 >= te2.
2337                  */
2338                 PG_RETURN_BOOL(false);
2339         }
2340         else if (TIMETZ_LT(ts1, ts2))
2341         {
2342                 /* This case is ts2 < te1 OR te2 < te1 */
2343                 if (te1IsNull)
2344                         PG_RETURN_NULL();
2345                 if (TIMETZ_LT(ts2, te1))
2346                         PG_RETURN_BOOL(true);
2347                 if (te2IsNull)
2348                         PG_RETURN_NULL();
2349
2350                 /*
2351                  * If te2 is not null then we had ts2 <= te2 above, and we just found
2352                  * ts2 >= te1, hence te2 >= te1.
2353                  */
2354                 PG_RETURN_BOOL(false);
2355         }
2356         else
2357         {
2358                 /*
2359                  * For ts1 = ts2 the spec says te1 <> te2 OR te1 = te2, which is a
2360                  * rather silly way of saying "true if both are nonnull, else null".
2361                  */
2362                 if (te1IsNull || te2IsNull)
2363                         PG_RETURN_NULL();
2364                 PG_RETURN_BOOL(true);
2365         }
2366
2367 #undef TIMETZ_GT
2368 #undef TIMETZ_LT
2369 }
2370
2371
2372 Datum
2373 timetz_time(PG_FUNCTION_ARGS)
2374 {
2375         TimeTzADT  *timetz = PG_GETARG_TIMETZADT_P(0);
2376         TimeADT         result;
2377
2378         /* swallow the time zone and just return the time */
2379         result = timetz->time;
2380
2381         PG_RETURN_TIMEADT(result);
2382 }
2383
2384
2385 Datum
2386 time_timetz(PG_FUNCTION_ARGS)
2387 {
2388         TimeADT         time = PG_GETARG_TIMEADT(0);
2389         TimeTzADT  *result;
2390         struct pg_tm tt,
2391                            *tm = &tt;
2392         fsec_t          fsec;
2393         int                     tz;
2394
2395         GetCurrentDateTime(tm);
2396         time2tm(time, tm, &fsec);
2397         tz = DetermineTimeZoneOffset(tm, session_timezone);
2398
2399         result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
2400
2401         result->time = time;
2402         result->zone = tz;
2403
2404         PG_RETURN_TIMETZADT_P(result);
2405 }
2406
2407
2408 /* timestamptz_timetz()
2409  * Convert timestamp to timetz data type.
2410  */
2411 Datum
2412 timestamptz_timetz(PG_FUNCTION_ARGS)
2413 {
2414         TimestampTz timestamp = PG_GETARG_TIMESTAMP(0);
2415         TimeTzADT  *result;
2416         struct pg_tm tt,
2417                            *tm = &tt;
2418         int                     tz;
2419         fsec_t          fsec;
2420         char       *tzn;
2421
2422         if (TIMESTAMP_NOT_FINITE(timestamp))
2423                 PG_RETURN_NULL();
2424
2425         if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
2426                 ereport(ERROR,
2427                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2428                                  errmsg("timestamp out of range")));
2429
2430         result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
2431
2432         tm2timetz(tm, fsec, tz, result);
2433
2434         PG_RETURN_TIMETZADT_P(result);
2435 }
2436
2437
2438 /* datetimetz_timestamptz()
2439  * Convert date and timetz to timestamp with time zone data type.
2440  * Timestamp is stored in GMT, so add the time zone
2441  * stored with the timetz to the result.
2442  * - thomas 2000-03-10
2443  */
2444 Datum
2445 datetimetz_timestamptz(PG_FUNCTION_ARGS)
2446 {
2447         DateADT         date = PG_GETARG_DATEADT(0);
2448         TimeTzADT  *time = PG_GETARG_TIMETZADT_P(1);
2449         TimestampTz result;
2450
2451         if (DATE_IS_NOBEGIN(date))
2452                 TIMESTAMP_NOBEGIN(result);
2453         else if (DATE_IS_NOEND(date))
2454                 TIMESTAMP_NOEND(result);
2455         else
2456         {
2457 #ifdef HAVE_INT64_TIMESTAMP
2458                 result = date * USECS_PER_DAY + time->time + time->zone * USECS_PER_SEC;
2459 #else
2460                 result = date * (double) SECS_PER_DAY + time->time + time->zone;
2461 #endif
2462         }
2463
2464         PG_RETURN_TIMESTAMP(result);
2465 }
2466
2467
2468 /* timetz_part()
2469  * Extract specified field from time type.
2470  */
2471 Datum
2472 timetz_part(PG_FUNCTION_ARGS)
2473 {
2474         text       *units = PG_GETARG_TEXT_PP(0);
2475         TimeTzADT  *time = PG_GETARG_TIMETZADT_P(1);
2476         float8          result;
2477         int                     type,
2478                                 val;
2479         char       *lowunits;
2480
2481         lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
2482                                                                                         VARSIZE_ANY_EXHDR(units),
2483                                                                                         false);
2484
2485         type = DecodeUnits(0, lowunits, &val);
2486         if (type == UNKNOWN_FIELD)
2487                 type = DecodeSpecial(0, lowunits, &val);
2488
2489         if (type == UNITS)
2490         {
2491                 double          dummy;
2492                 int                     tz;
2493                 fsec_t          fsec;
2494                 struct pg_tm tt,
2495                                    *tm = &tt;
2496
2497                 timetz2tm(time, tm, &fsec, &tz);
2498
2499                 switch (val)
2500                 {
2501                         case DTK_TZ:
2502                                 result = -tz;
2503                                 break;
2504
2505                         case DTK_TZ_MINUTE:
2506                                 result = -tz;
2507                                 result /= SECS_PER_MINUTE;
2508                                 FMODULO(result, dummy, (double) SECS_PER_MINUTE);
2509                                 break;
2510
2511                         case DTK_TZ_HOUR:
2512                                 dummy = -tz;
2513                                 FMODULO(dummy, result, (double) SECS_PER_HOUR);
2514                                 break;
2515
2516                         case DTK_MICROSEC:
2517 #ifdef HAVE_INT64_TIMESTAMP
2518                                 result = tm->tm_sec * 1000000.0 + fsec;
2519 #else
2520                                 result = (tm->tm_sec + fsec) * 1000000;
2521 #endif
2522                                 break;
2523
2524                         case DTK_MILLISEC:
2525 #ifdef HAVE_INT64_TIMESTAMP
2526                                 result = tm->tm_sec * 1000.0 + fsec / 1000.0;
2527 #else
2528                                 result = (tm->tm_sec + fsec) * 1000;
2529 #endif
2530                                 break;
2531
2532                         case DTK_SECOND:
2533 #ifdef HAVE_INT64_TIMESTAMP
2534                                 result = tm->tm_sec + fsec / 1000000.0;
2535 #else
2536                                 result = tm->tm_sec + fsec;
2537 #endif
2538                                 break;
2539
2540                         case DTK_MINUTE:
2541                                 result = tm->tm_min;
2542                                 break;
2543
2544                         case DTK_HOUR:
2545                                 result = tm->tm_hour;
2546                                 break;
2547
2548                         case DTK_DAY:
2549                         case DTK_MONTH:
2550                         case DTK_QUARTER:
2551                         case DTK_YEAR:
2552                         case DTK_DECADE:
2553                         case DTK_CENTURY:
2554                         case DTK_MILLENNIUM:
2555                         default:
2556                                 ereport(ERROR,
2557                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2558                                 errmsg("\"time with time zone\" units \"%s\" not recognized",
2559                                            lowunits)));
2560                                 result = 0;
2561                 }
2562         }
2563         else if (type == RESERV && val == DTK_EPOCH)
2564         {
2565 #ifdef HAVE_INT64_TIMESTAMP
2566                 result = time->time / 1000000.0 + time->zone;
2567 #else
2568                 result = time->time + time->zone;
2569 #endif
2570         }
2571         else
2572         {
2573                 ereport(ERROR,
2574                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2575                                  errmsg("\"time with time zone\" units \"%s\" not recognized",
2576                                                 lowunits)));
2577                 result = 0;
2578         }
2579
2580         PG_RETURN_FLOAT8(result);
2581 }
2582
2583 /* timetz_zone()
2584  * Encode time with time zone type with specified time zone.
2585  * Applies DST rules as of the current date.
2586  */
2587 Datum
2588 timetz_zone(PG_FUNCTION_ARGS)
2589 {
2590         text       *zone = PG_GETARG_TEXT_PP(0);
2591         TimeTzADT  *t = PG_GETARG_TIMETZADT_P(1);
2592         TimeTzADT  *result;
2593         int                     tz;
2594         char            tzname[TZ_STRLEN_MAX + 1];
2595         char       *lowzone;
2596         int                     type,
2597                                 val;
2598         pg_tz      *tzp;
2599
2600         /*
2601          * Look up the requested timezone.      First we look in the date token table
2602          * (to handle cases like "EST"), and if that fails, we look in the
2603          * timezone database (to handle cases like "America/New_York").  (This
2604          * matches the order in which timestamp input checks the cases; it's
2605          * important because the timezone database unwisely uses a few zone names
2606          * that are identical to offset abbreviations.)
2607          */
2608         text_to_cstring_buffer(zone, tzname, sizeof(tzname));
2609         lowzone = downcase_truncate_identifier(tzname,
2610                                                                                    strlen(tzname),
2611                                                                                    false);
2612
2613         type = DecodeSpecial(0, lowzone, &val);
2614
2615         if (type == TZ || type == DTZ)
2616                 tz = val * MINS_PER_HOUR;
2617         else
2618         {
2619                 tzp = pg_tzset(tzname);
2620                 if (tzp)
2621                 {
2622                         /* Get the offset-from-GMT that is valid today for the zone */
2623                         pg_time_t       now = (pg_time_t) time(NULL);
2624                         struct pg_tm *tm;
2625
2626                         tm = pg_localtime(&now, tzp);
2627                         tz = -tm->tm_gmtoff;
2628                 }
2629                 else
2630                 {
2631                         ereport(ERROR,
2632                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2633                                          errmsg("time zone \"%s\" not recognized", tzname)));
2634                         tz = 0;                         /* keep compiler quiet */
2635                 }
2636         }
2637
2638         result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
2639
2640 #ifdef HAVE_INT64_TIMESTAMP
2641         result->time = t->time + (t->zone - tz) * USECS_PER_SEC;
2642         while (result->time < INT64CONST(0))
2643                 result->time += USECS_PER_DAY;
2644         while (result->time >= USECS_PER_DAY)
2645                 result->time -= USECS_PER_DAY;
2646 #else
2647         result->time = t->time + (t->zone - tz);
2648         while (result->time < 0)
2649                 result->time += SECS_PER_DAY;
2650         while (result->time >= SECS_PER_DAY)
2651                 result->time -= SECS_PER_DAY;
2652 #endif
2653
2654         result->zone = tz;
2655
2656         PG_RETURN_TIMETZADT_P(result);
2657 }
2658
2659 /* timetz_izone()
2660  * Encode time with time zone type with specified time interval as time zone.
2661  */
2662 Datum
2663 timetz_izone(PG_FUNCTION_ARGS)
2664 {
2665         Interval   *zone = PG_GETARG_INTERVAL_P(0);
2666         TimeTzADT  *time = PG_GETARG_TIMETZADT_P(1);
2667         TimeTzADT  *result;
2668         int                     tz;
2669
2670         if (zone->month != 0)
2671                 ereport(ERROR,
2672                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2673                                  errmsg("\"interval\" time zone \"%s\" not valid",
2674                                                 DatumGetCString(DirectFunctionCall1(interval_out,
2675                                                                                                   PointerGetDatum(zone))))));
2676
2677 #ifdef HAVE_INT64_TIMESTAMP
2678         tz = -(zone->time / USECS_PER_SEC);
2679 #else
2680         tz = -(zone->time);
2681 #endif
2682
2683         result = (TimeTzADT *) palloc(sizeof(TimeTzADT));
2684
2685 #ifdef HAVE_INT64_TIMESTAMP
2686         result->time = time->time + (time->zone - tz) * USECS_PER_SEC;
2687         while (result->time < INT64CONST(0))
2688                 result->time += USECS_PER_DAY;
2689         while (result->time >= USECS_PER_DAY)
2690                 result->time -= USECS_PER_DAY;
2691 #else
2692         result->time = time->time + (time->zone - tz);
2693         while (result->time < 0)
2694                 result->time += SECS_PER_DAY;
2695         while (result->time >= SECS_PER_DAY)
2696                 result->time -= SECS_PER_DAY;
2697 #endif
2698
2699         result->zone = tz;
2700
2701         PG_RETURN_TIMETZADT_P(result);
2702 }