]> granicus.if.org Git - postgresql/blob - src/backend/utils/adt/nabstime.c
minor code cleanup - replace useless struct timezone argument to
[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-2005, 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.146 2005/10/22 14:27:29 adunstan 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 "access/xact.h"
26 #include "libpq/pqformat.h"
27 #include "miscadmin.h"
28 #include "pgtime.h"
29 #include "utils/builtins.h"
30 #include "utils/nabstime.h"
31
32 #define MIN_DAYNUM (-24856)             /* December 13, 1901 */
33 #define MAX_DAYNUM 24854                /* January 18, 2038 */
34
35 #define INVALID_RELTIME_STR             "Undefined RelTime"
36 #define INVALID_RELTIME_STR_LEN (sizeof(INVALID_RELTIME_STR)-1)
37 #define RELTIME_LABEL                   '@'
38 #define RELTIME_PAST                    "ago"
39 #define DIRMAXLEN                               (sizeof(RELTIME_PAST)-1)
40
41 /*
42  * Unix epoch is Jan  1 00:00:00 1970.
43  * Postgres knows about times sixty-eight years on either side of that
44  * for these 4-byte types.
45  *
46  * "tinterval" is two 4-byte fields.
47  * Definitions for parsing tinterval.
48  */
49
50 #define IsSpace(C)                              ((C) == ' ')
51
52 #define T_INTERVAL_INVAL   0    /* data represents no valid tinterval */
53 #define T_INTERVAL_VALID   1    /* data represents a valid tinterval */
54 /*
55  * ['Mon May 10 23:59:12 1943 PST' 'Sun Jan 14 03:14:21 1973 PST']
56  * 0            1                 2                     3                 4                     5                 6
57  * 1234567890123456789012345678901234567890123456789012345678901234
58  *
59  * we allocate some extra -- timezones are usually 3 characters but
60  * this is not in the POSIX standard...
61  */
62 #define T_INTERVAL_LEN                                  80
63 #define INVALID_INTERVAL_STR                    "Undefined Range"
64 #define INVALID_INTERVAL_STR_LEN                (sizeof(INVALID_INTERVAL_STR)-1)
65
66 #define ABSTIMEMIN(t1, t2) \
67         (DatumGetBool(DirectFunctionCall2(abstimele, \
68                                   AbsoluteTimeGetDatum(t1), \
69                                   AbsoluteTimeGetDatum(t2))) ? (t1) : (t2))
70 #define ABSTIMEMAX(t1, t2) \
71         (DatumGetBool(DirectFunctionCall2(abstimelt, \
72                                   AbsoluteTimeGetDatum(t1), \
73                                   AbsoluteTimeGetDatum(t2))) ? (t2) : (t1))
74
75
76 /*
77  * Function prototypes -- internal to this file only
78  */
79
80 static AbsoluteTime tm2abstime(struct pg_tm * tm, int tz);
81 static void reltime2tm(RelativeTime time, struct pg_tm * tm);
82 static void parsetinterval(char *i_string,
83                            AbsoluteTime *i_start,
84                            AbsoluteTime *i_end);
85
86
87 /*
88  * GetCurrentAbsoluteTime()
89  *
90  * Get the current system time (relative to Unix epoch).
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, global_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, global_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, &dtype, tm, &fsec);
636         if (dterr != 0)
637         {
638                 if (dterr == DTERR_FIELD_OVERFLOW)
639                         dterr = DTERR_INTERVAL_OVERFLOW;
640                 DateTimeParseError(dterr, str, "reltime");
641         }
642
643         switch (dtype)
644         {
645                 case DTK_DELTA:
646                         result = ((tm->tm_hour * MINS_PER_HOUR + tm->tm_min) * SECS_PER_MINUTE) + tm->tm_sec;
647                         result += tm->tm_year * SECS_PER_YEAR + ((tm->tm_mon * DAYS_PER_MONTH) + tm->tm_mday) * SECS_PER_DAY;
648                         break;
649
650                 default:
651                         elog(ERROR, "unexpected dtype %d while parsing reltime \"%s\"",
652                                  dtype, str);
653                         result = INVALID_RELTIME;
654                         break;
655         }
656
657         PG_RETURN_RELATIVETIME(result);
658 }
659
660 /*
661  *              reltimeout              - converts the internal format to a reltime string
662  */
663 Datum
664 reltimeout(PG_FUNCTION_ARGS)
665 {
666         RelativeTime time = PG_GETARG_RELATIVETIME(0);
667         char       *result;
668         struct pg_tm tt,
669                            *tm = &tt;
670         char            buf[MAXDATELEN + 1];
671
672         reltime2tm(time, tm);
673         EncodeInterval(tm, 0, DateStyle, buf);
674
675         result = pstrdup(buf);
676         PG_RETURN_CSTRING(result);
677 }
678
679 /*
680  *              reltimerecv                     - converts external binary format to reltime
681  */
682 Datum
683 reltimerecv(PG_FUNCTION_ARGS)
684 {
685         StringInfo      buf = (StringInfo) PG_GETARG_POINTER(0);
686
687         PG_RETURN_RELATIVETIME((RelativeTime) pq_getmsgint(buf, sizeof(RelativeTime)));
688 }
689
690 /*
691  *              reltimesend                     - converts reltime to binary format
692  */
693 Datum
694 reltimesend(PG_FUNCTION_ARGS)
695 {
696         RelativeTime time = PG_GETARG_RELATIVETIME(0);
697         StringInfoData buf;
698
699         pq_begintypsend(&buf);
700         pq_sendint(&buf, time, sizeof(time));
701         PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
702 }
703
704
705 static void
706 reltime2tm(RelativeTime time, struct pg_tm * tm)
707 {
708         double          dtime = time;
709
710         FMODULO(dtime, tm->tm_year, 31557600);
711         FMODULO(dtime, tm->tm_mon, 2592000);
712         FMODULO(dtime, tm->tm_mday, SECS_PER_DAY);
713         FMODULO(dtime, tm->tm_hour, SECS_PER_HOUR);
714         FMODULO(dtime, tm->tm_min, SECS_PER_MINUTE);
715         FMODULO(dtime, tm->tm_sec, 1);
716 }
717
718
719 /*
720  *              tintervalin             - converts an tinterval string to internal format
721  */
722 Datum
723 tintervalin(PG_FUNCTION_ARGS)
724 {
725         char       *tintervalstr = PG_GETARG_CSTRING(0);
726         TimeInterval tinterval;
727         AbsoluteTime i_start,
728                                 i_end,
729                                 t1,
730                                 t2;
731
732         parsetinterval(tintervalstr, &t1, &t2);
733
734         tinterval = (TimeInterval) palloc(sizeof(TimeIntervalData));
735
736         if (t1 == INVALID_ABSTIME || t2 == INVALID_ABSTIME)
737                 tinterval->status = T_INTERVAL_INVAL;   /* undefined  */
738         else
739                 tinterval->status = T_INTERVAL_VALID;
740
741         i_start = ABSTIMEMIN(t1, t2);
742         i_end = ABSTIMEMAX(t1, t2);
743         tinterval->data[0] = i_start;
744         tinterval->data[1] = i_end;
745
746         PG_RETURN_TIMEINTERVAL(tinterval);
747 }
748
749
750 /*
751  *              tintervalout    - converts an internal tinterval format to a string
752  */
753 Datum
754 tintervalout(PG_FUNCTION_ARGS)
755 {
756         TimeInterval tinterval = PG_GETARG_TIMEINTERVAL(0);
757         char       *i_str,
758                            *p;
759
760         i_str = (char *) palloc(T_INTERVAL_LEN);        /* ["..." "..."] */
761         strcpy(i_str, "[\"");
762         if (tinterval->status == T_INTERVAL_INVAL)
763                 strcat(i_str, INVALID_INTERVAL_STR);
764         else
765         {
766                 p = DatumGetCString(DirectFunctionCall1(abstimeout,
767                                                                   AbsoluteTimeGetDatum(tinterval->data[0])));
768                 strcat(i_str, p);
769                 pfree(p);
770                 strcat(i_str, "\" \"");
771                 p = DatumGetCString(DirectFunctionCall1(abstimeout,
772                                                                   AbsoluteTimeGetDatum(tinterval->data[1])));
773                 strcat(i_str, p);
774                 pfree(p);
775         }
776         strcat(i_str, "\"]");
777         PG_RETURN_CSTRING(i_str);
778 }
779
780 /*
781  *              tintervalrecv                   - converts external binary format to tinterval
782  */
783 Datum
784 tintervalrecv(PG_FUNCTION_ARGS)
785 {
786         StringInfo      buf = (StringInfo) PG_GETARG_POINTER(0);
787         TimeInterval tinterval;
788
789         tinterval = (TimeInterval) palloc(sizeof(TimeIntervalData));
790
791         tinterval->status = pq_getmsgint(buf, sizeof(tinterval->status));
792
793         if (!(tinterval->status == T_INTERVAL_INVAL ||
794                   tinterval->status == T_INTERVAL_VALID))
795                 ereport(ERROR,
796                                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
797                                  errmsg("invalid status in external \"tinterval\" value")));
798
799         tinterval->data[0] = pq_getmsgint(buf, sizeof(tinterval->data[0]));
800         tinterval->data[1] = pq_getmsgint(buf, sizeof(tinterval->data[1]));
801
802         PG_RETURN_TIMEINTERVAL(tinterval);
803 }
804
805 /*
806  *              tintervalsend                   - converts tinterval to binary format
807  */
808 Datum
809 tintervalsend(PG_FUNCTION_ARGS)
810 {
811         TimeInterval tinterval = PG_GETARG_TIMEINTERVAL(0);
812         StringInfoData buf;
813
814         pq_begintypsend(&buf);
815         pq_sendint(&buf, tinterval->status, sizeof(tinterval->status));
816         pq_sendint(&buf, tinterval->data[0], sizeof(tinterval->data[0]));
817         pq_sendint(&buf, tinterval->data[1], sizeof(tinterval->data[1]));
818         PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
819 }
820
821
822 /*****************************************************************************
823  *       PUBLIC ROUTINES                                                                                                                 *
824  *****************************************************************************/
825
826 Datum
827 interval_reltime(PG_FUNCTION_ARGS)
828 {
829         Interval   *interval = PG_GETARG_INTERVAL_P(0);
830         RelativeTime time;
831         int                     year,
832                                 month,
833                                 day;
834
835 #ifdef HAVE_INT64_TIMESTAMP
836         int64           span;
837 #else
838         double          span;
839 #endif
840
841         year = interval->month / MONTHS_PER_YEAR;
842         month = interval->month % MONTHS_PER_YEAR;
843         day = interval->day;
844
845 #ifdef HAVE_INT64_TIMESTAMP
846         span = ((INT64CONST(365250000) * year + INT64CONST(30000000) * month +
847                          INT64CONST(1000000) * day) * INT64CONST(86400)) +
848                 interval->time;
849         span /= USECS_PER_SEC;
850 #else
851         span = (DAYS_PER_YEAR * year + (double) DAYS_PER_MONTH * month + day) * SECS_PER_DAY + interval->time;
852 #endif
853
854         if (span < INT_MIN || span > INT_MAX)
855                 time = INVALID_RELTIME;
856         else
857                 time = span;
858
859         PG_RETURN_RELATIVETIME(time);
860 }
861
862
863 Datum
864 reltime_interval(PG_FUNCTION_ARGS)
865 {
866         RelativeTime reltime = PG_GETARG_RELATIVETIME(0);
867         Interval   *result;
868         int                     year,
869                                 month,
870                                 day;
871
872         result = (Interval *) palloc(sizeof(Interval));
873
874         switch (reltime)
875         {
876                 case INVALID_RELTIME:
877                         ereport(ERROR,
878                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
879                                   errmsg("cannot convert reltime \"invalid\" to interval")));
880                         result->time = 0;
881                         result->day = 0;
882                         result->month = 0;
883                         break;
884
885                 default:
886 #ifdef HAVE_INT64_TIMESTAMP
887                         year = reltime / SECS_PER_YEAR;
888                         reltime -= year * SECS_PER_YEAR;
889                         month = reltime / (DAYS_PER_MONTH * SECS_PER_DAY);
890                         reltime -= month * (DAYS_PER_MONTH * SECS_PER_DAY);
891                         day = reltime / SECS_PER_DAY;
892                         reltime -= day * SECS_PER_DAY;
893
894                         result->time = (reltime * USECS_PER_SEC);
895 #else
896                         TMODULO(reltime, year, SECS_PER_YEAR);
897                         TMODULO(reltime, month, DAYS_PER_MONTH * SECS_PER_DAY);
898                         TMODULO(reltime, day, SECS_PER_DAY);
899
900                         result->time = reltime;
901 #endif
902                         result->month = MONTHS_PER_YEAR * year + month;
903                         result->day = day;
904                         break;
905         }
906
907         PG_RETURN_INTERVAL_P(result);
908 }
909
910
911 /*
912  *              mktinterval             - creates a time interval with endpoints t1 and t2
913  */
914 Datum
915 mktinterval(PG_FUNCTION_ARGS)
916 {
917         AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
918         AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
919         AbsoluteTime tstart = ABSTIMEMIN(t1, t2);
920         AbsoluteTime tend = ABSTIMEMAX(t1, t2);
921         TimeInterval tinterval;
922
923         tinterval = (TimeInterval) palloc(sizeof(TimeIntervalData));
924
925         if (t1 == INVALID_ABSTIME || t2 == INVALID_ABSTIME)
926                 tinterval->status = T_INTERVAL_INVAL;
927
928         else
929         {
930                 tinterval->status = T_INTERVAL_VALID;
931                 tinterval->data[0] = tstart;
932                 tinterval->data[1] = tend;
933         }
934
935         PG_RETURN_TIMEINTERVAL(tinterval);
936 }
937
938 /*
939  *              timepl, timemi and abstimemi use the formula
940  *                              abstime + reltime = abstime
941  *              so              abstime - reltime = abstime
942  *              and             abstime - abstime = reltime
943  */
944
945 /*
946  *              timepl                  - returns the value of (abstime t1 + reltime t2)
947  */
948 Datum
949 timepl(PG_FUNCTION_ARGS)
950 {
951         AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
952         RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
953
954         if (AbsoluteTimeIsReal(t1) &&
955                 RelativeTimeIsValid(t2) &&
956                 ((t2 > 0 && t1 < NOEND_ABSTIME - t2) ||
957                  (t2 <= 0 && t1 > NOSTART_ABSTIME - t2)))               /* prevent overflow */
958                 PG_RETURN_ABSOLUTETIME(t1 + t2);
959
960         PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
961 }
962
963
964 /*
965  *              timemi                  - returns the value of (abstime t1 - reltime t2)
966  */
967 Datum
968 timemi(PG_FUNCTION_ARGS)
969 {
970         AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
971         RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
972
973         if (AbsoluteTimeIsReal(t1) &&
974                 RelativeTimeIsValid(t2) &&
975                 ((t2 > 0 && t1 > NOSTART_ABSTIME + t2) ||
976                  (t2 <= 0 && t1 < NOEND_ABSTIME + t2))) /* prevent overflow */
977                 PG_RETURN_ABSOLUTETIME(t1 - t2);
978
979         PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
980 }
981
982
983 /*
984  *              intinterval             - returns true iff absolute date is in the tinterval
985  */
986 Datum
987 intinterval(PG_FUNCTION_ARGS)
988 {
989         AbsoluteTime t = PG_GETARG_ABSOLUTETIME(0);
990         TimeInterval tinterval = PG_GETARG_TIMEINTERVAL(1);
991
992         if (tinterval->status == T_INTERVAL_VALID && t != INVALID_ABSTIME)
993         {
994                 if (DatumGetBool(DirectFunctionCall2(abstimege,
995                                                                                          AbsoluteTimeGetDatum(t),
996                                                                 AbsoluteTimeGetDatum(tinterval->data[0]))) &&
997                         DatumGetBool(DirectFunctionCall2(abstimele,
998                                                                                          AbsoluteTimeGetDatum(t),
999                                                                   AbsoluteTimeGetDatum(tinterval->data[1]))))
1000                         PG_RETURN_BOOL(true);
1001         }
1002         PG_RETURN_BOOL(false);
1003 }
1004
1005 /*
1006  *              tintervalrel            - returns  relative time corresponding to tinterval
1007  */
1008 Datum
1009 tintervalrel(PG_FUNCTION_ARGS)
1010 {
1011         TimeInterval tinterval = PG_GETARG_TIMEINTERVAL(0);
1012         AbsoluteTime t1 = tinterval->data[0];
1013         AbsoluteTime t2 = tinterval->data[1];
1014
1015         if (tinterval->status != T_INTERVAL_VALID)
1016                 PG_RETURN_RELATIVETIME(INVALID_RELTIME);
1017
1018         if (AbsoluteTimeIsReal(t1) &&
1019                 AbsoluteTimeIsReal(t2))
1020                 PG_RETURN_RELATIVETIME(t2 - t1);
1021
1022         PG_RETURN_RELATIVETIME(INVALID_RELTIME);
1023 }
1024
1025
1026 /*
1027  *              timenow                 - returns  time "now", internal format
1028  *
1029  *              Now AbsoluteTime is time since Jan 1 1970 -mer 7 Feb 1992
1030  */
1031 Datum
1032 timenow(PG_FUNCTION_ARGS)
1033 {
1034         time_t          sec;
1035
1036         if (time(&sec) < 0)
1037                 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
1038
1039         PG_RETURN_ABSOLUTETIME((AbsoluteTime) sec);
1040 }
1041
1042 /*
1043  * reltime comparison routines
1044  */
1045 static int
1046 reltime_cmp_internal(RelativeTime a, RelativeTime b)
1047 {
1048         /*
1049          * We consider all INVALIDs to be equal and larger than any non-INVALID.
1050          * This is somewhat arbitrary; the important thing is to have a consistent
1051          * sort order.
1052          */
1053         if (a == INVALID_RELTIME)
1054         {
1055                 if (b == INVALID_RELTIME)
1056                         return 0;                       /* INVALID = INVALID */
1057                 else
1058                         return 1;                       /* INVALID > non-INVALID */
1059         }
1060
1061         if (b == INVALID_RELTIME)
1062                 return -1;                              /* non-INVALID < INVALID */
1063
1064         if (a > b)
1065                 return 1;
1066         else if (a == b)
1067                 return 0;
1068         else
1069                 return -1;
1070 }
1071
1072 Datum
1073 reltimeeq(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 reltimene(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 reltimelt(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 reltimegt(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 reltimele(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 reltimege(PG_FUNCTION_ARGS)
1119 {
1120         RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1121         RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1122
1123         PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) >= 0);
1124 }
1125
1126 Datum
1127 btreltimecmp(PG_FUNCTION_ARGS)
1128 {
1129         RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1130         RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1131
1132         PG_RETURN_INT32(reltime_cmp_internal(t1, t2));
1133 }
1134
1135
1136 /*
1137  *              tintervalsame   - returns true iff tinterval i1 is same as tinterval i2
1138  *              Check begin and end time.
1139  */
1140 Datum
1141 tintervalsame(PG_FUNCTION_ARGS)
1142 {
1143         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1144         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1145
1146         if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL)
1147                 PG_RETURN_BOOL(false);
1148
1149         if (DatumGetBool(DirectFunctionCall2(abstimeeq,
1150                                                                                  AbsoluteTimeGetDatum(i1->data[0]),
1151                                                                            AbsoluteTimeGetDatum(i2->data[0]))) &&
1152                 DatumGetBool(DirectFunctionCall2(abstimeeq,
1153                                                                                  AbsoluteTimeGetDatum(i1->data[1]),
1154                                                                                  AbsoluteTimeGetDatum(i2->data[1]))))
1155                 PG_RETURN_BOOL(true);
1156         PG_RETURN_BOOL(false);
1157 }
1158
1159 /*
1160  * tinterval comparison routines
1161  *
1162  * Note: comparison is based on the lengths of the tintervals, not on
1163  * endpoint value.      This is pretty bogus, but since it's only a legacy
1164  * datatype I'm not going to propose changing it.
1165  */
1166 static int
1167 tinterval_cmp_internal(TimeInterval a, TimeInterval b)
1168 {
1169         bool            a_invalid;
1170         bool            b_invalid;
1171         AbsoluteTime a_len;
1172         AbsoluteTime b_len;
1173
1174         /*
1175          * We consider all INVALIDs to be equal and larger than any non-INVALID.
1176          * This is somewhat arbitrary; the important thing is to have a consistent
1177          * sort order.
1178          */
1179         a_invalid = a->status == T_INTERVAL_INVAL ||
1180                 a->data[0] == INVALID_ABSTIME ||
1181                 a->data[1] == INVALID_ABSTIME;
1182         b_invalid = b->status == T_INTERVAL_INVAL ||
1183                 b->data[0] == INVALID_ABSTIME ||
1184                 b->data[1] == INVALID_ABSTIME;
1185
1186         if (a_invalid)
1187         {
1188                 if (b_invalid)
1189                         return 0;                       /* INVALID = INVALID */
1190                 else
1191                         return 1;                       /* INVALID > non-INVALID */
1192         }
1193
1194         if (b_invalid)
1195                 return -1;                              /* non-INVALID < INVALID */
1196
1197         a_len = a->data[1] - a->data[0];
1198         b_len = b->data[1] - b->data[0];
1199
1200         if (a_len > b_len)
1201                 return 1;
1202         else if (a_len == b_len)
1203                 return 0;
1204         else
1205                 return -1;
1206 }
1207
1208 Datum
1209 tintervaleq(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 tintervalne(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 tintervallt(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 tintervalle(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 tintervalgt(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 tintervalge(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 bttintervalcmp(PG_FUNCTION_ARGS)
1264 {
1265         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1266         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1267
1268         PG_RETURN_INT32(tinterval_cmp_internal(i1, i2));
1269 }
1270
1271
1272 /*
1273  *              tintervalleneq  - returns true iff length of tinterval i is equal to
1274  *                                                              reltime t
1275  *              tintervallenne  - returns true iff length of tinterval i is not equal
1276  *                                                              to reltime t
1277  *              tintervallenlt  - returns true iff length of tinterval i is less than
1278  *                                                              reltime t
1279  *              tintervallengt  - returns true iff length of tinterval i is greater
1280  *                                                              than reltime t
1281  *              tintervallenle  - returns true iff length of tinterval i is less or
1282  *                                                              equal than reltime t
1283  *              tintervallenge  - returns true iff length of tinterval i is greater or
1284  *                                                              equal than reltime t
1285  */
1286 Datum
1287 tintervalleneq(PG_FUNCTION_ARGS)
1288 {
1289         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1290         RelativeTime t = PG_GETARG_RELATIVETIME(1);
1291         RelativeTime rt;
1292
1293         if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1294                 PG_RETURN_BOOL(false);
1295         rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1296                                                                                                   TimeIntervalGetDatum(i)));
1297         PG_RETURN_BOOL(rt != INVALID_RELTIME && rt == t);
1298 }
1299
1300 Datum
1301 tintervallenne(PG_FUNCTION_ARGS)
1302 {
1303         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1304         RelativeTime t = PG_GETARG_RELATIVETIME(1);
1305         RelativeTime rt;
1306
1307         if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1308                 PG_RETURN_BOOL(false);
1309         rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1310                                                                                                   TimeIntervalGetDatum(i)));
1311         PG_RETURN_BOOL(rt != INVALID_RELTIME && rt != t);
1312 }
1313
1314 Datum
1315 tintervallenlt(PG_FUNCTION_ARGS)
1316 {
1317         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1318         RelativeTime t = PG_GETARG_RELATIVETIME(1);
1319         RelativeTime rt;
1320
1321         if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1322                 PG_RETURN_BOOL(false);
1323         rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1324                                                                                                   TimeIntervalGetDatum(i)));
1325         PG_RETURN_BOOL(rt != INVALID_RELTIME && rt < t);
1326 }
1327
1328 Datum
1329 tintervallengt(PG_FUNCTION_ARGS)
1330 {
1331         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1332         RelativeTime t = PG_GETARG_RELATIVETIME(1);
1333         RelativeTime rt;
1334
1335         if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1336                 PG_RETURN_BOOL(false);
1337         rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1338                                                                                                   TimeIntervalGetDatum(i)));
1339         PG_RETURN_BOOL(rt != INVALID_RELTIME && rt > t);
1340 }
1341
1342 Datum
1343 tintervallenle(PG_FUNCTION_ARGS)
1344 {
1345         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1346         RelativeTime t = PG_GETARG_RELATIVETIME(1);
1347         RelativeTime rt;
1348
1349         if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1350                 PG_RETURN_BOOL(false);
1351         rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1352                                                                                                   TimeIntervalGetDatum(i)));
1353         PG_RETURN_BOOL(rt != INVALID_RELTIME && rt <= t);
1354 }
1355
1356 Datum
1357 tintervallenge(PG_FUNCTION_ARGS)
1358 {
1359         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1360         RelativeTime t = PG_GETARG_RELATIVETIME(1);
1361         RelativeTime rt;
1362
1363         if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1364                 PG_RETURN_BOOL(false);
1365         rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1366                                                                                                   TimeIntervalGetDatum(i)));
1367         PG_RETURN_BOOL(rt != INVALID_RELTIME && rt >= t);
1368 }
1369
1370 /*
1371  *              tintervalct             - returns true iff tinterval i1 contains tinterval i2
1372  */
1373 Datum
1374 tintervalct(PG_FUNCTION_ARGS)
1375 {
1376         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1377         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1378
1379         if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL)
1380                 PG_RETURN_BOOL(false);
1381         if (DatumGetBool(DirectFunctionCall2(abstimele,
1382                                                                                  AbsoluteTimeGetDatum(i1->data[0]),
1383                                                                            AbsoluteTimeGetDatum(i2->data[0]))) &&
1384                 DatumGetBool(DirectFunctionCall2(abstimege,
1385                                                                                  AbsoluteTimeGetDatum(i1->data[1]),
1386                                                                                  AbsoluteTimeGetDatum(i2->data[1]))))
1387                 PG_RETURN_BOOL(true);
1388         PG_RETURN_BOOL(false);
1389 }
1390
1391 /*
1392  *              tintervalov             - returns true iff tinterval i1 (partially) overlaps i2
1393  */
1394 Datum
1395 tintervalov(PG_FUNCTION_ARGS)
1396 {
1397         TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1398         TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1399
1400         if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL)
1401                 PG_RETURN_BOOL(false);
1402         if (DatumGetBool(DirectFunctionCall2(abstimelt,
1403                                                                                  AbsoluteTimeGetDatum(i1->data[1]),
1404                                                                            AbsoluteTimeGetDatum(i2->data[0]))) ||
1405                 DatumGetBool(DirectFunctionCall2(abstimegt,
1406                                                                                  AbsoluteTimeGetDatum(i1->data[0]),
1407                                                                                  AbsoluteTimeGetDatum(i2->data[1]))))
1408                 PG_RETURN_BOOL(false);
1409         PG_RETURN_BOOL(true);
1410 }
1411
1412 /*
1413  *              tintervalstart  - returns  the start of tinterval i
1414  */
1415 Datum
1416 tintervalstart(PG_FUNCTION_ARGS)
1417 {
1418         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1419
1420         if (i->status == T_INTERVAL_INVAL)
1421                 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
1422         PG_RETURN_ABSOLUTETIME(i->data[0]);
1423 }
1424
1425 /*
1426  *              tintervalend            - returns  the end of tinterval i
1427  */
1428 Datum
1429 tintervalend(PG_FUNCTION_ARGS)
1430 {
1431         TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1432
1433         if (i->status == T_INTERVAL_INVAL)
1434                 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
1435         PG_RETURN_ABSOLUTETIME(i->data[1]);
1436 }
1437
1438
1439 /*****************************************************************************
1440  *       PRIVATE ROUTINES                                                                                                                *
1441  *****************************************************************************/
1442
1443 /*
1444  *              parsetinterval -- parse a tinterval string
1445  *
1446  *              output parameters:
1447  *                              i_start, i_end: tinterval margins
1448  *
1449  *              Time interval:
1450  *              `[' {` '} `'' <AbsTime> `'' {` '} `'' <AbsTime> `'' {` '} `]'
1451  *
1452  *              OR      `Undefined Range'       (see also INVALID_INTERVAL_STR)
1453  *
1454  *              where <AbsTime> satisfies the syntax of absolute time.
1455  *
1456  *              e.g.  [  '  Jan 18 1902'   'Jan 1 00:00:00 1970']
1457  */
1458 static void
1459 parsetinterval(char *i_string,
1460                            AbsoluteTime *i_start,
1461                            AbsoluteTime *i_end)
1462 {
1463         char       *p,
1464                            *p1;
1465         char            c;
1466
1467         p = i_string;
1468         /* skip leading blanks up to '[' */
1469         while ((c = *p) != '\0')
1470         {
1471                 if (IsSpace(c))
1472                         p++;
1473                 else if (c != '[')
1474                         goto bogus;                     /* syntax error */
1475                 else
1476                         break;
1477         }
1478         if (c == '\0')
1479                 goto bogus;                             /* syntax error */
1480         p++;
1481         /* skip leading blanks up to '"' */
1482         while ((c = *p) != '\0')
1483         {
1484                 if (IsSpace(c))
1485                         p++;
1486                 else if (c != '"')
1487                         goto bogus;                     /* syntax error */
1488                 else
1489                         break;
1490         }
1491         if (c == '\0')
1492                 goto bogus;                             /* syntax error */
1493         p++;
1494         if (strncmp(INVALID_INTERVAL_STR, p, strlen(INVALID_INTERVAL_STR)) == 0)
1495                 goto bogus;                             /* undefined range, handled like a syntax err. */
1496         /* search for the end of the first date and change it to a \0 */
1497         p1 = p;
1498         while ((c = *p1) != '\0')
1499         {
1500                 if (c == '"')
1501                         break;
1502                 p1++;
1503         }
1504         if (c == '\0')
1505                 goto bogus;                             /* syntax error */
1506         *p1 = '\0';
1507         /* get the first date */
1508         *i_start = DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
1509                                                                                                                 CStringGetDatum(p)));
1510         /* undo change to \0 */
1511         *p1 = c;
1512         p = ++p1;
1513         /* skip blanks up to '"', beginning of second date */
1514         while ((c = *p) != '\0')
1515         {
1516                 if (IsSpace(c))
1517                         p++;
1518                 else if (c != '"')
1519                         goto bogus;                     /* syntax error */
1520                 else
1521                         break;
1522         }
1523         if (c == '\0')
1524                 goto bogus;                             /* syntax error */
1525         p++;
1526         /* search for the end of the second date and change it to a \0 */
1527         p1 = p;
1528         while ((c = *p1) != '\0')
1529         {
1530                 if (c == '"')
1531                         break;
1532                 p1++;
1533         }
1534         if (c == '\0')
1535                 goto bogus;                             /* syntax error */
1536         *p1 = '\0';
1537         /* get the second date */
1538         *i_end = DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
1539                                                                                                           CStringGetDatum(p)));
1540         /* undo change to \0 */
1541         *p1 = c;
1542         p = ++p1;
1543         /* skip blanks up to ']' */
1544         while ((c = *p) != '\0')
1545         {
1546                 if (IsSpace(c))
1547                         p++;
1548                 else if (c != ']')
1549                         goto bogus;                     /* syntax error */
1550                 else
1551                         break;
1552         }
1553         if (c == '\0')
1554                 goto bogus;                             /* syntax error */
1555         p++;
1556         c = *p;
1557         if (c != '\0')
1558                 goto bogus;                             /* syntax error */
1559
1560         /* it seems to be a valid tinterval */
1561         return;
1562
1563 bogus:
1564         ereport(ERROR,
1565                         (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
1566                          errmsg("invalid input syntax for type tinterval: \"%s\"",
1567                                         i_string)));
1568         *i_start = *i_end = INVALID_ABSTIME;            /* keep compiler quiet */
1569 }
1570
1571
1572 /*****************************************************************************
1573  *
1574  *****************************************************************************/
1575
1576 /*
1577  * timeofday -
1578  *         returns the current time as a text. similar to timenow() but returns
1579  *         seconds with more precision (up to microsecs). (I need this to compare
1580  *         the Wisconsin benchmark with Illustra whose TimeNow() shows current
1581  *         time with precision up to microsecs.)                          - ay 3/95
1582  */
1583 Datum
1584 timeofday(PG_FUNCTION_ARGS)
1585 {
1586         struct timeval tp;
1587         char            templ[128];
1588         char            buf[128];
1589         text       *result;
1590         int                     len;
1591         pg_time_t       tt;
1592
1593         gettimeofday(&tp, NULL);
1594         tt = (pg_time_t) tp.tv_sec;
1595         pg_strftime(templ, sizeof(templ), "%a %b %d %H:%M:%S.%%06d %Y %Z",
1596                                 pg_localtime(&tt, global_timezone));
1597         snprintf(buf, sizeof(buf), templ, tp.tv_usec);
1598
1599         len = VARHDRSZ + strlen(buf);
1600         result = (text *) palloc(len);
1601         VARATT_SIZEP(result) = len;
1602         memcpy(VARDATA(result), buf, strlen(buf));
1603         PG_RETURN_TEXT_P(result);
1604 }