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-2003, 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.122 2004/05/21 16:08:47 tgl Exp $
15 *-------------------------------------------------------------------------
24 #include "access/xact.h"
25 #include "libpq/pqformat.h"
26 #include "miscadmin.h"
28 #include "utils/builtins.h"
31 #define MIN_DAYNUM -24856 /* December 13, 1901 */
32 #define MAX_DAYNUM 24854 /* January 18, 2038 */
34 #define INVALID_RELTIME_STR "Undefined RelTime"
35 #define INVALID_RELTIME_STR_LEN (sizeof(INVALID_RELTIME_STR)-1)
36 #define RELTIME_LABEL '@'
37 #define RELTIME_PAST "ago"
38 #define DIRMAXLEN (sizeof(RELTIME_PAST)-1)
41 * Unix epoch is Jan 1 00:00:00 1970.
42 * Postgres knows about times sixty-eight years on either side of that
43 * for these 4-byte types.
45 * "tinterval" is two 4-byte fields.
46 * Definitions for parsing tinterval.
49 #define IsSpace(C) ((C) == ' ')
51 #define T_INTERVAL_INVAL 0 /* data represents no valid interval */
52 #define T_INTERVAL_VALID 1 /* data represents a valid interval */
54 * ['Mon May 10 23:59:12 1943 PST' 'Sun Jan 14 03:14:21 1973 PST']
56 * 1234567890123456789012345678901234567890123456789012345678901234
58 * we allocate some extra -- timezones are usually 3 characters but
59 * this is not in the POSIX standard...
61 #define T_INTERVAL_LEN 80
62 #define INVALID_INTERVAL_STR "Undefined Range"
63 #define INVALID_INTERVAL_STR_LEN (sizeof(INVALID_INTERVAL_STR)-1)
65 #define ABSTIMEMIN(t1, t2) \
66 (DatumGetBool(DirectFunctionCall2(abstimele, \
67 AbsoluteTimeGetDatum(t1), \
68 AbsoluteTimeGetDatum(t2))) ? (t1) : (t2))
69 #define ABSTIMEMAX(t1, t2) \
70 (DatumGetBool(DirectFunctionCall2(abstimelt, \
71 AbsoluteTimeGetDatum(t1), \
72 AbsoluteTimeGetDatum(t2))) ? (t2) : (t1))
76 * Function prototypes -- internal to this file only
79 static AbsoluteTime tm2abstime(struct pg_tm * tm, int tz);
80 static void reltime2tm(RelativeTime time, struct pg_tm * tm);
81 static int istinterval(char *i_string,
82 AbsoluteTime *i_start,
87 * GetCurrentAbsoluteTime()
89 * Get the current system time (relative to Unix epoch).
92 GetCurrentAbsoluteTime(void)
97 return (AbsoluteTime) now;
102 * GetCurrentAbsoluteTimeUsec()
104 * Get the current system time (relative to Unix epoch), including fractional
105 * seconds expressed as microseconds.
108 GetCurrentAbsoluteTimeUsec(int *usec)
113 gettimeofday(&tp, NULL);
116 return (AbsoluteTime) now;
121 * AbsoluteTimeUsecToTimestampTz()
123 * Convert system time including microseconds to TimestampTz representation.
126 AbsoluteTimeUsecToTimestampTz(AbsoluteTime sec, int usec)
130 #ifdef HAVE_INT64_TIMESTAMP
131 result = ((sec - ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * 86400))
132 * INT64CONST(1000000)) + usec;
134 result = sec - ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * 86400)
135 + (usec / 1000000.0);
143 * GetCurrentDateTime()
145 * Get the transaction start time ("now()") broken down as a struct pg_tm.
148 GetCurrentDateTime(struct pg_tm * tm)
152 abstime2tm(GetCurrentTransactionStartTime(), &tz, tm, NULL);
156 * GetCurrentTimeUsec()
158 * Get the transaction start time ("now()") broken down as a struct pg_tm,
159 * including fractional seconds and timezone offset.
162 GetCurrentTimeUsec(struct pg_tm * tm, fsec_t *fsec, int *tzp)
167 abstime2tm(GetCurrentTransactionStartTimeUsec(&usec), &tz, tm, NULL);
168 /* Note: don't pass NULL tzp to abstime2tm; affects behavior */
171 #ifdef HAVE_INT64_TIMESTAMP
174 *fsec = usec / 1000000.0;
180 abstime2tm(AbsoluteTime _time, int *tzp, struct pg_tm * tm, char **tzn)
182 time_t time = (time_t) _time;
186 * If HasCTZSet is true then we have a brute force time zone
187 * specified. Go ahead and rotate to the local time zone since we will
188 * later bypass any calls which adjust the tm fields.
190 if (HasCTZSet && (tzp != NULL))
193 if ((!HasCTZSet) && (tzp != NULL))
194 tx = pg_localtime(&time);
196 tx = pg_gmtime(&time);
198 tm->tm_year = tx->tm_year + 1900;
199 tm->tm_mon = tx->tm_mon + 1;
200 tm->tm_mday = tx->tm_mday;
201 tm->tm_hour = tx->tm_hour;
202 tm->tm_min = tx->tm_min;
203 tm->tm_sec = tx->tm_sec;
204 tm->tm_isdst = tx->tm_isdst;
206 tm->tm_gmtoff = tx->tm_gmtoff;
207 tm->tm_zone = tx->tm_zone;
212 * We have a brute force time zone per SQL99? Then use it without
213 * change since we have already rotated to the time zone.
218 tm->tm_gmtoff = CTimeZone;
226 *tzp = -tm->tm_gmtoff; /* tm_gmtoff is Sun/DEC-ism */
229 * XXX FreeBSD man pages indicate that this should work - tgl
235 * Copy no more than MAXTZLEN bytes of timezone to tzn, in
236 * case it contains an error message, which doesn't fit in
239 StrNCpy(*tzn, tm->tm_zone, MAXTZLEN + 1);
240 if (strlen(tm->tm_zone) > MAXTZLEN)
242 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
243 errmsg("invalid time zone name: \"%s\"",
254 * Convert a tm structure to abstime.
255 * Note that tm has full year (not 1900-based) and 1-based month.
258 tm2abstime(struct pg_tm * tm, int tz)
263 /* validate, before going out of range on some members */
264 if (tm->tm_year < 1901 || tm->tm_year > 2038
265 || tm->tm_mon < 1 || tm->tm_mon > 12
266 || tm->tm_mday < 1 || tm->tm_mday > 31
267 || tm->tm_hour < 0 || tm->tm_hour > 23
268 || tm->tm_min < 0 || tm->tm_min > 59
269 || tm->tm_sec < 0 || tm->tm_sec > 60)
270 return INVALID_ABSTIME;
272 day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - UNIX_EPOCH_JDATE;
274 /* check for time out of range */
275 if ((day < MIN_DAYNUM) || (day > MAX_DAYNUM))
276 return INVALID_ABSTIME;
278 /* convert to seconds */
279 sec = tm->tm_sec + tz + (tm->tm_min + (day * 24 + tm->tm_hour) * 60) * 60;
281 /* check for overflow */
282 if ((day == MAX_DAYNUM && sec < 0) ||
283 (day == MIN_DAYNUM && sec > 0))
284 return INVALID_ABSTIME;
286 /* check for reserved values (e.g. "current" on edge of usual range */
287 if (!AbsoluteTimeIsReal(sec))
288 return INVALID_ABSTIME;
295 * Decode date/time string and return abstime.
298 abstimein(PG_FUNCTION_ARGS)
300 char *str = PG_GETARG_CSTRING(0);
307 char *field[MAXDATEFIELDS];
308 char lowstr[MAXDATELEN + 1];
311 ftype[MAXDATEFIELDS];
313 if (strlen(str) >= sizeof(lowstr))
314 dterr = DTERR_BAD_FORMAT;
316 dterr = ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf);
318 dterr = DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz);
320 DateTimeParseError(dterr, str, "abstime");
325 result = tm2abstime(tm, tz);
331 * Don't bother retaining this as a reserved value, but
332 * instead just set to the actual epoch time (1970-01-01)
338 result = NOEND_ABSTIME;
342 result = NOSTART_ABSTIME;
346 result = INVALID_ABSTIME;
350 elog(ERROR, "unexpected dtype %d while parsing abstime \"%s\"",
352 result = INVALID_ABSTIME;
356 PG_RETURN_ABSOLUTETIME(result);
361 * Given an AbsoluteTime return the English text version of the date
364 abstimeout(PG_FUNCTION_ARGS)
366 AbsoluteTime time = PG_GETARG_ABSOLUTETIME(0);
372 char buf[MAXDATELEN + 1];
373 char zone[MAXDATELEN + 1],
379 * Note that timestamp no longer supports 'invalid'. Retain
380 * 'invalid' for abstime for now, but dump it someday.
382 case INVALID_ABSTIME:
383 strcpy(buf, INVALID);
388 case NOSTART_ABSTIME:
392 abstime2tm(time, &tz, tm, &tzn);
393 EncodeDateTime(tm, fsec, &tz, &tzn, DateStyle, buf);
397 result = pstrdup(buf);
398 PG_RETURN_CSTRING(result);
402 * abstimerecv - converts external binary format to abstime
405 abstimerecv(PG_FUNCTION_ARGS)
407 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
409 PG_RETURN_ABSOLUTETIME((AbsoluteTime) pq_getmsgint(buf, sizeof(AbsoluteTime)));
413 * abstimesend - converts abstime to binary format
416 abstimesend(PG_FUNCTION_ARGS)
418 AbsoluteTime time = PG_GETARG_ABSOLUTETIME(0);
421 pq_begintypsend(&buf);
422 pq_sendint(&buf, time, sizeof(time));
423 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
430 abstime_finite(PG_FUNCTION_ARGS)
432 AbsoluteTime abstime = PG_GETARG_ABSOLUTETIME(0);
434 PG_RETURN_BOOL((abstime != INVALID_ABSTIME) &&
435 (abstime != NOSTART_ABSTIME) &&
436 (abstime != NOEND_ABSTIME));
441 * abstime comparison routines
444 abstime_cmp_internal(AbsoluteTime a, AbsoluteTime b)
447 * We consider all INVALIDs to be equal and larger than any non-INVALID.
448 * This is somewhat arbitrary; the important thing is to have a
449 * consistent sort order.
451 if (a == INVALID_ABSTIME)
453 if (b == INVALID_ABSTIME)
454 return 0; /* INVALID = INVALID */
456 return 1; /* INVALID > non-INVALID */
459 if (b == INVALID_ABSTIME)
460 return -1; /* non-INVALID < INVALID */
463 /* CURRENT is no longer stored internally... */
464 /* XXX this is broken, should go away: */
465 if (a == CURRENT_ABSTIME)
466 a = GetCurrentTransactionStartTime();
467 if (b == CURRENT_ABSTIME)
468 b = GetCurrentTransactionStartTime();
480 abstimeeq(PG_FUNCTION_ARGS)
482 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
483 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
485 PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) == 0);
489 abstimene(PG_FUNCTION_ARGS)
491 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
492 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
494 PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) != 0);
498 abstimelt(PG_FUNCTION_ARGS)
500 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
501 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
503 PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) < 0);
507 abstimegt(PG_FUNCTION_ARGS)
509 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
510 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
512 PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) > 0);
516 abstimele(PG_FUNCTION_ARGS)
518 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
519 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
521 PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) <= 0);
525 abstimege(PG_FUNCTION_ARGS)
527 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
528 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
530 PG_RETURN_BOOL(abstime_cmp_internal(t1, t2) >= 0);
534 btabstimecmp(PG_FUNCTION_ARGS)
536 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
537 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
539 PG_RETURN_INT32(abstime_cmp_internal(t1, t2));
543 /* timestamp_abstime()
544 * Convert timestamp to abstime.
547 timestamp_abstime(PG_FUNCTION_ARGS)
549 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
556 if (TIMESTAMP_IS_NOBEGIN(timestamp))
557 result = NOSTART_ABSTIME;
558 else if (TIMESTAMP_IS_NOEND(timestamp))
559 result = NOEND_ABSTIME;
560 else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) == 0)
562 tz = DetermineLocalTimeZone(tm);
563 result = tm2abstime(tm, tz);
568 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
569 errmsg("timestamp out of range")));
570 result = INVALID_ABSTIME;
573 PG_RETURN_ABSOLUTETIME(result);
576 /* abstime_timestamp()
577 * Convert abstime to timestamp.
580 abstime_timestamp(PG_FUNCTION_ARGS)
582 AbsoluteTime abstime = PG_GETARG_ABSOLUTETIME(0);
587 char zone[MAXDATELEN + 1],
592 case INVALID_ABSTIME:
594 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
595 errmsg("cannot convert abstime \"invalid\" to timestamp")));
596 TIMESTAMP_NOBEGIN(result);
599 case NOSTART_ABSTIME:
600 TIMESTAMP_NOBEGIN(result);
604 TIMESTAMP_NOEND(result);
608 abstime2tm(abstime, &tz, tm, &tzn);
609 if (tm2timestamp(tm, 0, NULL, &result) != 0)
611 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
612 errmsg("timestamp out of range")));
616 PG_RETURN_TIMESTAMP(result);
620 /* timestamptz_abstime()
621 * Convert timestamp with time zone to abstime.
624 timestamptz_abstime(PG_FUNCTION_ARGS)
626 TimestampTz timestamp = PG_GETARG_TIMESTAMP(0);
632 if (TIMESTAMP_IS_NOBEGIN(timestamp))
633 result = NOSTART_ABSTIME;
634 else if (TIMESTAMP_IS_NOEND(timestamp))
635 result = NOEND_ABSTIME;
636 else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL) == 0)
637 result = tm2abstime(tm, 0);
641 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
642 errmsg("timestamp out of range")));
643 result = INVALID_ABSTIME;
646 PG_RETURN_ABSOLUTETIME(result);
649 /* abstime_timestamptz()
650 * Convert abstime to timestamp with time zone.
653 abstime_timestamptz(PG_FUNCTION_ARGS)
655 AbsoluteTime abstime = PG_GETARG_ABSOLUTETIME(0);
660 char zone[MAXDATELEN + 1],
665 case INVALID_ABSTIME:
667 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
668 errmsg("cannot convert abstime \"invalid\" to timestamp")));
669 TIMESTAMP_NOBEGIN(result);
672 case NOSTART_ABSTIME:
673 TIMESTAMP_NOBEGIN(result);
677 TIMESTAMP_NOEND(result);
681 abstime2tm(abstime, &tz, tm, &tzn);
682 if (tm2timestamp(tm, 0, &tz, &result) != 0)
684 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
685 errmsg("timestamp out of range")));
689 PG_RETURN_TIMESTAMP(result);
693 /*****************************************************************************
694 * USER I/O ROUTINES *
695 *****************************************************************************/
698 * reltimein - converts a reltime string in an internal format
701 reltimein(PG_FUNCTION_ARGS)
703 char *str = PG_GETARG_CSTRING(0);
710 char *field[MAXDATEFIELDS];
712 ftype[MAXDATEFIELDS];
713 char lowstr[MAXDATELEN + 1];
715 if (strlen(str) >= sizeof(lowstr))
716 dterr = DTERR_BAD_FORMAT;
718 dterr = ParseDateTime(str, lowstr, field, ftype, MAXDATEFIELDS, &nf);
720 dterr = DecodeInterval(field, ftype, nf, &dtype, tm, &fsec);
723 if (dterr == DTERR_FIELD_OVERFLOW)
724 dterr = DTERR_INTERVAL_OVERFLOW;
725 DateTimeParseError(dterr, str, "reltime");
731 result = ((((tm->tm_hour * 60) + tm->tm_min) * 60) + tm->tm_sec);
732 result += ((tm->tm_year * 36525 * 864) + (((tm->tm_mon * 30) + tm->tm_mday) * 86400));
736 elog(ERROR, "unexpected dtype %d while parsing reltime \"%s\"",
738 result = INVALID_RELTIME;
742 PG_RETURN_RELATIVETIME(result);
746 * reltimeout - converts the internal format to a reltime string
749 reltimeout(PG_FUNCTION_ARGS)
751 RelativeTime time = PG_GETARG_RELATIVETIME(0);
755 char buf[MAXDATELEN + 1];
757 reltime2tm(time, tm);
758 EncodeInterval(tm, 0, DateStyle, buf);
760 result = pstrdup(buf);
761 PG_RETURN_CSTRING(result);
765 * reltimerecv - converts external binary format to reltime
768 reltimerecv(PG_FUNCTION_ARGS)
770 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
772 PG_RETURN_RELATIVETIME((RelativeTime) pq_getmsgint(buf, sizeof(RelativeTime)));
776 * reltimesend - converts reltime to binary format
779 reltimesend(PG_FUNCTION_ARGS)
781 RelativeTime time = PG_GETARG_RELATIVETIME(0);
784 pq_begintypsend(&buf);
785 pq_sendint(&buf, time, sizeof(time));
786 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
791 reltime2tm(RelativeTime time, struct pg_tm * tm)
795 FMODULO(dtime, tm->tm_year, 31557600);
796 FMODULO(dtime, tm->tm_mon, 2592000);
797 FMODULO(dtime, tm->tm_mday, 86400);
798 FMODULO(dtime, tm->tm_hour, 3600);
799 FMODULO(dtime, tm->tm_min, 60);
800 FMODULO(dtime, tm->tm_sec, 1);
805 * tintervalin - converts an interval string to internal format
808 tintervalin(PG_FUNCTION_ARGS)
810 char *intervalstr = PG_GETARG_CSTRING(0);
811 TimeInterval interval;
812 AbsoluteTime i_start,
817 interval = (TimeInterval) palloc(sizeof(TimeIntervalData));
818 if (istinterval(intervalstr, &t1, &t2) == 0)
820 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
821 errmsg("invalid input syntax for type tinterval: \"%s\"",
824 if (t1 == INVALID_ABSTIME || t2 == INVALID_ABSTIME)
825 interval->status = T_INTERVAL_INVAL; /* undefined */
827 interval->status = T_INTERVAL_VALID;
829 i_start = ABSTIMEMIN(t1, t2);
830 i_end = ABSTIMEMAX(t1, t2);
831 interval->data[0] = i_start;
832 interval->data[1] = i_end;
834 PG_RETURN_TIMEINTERVAL(interval);
839 * tintervalout - converts an internal interval format to a string
842 tintervalout(PG_FUNCTION_ARGS)
844 TimeInterval interval = PG_GETARG_TIMEINTERVAL(0);
848 i_str = (char *) palloc(T_INTERVAL_LEN); /* ["..." "..."] */
849 strcpy(i_str, "[\"");
850 if (interval->status == T_INTERVAL_INVAL)
851 strcat(i_str, INVALID_INTERVAL_STR);
854 p = DatumGetCString(DirectFunctionCall1(abstimeout,
855 AbsoluteTimeGetDatum(interval->data[0])));
858 strcat(i_str, "\" \"");
859 p = DatumGetCString(DirectFunctionCall1(abstimeout,
860 AbsoluteTimeGetDatum(interval->data[1])));
864 strcat(i_str, "\"]");
865 PG_RETURN_CSTRING(i_str);
869 * tintervalrecv - converts external binary format to tinterval
872 tintervalrecv(PG_FUNCTION_ARGS)
874 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
875 TimeInterval interval;
877 interval = (TimeInterval) palloc(sizeof(TimeIntervalData));
879 interval->status = pq_getmsgint(buf, sizeof(interval->status));
880 if (!(interval->status == T_INTERVAL_INVAL ||
881 interval->status == T_INTERVAL_VALID))
883 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
884 errmsg("invalid status in external \"tinterval\" value")));
886 interval->data[0] = pq_getmsgint(buf, sizeof(interval->data[0]));
887 interval->data[1] = pq_getmsgint(buf, sizeof(interval->data[1]));
889 PG_RETURN_TIMEINTERVAL(interval);
893 * tintervalsend - converts tinterval to binary format
896 tintervalsend(PG_FUNCTION_ARGS)
898 TimeInterval interval = PG_GETARG_TIMEINTERVAL(0);
901 pq_begintypsend(&buf);
902 pq_sendint(&buf, interval->status, sizeof(interval->status));
903 pq_sendint(&buf, interval->data[0], sizeof(interval->data[0]));
904 pq_sendint(&buf, interval->data[1], sizeof(interval->data[1]));
905 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
909 /*****************************************************************************
911 *****************************************************************************/
914 interval_reltime(PG_FUNCTION_ARGS)
916 Interval *interval = PG_GETARG_INTERVAL_P(0);
921 #ifdef HAVE_INT64_TIMESTAMP
928 if (interval->month == 0)
933 else if (abs(interval->month) >= 12)
935 year = (interval->month / 12);
936 month = (interval->month % 12);
941 month = interval->month;
944 #ifdef HAVE_INT64_TIMESTAMP
945 span = ((((INT64CONST(365250000) * year) + (INT64CONST(30000000) * month))
946 * INT64CONST(86400)) + interval->time);
947 span /= INT64CONST(1000000);
949 span = (((((double) 365.25 * year) + ((double) 30 * month)) * 86400) + interval->time);
952 if ((span < INT_MIN) || (span > INT_MAX))
953 time = INVALID_RELTIME;
957 PG_RETURN_RELATIVETIME(time);
962 reltime_interval(PG_FUNCTION_ARGS)
964 RelativeTime reltime = PG_GETARG_RELATIVETIME(0);
969 result = (Interval *) palloc(sizeof(Interval));
973 case INVALID_RELTIME:
975 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
976 errmsg("cannot convert reltime \"invalid\" to interval")));
982 #ifdef HAVE_INT64_TIMESTAMP
983 year = (reltime / (36525 * 864));
984 reltime -= (year * (36525 * 864));
985 month = (reltime / (30 * 86400));
986 reltime -= (month * (30 * 86400));
988 result->time = (reltime * INT64CONST(1000000));
990 TMODULO(reltime, year, (36525 * 864));
991 TMODULO(reltime, month, (30 * 86400));
993 result->time = reltime;
995 result->month = ((12 * year) + month);
999 PG_RETURN_INTERVAL_P(result);
1004 * mktinterval - creates a time interval with endpoints t1 and t2
1007 mktinterval(PG_FUNCTION_ARGS)
1009 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
1010 AbsoluteTime t2 = PG_GETARG_ABSOLUTETIME(1);
1011 AbsoluteTime tstart = ABSTIMEMIN(t1, t2);
1012 AbsoluteTime tend = ABSTIMEMAX(t1, t2);
1013 TimeInterval interval;
1015 interval = (TimeInterval) palloc(sizeof(TimeIntervalData));
1017 if (t1 == INVALID_ABSTIME || t2 == INVALID_ABSTIME)
1018 interval->status = T_INTERVAL_INVAL;
1021 interval->status = T_INTERVAL_VALID;
1022 interval->data[0] = tstart;
1023 interval->data[1] = tend;
1026 PG_RETURN_TIMEINTERVAL(interval);
1030 * timepl, timemi and abstimemi use the formula
1031 * abstime + reltime = abstime
1032 * so abstime - reltime = abstime
1033 * and abstime - abstime = reltime
1037 * timepl - returns the value of (abstime t1 + reltime t2)
1040 timepl(PG_FUNCTION_ARGS)
1042 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
1043 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1045 if (AbsoluteTimeIsReal(t1) &&
1046 RelativeTimeIsValid(t2) &&
1047 ((t2 > 0) ? (t1 < NOEND_ABSTIME - t2)
1048 : (t1 > NOSTART_ABSTIME - t2))) /* prevent overflow */
1049 PG_RETURN_ABSOLUTETIME(t1 + t2);
1051 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
1056 * timemi - returns the value of (abstime t1 - reltime t2)
1059 timemi(PG_FUNCTION_ARGS)
1061 AbsoluteTime t1 = PG_GETARG_ABSOLUTETIME(0);
1062 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1064 if (AbsoluteTimeIsReal(t1) &&
1065 RelativeTimeIsValid(t2) &&
1066 ((t2 > 0) ? (t1 > NOSTART_ABSTIME + t2)
1067 : (t1 < NOEND_ABSTIME + t2))) /* prevent overflow */
1068 PG_RETURN_ABSOLUTETIME(t1 - t2);
1070 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
1075 * intinterval - returns true iff absolute date is in the interval
1078 intinterval(PG_FUNCTION_ARGS)
1080 AbsoluteTime t = PG_GETARG_ABSOLUTETIME(0);
1081 TimeInterval interval = PG_GETARG_TIMEINTERVAL(1);
1083 if (interval->status == T_INTERVAL_VALID && t != INVALID_ABSTIME)
1085 if (DatumGetBool(DirectFunctionCall2(abstimege,
1086 AbsoluteTimeGetDatum(t),
1087 AbsoluteTimeGetDatum(interval->data[0]))) &&
1088 DatumGetBool(DirectFunctionCall2(abstimele,
1089 AbsoluteTimeGetDatum(t),
1090 AbsoluteTimeGetDatum(interval->data[1]))))
1091 PG_RETURN_BOOL(true);
1093 PG_RETURN_BOOL(false);
1097 * tintervalrel - returns relative time corresponding to interval
1100 tintervalrel(PG_FUNCTION_ARGS)
1102 TimeInterval interval = PG_GETARG_TIMEINTERVAL(0);
1103 AbsoluteTime t1 = interval->data[0];
1104 AbsoluteTime t2 = interval->data[1];
1106 if (interval->status != T_INTERVAL_VALID)
1107 PG_RETURN_RELATIVETIME(INVALID_RELTIME);
1109 if (AbsoluteTimeIsReal(t1) &&
1110 AbsoluteTimeIsReal(t2))
1111 PG_RETURN_RELATIVETIME(t2 - t1);
1113 PG_RETURN_RELATIVETIME(INVALID_RELTIME);
1118 * timenow - returns time "now", internal format
1120 * Now AbsoluteTime is time since Jan 1 1970 -mer 7 Feb 1992
1123 timenow(PG_FUNCTION_ARGS)
1128 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
1130 PG_RETURN_ABSOLUTETIME((AbsoluteTime) sec);
1134 * reltime comparison routines
1137 reltime_cmp_internal(RelativeTime a, RelativeTime b)
1140 * We consider all INVALIDs to be equal and larger than any non-INVALID.
1141 * This is somewhat arbitrary; the important thing is to have a
1142 * consistent sort order.
1144 if (a == INVALID_RELTIME)
1146 if (b == INVALID_RELTIME)
1147 return 0; /* INVALID = INVALID */
1149 return 1; /* INVALID > non-INVALID */
1152 if (b == INVALID_RELTIME)
1153 return -1; /* non-INVALID < INVALID */
1164 reltimeeq(PG_FUNCTION_ARGS)
1166 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1167 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1169 PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) == 0);
1173 reltimene(PG_FUNCTION_ARGS)
1175 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1176 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1178 PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) != 0);
1182 reltimelt(PG_FUNCTION_ARGS)
1184 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1185 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1187 PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) < 0);
1191 reltimegt(PG_FUNCTION_ARGS)
1193 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1194 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1196 PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) > 0);
1200 reltimele(PG_FUNCTION_ARGS)
1202 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1203 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1205 PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) <= 0);
1209 reltimege(PG_FUNCTION_ARGS)
1211 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1212 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1214 PG_RETURN_BOOL(reltime_cmp_internal(t1, t2) >= 0);
1218 btreltimecmp(PG_FUNCTION_ARGS)
1220 RelativeTime t1 = PG_GETARG_RELATIVETIME(0);
1221 RelativeTime t2 = PG_GETARG_RELATIVETIME(1);
1223 PG_RETURN_INT32(reltime_cmp_internal(t1, t2));
1228 * tintervalsame - returns true iff interval i1 is same as interval i2
1229 * Check begin and end time.
1232 tintervalsame(PG_FUNCTION_ARGS)
1234 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1235 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1237 if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL)
1238 PG_RETURN_BOOL(false);
1240 if (DatumGetBool(DirectFunctionCall2(abstimeeq,
1241 AbsoluteTimeGetDatum(i1->data[0]),
1242 AbsoluteTimeGetDatum(i2->data[0]))) &&
1243 DatumGetBool(DirectFunctionCall2(abstimeeq,
1244 AbsoluteTimeGetDatum(i1->data[1]),
1245 AbsoluteTimeGetDatum(i2->data[1]))))
1246 PG_RETURN_BOOL(true);
1247 PG_RETURN_BOOL(false);
1251 * tinterval comparison routines
1253 * Note: comparison is based on the lengths of the intervals, not on
1254 * endpoint value. This is pretty bogus, but since it's only a legacy
1255 * datatype I'm not going to propose changing it.
1258 tinterval_cmp_internal(TimeInterval a, TimeInterval b)
1266 * We consider all INVALIDs to be equal and larger than any non-INVALID.
1267 * This is somewhat arbitrary; the important thing is to have a
1268 * consistent sort order.
1270 a_invalid = ((a->status == T_INTERVAL_INVAL) ||
1271 (a->data[0] == INVALID_ABSTIME) ||
1272 (a->data[1] == INVALID_ABSTIME));
1273 b_invalid = ((b->status == T_INTERVAL_INVAL) ||
1274 (b->data[0] == INVALID_ABSTIME) ||
1275 (b->data[1] == INVALID_ABSTIME));
1280 return 0; /* INVALID = INVALID */
1282 return 1; /* INVALID > non-INVALID */
1286 return -1; /* non-INVALID < INVALID */
1288 a_len = a->data[1] - a->data[0];
1289 b_len = b->data[1] - b->data[0];
1293 else if (a_len == b_len)
1300 tintervaleq(PG_FUNCTION_ARGS)
1302 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1303 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1305 PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) == 0);
1309 tintervalne(PG_FUNCTION_ARGS)
1311 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1312 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1314 PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) != 0);
1318 tintervallt(PG_FUNCTION_ARGS)
1320 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1321 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1323 PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) < 0);
1327 tintervalle(PG_FUNCTION_ARGS)
1329 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1330 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1332 PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) <= 0);
1336 tintervalgt(PG_FUNCTION_ARGS)
1338 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1339 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1341 PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) > 0);
1345 tintervalge(PG_FUNCTION_ARGS)
1347 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1348 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1350 PG_RETURN_BOOL(tinterval_cmp_internal(i1, i2) >= 0);
1354 bttintervalcmp(PG_FUNCTION_ARGS)
1356 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1357 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1359 PG_RETURN_INT32(tinterval_cmp_internal(i1, i2));
1364 * tintervalleneq - returns true iff length of interval i is equal to
1366 * tintervallenne - returns true iff length of interval i is not equal
1368 * tintervallenlt - returns true iff length of interval i is less than
1370 * tintervallengt - returns true iff length of interval i is greater
1372 * tintervallenle - returns true iff length of interval i is less or
1373 * equal than reltime t
1374 * tintervallenge - returns true iff length of interval i is greater or
1375 * equal than reltime t
1378 tintervalleneq(PG_FUNCTION_ARGS)
1380 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1381 RelativeTime t = PG_GETARG_RELATIVETIME(1);
1384 if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1385 PG_RETURN_BOOL(false);
1386 rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1387 TimeIntervalGetDatum(i)));
1388 PG_RETURN_BOOL((rt != INVALID_RELTIME) && (rt == t));
1392 tintervallenne(PG_FUNCTION_ARGS)
1394 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1395 RelativeTime t = PG_GETARG_RELATIVETIME(1);
1398 if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1399 PG_RETURN_BOOL(false);
1400 rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1401 TimeIntervalGetDatum(i)));
1402 PG_RETURN_BOOL((rt != INVALID_RELTIME) && (rt != t));
1406 tintervallenlt(PG_FUNCTION_ARGS)
1408 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1409 RelativeTime t = PG_GETARG_RELATIVETIME(1);
1412 if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1413 PG_RETURN_BOOL(false);
1414 rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1415 TimeIntervalGetDatum(i)));
1416 PG_RETURN_BOOL((rt != INVALID_RELTIME) && (rt < t));
1420 tintervallengt(PG_FUNCTION_ARGS)
1422 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1423 RelativeTime t = PG_GETARG_RELATIVETIME(1);
1426 if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1427 PG_RETURN_BOOL(false);
1428 rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1429 TimeIntervalGetDatum(i)));
1430 PG_RETURN_BOOL((rt != INVALID_RELTIME) && (rt > t));
1434 tintervallenle(PG_FUNCTION_ARGS)
1436 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1437 RelativeTime t = PG_GETARG_RELATIVETIME(1);
1440 if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1441 PG_RETURN_BOOL(false);
1442 rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1443 TimeIntervalGetDatum(i)));
1444 PG_RETURN_BOOL((rt != INVALID_RELTIME) && (rt <= t));
1448 tintervallenge(PG_FUNCTION_ARGS)
1450 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1451 RelativeTime t = PG_GETARG_RELATIVETIME(1);
1454 if (i->status == T_INTERVAL_INVAL || t == INVALID_RELTIME)
1455 PG_RETURN_BOOL(false);
1456 rt = DatumGetRelativeTime(DirectFunctionCall1(tintervalrel,
1457 TimeIntervalGetDatum(i)));
1458 PG_RETURN_BOOL((rt != INVALID_RELTIME) && (rt >= t));
1462 * tintervalct - returns true iff interval i1 contains interval i2
1465 tintervalct(PG_FUNCTION_ARGS)
1467 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1468 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1470 if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL)
1471 PG_RETURN_BOOL(false);
1472 if (DatumGetBool(DirectFunctionCall2(abstimele,
1473 AbsoluteTimeGetDatum(i1->data[0]),
1474 AbsoluteTimeGetDatum(i2->data[0]))) &&
1475 DatumGetBool(DirectFunctionCall2(abstimege,
1476 AbsoluteTimeGetDatum(i1->data[1]),
1477 AbsoluteTimeGetDatum(i2->data[1]))))
1478 PG_RETURN_BOOL(true);
1479 PG_RETURN_BOOL(false);
1483 * tintervalov - returns true iff interval i1 (partially) overlaps i2
1486 tintervalov(PG_FUNCTION_ARGS)
1488 TimeInterval i1 = PG_GETARG_TIMEINTERVAL(0);
1489 TimeInterval i2 = PG_GETARG_TIMEINTERVAL(1);
1491 if (i1->status == T_INTERVAL_INVAL || i2->status == T_INTERVAL_INVAL)
1492 PG_RETURN_BOOL(false);
1493 if (DatumGetBool(DirectFunctionCall2(abstimelt,
1494 AbsoluteTimeGetDatum(i1->data[1]),
1495 AbsoluteTimeGetDatum(i2->data[0]))) ||
1496 DatumGetBool(DirectFunctionCall2(abstimegt,
1497 AbsoluteTimeGetDatum(i1->data[0]),
1498 AbsoluteTimeGetDatum(i2->data[1]))))
1499 PG_RETURN_BOOL(false);
1500 PG_RETURN_BOOL(true);
1504 * tintervalstart - returns the start of interval i
1507 tintervalstart(PG_FUNCTION_ARGS)
1509 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1511 if (i->status == T_INTERVAL_INVAL)
1512 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
1513 PG_RETURN_ABSOLUTETIME(i->data[0]);
1517 * tintervalend - returns the end of interval i
1520 tintervalend(PG_FUNCTION_ARGS)
1522 TimeInterval i = PG_GETARG_TIMEINTERVAL(0);
1524 if (i->status == T_INTERVAL_INVAL)
1525 PG_RETURN_ABSOLUTETIME(INVALID_ABSTIME);
1526 PG_RETURN_ABSOLUTETIME(i->data[1]);
1530 /*****************************************************************************
1531 * PRIVATE ROUTINES *
1532 *****************************************************************************/
1535 * istinterval - returns 1, iff i_string is a valid interval descr.
1536 * 0, iff i_string is NOT a valid interval desc.
1537 * 2, iff any time is INVALID_ABSTIME
1540 * i_start, i_end: interval margins
1543 * `[' {` '} `'' <AbsTime> `'' {` '} `'' <AbsTime> `'' {` '} `]'
1545 * OR `Undefined Range' (see also INVALID_INTERVAL_STR)
1547 * where <AbsTime> satisfies the syntax of absolute time.
1549 * e.g. [ ' Jan 18 1902' 'Jan 1 00:00:00 1970']
1552 istinterval(char *i_string,
1553 AbsoluteTime *i_start,
1554 AbsoluteTime *i_end)
1561 /* skip leading blanks up to '[' */
1562 while ((c = *p) != '\0')
1567 return 0; /* syntax error */
1572 /* skip leading blanks up to '"' */
1573 while ((c = *p) != '\0')
1578 return 0; /* syntax error */
1583 if (strncmp(INVALID_INTERVAL_STR, p, strlen(INVALID_INTERVAL_STR)) == 0)
1584 return 0; /* undefined range, handled like a syntax
1586 /* search for the end of the first date and change it to a NULL */
1588 while ((c = *p1) != '\0')
1597 /* get the first date */
1598 *i_start = DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
1599 CStringGetDatum(p)));
1600 /* rechange NULL at the end of the first date to a '"' */
1603 /* skip blanks up to '"', beginning of second date */
1604 while ((c = *p) != '\0')
1609 return 0; /* syntax error */
1614 /* search for the end of the second date and change it to a NULL */
1616 while ((c = *p1) != '\0')
1625 /* get the second date */
1626 *i_end = DatumGetAbsoluteTime(DirectFunctionCall1(abstimein,
1627 CStringGetDatum(p)));
1628 /* rechange NULL at the end of the first date to a '"' */
1631 /* skip blanks up to ']' */
1632 while ((c = *p) != '\0')
1637 return 0; /* syntax error */
1644 return 0; /* syntax error */
1645 /* it seems to be a valid interval */
1650 /*****************************************************************************
1652 *****************************************************************************/
1656 * returns the current time as a text. similar to timenow() but returns
1657 * seconds with more precision (up to microsecs). (I need this to compare
1658 * the Wisconsin benchmark with Illustra whose TimeNow() shows current
1659 * time with precision up to microsecs.) - ay 3/95
1662 timeofday(PG_FUNCTION_ARGS)
1665 struct timezone tpz;
1672 gettimeofday(&tp, &tpz);
1673 tt = (time_t) tp.tv_sec;
1674 pg_strftime(templ, sizeof(templ), "%a %b %d %H:%M:%S.%%06d %Y %Z",
1676 snprintf(buf, sizeof(buf), templ, tp.tv_usec);
1678 len = VARHDRSZ + strlen(buf);
1679 result = (text *) palloc(len);
1680 VARATT_SIZEP(result) = len;
1681 memcpy(VARDATA(result), buf, strlen(buf));
1682 PG_RETURN_TEXT_P(result);