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