1 /*-------------------------------------------------------------------------
4 * Utilities for the built-in type "AbsoluteTime".
5 * Functions for the built-in type "RelativeTime".
6 * Functions for the built-in type "TimeInterval".
8 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
13 * $PostgreSQL: pgsql/src/backend/utils/adt/nabstime.c,v 1.156 2008/09/10 18:29:41 tgl Exp $
15 *-------------------------------------------------------------------------
25 #include "libpq/pqformat.h"
26 #include "miscadmin.h"
27 #include "utils/builtins.h"
28 #include "utils/nabstime.h"
30 #define MIN_DAYNUM (-24856) /* December 13, 1901 */
31 #define MAX_DAYNUM 24854 /* January 18, 2038 */
33 #define INVALID_RELTIME_STR "Undefined RelTime"
34 #define INVALID_RELTIME_STR_LEN (sizeof(INVALID_RELTIME_STR)-1)
35 #define RELTIME_LABEL '@'
36 #define RELTIME_PAST "ago"
37 #define DIRMAXLEN (sizeof(RELTIME_PAST)-1)
40 * Unix epoch is Jan 1 00:00:00 1970.
41 * Postgres knows about times sixty-eight years on either side of that
42 * for these 4-byte types.
44 * "tinterval" is two 4-byte fields.
45 * Definitions for parsing tinterval.
48 #define IsSpace(C) ((C) == ' ')
50 #define T_INTERVAL_INVAL 0 /* data represents no valid tinterval */
51 #define T_INTERVAL_VALID 1 /* data represents a valid tinterval */
53 * ['Mon May 10 23:59:12 1943 PST' 'Sun Jan 14 03:14:21 1973 PST']
55 * 1234567890123456789012345678901234567890123456789012345678901234
57 * we allocate some extra -- timezones are usually 3 characters but
58 * this is not in the POSIX standard...
60 #define T_INTERVAL_LEN 80
61 #define INVALID_INTERVAL_STR "Undefined Range"
62 #define INVALID_INTERVAL_STR_LEN (sizeof(INVALID_INTERVAL_STR)-1)
64 #define ABSTIMEMIN(t1, t2) \
65 (DatumGetBool(DirectFunctionCall2(abstimele, \
66 AbsoluteTimeGetDatum(t1), \
67 AbsoluteTimeGetDatum(t2))) ? (t1) : (t2))
68 #define ABSTIMEMAX(t1, t2) \
69 (DatumGetBool(DirectFunctionCall2(abstimelt, \
70 AbsoluteTimeGetDatum(t1), \
71 AbsoluteTimeGetDatum(t2))) ? (t2) : (t1))
75 * Function prototypes -- internal to this file only
78 static AbsoluteTime tm2abstime(struct pg_tm * tm, int tz);
79 static void reltime2tm(RelativeTime time, struct pg_tm * tm);
80 static void parsetinterval(char *i_string,
81 AbsoluteTime *i_start,
86 * GetCurrentAbsoluteTime()
88 * Get the current system time (relative to Unix epoch).
90 * NB: this will overflow in 2038; it should be gone long before that.
93 GetCurrentAbsoluteTime(void)
98 return (AbsoluteTime) now;
103 abstime2tm(AbsoluteTime _time, int *tzp, struct pg_tm * tm, char **tzn)
105 pg_time_t time = (pg_time_t) _time;
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.
113 if (HasCTZSet && (tzp != NULL))
116 if (!HasCTZSet && tzp != NULL)
117 tx = pg_localtime(&time, session_timezone);
119 tx = pg_gmtime(&time);
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;
129 tm->tm_gmtoff = tx->tm_gmtoff;
130 tm->tm_zone = tx->tm_zone;
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.
141 tm->tm_gmtoff = CTimeZone;
149 *tzp = -tm->tm_gmtoff; /* tm_gmtoff is Sun/DEC-ism */
152 * XXX FreeBSD man pages indicate that this should work - tgl
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
162 StrNCpy(*tzn, tm->tm_zone, MAXTZLEN + 1);
163 if (strlen(tm->tm_zone) > MAXTZLEN)
165 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
166 errmsg("invalid time zone name: \"%s\"",
177 * Convert a tm structure to abstime.
178 * Note that tm has full year (not 1900-based) and 1-based month.
181 tm2abstime(struct pg_tm * tm, int tz)
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 ||
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;
197 day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - UNIX_EPOCH_JDATE;
199 /* check for time out of range */
200 if (day < MIN_DAYNUM || day > MAX_DAYNUM)
201 return INVALID_ABSTIME;
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;
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.
210 if ((day >= MAX_DAYNUM - 10 && sec < 0) ||
211 (day <= MIN_DAYNUM + 10 && sec > 0))
212 return INVALID_ABSTIME;
214 /* check for reserved values (e.g. "current" on edge of usual range */
215 if (!AbsoluteTimeIsReal(sec))
216 return INVALID_ABSTIME;
223 * Decode date/time string and return abstime.
226 abstimein(PG_FUNCTION_ARGS)
228 char *str = PG_GETARG_CSTRING(0);
235 char *field[MAXDATEFIELDS];
236 char workbuf[MAXDATELEN + 1];
239 ftype[MAXDATEFIELDS];
241 dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
242 field, ftype, MAXDATEFIELDS, &nf);
244 dterr = DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz);
246 DateTimeParseError(dterr, str, "abstime");
251 result = tm2abstime(tm, tz);
257 * Don't bother retaining this as a reserved value, but instead
258 * just set to the actual epoch time (1970-01-01)
264 result = NOEND_ABSTIME;
268 result = NOSTART_ABSTIME;
272 result = INVALID_ABSTIME;
276 elog(ERROR, "unexpected dtype %d while parsing abstime \"%s\"",
278 result = INVALID_ABSTIME;
282 PG_RETURN_ABSOLUTETIME(result);
287 * Given an AbsoluteTime return the English text version of the date
290 abstimeout(PG_FUNCTION_ARGS)
292 AbsoluteTime time = PG_GETARG_ABSOLUTETIME(0);
298 char buf[MAXDATELEN + 1];
299 char zone[MAXDATELEN + 1],
305 * Note that timestamp no longer supports 'invalid'. Retain
306 * 'invalid' for abstime for now, but dump it someday.
308 case INVALID_ABSTIME:
309 strcpy(buf, INVALID);
314 case NOSTART_ABSTIME:
318 abstime2tm(time, &tz, tm, &tzn);
319 EncodeDateTime(tm, fsec, &tz, &tzn, DateStyle, buf);
323 result = pstrdup(buf);
324 PG_RETURN_CSTRING(result);
328 * abstimerecv - converts external binary format to abstime
331 abstimerecv(PG_FUNCTION_ARGS)
333 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
335 PG_RETURN_ABSOLUTETIME((AbsoluteTime) pq_getmsgint(buf, sizeof(AbsoluteTime)));
339 * abstimesend - converts abstime to binary format
342 abstimesend(PG_FUNCTION_ARGS)
344 AbsoluteTime time = PG_GETARG_ABSOLUTETIME(0);
347 pq_begintypsend(&buf);
348 pq_sendint(&buf, time, sizeof(time));
349 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
356 abstime_finite(PG_FUNCTION_ARGS)
358 AbsoluteTime abstime = PG_GETARG_ABSOLUTETIME(0);
360 PG_RETURN_BOOL(abstime != INVALID_ABSTIME &&
361 abstime != NOSTART_ABSTIME &&
362 abstime != NOEND_ABSTIME);
367 * abstime comparison routines
370 abstime_cmp_internal(AbsoluteTime a, AbsoluteTime b)
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
377 if (a == INVALID_ABSTIME)
379 if (b == INVALID_ABSTIME)
380 return 0; /* INVALID = INVALID */
382 return 1; /* INVALID > non-INVALID */
385 if (b == INVALID_ABSTIME)
386 return -1; /* non-INVALID < INVALID */
397 abstimeeq(PG_FUNCTION_ARGS)
399 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
400 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
402 PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) == 0);
406 abstimene(PG_FUNCTION_ARGS)
408 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
409 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
411 PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) != 0);
415 abstimelt(PG_FUNCTION_ARGS)
417 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
418 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
420 PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) < 0);
424 abstimegt(PG_FUNCTION_ARGS)
426 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
427 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
429 PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) > 0);
433 abstimele(PG_FUNCTION_ARGS)
435 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
436 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
438 PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) <= 0);
442 abstimege(PG_FUNCTION_ARGS)
444 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
445 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
447 PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) >= 0);
451 btabstimecmp(PG_FUNCTION_ARGS)
453 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
454 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
456 PG_RETURN_INT32(abstime_cmp_internal(t1, t2));
460 /* timestamp_abstime()
461 * Convert timestamp to abstime.
464 timestamp_abstime(PG_FUNCTION_ARGS)
466 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
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)
479 tz = DetermineTimeZoneOffset(tm, session_timezone);
480 result = tm2abstime(tm, tz);
485 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
486 errmsg("timestamp out of range")));
487 result = INVALID_ABSTIME;
490 PG_RETURN_ABSOLUTETIME(result);
493 /* abstime_timestamp()
494 * Convert abstime to timestamp.
497 abstime_timestamp(PG_FUNCTION_ARGS)
499 AbsoluteTime abstime = PG_GETARG_ABSOLUTETIME(0);
504 char zone[MAXDATELEN + 1],
509 case INVALID_ABSTIME:
511 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
512 errmsg("cannot convert abstime \"invalid\" to timestamp")));
513 TIMESTAMP_NOBEGIN(result);
516 case NOSTART_ABSTIME:
517 TIMESTAMP_NOBEGIN(result);
521 TIMESTAMP_NOEND(result);
525 abstime2tm(abstime, &tz, tm, &tzn);
526 if (tm2timestamp(tm, 0, NULL, &result) != 0)
528 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
529 errmsg("timestamp out of range")));
533 PG_RETURN_TIMESTAMP(result);
537 /* timestamptz_abstime()
538 * Convert timestamp with time zone to abstime.
541 timestamptz_abstime(PG_FUNCTION_ARGS)
543 TimestampTz timestamp = PG_GETARG_TIMESTAMP(0);
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);
558 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
559 errmsg("timestamp out of range")));
560 result = INVALID_ABSTIME;
563 PG_RETURN_ABSOLUTETIME(result);
566 /* abstime_timestamptz()
567 * Convert abstime to timestamp with time zone.
570 abstime_timestamptz(PG_FUNCTION_ARGS)
572 AbsoluteTime abstime = PG_GETARG_ABSOLUTETIME(0);
577 char zone[MAXDATELEN + 1],
582 case INVALID_ABSTIME:
584 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
585 errmsg("cannot convert abstime \"invalid\" to timestamp")));
586 TIMESTAMP_NOBEGIN(result);
589 case NOSTART_ABSTIME:
590 TIMESTAMP_NOBEGIN(result);
594 TIMESTAMP_NOEND(result);
598 abstime2tm(abstime, &tz, tm, &tzn);
599 if (tm2timestamp(tm, 0, &tz, &result) != 0)
601 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
602 errmsg("timestamp out of range")));
606 PG_RETURN_TIMESTAMP(result);
610 /*****************************************************************************
611 * USER I/O ROUTINES *
612 *****************************************************************************/
615 * reltimein - converts a reltime string in an internal format
618 reltimein(PG_FUNCTION_ARGS)
620 char *str = PG_GETARG_CSTRING(0);
627 char *field[MAXDATEFIELDS];
629 ftype[MAXDATEFIELDS];
630 char workbuf[MAXDATELEN + 1];
632 dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
633 field, ftype, MAXDATEFIELDS, &nf);
635 dterr = DecodeInterval(field, ftype, nf, INTERVAL_FULL_RANGE,
639 if (dterr == DTERR_FIELD_OVERFLOW)
640 dterr = DTERR_INTERVAL_OVERFLOW;
641 DateTimeParseError(dterr, str, "reltime");
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;
652 elog(ERROR, "unexpected dtype %d while parsing reltime \"%s\"",
654 result = INVALID_RELTIME;
658 PG_RETURN_RELATIVETIME(result);
662 * reltimeout - converts the internal format to a reltime string
665 reltimeout(PG_FUNCTION_ARGS)
667 RelativeTime time = PG_GETARG_RELATIVETIME(0);
671 char buf[MAXDATELEN + 1];
673 reltime2tm(time, tm);
674 EncodeInterval(tm, 0, DateStyle, buf);
676 result = pstrdup(buf);
677 PG_RETURN_CSTRING(result);
681 * reltimerecv - converts external binary format to reltime
684 reltimerecv(PG_FUNCTION_ARGS)
686 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
688 PG_RETURN_RELATIVETIME((RelativeTime) pq_getmsgint(buf, sizeof(RelativeTime)));
692 * reltimesend - converts reltime to binary format
695 reltimesend(PG_FUNCTION_ARGS)
697 RelativeTime time = PG_GETARG_RELATIVETIME(0);
700 pq_begintypsend(&buf);
701 pq_sendint(&buf, time, sizeof(time));
702 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
707 reltime2tm(RelativeTime time, struct pg_tm * tm)
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);
721 * tintervalin - converts an tinterval string to internal format
724 tintervalin(PG_FUNCTION_ARGS)
726 char *tintervalstr = PG_GETARG_CSTRING(0);
727 TimeInterval tinterval;
728 AbsoluteTime i_start,
733 parsetinterval(tintervalstr, &t1, &t2);
735 tinterval = (TimeInterval) palloc(sizeof(TimeIntervalData));
737 if (t1 == INVALID_ABSTIME || t2 == INVALID_ABSTIME)
738 tinterval->status = T_INTERVAL_INVAL; /* undefined */
740 tinterval->status = T_INTERVAL_VALID;
742 i_start = ABSTIMEMIN(t1, t2);
743 i_end = ABSTIMEMAX(t1, t2);
744 tinterval->data[0] = i_start;
745 tinterval->data[1] = i_end;
747 PG_RETURN_TIMEINTERVAL(tinterval);
752 * tintervalout - converts an internal tinterval format to a string
755 tintervalout(PG_FUNCTION_ARGS)
757 TimeInterval tinterval = PG_GETARG_TIMEINTERVAL(0);
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);
767 p = DatumGetCString(DirectFunctionCall1(abstimeout,
768 AbsoluteTimeGetDatum(tinterval->data[0])));
771 strcat(i_str, "\" \"");
772 p = DatumGetCString(DirectFunctionCall1(abstimeout,
773 AbsoluteTimeGetDatum(tinterval->data[1])));
777 strcat(i_str, "\"]");
778 PG_RETURN_CSTRING(i_str);
782 * tintervalrecv - converts external binary format to tinterval
785 tintervalrecv(PG_FUNCTION_ARGS)
787 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
788 TimeInterval tinterval;
790 tinterval = (TimeInterval) palloc(sizeof(TimeIntervalData));
792 tinterval->status = pq_getmsgint(buf, sizeof(tinterval->status));
794 if (!(tinterval->status == T_INTERVAL_INVAL ||
795 tinterval->status == T_INTERVAL_VALID))
797 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
798 errmsg("invalid status in external \"tinterval\" value")));
800 tinterval->data[0] = pq_getmsgint(buf, sizeof(tinterval->data[0]));
801 tinterval->data[1] = pq_getmsgint(buf, sizeof(tinterval->data[1]));
803 PG_RETURN_TIMEINTERVAL(tinterval);
807 * tintervalsend - converts tinterval to binary format
810 tintervalsend(PG_FUNCTION_ARGS)
812 TimeInterval tinterval = PG_GETARG_TIMEINTERVAL(0);
815 pq_begintypsend(&buf);
816 pq_sendint(&buf, tinterval->status, sizeof(tinterval->status));
817 pq_sendint(&buf, tinterval->data[0], sizeof(tinterval->data[0]));
818 pq_sendint(&buf, tinterval->data[1], sizeof(tinterval->data[1]));
819 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
823 /*****************************************************************************
825 *****************************************************************************/
828 interval_reltime(PG_FUNCTION_ARGS)
830 Interval *interval = PG_GETARG_INTERVAL_P(0);
837 year = interval->month / MONTHS_PER_YEAR;
838 month = interval->month % MONTHS_PER_YEAR;
841 #ifdef HAVE_INT64_TIMESTAMP
842 span = ((INT64CONST(365250000) * year + INT64CONST(30000000) * month +
843 INT64CONST(1000000) * day) * INT64CONST(86400)) +
845 span /= USECS_PER_SEC;
847 span = (DAYS_PER_YEAR * year + (double) DAYS_PER_MONTH * month + day) * SECS_PER_DAY + interval->time;
850 if (span < INT_MIN || span > INT_MAX)
851 time = INVALID_RELTIME;
855 PG_RETURN_RELATIVETIME(time);
860 reltime_interval(PG_FUNCTION_ARGS)
862 RelativeTime reltime = PG_GETARG_RELATIVETIME(0);
868 result = (Interval *) palloc(sizeof(Interval));
872 case INVALID_RELTIME:
874 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
875 errmsg("cannot convert reltime \"invalid\" to interval")));
882 #ifdef HAVE_INT64_TIMESTAMP
883 year = reltime / SECS_PER_YEAR;
884 reltime -= year * SECS_PER_YEAR;
885 month = reltime / (DAYS_PER_MONTH * SECS_PER_DAY);
886 reltime -= month * (DAYS_PER_MONTH * SECS_PER_DAY);
887 day = reltime / SECS_PER_DAY;
888 reltime -= day * SECS_PER_DAY;
890 result->time = (reltime * USECS_PER_SEC);
892 TMODULO(reltime, year, SECS_PER_YEAR);
893 TMODULO(reltime, month, DAYS_PER_MONTH * SECS_PER_DAY);
894 TMODULO(reltime, day, SECS_PER_DAY);
896 result->time = reltime;
898 result->month = MONTHS_PER_YEAR * year + month;
903 PG_RETURN_INTERVAL_P(result);
908 * mktinterval - creates a time interval with endpoints t1 and t2
911 mktinterval(PG_FUNCTION_ARGS)
913 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
914 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
915 AbsoluteTime tstart = ABSTIMEMIN(t1, t2);
916 AbsoluteTime tend = ABSTIMEMAX(t1, t2);
917 TimeInterval tinterval;
919 tinterval = (TimeInterval) palloc(sizeof(TimeIntervalData));
921 if (t1 == INVALID_ABSTIME || t2 == INVALID_ABSTIME)
922 tinterval->status = T_INTERVAL_INVAL;
926 tinterval->status = T_INTERVAL_VALID;
927 tinterval->data[0] = tstart;
928 tinterval->data[1] = tend;
931 PG_RETURN_TIMEINTERVAL(tinterval);
935 * timepl, timemi and abstimemi use the formula
936 * abstime + reltime = abstime
937 * so abstime - reltime = abstime
938 * and abstime - abstime = reltime
942 * timepl - returns the value of (abstime t1 + reltime t2)
945 timepl(PG_FUNCTION_ARGS)
947 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
948 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
950 if (AbsoluteTimeIsReal(t1) &&
951 RelativeTimeIsValid(t2) &&
952 ((t2 > 0 && t1 < NOEND_ABSTIME - t2) ||
953 (t2 <= 0 && t1 > NOSTART_ABSTIME - t2))) /* prevent overflow */
954 PG_RETURN_ABSOLUTETIME(t1 + t2);
956 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
961 * timemi - returns the value of (abstime t1 - reltime t2)
964 timemi(PG_FUNCTION_ARGS)
966 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
967 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
969 if (AbsoluteTimeIsReal(t1) &&
970 RelativeTimeIsValid(t2) &&
971 ((t2 > 0 && t1 > NOSTART_ABSTIME + t2) ||
972 (t2 <= 0 && t1 < NOEND_ABSTIME + t2))) /* prevent overflow */
973 PG_RETURN_ABSOLUTETIME(t1 - t2);
975 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
980 * intinterval - returns true iff absolute date is in the tinterval
983 intinterval(PG_FUNCTION_ARGS)
985 AbsoluteTime t = PG_GETARG_ABSOLUTETIME(0);
986 TimeInterval tinterval = PG_GETARG_TIMEINTERVAL(1);
988 if (tinterval->status == T_INTERVAL_VALID && t != INVALID_ABSTIME)
990 if (DatumGetBool(DirectFunctionCall2(abstimege,
991 AbsoluteTimeGetDatum(t),
992 AbsoluteTimeGetDatum(tinterval->data[0]))) &&
993 DatumGetBool(DirectFunctionCall2(abstimele,
994 AbsoluteTimeGetDatum(t),
995 AbsoluteTimeGetDatum(tinterval->data[1]))))
996 PG_RETURN_BOOL(true);
998 PG_RETURN_BOOL(false);
1002 * tintervalrel - returns relative time corresponding to tinterval
1005 tintervalrel(PG_FUNCTION_ARGS)
1007 TimeInterval tinterval = PG_GETARG_TIMEINTERVAL(0);
1008 AbsoluteTime t1 = tinterval->data[0];
1009 AbsoluteTime t2 = tinterval->data[1];
1011 if (tinterval->status != T_INTERVAL_VALID)
1012 PG_RETURN_RELATIVETIME(INVALID_RELTIME);
1014 if (AbsoluteTimeIsReal(t1) &&
1015 AbsoluteTimeIsReal(t2))
1016 PG_RETURN_RELATIVETIME(t2 - t1);
1018 PG_RETURN_RELATIVETIME(INVALID_RELTIME);
1023 * timenow - returns time "now", internal format
1025 * Now AbsoluteTime is time since Jan 1 1970 -mer 7 Feb 1992
1028 timenow(PG_FUNCTION_ARGS)
1030 PG_RETURN_ABSOLUTETIME(GetCurrentAbsoluteTime());
1034 * reltime comparison routines
1037 reltime_cmp_internal(RelativeTime a, RelativeTime b)
1040 * We consider all INVALIDs to be equal and larger than any non-INVALID.
1041 * This is somewhat arbitrary; the important thing is to have a consistent
1044 if (a == INVALID_RELTIME)
1046 if (b == INVALID_RELTIME)
1047 return 0; /* INVALID = INVALID */
1049 return 1; /* INVALID > non-INVALID */
1052 if (b == INVALID_RELTIME)
1053 return -1; /* non-INVALID < INVALID */
1064 reltimeeq(PG_FUNCTION_ARGS)
1066 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1067 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1069 PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) == 0);
1073 reltimene(PG_FUNCTION_ARGS)
1075 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1076 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1078 PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) != 0);
1082 reltimelt(PG_FUNCTION_ARGS)
1084 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1085 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1087 PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) < 0);
1091 reltimegt(PG_FUNCTION_ARGS)
1093 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1094 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1096 PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) > 0);
1100 reltimele(PG_FUNCTION_ARGS)
1102 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1103 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1105 PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) <= 0);
1109 reltimege(PG_FUNCTION_ARGS)
1111 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1112 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1114 PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) >= 0);
1118 btreltimecmp(PG_FUNCTION_ARGS)
1120 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1121 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1123 PG_RETURN_INT32(reltime_cmp_internal(t1, t2));
1128 * tintervalsame - returns true iff tinterval i1 is same as tinterval i2
1129 * Check begin and end time.
1132 tintervalsame(PG_FUNCTION_ARGS)
1134 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1135 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1137 if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL)
1138 PG_RETURN_BOOL(false);
1140 if (DatumGetBool(DirectFunctionCall2(abstimeeq,
1141 AbsoluteTimeGetDatum(i1->data[0]),
1142 AbsoluteTimeGetDatum(i2->data[0]))) &&
1143 DatumGetBool(DirectFunctionCall2(abstimeeq,
1144 AbsoluteTimeGetDatum(i1->data[1]),
1145 AbsoluteTimeGetDatum(i2->data[1]))))
1146 PG_RETURN_BOOL(true);
1147 PG_RETURN_BOOL(false);
1151 * tinterval comparison routines
1153 * Note: comparison is based on the lengths of the tintervals, not on
1154 * endpoint value. This is pretty bogus, but since it's only a legacy
1155 * datatype I'm not going to propose changing it.
1158 tinterval_cmp_internal(TimeInterval a, TimeInterval b)
1166 * We consider all INVALIDs to be equal and larger than any non-INVALID.
1167 * This is somewhat arbitrary; the important thing is to have a consistent
1170 a_invalid = a->status == T_INTERVAL_INVAL ||
1171 a->data[0] == INVALID_ABSTIME ||
1172 a->data[1] == INVALID_ABSTIME;
1173 b_invalid = b->status == T_INTERVAL_INVAL ||
1174 b->data[0] == INVALID_ABSTIME ||
1175 b->data[1] == INVALID_ABSTIME;
1180 return 0; /* INVALID = INVALID */
1182 return 1; /* INVALID > non-INVALID */
1186 return -1; /* non-INVALID < INVALID */
1188 a_len = a->data[1] - a->data[0];
1189 b_len = b->data[1] - b->data[0];
1193 else if (a_len == b_len)
1200 tintervaleq(PG_FUNCTION_ARGS)
1202 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1203 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1205 PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) == 0);
1209 tintervalne(PG_FUNCTION_ARGS)
1211 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1212 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1214 PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) != 0);
1218 tintervallt(PG_FUNCTION_ARGS)
1220 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1221 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1223 PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) < 0);
1227 tintervalle(PG_FUNCTION_ARGS)
1229 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1230 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1232 PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) <= 0);
1236 tintervalgt(PG_FUNCTION_ARGS)
1238 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1239 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1241 PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) > 0);
1245 tintervalge(PG_FUNCTION_ARGS)
1247 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1248 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1250 PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) >= 0);
1254 bttintervalcmp(PG_FUNCTION_ARGS)
1256 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1257 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1259 PG_RETURN_INT32(tinterval_cmp_internal(i1, i2));
1264 * tintervalleneq - returns true iff length of tinterval i is equal to
1266 * tintervallenne - returns true iff length of tinterval i is not equal
1268 * tintervallenlt - returns true iff length of tinterval i is less than
1270 * tintervallengt - returns true iff length of tinterval i is greater
1272 * tintervallenle - returns true iff length of tinterval i is less or
1273 * equal than reltime t
1274 * tintervallenge - returns true iff length of tinterval i is greater or
1275 * equal than reltime t
1278 tintervalleneq(PG_FUNCTION_ARGS)
1280 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1281 RelativeTime t = PG_GETARG_RELATIVETIME(1);
1284 if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1285 PG_RETURN_BOOL(false);
1286 rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1287 TimeIntervalGetDatum(i)));
1288 PG_RETURN_BOOL(rt != INVALID_RELTIME && rt == t);
1292 tintervallenne(PG_FUNCTION_ARGS)
1294 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1295 RelativeTime t = PG_GETARG_RELATIVETIME(1);
1298 if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1299 PG_RETURN_BOOL(false);
1300 rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1301 TimeIntervalGetDatum(i)));
1302 PG_RETURN_BOOL(rt != INVALID_RELTIME && rt != t);
1306 tintervallenlt(PG_FUNCTION_ARGS)
1308 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1309 RelativeTime t = PG_GETARG_RELATIVETIME(1);
1312 if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1313 PG_RETURN_BOOL(false);
1314 rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1315 TimeIntervalGetDatum(i)));
1316 PG_RETURN_BOOL(rt != INVALID_RELTIME && rt < t);
1320 tintervallengt(PG_FUNCTION_ARGS)
1322 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1323 RelativeTime t = PG_GETARG_RELATIVETIME(1);
1326 if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1327 PG_RETURN_BOOL(false);
1328 rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1329 TimeIntervalGetDatum(i)));
1330 PG_RETURN_BOOL(rt != INVALID_RELTIME && rt > t);
1334 tintervallenle(PG_FUNCTION_ARGS)
1336 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1337 RelativeTime t = PG_GETARG_RELATIVETIME(1);
1340 if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1341 PG_RETURN_BOOL(false);
1342 rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1343 TimeIntervalGetDatum(i)));
1344 PG_RETURN_BOOL(rt != INVALID_RELTIME && rt <= t);
1348 tintervallenge(PG_FUNCTION_ARGS)
1350 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1351 RelativeTime t = PG_GETARG_RELATIVETIME(1);
1354 if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1355 PG_RETURN_BOOL(false);
1356 rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1357 TimeIntervalGetDatum(i)));
1358 PG_RETURN_BOOL(rt != INVALID_RELTIME && rt >= t);
1362 * tintervalct - returns true iff tinterval i1 contains tinterval i2
1365 tintervalct(PG_FUNCTION_ARGS)
1367 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1368 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1370 if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL)
1371 PG_RETURN_BOOL(false);
1372 if (DatumGetBool(DirectFunctionCall2(abstimele,
1373 AbsoluteTimeGetDatum(i1->data[0]),
1374 AbsoluteTimeGetDatum(i2->data[0]))) &&
1375 DatumGetBool(DirectFunctionCall2(abstimege,
1376 AbsoluteTimeGetDatum(i1->data[1]),
1377 AbsoluteTimeGetDatum(i2->data[1]))))
1378 PG_RETURN_BOOL(true);
1379 PG_RETURN_BOOL(false);
1383 * tintervalov - returns true iff tinterval i1 (partially) overlaps i2
1386 tintervalov(PG_FUNCTION_ARGS)
1388 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1389 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1391 if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL)
1392 PG_RETURN_BOOL(false);
1393 if (DatumGetBool(DirectFunctionCall2(abstimelt,
1394 AbsoluteTimeGetDatum(i1->data[1]),
1395 AbsoluteTimeGetDatum(i2->data[0]))) ||
1396 DatumGetBool(DirectFunctionCall2(abstimegt,
1397 AbsoluteTimeGetDatum(i1->data[0]),
1398 AbsoluteTimeGetDatum(i2->data[1]))))
1399 PG_RETURN_BOOL(false);
1400 PG_RETURN_BOOL(true);
1404 * tintervalstart - returns the start of tinterval i
1407 tintervalstart(PG_FUNCTION_ARGS)
1409 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1411 if (i->status == T_INTERVAL_INVAL)
1412 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
1413 PG_RETURN_ABSOLUTETIME(i->data[0]);
1417 * tintervalend - returns the end of tinterval i
1420 tintervalend(PG_FUNCTION_ARGS)
1422 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1424 if (i->status == T_INTERVAL_INVAL)
1425 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
1426 PG_RETURN_ABSOLUTETIME(i->data[1]);
1430 /*****************************************************************************
1431 * PRIVATE ROUTINES *
1432 *****************************************************************************/
1435 * parsetinterval -- parse a tinterval string
1437 * output parameters:
1438 * i_start, i_end: tinterval margins
1441 * `[' {` '} `'' <AbsTime> `'' {` '} `'' <AbsTime> `'' {` '} `]'
1443 * OR `Undefined Range' (see also INVALID_INTERVAL_STR)
1445 * where <AbsTime> satisfies the syntax of absolute time.
1447 * e.g. [ ' Jan 18 1902' 'Jan 1 00:00:00 1970']
1450 parsetinterval(char *i_string,
1451 AbsoluteTime *i_start,
1452 AbsoluteTime *i_end)
1459 /* skip leading blanks up to '[' */
1460 while ((c = *p) != '\0')
1465 goto bogus; /* syntax error */
1470 goto bogus; /* syntax error */
1472 /* skip leading blanks up to '"' */
1473 while ((c = *p) != '\0')
1478 goto bogus; /* syntax error */
1483 goto bogus; /* syntax error */
1485 if (strncmp(INVALID_INTERVAL_STR, p, strlen(INVALID_INTERVAL_STR)) == 0)
1486 goto bogus; /* undefined range, handled like a syntax err. */
1487 /* search for the end of the first date and change it to a \0 */
1489 while ((c = *p1) != '\0')
1496 goto bogus; /* syntax error */
1498 /* get the first date */
1499 *i_start = DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
1500 CStringGetDatum(p)));
1501 /* undo change to \0 */
1504 /* skip blanks up to '"', beginning of second date */
1505 while ((c = *p) != '\0')
1510 goto bogus; /* syntax error */
1515 goto bogus; /* syntax error */
1517 /* search for the end of the second date and change it to a \0 */
1519 while ((c = *p1) != '\0')
1526 goto bogus; /* syntax error */
1528 /* get the second date */
1529 *i_end = DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
1530 CStringGetDatum(p)));
1531 /* undo change to \0 */
1534 /* skip blanks up to ']' */
1535 while ((c = *p) != '\0')
1540 goto bogus; /* syntax error */
1545 goto bogus; /* syntax error */
1549 goto bogus; /* syntax error */
1551 /* it seems to be a valid tinterval */
1556 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
1557 errmsg("invalid input syntax for type tinterval: \"%s\"",
1559 *i_start = *i_end = INVALID_ABSTIME; /* keep compiler quiet */
1563 /*****************************************************************************
1565 *****************************************************************************/
1569 * returns the current time as a text. similar to timenow() but returns
1570 * seconds with more precision (up to microsecs). (I need this to compare
1571 * the Wisconsin benchmark with Illustra whose TimeNow() shows current
1572 * time with precision up to microsecs.) - ay 3/95
1575 timeofday(PG_FUNCTION_ARGS)
1582 gettimeofday(&tp, NULL);
1583 tt = (pg_time_t) tp.tv_sec;
1584 pg_strftime(templ, sizeof(templ), "%a %b %d %H:%M:%S.%%06d %Y %Z",
1585 pg_localtime(&tt, session_timezone));
1586 snprintf(buf, sizeof(buf), templ, tp.tv_usec);
1588 PG_RETURN_TEXT_P(cstring_to_text(buf));