]> granicus.if.org Git - postgresql/blob - src/backend/utils/adt/nabstime.c
Make our parsing of INTERVAL literals spec-compliant (or at least a heck of
[postgresql] / src / backend / utils / adt / nabstime.c
1 /*-------------------------------------------------------------------------
2  *
3  * nabstime.c
4  *        Utilities for the built-in type "AbsoluteTime".
5  *        Functions for the built-in type "RelativeTime".
6  *        Functions for the built-in type "TimeInterval".
7  *
8  * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
9  * Portions Copyright (c) 1994, Regents of the University of California
10  *
11  *
12  * IDENTIFICATION
13  *        $PostgreSQL: pgsql/src/backend/utils/adt/nabstime.c,v 1.156 2008/09/10 18:29:41 tgl Exp $
14  *
15  *-------------------------------------------------------------------------
16  */
17 #include "postgres.h"
18
19 #include <ctype.h>
20 #include <float.h>
21 #include <limits.h>
22 #include <time.h>
23 #include <sys/time.h>
24
25 #include "libpq/pqformat.h"
26 #include "miscadmin.h"
27 #include "utils/builtins.h"
28 #include "utils/nabstime.h"
29
30 #define MIN_DAYNUM (-24856)             /* December 13, 1901 */
31 #define MAX_DAYNUM 24854                /* January 18, 2038 */
32
33 #define INVALID_RELTIME_STR             "Undefined RelTime"
34 #define INVALID_RELTIME_STR_LEN (sizeof(INVALID_RELTIME_STR)-1)
35 #define RELTIME_LABEL                   '@'
36 #define RELTIME_PAST                    "ago"
37 #define DIRMAXLEN                               (sizeof(RELTIME_PAST)-1)
38
39 /*
40  * Unix epoch is Jan  1 00:00:00 1970.
41  * Postgres knows about times sixty-eight years on either side of that
42  * for these 4-byte types.
43  *
44  * "tinterval" is two 4-byte fields.
45  * Definitions for parsing tinterval.
46  */
47
48 #define IsSpace(C)                              ((C) == ' ')
49
50 #define T_INTERVAL_INVAL   0    /* data represents no valid tinterval */
51 #define T_INTERVAL_VALID   1    /* data represents a valid tinterval */
52 /*
53  * ['Mon May 10 23:59:12 1943 PST' 'Sun Jan 14 03:14:21 1973 PST']
54  * 0            1                 2                     3                 4                     5                 6
55  * 1234567890123456789012345678901234567890123456789012345678901234
56  *
57  * we allocate some extra -- timezones are usually 3 characters but
58  * this is not in the POSIX standard...
59  */
60 #define T_INTERVAL_LEN                                  80
61 #define INVALID_INTERVAL_STR                    "Undefined Range"
62 #define INVALID_INTERVAL_STR_LEN                (sizeof(INVALID_INTERVAL_STR)-1)
63
64 #define ABSTIMEMIN(t1, t2) \
65         (DatumGetBool(DirectFunctionCall2(abstimele, \
66                                   AbsoluteTimeGetDatum(t1), \
67                                   AbsoluteTimeGetDatum(t2))) ? (t1) : (t2))
68 #define ABSTIMEMAX(t1, t2) \
69         (DatumGetBool(DirectFunctionCall2(abstimelt, \
70                                   AbsoluteTimeGetDatum(t1), \
71                                   AbsoluteTimeGetDatum(t2))) ? (t2) : (t1))
72
73
74 /*
75  * Function prototypes -- internal to this file only
76  */
77
78 static AbsoluteTime tm2abstime(struct pg_tm * tm, int tz);
79 static void reltime2tm(RelativeTime time, struct pg_tm * tm);
80 static void parsetinterval(char *i_string,
81                            AbsoluteTime *i_start,
82                            AbsoluteTime *i_end);
83
84
85 /*
86  * GetCurrentAbsoluteTime()
87  *
88  * Get the current system time (relative to Unix epoch).
89  *
90  * NB: this will overflow in 2038; it should be gone long before that.
91  */
92 AbsoluteTime
93 GetCurrentAbsoluteTime(void)
94 {
95         time_t          now;
96
97         now = time(NULL);
98         return (AbsoluteTime) now;
99 }
100
101
102 void
103 abstime2tm(AbsoluteTime _time, int *tzp, struct pg_tm * tm, char **tzn)
104 {
105         pg_time_t       time = (pg_time_t) _time;
106         struct pg_tm *tx;
107
108         /*
109          * If HasCTZSet is true then we have a brute force time zone specified. Go
110          * ahead and rotate to the local time zone since we will later bypass any
111          * calls which adjust the tm fields.
112          */
113         if (HasCTZSet && (tzp != NULL))
114                 time -= CTimeZone;
115
116         if (!HasCTZSet && tzp != NULL)
117                 tx = pg_localtime(&time, session_timezone);
118         else
119                 tx = pg_gmtime(&time);
120
121         tm->tm_year = tx->tm_year + 1900;
122         tm->tm_mon = tx->tm_mon + 1;
123         tm->tm_mday = tx->tm_mday;
124         tm->tm_hour = tx->tm_hour;
125         tm->tm_min = tx->tm_min;
126         tm->tm_sec = tx->tm_sec;
127         tm->tm_isdst = tx->tm_isdst;
128
129         tm->tm_gmtoff = tx->tm_gmtoff;
130         tm->tm_zone = tx->tm_zone;
131
132         if (tzp != NULL)
133         {
134                 /*
135                  * We have a brute force time zone per SQL99? Then use it without
136                  * change since we have already rotated to the time zone.
137                  */
138                 if (HasCTZSet)
139                 {
140                         *tzp = CTimeZone;
141                         tm->tm_gmtoff = CTimeZone;
142                         tm->tm_isdst = 0;
143                         tm->tm_zone = NULL;
144                         if (tzn != NULL)
145                                 *tzn = NULL;
146                 }
147                 else
148                 {
149                         *tzp = -tm->tm_gmtoff;          /* tm_gmtoff is Sun/DEC-ism */
150
151                         /*
152                          * XXX FreeBSD man pages indicate that this should work - tgl
153                          * 97/04/23
154                          */
155                         if (tzn != NULL)
156                         {
157                                 /*
158                                  * Copy no more than MAXTZLEN bytes of timezone to tzn, in
159                                  * case it contains an error message, which doesn't fit in the
160                                  * buffer
161                                  */
162                                 StrNCpy(*tzn, tm->tm_zone, MAXTZLEN + 1);
163                                 if (strlen(tm->tm_zone) > MAXTZLEN)
164                                         ereport(WARNING,
165                                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
166                                                          errmsg("invalid time zone name: \"%s\"",
167                                                                         tm->tm_zone)));
168                         }
169                 }
170         }
171         else
172                 tm->tm_isdst = -1;
173 }
174
175
176 /* tm2abstime()
177  * Convert a tm structure to abstime.
178  * Note that tm has full year (not 1900-based) and 1-based month.
179  */
180 static AbsoluteTime
181 tm2abstime(struct pg_tm * tm, int tz)
182 {
183         int                     day;
184         AbsoluteTime sec;
185
186         /* validate, before going out of range on some members */
187         if (tm->tm_year < 1901 || tm->tm_year > 2038 ||
188                 tm->tm_mon < 1 || tm->tm_mon > 12 ||
189                 tm->tm_mday < 1 || tm->tm_mday > 31 ||
190                 tm->tm_hour < 0 ||
191                 tm->tm_hour > 24 ||             /* test for > 24:00:00 */
192                 (tm->tm_hour == 24 && (tm->tm_min > 0 || tm->tm_sec > 0)) ||
193                 tm->tm_min < 0 || tm->tm_min > 59 ||
194                 tm->tm_sec < 0 || tm->tm_sec > 60)
195                 return INVALID_ABSTIME;
196
197         day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - UNIX_EPOCH_JDATE;
198
199         /* check for time out of range */
200         if (day < MIN_DAYNUM || day > MAX_DAYNUM)
201                 return INVALID_ABSTIME;
202
203         /* convert to seconds */
204         sec = tm->tm_sec + tz + (tm->tm_min + (day * HOURS_PER_DAY + tm->tm_hour) * MINS_PER_HOUR) * SECS_PER_MINUTE;
205
206         /*
207          * check for overflow.  We need a little slop here because the H/M/S plus
208          * TZ offset could add up to more than 1 day.
209          */
210         if ((day >= MAX_DAYNUM - 10 && sec < 0) ||
211                 (day <= MIN_DAYNUM + 10 && sec > 0))
212                 return INVALID_ABSTIME;
213
214         /* check for reserved values (e.g. "current" on edge of usual range */
215         if (!AbsoluteTimeIsReal(sec))
216                 return INVALID_ABSTIME;
217
218         return sec;
219 }
220
221
222 /* abstimein()
223  * Decode date/time string and return abstime.
224  */
225 Datum
226 abstimein(PG_FUNCTION_ARGS)
227 {
228         char       *str = PG_GETARG_CSTRING(0);
229         AbsoluteTime result;
230         fsec_t          fsec;
231         int                     tz = 0;
232         struct pg_tm date,
233                            *tm = &date;
234         int                     dterr;
235         char       *field[MAXDATEFIELDS];
236         char            workbuf[MAXDATELEN + 1];
237         int                     dtype;
238         int                     nf,
239                                 ftype[MAXDATEFIELDS];
240
241         dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
242                                                   field, ftype, MAXDATEFIELDS, &nf);
243         if (dterr == 0)
244                 dterr = DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz);
245         if (dterr != 0)
246                 DateTimeParseError(dterr, str, "abstime");
247
248         switch (dtype)
249         {
250                 case DTK_DATE:
251                         result = tm2abstime(tm, tz);
252                         break;
253
254                 case DTK_EPOCH:
255
256                         /*
257                          * Don't bother retaining this as a reserved value, but instead
258                          * just set to the actual epoch time (1970-01-01)
259                          */
260                         result = 0;
261                         break;
262
263                 case DTK_LATE:
264                         result = NOEND_ABSTIME;
265                         break;
266
267                 case DTK_EARLY:
268                         result = NOSTART_ABSTIME;
269                         break;
270
271                 case DTK_INVALID:
272                         result = INVALID_ABSTIME;
273                         break;
274
275                 default:
276                         elog(ERROR, "unexpected dtype %d while parsing abstime \"%s\"",
277                                  dtype, str);
278                         result = INVALID_ABSTIME;
279                         break;
280         };
281
282         PG_RETURN_ABSOLUTETIME(result);
283 }
284
285
286 /* abstimeout()
287  * Given an AbsoluteTime return the English text version of the date
288  */
289 Datum
290 abstimeout(PG_FUNCTION_ARGS)
291 {
292         AbsoluteTime time = PG_GETARG_ABSOLUTETIME(0);
293         char       *result;
294         int                     tz;
295         double          fsec = 0;
296         struct pg_tm tt,
297                            *tm = &tt;
298         char            buf[MAXDATELEN + 1];
299         char            zone[MAXDATELEN + 1],
300                            *tzn = zone;
301
302         switch (time)
303         {
304                         /*
305                          * Note that timestamp no longer supports 'invalid'. Retain
306                          * 'invalid' for abstime for now, but dump it someday.
307                          */
308                 case INVALID_ABSTIME:
309                         strcpy(buf, INVALID);
310                         break;
311                 case NOEND_ABSTIME:
312                         strcpy(buf, LATE);
313                         break;
314                 case NOSTART_ABSTIME:
315                         strcpy(buf, EARLY);
316                         break;
317                 default:
318                         abstime2tm(time, &tz, tm, &tzn);
319                         EncodeDateTime(tm, fsec, &tz, &tzn, DateStyle, buf);
320                         break;
321         }
322
323         result = pstrdup(buf);
324         PG_RETURN_CSTRING(result);
325 }
326
327 /*
328  *              abstimerecv                     - converts external binary format to abstime
329  */
330 Datum
331 abstimerecv(PG_FUNCTION_ARGS)
332 {
333         StringInfo      buf = (StringInfo) PG_GETARG_POINTER(0);
334
335         PG_RETURN_ABSOLUTETIME((AbsoluteTime) pq_getmsgint(buf, sizeof(AbsoluteTime)));
336 }
337
338 /*
339  *              abstimesend                     - converts abstime to binary format
340  */
341 Datum
342 abstimesend(PG_FUNCTION_ARGS)
343 {
344         AbsoluteTime time = PG_GETARG_ABSOLUTETIME(0);
345         StringInfoData buf;
346
347         pq_begintypsend(&buf);
348         pq_sendint(&buf, time, sizeof(time));
349         PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
350 }
351
352
353 /* abstime_finite()
354  */
355 Datum
356 abstime_finite(PG_FUNCTION_ARGS)
357 {
358         AbsoluteTime abstime = PG_GETARG_ABSOLUTETIME(0);
359
360         PG_RETURN_BOOL(abstime != INVALID_ABSTIME &&
361                                    abstime != NOSTART_ABSTIME &&
362                                    abstime != NOEND_ABSTIME);
363 }
364
365
366 /*
367  * abstime comparison routines
368  */
369 static int
370 abstime_cmp_internal(AbsoluteTime a, AbsoluteTime b)
371 {
372         /*
373          * We consider all INVALIDs to be equal and larger than any non-INVALID.
374          * This is somewhat arbitrary; the important thing is to have a consistent
375          * sort order.
376          */
377         if (a == INVALID_ABSTIME)
378         {
379                 if (b == INVALID_ABSTIME)
380                         return 0;                       /* INVALID = INVALID */
381                 else
382                         return 1;                       /* INVALID > non-INVALID */
383         }
384
385         if (b == INVALID_ABSTIME)
386                 return -1;                              /* non-INVALID < INVALID */
387
388         if (a > b)
389                 return 1;
390         else if (a == b)
391                 return 0;
392         else
393                 return -1;
394 }
395
396 Datum
397 abstimeeq(PG_FUNCTION_ARGS)
398 {
399         AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
400         AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
401
402         PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) == 0);
403 }
404
405 Datum
406 abstimene(PG_FUNCTION_ARGS)
407 {
408         AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
409         AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
410
411         PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) != 0);
412 }
413
414 Datum
415 abstimelt(PG_FUNCTION_ARGS)
416 {
417         AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
418         AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
419
420         PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) < 0);
421 }
422
423 Datum
424 abstimegt(PG_FUNCTION_ARGS)
425 {
426         AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
427         AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
428
429         PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) > 0);
430 }
431
432 Datum
433 abstimele(PG_FUNCTION_ARGS)
434 {
435         AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
436         AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
437
438         PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) <= 0);
439 }
440
441 Datum
442 abstimege(PG_FUNCTION_ARGS)
443 {
444         AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
445         AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
446
447         PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) >= 0);
448 }
449
450 Datum
451 btabstimecmp(PG_FUNCTION_ARGS)
452 {
453         AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
454         AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
455
456         PG_RETURN_INT32(abstime_cmp_internal(t1, t2));
457 }
458
459
460 /* timestamp_abstime()
461  * Convert timestamp to abstime.
462  */
463 Datum
464 timestamp_abstime(PG_FUNCTION_ARGS)
465 {
466         Timestamp       timestamp = PG_GETARG_TIMESTAMP(0);
467         AbsoluteTime result;
468         fsec_t          fsec;
469         int                     tz;
470         struct pg_tm tt,
471                            *tm = &tt;
472
473         if (TIMESTAMP_IS_NOBEGIN(timestamp))
474                 result = NOSTART_ABSTIME;
475         else if (TIMESTAMP_IS_NOEND(timestamp))
476                 result = NOEND_ABSTIME;
477         else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) == 0)
478         {
479                 tz = DetermineTimeZoneOffset(tm, session_timezone);
480                 result = tm2abstime(tm, tz);
481         }
482         else
483         {
484                 ereport(ERROR,
485                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
486                                  errmsg("timestamp out of range")));
487                 result = INVALID_ABSTIME;
488         }
489
490         PG_RETURN_ABSOLUTETIME(result);
491 }
492
493 /* abstime_timestamp()
494  * Convert abstime to timestamp.
495  */
496 Datum
497 abstime_timestamp(PG_FUNCTION_ARGS)
498 {
499         AbsoluteTime abstime = PG_GETARG_ABSOLUTETIME(0);
500         Timestamp       result;
501         struct pg_tm tt,
502                            *tm = &tt;
503         int                     tz;
504         char            zone[MAXDATELEN + 1],
505                            *tzn = zone;
506
507         switch (abstime)
508         {
509                 case INVALID_ABSTIME:
510                         ereport(ERROR,
511                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
512                                  errmsg("cannot convert abstime \"invalid\" to timestamp")));
513                         TIMESTAMP_NOBEGIN(result);
514                         break;
515
516                 case NOSTART_ABSTIME:
517                         TIMESTAMP_NOBEGIN(result);
518                         break;
519
520                 case NOEND_ABSTIME:
521                         TIMESTAMP_NOEND(result);
522                         break;
523
524                 default:
525                         abstime2tm(abstime, &tz, tm, &tzn);
526                         if (tm2timestamp(tm, 0, NULL, &result) != 0)
527                                 ereport(ERROR,
528                                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
529                                                  errmsg("timestamp out of range")));
530                         break;
531         };
532
533         PG_RETURN_TIMESTAMP(result);
534 }
535
536
537 /* timestamptz_abstime()
538  * Convert timestamp with time zone to abstime.
539  */
540 Datum
541 timestamptz_abstime(PG_FUNCTION_ARGS)
542 {
543         TimestampTz timestamp = PG_GETARG_TIMESTAMP(0);
544         AbsoluteTime result;
545         fsec_t          fsec;
546         struct pg_tm tt,
547                            *tm = &tt;
548
549         if (TIMESTAMP_IS_NOBEGIN(timestamp))
550                 result = NOSTART_ABSTIME;
551         else if (TIMESTAMP_IS_NOEND(timestamp))
552                 result = NOEND_ABSTIME;
553         else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) == 0)
554                 result = tm2abstime(tm, 0);
555         else
556         {
557                 ereport(ERROR,
558                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
559                                  errmsg("timestamp out of range")));
560                 result = INVALID_ABSTIME;
561         }
562
563         PG_RETURN_ABSOLUTETIME(result);
564 }
565
566 /* abstime_timestamptz()
567  * Convert abstime to timestamp with time zone.
568  */
569 Datum
570 abstime_timestamptz(PG_FUNCTION_ARGS)
571 {
572         AbsoluteTime abstime = PG_GETARG_ABSOLUTETIME(0);
573         TimestampTz result;
574         struct pg_tm tt,
575                            *tm = &tt;
576         int                     tz;
577         char            zone[MAXDATELEN + 1],
578                            *tzn = zone;
579
580         switch (abstime)
581         {
582                 case INVALID_ABSTIME:
583                         ereport(ERROR,
584                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
585                                  errmsg("cannot convert abstime \"invalid\" to timestamp")));
586                         TIMESTAMP_NOBEGIN(result);
587                         break;
588
589                 case NOSTART_ABSTIME:
590                         TIMESTAMP_NOBEGIN(result);
591                         break;
592
593                 case NOEND_ABSTIME:
594                         TIMESTAMP_NOEND(result);
595                         break;
596
597                 default:
598                         abstime2tm(abstime, &tz, tm, &tzn);
599                         if (tm2timestamp(tm, 0, &tz, &result) != 0)
600                                 ereport(ERROR,
601                                                 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
602                                                  errmsg("timestamp out of range")));
603                         break;
604         };
605
606         PG_RETURN_TIMESTAMP(result);
607 }
608
609
610 /*****************************************************************************
611  *       USER I/O ROUTINES                                                                                                               *
612  *****************************************************************************/
613
614 /*
615  *              reltimein               - converts a reltime string in an internal format
616  */
617 Datum
618 reltimein(PG_FUNCTION_ARGS)
619 {
620         char       *str = PG_GETARG_CSTRING(0);
621         RelativeTime result;
622         struct pg_tm tt,
623                            *tm = &tt;
624         fsec_t          fsec;
625         int                     dtype;
626         int                     dterr;
627         char       *field[MAXDATEFIELDS];
628         int                     nf,
629                                 ftype[MAXDATEFIELDS];
630         char            workbuf[MAXDATELEN + 1];
631
632         dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
633                                                   field, ftype, MAXDATEFIELDS, &nf);
634         if (dterr == 0)
635                 dterr = DecodeInterval(field, ftype, nf, INTERVAL_FULL_RANGE,
636                                                            &dtype, tm, &fsec);
637         if (dterr != 0)
638         {
639                 if (dterr == DTERR_FIELD_OVERFLOW)
640                         dterr = DTERR_INTERVAL_OVERFLOW;
641                 DateTimeParseError(dterr, str, "reltime");
642         }
643
644         switch (dtype)
645         {
646                 case DTK_DELTA:
647                         result = ((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec;
648                         result += tm->tm_year * SECS_PER_YEAR + ((tm->tm_mon * DAYS_PER_MONTH) + tm->tm_mday) * SECS_PER_DAY;
649                         break;
650
651                 default:
652                         elog(ERROR, "unexpected dtype %d while parsing reltime \"%s\"",
653                                  dtype, str);
654                         result = INVALID_RELTIME;
655                         break;
656         }
657
658         PG_RETURN_RELATIVETIME(result);
659 }
660
661 /*
662  *              reltimeout              - converts the internal format to a reltime string
663  */
664 Datum
665 reltimeout(PG_FUNCTION_ARGS)
666 {
667         RelativeTime time = PG_GETARG_RELATIVETIME(0);
668         char       *result;
669         struct pg_tm tt,
670                            *tm = &tt;
671         char            buf[MAXDATELEN + 1];
672
673         reltime2tm(time, tm);
674         EncodeInterval(tm, 0, DateStyle, buf);
675
676         result = pstrdup(buf);
677         PG_RETURN_CSTRING(result);
678 }
679
680 /*
681  *              reltimerecv                     - converts external binary format to reltime
682  */
683 Datum
684 reltimerecv(PG_FUNCTION_ARGS)
685 {
686         StringInfo      buf = (StringInfo) PG_GETARG_POINTER(0);
687
688         PG_RETURN_RELATIVETIME((RelativeTime) pq_getmsgint(buf, sizeof(RelativeTime)));
689 }
690
691 /*
692  *              reltimesend                     - converts reltime to binary format
693  */
694 Datum
695 reltimesend(PG_FUNCTION_ARGS)
696 {
697         RelativeTime time = PG_GETARG_RELATIVETIME(0);
698         StringInfoData buf;
699
700         pq_begintypsend(&buf);
701         pq_sendint(&buf, time, sizeof(time));
702         PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
703 }
704
705
706 static void
707 reltime2tm(RelativeTime time, struct pg_tm * tm)
708 {
709         double          dtime = time;
710
711         FMODULO(dtime, tm->tm_year, 31557600);
712         FMODULO(dtime, tm->tm_mon, 2592000);
713         FMODULO(dtime, tm->tm_mday, SECS_PER_DAY);
714         FMODULO(dtime, tm->tm_hour, SECS_PER_HOUR);
715         FMODULO(dtime, tm->tm_min, SECS_PER_MINUTE);
716         FMODULO(dtime, tm->tm_sec, 1);
717 }
718
719
720 /*
721  *              tintervalin             - converts an tinterval string to internal format
722  */
723 Datum
724 tintervalin(PG_FUNCTION_ARGS)
725 {
726         char       *tintervalstr = PG_GETARG_CSTRING(0);
727         TimeInterval tinterval;
728         AbsoluteTime i_start,
729                                 i_end,
730                                 t1,
731                                 t2;
732
733         parsetinterval(tintervalstr, &t1, &t2);
734
735         tinterval = (TimeInterval) palloc(sizeof(TimeIntervalData));
736
737         if (t1 == INVALID_ABSTIME || t2 == INVALID_ABSTIME)
738                 tinterval->status = T_INTERVAL_INVAL;   /* undefined  */
739         else
740                 tinterval->status = T_INTERVAL_VALID;
741
742         i_start = ABSTIMEMIN(t1, t2);
743         i_end = ABSTIMEMAX(t1, t2);
744         tinterval->data[0] = i_start;
745         tinterval->data[1] = i_end;
746
747         PG_RETURN_TIMEINTERVAL(tinterval);
748 }
749
750
751 /*
752  *              tintervalout    - converts an internal tinterval format to a string
753  */
754 Datum
755 tintervalout(PG_FUNCTION_ARGS)
756 {
757         TimeInterval tinterval = PG_GETARG_TIMEINTERVAL(0);
758         char       *i_str,
759                            *p;
760
761         i_str = (char *) palloc(T_INTERVAL_LEN);        /* ["..." "..."] */
762         strcpy(i_str, "[\"");
763         if (tinterval->status == T_INTERVAL_INVAL)
764                 strcat(i_str, INVALID_INTERVAL_STR);
765         else
766         {
767                 p = DatumGetCString(DirectFunctionCall1(abstimeout,
768                                                                   AbsoluteTimeGetDatum(tinterval->data[0])));
769                 strcat(i_str, p);
770                 pfree(p);
771                 strcat(i_str, "\" \"");
772                 p = DatumGetCString(DirectFunctionCall1(abstimeout,
773                                                                   AbsoluteTimeGetDatum(tinterval->data[1])));
774                 strcat(i_str, p);
775                 pfree(p);
776         }
777         strcat(i_str, "\"]");
778         PG_RETURN_CSTRING(i_str);
779 }
780
781 /*
782  *              tintervalrecv                   - converts external binary format to tinterval
783  */
784 Datum
785 tintervalrecv(PG_FUNCTION_ARGS)
786 {
787         StringInfo      buf = (StringInfo) PG_GETARG_POINTER(0);
788         TimeInterval tinterval;
789
790         tinterval = (TimeInterval) palloc(sizeof(TimeIntervalData));
791
792         tinterval->status = pq_getmsgint(buf, sizeof(tinterval->status));
793
794         if (!(tinterval->status == T_INTERVAL_INVAL ||
795                   tinterval->status == T_INTERVAL_VALID))
796                 ereport(ERROR,
797                                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
798                                  errmsg("invalid status in external \"tinterval\" value")));
799
800         tinterval->data[0] = pq_getmsgint(buf, sizeof(tinterval->data[0]));
801         tinterval->data[1] = pq_getmsgint(buf, sizeof(tinterval->data[1]));
802
803         PG_RETURN_TIMEINTERVAL(tinterval);
804 }
805
806 /*
807  *              tintervalsend                   - converts tinterval to binary format
808  */
809 Datum
810 tintervalsend(PG_FUNCTION_ARGS)
811 {
812         TimeInterval tinterval = PG_GETARG_TIMEINTERVAL(0);
813         StringInfoData buf;
814
815         pq_begintypsend(&buf);
816         pq_sendint(&buf, tinterval->status, sizeof(tinterval->status));
817         pq_sendint(&buf, tinterval->data[0], sizeof(tinterval->data[0]));
818         pq_sendint(&buf, tinterval->data[1], sizeof(tinterval->data[1]));
819         PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
820 }
821
822
823 /*****************************************************************************
824  *       PUBLIC ROUTINES                                                                                                                 *
825  *****************************************************************************/
826
827 Datum
828 interval_reltime(PG_FUNCTION_ARGS)
829 {
830         Interval   *interval = PG_GETARG_INTERVAL_P(0);
831         RelativeTime time;
832         int                     year,
833                                 month,
834                                 day;
835         TimeOffset      span;
836
837         year = interval->month / MONTHS_PER_YEAR;
838         month = interval->month % MONTHS_PER_YEAR;
839         day = interval->day;
840
841 #ifdef HAVE_INT64_TIMESTAMP
842         span = ((INT64CONST(365250000) * year + INT64CONST(30000000) * month +
843                          INT64CONST(1000000) * day) * INT64CONST(86400)) +
844                 interval->time;
845         span /= USECS_PER_SEC;
846 #else
847         span = (DAYS_PER_YEAR * year + (double) DAYS_PER_MONTH * month + day) * SECS_PER_DAY + interval->time;
848 #endif
849
850         if (span < INT_MIN || span > INT_MAX)
851                 time = INVALID_RELTIME;
852         else
853                 time = span;
854
855         PG_RETURN_RELATIVETIME(time);
856 }
857
858
859 Datum
860 reltime_interval(PG_FUNCTION_ARGS)
861 {
862         RelativeTime reltime = PG_GETARG_RELATIVETIME(0);
863         Interval   *result;
864         int                     year,
865                                 month,
866                                 day;
867
868         result = (Interval *) palloc(sizeof(Interval));
869
870         switch (reltime)
871         {
872                 case INVALID_RELTIME:
873                         ereport(ERROR,
874                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
875                                   errmsg("cannot convert reltime \"invalid\" to interval")));
876                         result->time = 0;
877                         result->day = 0;
878                         result->month = 0;
879                         break;
880
881                 default:
882 #ifdef HAVE_INT64_TIMESTAMP
883                         year = reltime / SECS_PER_YEAR;
884                         reltime -= year * SECS_PER_YEAR;
885                         month = reltime / (DAYS_PER_MONTH * SECS_PER_DAY);
886                         reltime -= month * (DAYS_PER_MONTH * SECS_PER_DAY);
887                         day = reltime / SECS_PER_DAY;
888                         reltime -= day * SECS_PER_DAY;
889
890                         result->time = (reltime * USECS_PER_SEC);
891 #else
892                         TMODULO(reltime, year, SECS_PER_YEAR);
893                         TMODULO(reltime, month, DAYS_PER_MONTH * SECS_PER_DAY);
894                         TMODULO(reltime, day, SECS_PER_DAY);
895
896                         result->time = reltime;
897 #endif
898                         result->month = MONTHS_PER_YEAR * year + month;
899                         result->day = day;
900                         break;
901         }
902
903         PG_RETURN_INTERVAL_P(result);
904 }
905
906
907 /*
908  *              mktinterval             - creates a time interval with endpoints t1 and t2
909  */
910 Datum
911 mktinterval(PG_FUNCTION_ARGS)
912 {
913         AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
914         AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
915         AbsoluteTime tstart = ABSTIMEMIN(t1, t2);
916         AbsoluteTime tend = ABSTIMEMAX(t1, t2);
917         TimeInterval tinterval;
918
919         tinterval = (TimeInterval) palloc(sizeof(TimeIntervalData));
920
921         if (t1 == INVALID_ABSTIME || t2 == INVALID_ABSTIME)
922                 tinterval->status = T_INTERVAL_INVAL;
923
924         else
925         {
926                 tinterval->status = T_INTERVAL_VALID;
927                 tinterval->data[0] = tstart;
928                 tinterval->data[1] = tend;
929         }
930
931         PG_RETURN_TIMEINTERVAL(tinterval);
932 }
933
934 /*
935  *              timepl, timemi and abstimemi use the formula
936  *                              abstime + reltime = abstime
937  *              so              abstime - reltime = abstime
938  *              and             abstime - abstime = reltime
939  */
940
941 /*
942  *              timepl                  - returns the value of (abstime t1 + reltime t2)
943  */
944 Datum
945 timepl(PG_FUNCTION_ARGS)
946 {
947         AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
948         RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
949
950         if (AbsoluteTimeIsReal(t1) &&
951                 RelativeTimeIsValid(t2) &&
952                 ((t2 > 0 && t1 < NOEND_ABSTIME - t2) ||
953                  (t2 <= 0 && t1 > NOSTART_ABSTIME - t2)))               /* prevent overflow */
954                 PG_RETURN_ABSOLUTETIME(t1 + t2);
955
956         PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
957 }
958
959
960 /*
961  *              timemi                  - returns the value of (abstime t1 - reltime t2)
962  */
963 Datum
964 timemi(PG_FUNCTION_ARGS)
965 {
966         AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
967         RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
968
969         if (AbsoluteTimeIsReal(t1) &&
970                 RelativeTimeIsValid(t2) &&
971                 ((t2 > 0 && t1 > NOSTART_ABSTIME + t2) ||
972                  (t2 <= 0 && t1 < NOEND_ABSTIME + t2))) /* prevent overflow */
973                 PG_RETURN_ABSOLUTETIME(t1 - t2);
974
975         PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
976 }
977
978
979 /*
980  *              intinterval             - returns true iff absolute date is in the tinterval
981  */
982 Datum
983 intinterval(PG_FUNCTION_ARGS)
984 {
985         AbsoluteTime t = PG_GETARG_ABSOLUTETIME(0);
986         TimeInterval tinterval = PG_GETARG_TIMEINTERVAL(1);
987
988         if (tinterval->status == T_INTERVAL_VALID && t != INVALID_ABSTIME)
989         {
990                 if (DatumGetBool(DirectFunctionCall2(abstimege,
991                                                                                          AbsoluteTimeGetDatum(t),
992                                                                 AbsoluteTimeGetDatum(tinterval->data[0]))) &&
993                         DatumGetBool(DirectFunctionCall2(abstimele,
994                                                                                          AbsoluteTimeGetDatum(t),
995                                                                   AbsoluteTimeGetDatum(tinterval->data[1]))))
996                         PG_RETURN_BOOL(true);
997         }
998         PG_RETURN_BOOL(false);
999 }
1000
1001 /*
1002  *              tintervalrel            - returns  relative time corresponding to tinterval
1003  */
1004 Datum
1005 tintervalrel(PG_FUNCTION_ARGS)
1006 {
1007         TimeInterval tinterval = PG_GETARG_TIMEINTERVAL(0);
1008         AbsoluteTime t1 = tinterval->data[0];
1009         AbsoluteTime t2 = tinterval->data[1];
1010
1011         if (tinterval->status != T_INTERVAL_VALID)
1012                 PG_RETURN_RELATIVETIME(INVALID_RELTIME);
1013
1014         if (AbsoluteTimeIsReal(t1) &&
1015                 AbsoluteTimeIsReal(t2))
1016                 PG_RETURN_RELATIVETIME(t2 - t1);
1017
1018         PG_RETURN_RELATIVETIME(INVALID_RELTIME);
1019 }
1020
1021
1022 /*
1023  *              timenow                 - returns  time "now", internal format
1024  *
1025  *              Now AbsoluteTime is time since Jan 1 1970 -mer 7 Feb 1992
1026  */
1027 Datum
1028 timenow(PG_FUNCTION_ARGS)
1029 {
1030         PG_RETURN_ABSOLUTETIME(GetCurrentAbsoluteTime());
1031 }
1032
1033 /*
1034  * reltime comparison routines
1035  */
1036 static int
1037 reltime_cmp_internal(RelativeTime a, RelativeTime b)
1038 {
1039         /*
1040          * We consider all INVALIDs to be equal and larger than any non-INVALID.
1041          * This is somewhat arbitrary; the important thing is to have a consistent
1042          * sort order.
1043          */
1044         if (a == INVALID_RELTIME)
1045         {
1046                 if (b == INVALID_RELTIME)
1047                         return 0;                       /* INVALID = INVALID */
1048                 else
1049                         return 1;                       /* INVALID > non-INVALID */
1050         }
1051
1052         if (b == INVALID_RELTIME)
1053                 return -1;                              /* non-INVALID < INVALID */
1054
1055         if (a > b)
1056                 return 1;
1057         else if (a == b)
1058                 return 0;
1059         else
1060                 return -1;
1061 }
1062
1063 Datum
1064 reltimeeq(PG_FUNCTION_ARGS)
1065 {
1066         RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1067         RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1068
1069         PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) == 0);
1070 }
1071
1072 Datum
1073 reltimene(PG_FUNCTION_ARGS)
1074 {
1075         RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1076         RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1077
1078         PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) != 0);
1079 }
1080
1081 Datum
1082 reltimelt(PG_FUNCTION_ARGS)
1083 {
1084         RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1085         RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1086
1087         PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) < 0);
1088 }
1089
1090 Datum
1091 reltimegt(PG_FUNCTION_ARGS)
1092 {
1093         RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1094         RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1095
1096         PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) > 0);
1097 }
1098
1099 Datum
1100 reltimele(PG_FUNCTION_ARGS)
1101 {
1102         RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1103         RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1104
1105         PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) <= 0);
1106 }
1107
1108 Datum
1109 reltimege(PG_FUNCTION_ARGS)
1110 {
1111         RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1112         RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1113
1114         PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) >= 0);
1115 }
1116
1117 Datum
1118 btreltimecmp(PG_FUNCTION_ARGS)
1119 {
1120         RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1121         RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1122
1123         PG_RETURN_INT32(reltime_cmp_internal(t1, t2));
1124 }
1125
1126
1127 /*
1128  *              tintervalsame   - returns true iff tinterval i1 is same as tinterval i2
1129  *              Check begin and end time.
1130  */
1131 Datum
1132 tintervalsame(PG_FUNCTION_ARGS)
1133 {
1134         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1135         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1136
1137         if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL)
1138                 PG_RETURN_BOOL(false);
1139
1140         if (DatumGetBool(DirectFunctionCall2(abstimeeq,
1141                                                                                  AbsoluteTimeGetDatum(i1->data[0]),
1142                                                                            AbsoluteTimeGetDatum(i2->data[0]))) &&
1143                 DatumGetBool(DirectFunctionCall2(abstimeeq,
1144                                                                                  AbsoluteTimeGetDatum(i1->data[1]),
1145                                                                                  AbsoluteTimeGetDatum(i2->data[1]))))
1146                 PG_RETURN_BOOL(true);
1147         PG_RETURN_BOOL(false);
1148 }
1149
1150 /*
1151  * tinterval comparison routines
1152  *
1153  * Note: comparison is based on the lengths of the tintervals, not on
1154  * endpoint value.      This is pretty bogus, but since it's only a legacy
1155  * datatype I'm not going to propose changing it.
1156  */
1157 static int
1158 tinterval_cmp_internal(TimeInterval a, TimeInterval b)
1159 {
1160         bool            a_invalid;
1161         bool            b_invalid;
1162         AbsoluteTime a_len;
1163         AbsoluteTime b_len;
1164
1165         /*
1166          * We consider all INVALIDs to be equal and larger than any non-INVALID.
1167          * This is somewhat arbitrary; the important thing is to have a consistent
1168          * sort order.
1169          */
1170         a_invalid = a->status == T_INTERVAL_INVAL ||
1171                 a->data[0] == INVALID_ABSTIME ||
1172                 a->data[1] == INVALID_ABSTIME;
1173         b_invalid = b->status == T_INTERVAL_INVAL ||
1174                 b->data[0] == INVALID_ABSTIME ||
1175                 b->data[1] == INVALID_ABSTIME;
1176
1177         if (a_invalid)
1178         {
1179                 if (b_invalid)
1180                         return 0;                       /* INVALID = INVALID */
1181                 else
1182                         return 1;                       /* INVALID > non-INVALID */
1183         }
1184
1185         if (b_invalid)
1186                 return -1;                              /* non-INVALID < INVALID */
1187
1188         a_len = a->data[1] - a->data[0];
1189         b_len = b->data[1] - b->data[0];
1190
1191         if (a_len > b_len)
1192                 return 1;
1193         else if (a_len == b_len)
1194                 return 0;
1195         else
1196                 return -1;
1197 }
1198
1199 Datum
1200 tintervaleq(PG_FUNCTION_ARGS)
1201 {
1202         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1203         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1204
1205         PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) == 0);
1206 }
1207
1208 Datum
1209 tintervalne(PG_FUNCTION_ARGS)
1210 {
1211         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1212         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1213
1214         PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) != 0);
1215 }
1216
1217 Datum
1218 tintervallt(PG_FUNCTION_ARGS)
1219 {
1220         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1221         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1222
1223         PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) < 0);
1224 }
1225
1226 Datum
1227 tintervalle(PG_FUNCTION_ARGS)
1228 {
1229         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1230         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1231
1232         PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) <= 0);
1233 }
1234
1235 Datum
1236 tintervalgt(PG_FUNCTION_ARGS)
1237 {
1238         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1239         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1240
1241         PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) > 0);
1242 }
1243
1244 Datum
1245 tintervalge(PG_FUNCTION_ARGS)
1246 {
1247         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1248         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1249
1250         PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) >= 0);
1251 }
1252
1253 Datum
1254 bttintervalcmp(PG_FUNCTION_ARGS)
1255 {
1256         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1257         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1258
1259         PG_RETURN_INT32(tinterval_cmp_internal(i1, i2));
1260 }
1261
1262
1263 /*
1264  *              tintervalleneq  - returns true iff length of tinterval i is equal to
1265  *                                                              reltime t
1266  *              tintervallenne  - returns true iff length of tinterval i is not equal
1267  *                                                              to reltime t
1268  *              tintervallenlt  - returns true iff length of tinterval i is less than
1269  *                                                              reltime t
1270  *              tintervallengt  - returns true iff length of tinterval i is greater
1271  *                                                              than reltime t
1272  *              tintervallenle  - returns true iff length of tinterval i is less or
1273  *                                                              equal than reltime t
1274  *              tintervallenge  - returns true iff length of tinterval i is greater or
1275  *                                                              equal than reltime t
1276  */
1277 Datum
1278 tintervalleneq(PG_FUNCTION_ARGS)
1279 {
1280         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1281         RelativeTime t = PG_GETARG_RELATIVETIME(1);
1282         RelativeTime rt;
1283
1284         if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1285                 PG_RETURN_BOOL(false);
1286         rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1287                                                                                                   TimeIntervalGetDatum(i)));
1288         PG_RETURN_BOOL(rt != INVALID_RELTIME && rt == t);
1289 }
1290
1291 Datum
1292 tintervallenne(PG_FUNCTION_ARGS)
1293 {
1294         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1295         RelativeTime t = PG_GETARG_RELATIVETIME(1);
1296         RelativeTime rt;
1297
1298         if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1299                 PG_RETURN_BOOL(false);
1300         rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1301                                                                                                   TimeIntervalGetDatum(i)));
1302         PG_RETURN_BOOL(rt != INVALID_RELTIME && rt != t);
1303 }
1304
1305 Datum
1306 tintervallenlt(PG_FUNCTION_ARGS)
1307 {
1308         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1309         RelativeTime t = PG_GETARG_RELATIVETIME(1);
1310         RelativeTime rt;
1311
1312         if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1313                 PG_RETURN_BOOL(false);
1314         rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1315                                                                                                   TimeIntervalGetDatum(i)));
1316         PG_RETURN_BOOL(rt != INVALID_RELTIME && rt < t);
1317 }
1318
1319 Datum
1320 tintervallengt(PG_FUNCTION_ARGS)
1321 {
1322         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1323         RelativeTime t = PG_GETARG_RELATIVETIME(1);
1324         RelativeTime rt;
1325
1326         if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1327                 PG_RETURN_BOOL(false);
1328         rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1329                                                                                                   TimeIntervalGetDatum(i)));
1330         PG_RETURN_BOOL(rt != INVALID_RELTIME && rt > t);
1331 }
1332
1333 Datum
1334 tintervallenle(PG_FUNCTION_ARGS)
1335 {
1336         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1337         RelativeTime t = PG_GETARG_RELATIVETIME(1);
1338         RelativeTime rt;
1339
1340         if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1341                 PG_RETURN_BOOL(false);
1342         rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1343                                                                                                   TimeIntervalGetDatum(i)));
1344         PG_RETURN_BOOL(rt != INVALID_RELTIME && rt <= t);
1345 }
1346
1347 Datum
1348 tintervallenge(PG_FUNCTION_ARGS)
1349 {
1350         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1351         RelativeTime t = PG_GETARG_RELATIVETIME(1);
1352         RelativeTime rt;
1353
1354         if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1355                 PG_RETURN_BOOL(false);
1356         rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1357                                                                                                   TimeIntervalGetDatum(i)));
1358         PG_RETURN_BOOL(rt != INVALID_RELTIME && rt >= t);
1359 }
1360
1361 /*
1362  *              tintervalct             - returns true iff tinterval i1 contains tinterval i2
1363  */
1364 Datum
1365 tintervalct(PG_FUNCTION_ARGS)
1366 {
1367         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1368         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1369
1370         if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL)
1371                 PG_RETURN_BOOL(false);
1372         if (DatumGetBool(DirectFunctionCall2(abstimele,
1373                                                                                  AbsoluteTimeGetDatum(i1->data[0]),
1374                                                                            AbsoluteTimeGetDatum(i2->data[0]))) &&
1375                 DatumGetBool(DirectFunctionCall2(abstimege,
1376                                                                                  AbsoluteTimeGetDatum(i1->data[1]),
1377                                                                                  AbsoluteTimeGetDatum(i2->data[1]))))
1378                 PG_RETURN_BOOL(true);
1379         PG_RETURN_BOOL(false);
1380 }
1381
1382 /*
1383  *              tintervalov             - returns true iff tinterval i1 (partially) overlaps i2
1384  */
1385 Datum
1386 tintervalov(PG_FUNCTION_ARGS)
1387 {
1388         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1389         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1390
1391         if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL)
1392                 PG_RETURN_BOOL(false);
1393         if (DatumGetBool(DirectFunctionCall2(abstimelt,
1394                                                                                  AbsoluteTimeGetDatum(i1->data[1]),
1395                                                                            AbsoluteTimeGetDatum(i2->data[0]))) ||
1396                 DatumGetBool(DirectFunctionCall2(abstimegt,
1397                                                                                  AbsoluteTimeGetDatum(i1->data[0]),
1398                                                                                  AbsoluteTimeGetDatum(i2->data[1]))))
1399                 PG_RETURN_BOOL(false);
1400         PG_RETURN_BOOL(true);
1401 }
1402
1403 /*
1404  *              tintervalstart  - returns  the start of tinterval i
1405  */
1406 Datum
1407 tintervalstart(PG_FUNCTION_ARGS)
1408 {
1409         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1410
1411         if (i->status == T_INTERVAL_INVAL)
1412                 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
1413         PG_RETURN_ABSOLUTETIME(i->data[0]);
1414 }
1415
1416 /*
1417  *              tintervalend            - returns  the end of tinterval i
1418  */
1419 Datum
1420 tintervalend(PG_FUNCTION_ARGS)
1421 {
1422         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1423
1424         if (i->status == T_INTERVAL_INVAL)
1425                 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
1426         PG_RETURN_ABSOLUTETIME(i->data[1]);
1427 }
1428
1429
1430 /*****************************************************************************
1431  *       PRIVATE ROUTINES                                                                                                                *
1432  *****************************************************************************/
1433
1434 /*
1435  *              parsetinterval -- parse a tinterval string
1436  *
1437  *              output parameters:
1438  *                              i_start, i_end: tinterval margins
1439  *
1440  *              Time interval:
1441  *              `[' {` '} `'' <AbsTime> `'' {` '} `'' <AbsTime> `'' {` '} `]'
1442  *
1443  *              OR      `Undefined Range'       (see also INVALID_INTERVAL_STR)
1444  *
1445  *              where <AbsTime> satisfies the syntax of absolute time.
1446  *
1447  *              e.g.  [  '  Jan 18 1902'   'Jan 1 00:00:00 1970']
1448  */
1449 static void
1450 parsetinterval(char *i_string,
1451                            AbsoluteTime *i_start,
1452                            AbsoluteTime *i_end)
1453 {
1454         char       *p,
1455                            *p1;
1456         char            c;
1457
1458         p = i_string;
1459         /* skip leading blanks up to '[' */
1460         while ((c = *p) != '\0')
1461         {
1462                 if (IsSpace(c))
1463                         p++;
1464                 else if (c != '[')
1465                         goto bogus;                     /* syntax error */
1466                 else
1467                         break;
1468         }
1469         if (c == '\0')
1470                 goto bogus;                             /* syntax error */
1471         p++;
1472         /* skip leading blanks up to '"' */
1473         while ((c = *p) != '\0')
1474         {
1475                 if (IsSpace(c))
1476                         p++;
1477                 else if (c != '"')
1478                         goto bogus;                     /* syntax error */
1479                 else
1480                         break;
1481         }
1482         if (c == '\0')
1483                 goto bogus;                             /* syntax error */
1484         p++;
1485         if (strncmp(INVALID_INTERVAL_STR, p, strlen(INVALID_INTERVAL_STR)) == 0)
1486                 goto bogus;                             /* undefined range, handled like a syntax err. */
1487         /* search for the end of the first date and change it to a \0 */
1488         p1 = p;
1489         while ((c = *p1) != '\0')
1490         {
1491                 if (c == '"')
1492                         break;
1493                 p1++;
1494         }
1495         if (c == '\0')
1496                 goto bogus;                             /* syntax error */
1497         *p1 = '\0';
1498         /* get the first date */
1499         *i_start = DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
1500                                                                                                                 CStringGetDatum(p)));
1501         /* undo change to \0 */
1502         *p1 = c;
1503         p = ++p1;
1504         /* skip blanks up to '"', beginning of second date */
1505         while ((c = *p) != '\0')
1506         {
1507                 if (IsSpace(c))
1508                         p++;
1509                 else if (c != '"')
1510                         goto bogus;                     /* syntax error */
1511                 else
1512                         break;
1513         }
1514         if (c == '\0')
1515                 goto bogus;                             /* syntax error */
1516         p++;
1517         /* search for the end of the second date and change it to a \0 */
1518         p1 = p;
1519         while ((c = *p1) != '\0')
1520         {
1521                 if (c == '"')
1522                         break;
1523                 p1++;
1524         }
1525         if (c == '\0')
1526                 goto bogus;                             /* syntax error */
1527         *p1 = '\0';
1528         /* get the second date */
1529         *i_end = DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
1530                                                                                                           CStringGetDatum(p)));
1531         /* undo change to \0 */
1532         *p1 = c;
1533         p = ++p1;
1534         /* skip blanks up to ']' */
1535         while ((c = *p) != '\0')
1536         {
1537                 if (IsSpace(c))
1538                         p++;
1539                 else if (c != ']')
1540                         goto bogus;                     /* syntax error */
1541                 else
1542                         break;
1543         }
1544         if (c == '\0')
1545                 goto bogus;                             /* syntax error */
1546         p++;
1547         c = *p;
1548         if (c != '\0')
1549                 goto bogus;                             /* syntax error */
1550
1551         /* it seems to be a valid tinterval */
1552         return;
1553
1554 bogus:
1555         ereport(ERROR,
1556                         (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
1557                          errmsg("invalid input syntax for type tinterval: \"%s\"",
1558                                         i_string)));
1559         *i_start = *i_end = INVALID_ABSTIME;            /* keep compiler quiet */
1560 }
1561
1562
1563 /*****************************************************************************
1564  *
1565  *****************************************************************************/
1566
1567 /*
1568  * timeofday -
1569  *         returns the current time as a text. similar to timenow() but returns
1570  *         seconds with more precision (up to microsecs). (I need this to compare
1571  *         the Wisconsin benchmark with Illustra whose TimeNow() shows current
1572  *         time with precision up to microsecs.)                          - ay 3/95
1573  */
1574 Datum
1575 timeofday(PG_FUNCTION_ARGS)
1576 {
1577         struct timeval tp;
1578         char            templ[128];
1579         char            buf[128];
1580         pg_time_t       tt;
1581
1582         gettimeofday(&tp, NULL);
1583         tt = (pg_time_t) tp.tv_sec;
1584         pg_strftime(templ, sizeof(templ), "%a %b %d %H:%M:%S.%%06d %Y %Z",
1585                                 pg_localtime(&tt, session_timezone));
1586         snprintf(buf, sizeof(buf), templ, tp.tv_usec);
1587
1588         PG_RETURN_TEXT_P(cstring_to_text(buf));
1589 }