1 /*-------------------------------------------------------------------------
4 * Functions for the built-in SQL92 types "timestamp" and "interval".
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/utils/adt/timestamp.c
13 *-------------------------------------------------------------------------
24 #include "access/hash.h"
25 #include "access/xact.h"
26 #include "catalog/pg_type.h"
28 #include "libpq/pqformat.h"
29 #include "miscadmin.h"
30 #include "parser/scansup.h"
31 #include "utils/array.h"
32 #include "utils/builtins.h"
33 #include "utils/datetime.h"
36 * gcc's -ffast-math switch breaks routines that expect exact results from
37 * expressions like timeval / SECS_PER_HOUR, where timeval is double.
40 #error -ffast-math is known to break this code
44 /* Set at postmaster start */
45 TimestampTz PgStartTime;
47 /* Set at configuration reload */
48 TimestampTz PgReloadTime;
56 } generate_series_timestamp_fctx;
64 } generate_series_timestamptz_fctx;
67 static TimeOffset time2t(const int hour, const int min, const int sec, const fsec_t fsec);
68 static void EncodeSpecialTimestamp(Timestamp dt, char *str);
69 static Timestamp dt2local(Timestamp dt, int timezone);
70 static void AdjustTimestampForTypmod(Timestamp *time, int32 typmod);
71 static void AdjustIntervalForTypmod(Interval *interval, int32 typmod);
72 static TimestampTz timestamp2timestamptz(Timestamp timestamp);
75 /* common code for timestamptypmodin and timestamptztypmodin */
77 anytimestamp_typmodin(bool istz, ArrayType *ta)
83 tl = ArrayGetIntegerTypmods(ta, &n);
86 * we're not too tense about good error message here because grammar
87 * shouldn't allow wrong number of modifiers for TIMESTAMP
91 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
92 errmsg("invalid type modifier")));
96 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
97 errmsg("TIMESTAMP(%d)%s precision must not be negative",
98 *tl, (istz ? " WITH TIME ZONE" : ""))));
99 if (*tl > MAX_TIMESTAMP_PRECISION)
102 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
103 errmsg("TIMESTAMP(%d)%s precision reduced to maximum allowed, %d",
104 *tl, (istz ? " WITH TIME ZONE" : ""),
105 MAX_TIMESTAMP_PRECISION)));
106 typmod = MAX_TIMESTAMP_PRECISION;
114 /* common code for timestamptypmodout and timestamptztypmodout */
116 anytimestamp_typmodout(bool istz, int32 typmod)
118 char *res = (char *) palloc(64);
119 const char *tz = istz ? " with time zone" : " without time zone";
122 snprintf(res, 64, "(%d)%s", (int) typmod, tz);
124 snprintf(res, 64, "%s", tz);
130 /*****************************************************************************
131 * USER I/O ROUTINES *
132 *****************************************************************************/
135 * Convert a string to internal form.
138 timestamp_in(PG_FUNCTION_ARGS)
140 char *str = PG_GETARG_CSTRING(0);
143 Oid typelem = PG_GETARG_OID(1);
145 int32 typmod = PG_GETARG_INT32(2);
154 char *field[MAXDATEFIELDS];
155 int ftype[MAXDATEFIELDS];
156 char workbuf[MAXDATELEN + MAXDATEFIELDS];
158 dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
159 field, ftype, MAXDATEFIELDS, &nf);
161 dterr = DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz);
163 DateTimeParseError(dterr, str, "timestamp");
168 if (tm2timestamp(tm, fsec, NULL, &result) != 0)
170 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
171 errmsg("timestamp out of range: \"%s\"", str)));
175 result = SetEpochTimestamp();
179 TIMESTAMP_NOEND(result);
183 TIMESTAMP_NOBEGIN(result);
188 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
189 errmsg("date/time value \"%s\" is no longer supported", str)));
191 TIMESTAMP_NOEND(result);
195 elog(ERROR, "unexpected dtype %d while parsing timestamp \"%s\"",
197 TIMESTAMP_NOEND(result);
200 AdjustTimestampForTypmod(&result, typmod);
202 PG_RETURN_TIMESTAMP(result);
206 * Convert a timestamp to external form.
209 timestamp_out(PG_FUNCTION_ARGS)
211 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
217 char buf[MAXDATELEN + 1];
219 if (TIMESTAMP_NOT_FINITE(timestamp))
220 EncodeSpecialTimestamp(timestamp, buf);
221 else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) == 0)
222 EncodeDateTime(tm, fsec, NULL, &tzn, DateStyle, buf);
225 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
226 errmsg("timestamp out of range")));
228 result = pstrdup(buf);
229 PG_RETURN_CSTRING(result);
233 * timestamp_recv - converts external binary format to timestamp
235 * We make no attempt to provide compatibility between int and float
236 * timestamp representations ...
239 timestamp_recv(PG_FUNCTION_ARGS)
241 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
244 Oid typelem = PG_GETARG_OID(1);
246 int32 typmod = PG_GETARG_INT32(2);
252 #ifdef HAVE_INT64_TIMESTAMP
253 timestamp = (Timestamp) pq_getmsgint64(buf);
255 timestamp = (Timestamp) pq_getmsgfloat8(buf);
257 if (isnan(timestamp))
259 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
260 errmsg("timestamp cannot be NaN")));
263 /* rangecheck: see if timestamp_out would like it */
264 if (TIMESTAMP_NOT_FINITE(timestamp))
266 else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
268 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
269 errmsg("timestamp out of range")));
271 AdjustTimestampForTypmod(×tamp, typmod);
273 PG_RETURN_TIMESTAMP(timestamp);
277 * timestamp_send - converts timestamp to binary format
280 timestamp_send(PG_FUNCTION_ARGS)
282 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
285 pq_begintypsend(&buf);
286 #ifdef HAVE_INT64_TIMESTAMP
287 pq_sendint64(&buf, timestamp);
289 pq_sendfloat8(&buf, timestamp);
291 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
295 timestamptypmodin(PG_FUNCTION_ARGS)
297 ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
299 PG_RETURN_INT32(anytimestamp_typmodin(false, ta));
303 timestamptypmodout(PG_FUNCTION_ARGS)
305 int32 typmod = PG_GETARG_INT32(0);
307 PG_RETURN_CSTRING(anytimestamp_typmodout(false, typmod));
312 * Adjust time type for specified scale factor.
313 * Used by PostgreSQL type system to stuff columns.
316 timestamp_scale(PG_FUNCTION_ARGS)
318 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
319 int32 typmod = PG_GETARG_INT32(1);
324 AdjustTimestampForTypmod(&result, typmod);
326 PG_RETURN_TIMESTAMP(result);
330 AdjustTimestampForTypmod(Timestamp *time, int32 typmod)
332 #ifdef HAVE_INT64_TIMESTAMP
333 static const int64 TimestampScales[MAX_TIMESTAMP_PRECISION + 1] = {
343 static const int64 TimestampOffsets[MAX_TIMESTAMP_PRECISION + 1] = {
353 static const double TimestampScales[MAX_TIMESTAMP_PRECISION + 1] = {
364 if (!TIMESTAMP_NOT_FINITE(*time)
365 && (typmod != -1) && (typmod != MAX_TIMESTAMP_PRECISION))
367 if (typmod < 0 || typmod > MAX_TIMESTAMP_PRECISION)
369 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
370 errmsg("timestamp(%d) precision must be between %d and %d",
371 typmod, 0, MAX_TIMESTAMP_PRECISION)));
374 * Note: this round-to-nearest code is not completely consistent about
375 * rounding values that are exactly halfway between integral values.
376 * On most platforms, rint() will implement round-to-nearest-even, but
377 * the integer code always rounds up (away from zero). Is it worth
378 * trying to be consistent?
380 #ifdef HAVE_INT64_TIMESTAMP
381 if (*time >= INT64CONST(0))
383 *time = ((*time + TimestampOffsets[typmod]) / TimestampScales[typmod]) *
384 TimestampScales[typmod];
388 *time = -((((-*time) + TimestampOffsets[typmod]) / TimestampScales[typmod])
389 * TimestampScales[typmod]);
392 *time = rint((double) *time * TimestampScales[typmod]) / TimestampScales[typmod];
399 * Convert a string to internal form.
402 timestamptz_in(PG_FUNCTION_ARGS)
404 char *str = PG_GETARG_CSTRING(0);
407 Oid typelem = PG_GETARG_OID(1);
409 int32 typmod = PG_GETARG_INT32(2);
418 char *field[MAXDATEFIELDS];
419 int ftype[MAXDATEFIELDS];
420 char workbuf[MAXDATELEN + MAXDATEFIELDS];
422 dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
423 field, ftype, MAXDATEFIELDS, &nf);
425 dterr = DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz);
427 DateTimeParseError(dterr, str, "timestamp with time zone");
432 if (tm2timestamp(tm, fsec, &tz, &result) != 0)
434 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
435 errmsg("timestamp out of range: \"%s\"", str)));
439 result = SetEpochTimestamp();
443 TIMESTAMP_NOEND(result);
447 TIMESTAMP_NOBEGIN(result);
452 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
453 errmsg("date/time value \"%s\" is no longer supported", str)));
455 TIMESTAMP_NOEND(result);
459 elog(ERROR, "unexpected dtype %d while parsing timestamptz \"%s\"",
461 TIMESTAMP_NOEND(result);
464 AdjustTimestampForTypmod(&result, typmod);
466 PG_RETURN_TIMESTAMPTZ(result);
470 * Convert a timestamp to external form.
473 timestamptz_out(PG_FUNCTION_ARGS)
475 TimestampTz dt = PG_GETARG_TIMESTAMPTZ(0);
482 char buf[MAXDATELEN + 1];
484 if (TIMESTAMP_NOT_FINITE(dt))
485 EncodeSpecialTimestamp(dt, buf);
486 else if (timestamp2tm(dt, &tz, tm, &fsec, &tzn, NULL) == 0)
487 EncodeDateTime(tm, fsec, &tz, &tzn, DateStyle, buf);
490 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
491 errmsg("timestamp out of range")));
493 result = pstrdup(buf);
494 PG_RETURN_CSTRING(result);
498 * timestamptz_recv - converts external binary format to timestamptz
500 * We make no attempt to provide compatibility between int and float
501 * timestamp representations ...
504 timestamptz_recv(PG_FUNCTION_ARGS)
506 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
509 Oid typelem = PG_GETARG_OID(1);
511 int32 typmod = PG_GETARG_INT32(2);
512 TimestampTz timestamp;
519 #ifdef HAVE_INT64_TIMESTAMP
520 timestamp = (TimestampTz) pq_getmsgint64(buf);
522 timestamp = (TimestampTz) pq_getmsgfloat8(buf);
525 /* rangecheck: see if timestamptz_out would like it */
526 if (TIMESTAMP_NOT_FINITE(timestamp))
528 else if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
530 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
531 errmsg("timestamp out of range")));
533 AdjustTimestampForTypmod(×tamp, typmod);
535 PG_RETURN_TIMESTAMPTZ(timestamp);
539 * timestamptz_send - converts timestamptz to binary format
542 timestamptz_send(PG_FUNCTION_ARGS)
544 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
547 pq_begintypsend(&buf);
548 #ifdef HAVE_INT64_TIMESTAMP
549 pq_sendint64(&buf, timestamp);
551 pq_sendfloat8(&buf, timestamp);
553 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
557 timestamptztypmodin(PG_FUNCTION_ARGS)
559 ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
561 PG_RETURN_INT32(anytimestamp_typmodin(true, ta));
565 timestamptztypmodout(PG_FUNCTION_ARGS)
567 int32 typmod = PG_GETARG_INT32(0);
569 PG_RETURN_CSTRING(anytimestamp_typmodout(true, typmod));
573 /* timestamptz_scale()
574 * Adjust time type for specified scale factor.
575 * Used by PostgreSQL type system to stuff columns.
578 timestamptz_scale(PG_FUNCTION_ARGS)
580 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
581 int32 typmod = PG_GETARG_INT32(1);
586 AdjustTimestampForTypmod(&result, typmod);
588 PG_RETURN_TIMESTAMPTZ(result);
593 * Convert a string to internal form.
595 * External format(s):
596 * Uses the generic date/time parsing and decoding routines.
599 interval_in(PG_FUNCTION_ARGS)
601 char *str = PG_GETARG_CSTRING(0);
604 Oid typelem = PG_GETARG_OID(1);
606 int32 typmod = PG_GETARG_INT32(2);
615 char *field[MAXDATEFIELDS];
616 int ftype[MAXDATEFIELDS];
628 range = INTERVAL_RANGE(typmod);
630 range = INTERVAL_FULL_RANGE;
632 dterr = ParseDateTime(str, workbuf, sizeof(workbuf), field,
633 ftype, MAXDATEFIELDS, &nf);
635 dterr = DecodeInterval(field, ftype, nf, range,
638 /* if those functions think it's a bad format, try ISO8601 style */
639 if (dterr == DTERR_BAD_FORMAT)
640 dterr = DecodeISO8601Interval(str,
645 if (dterr == DTERR_FIELD_OVERFLOW)
646 dterr = DTERR_INTERVAL_OVERFLOW;
647 DateTimeParseError(dterr, str, "interval");
650 result = (Interval *) palloc(sizeof(Interval));
655 if (tm2interval(tm, fsec, result) != 0)
657 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
658 errmsg("interval out of range")));
663 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
664 errmsg("date/time value \"%s\" is no longer supported", str)));
668 elog(ERROR, "unexpected dtype %d while parsing interval \"%s\"",
672 AdjustIntervalForTypmod(result, typmod);
674 PG_RETURN_INTERVAL_P(result);
678 * Convert a time span to external form.
681 interval_out(PG_FUNCTION_ARGS)
683 Interval *span = PG_GETARG_INTERVAL_P(0);
688 char buf[MAXDATELEN + 1];
690 if (interval2tm(*span, tm, &fsec) != 0)
691 elog(ERROR, "could not convert interval to tm");
693 EncodeInterval(tm, fsec, IntervalStyle, buf);
695 result = pstrdup(buf);
696 PG_RETURN_CSTRING(result);
700 * interval_recv - converts external binary format to interval
703 interval_recv(PG_FUNCTION_ARGS)
705 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
708 Oid typelem = PG_GETARG_OID(1);
710 int32 typmod = PG_GETARG_INT32(2);
713 interval = (Interval *) palloc(sizeof(Interval));
715 #ifdef HAVE_INT64_TIMESTAMP
716 interval->time = pq_getmsgint64(buf);
718 interval->time = pq_getmsgfloat8(buf);
720 interval->day = pq_getmsgint(buf, sizeof(interval->day));
721 interval->month = pq_getmsgint(buf, sizeof(interval->month));
723 AdjustIntervalForTypmod(interval, typmod);
725 PG_RETURN_INTERVAL_P(interval);
729 * interval_send - converts interval to binary format
732 interval_send(PG_FUNCTION_ARGS)
734 Interval *interval = PG_GETARG_INTERVAL_P(0);
737 pq_begintypsend(&buf);
738 #ifdef HAVE_INT64_TIMESTAMP
739 pq_sendint64(&buf, interval->time);
741 pq_sendfloat8(&buf, interval->time);
743 pq_sendint(&buf, interval->day, sizeof(interval->day));
744 pq_sendint(&buf, interval->month, sizeof(interval->month));
745 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
749 intervaltypmodin(PG_FUNCTION_ARGS)
751 ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
756 tl = ArrayGetIntegerTypmods(ta, &n);
759 * tl[0] - interval range (fields bitmask) tl[1] - precision (optional)
761 * Note we must validate tl[0] even though it's normally guaranteed
762 * correct by the grammar --- consider SELECT 'foo'::"interval"(1000).
768 case INTERVAL_MASK(YEAR):
769 case INTERVAL_MASK(MONTH):
770 case INTERVAL_MASK(DAY):
771 case INTERVAL_MASK(HOUR):
772 case INTERVAL_MASK(MINUTE):
773 case INTERVAL_MASK(SECOND):
774 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
775 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
776 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
777 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
778 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
779 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
780 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
781 case INTERVAL_FULL_RANGE:
786 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
787 errmsg("invalid INTERVAL type modifier")));
793 if (tl[0] != INTERVAL_FULL_RANGE)
794 typmod = INTERVAL_TYPMOD(INTERVAL_FULL_PRECISION, tl[0]);
802 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
803 errmsg("INTERVAL(%d) precision must not be negative",
805 if (tl[1] > MAX_INTERVAL_PRECISION)
808 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
809 errmsg("INTERVAL(%d) precision reduced to maximum allowed, %d",
810 tl[1], MAX_INTERVAL_PRECISION)));
811 typmod = INTERVAL_TYPMOD(MAX_INTERVAL_PRECISION, tl[0]);
814 typmod = INTERVAL_TYPMOD(tl[1], tl[0]);
819 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
820 errmsg("invalid INTERVAL type modifier")));
821 typmod = 0; /* keep compiler quiet */
824 PG_RETURN_INT32(typmod);
828 intervaltypmodout(PG_FUNCTION_ARGS)
830 int32 typmod = PG_GETARG_INT32(0);
831 char *res = (char *) palloc(64);
834 const char *fieldstr;
839 PG_RETURN_CSTRING(res);
842 fields = INTERVAL_RANGE(typmod);
843 precision = INTERVAL_PRECISION(typmod);
847 case INTERVAL_MASK(YEAR):
850 case INTERVAL_MASK(MONTH):
853 case INTERVAL_MASK(DAY):
856 case INTERVAL_MASK(HOUR):
859 case INTERVAL_MASK(MINUTE):
860 fieldstr = " minute";
862 case INTERVAL_MASK(SECOND):
863 fieldstr = " second";
865 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
866 fieldstr = " year to month";
868 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
869 fieldstr = " day to hour";
871 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
872 fieldstr = " day to minute";
874 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
875 fieldstr = " day to second";
877 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
878 fieldstr = " hour to minute";
880 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
881 fieldstr = " hour to second";
883 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
884 fieldstr = " minute to second";
886 case INTERVAL_FULL_RANGE:
890 elog(ERROR, "invalid INTERVAL typmod: 0x%x", typmod);
895 if (precision != INTERVAL_FULL_PRECISION)
896 snprintf(res, 64, "%s(%d)", fieldstr, precision);
898 snprintf(res, 64, "%s", fieldstr);
900 PG_RETURN_CSTRING(res);
905 * Adjust interval type for specified fields.
906 * Used by PostgreSQL type system to stuff columns.
909 interval_scale(PG_FUNCTION_ARGS)
911 Interval *interval = PG_GETARG_INTERVAL_P(0);
912 int32 typmod = PG_GETARG_INT32(1);
915 result = palloc(sizeof(Interval));
918 AdjustIntervalForTypmod(result, typmod);
920 PG_RETURN_INTERVAL_P(result);
924 * Adjust interval for specified precision, in both YEAR to SECOND
925 * range and sub-second precision.
928 AdjustIntervalForTypmod(Interval *interval, int32 typmod)
930 #ifdef HAVE_INT64_TIMESTAMP
931 static const int64 IntervalScales[MAX_INTERVAL_PRECISION + 1] = {
941 static const int64 IntervalOffsets[MAX_INTERVAL_PRECISION + 1] = {
951 static const double IntervalScales[MAX_INTERVAL_PRECISION + 1] = {
963 * Unspecified range and precision? Then not necessary to adjust. Setting
964 * typmod to -1 is the convention for all data types.
968 int range = INTERVAL_RANGE(typmod);
969 int precision = INTERVAL_PRECISION(typmod);
972 * Our interpretation of intervals with a limited set of fields is
973 * that fields to the right of the last one specified are zeroed out,
974 * but those to the left of it remain valid. Thus for example there
975 * is no operational difference between INTERVAL YEAR TO MONTH and
976 * INTERVAL MONTH. In some cases we could meaningfully enforce that
977 * higher-order fields are zero; for example INTERVAL DAY could reject
978 * nonzero "month" field. However that seems a bit pointless when we
979 * can't do it consistently. (We cannot enforce a range limit on the
980 * highest expected field, since we do not have any equivalent of
981 * SQL's <interval leading field precision>.)
983 * Note: before PG 8.4 we interpreted a limited set of fields as
984 * actually causing a "modulo" operation on a given value, potentially
985 * losing high-order as well as low-order information. But there is
986 * no support for such behavior in the standard, and it seems fairly
987 * undesirable on data consistency grounds anyway. Now we only
988 * perform truncation or rounding of low-order fields.
990 if (range == INTERVAL_FULL_RANGE)
994 else if (range == INTERVAL_MASK(YEAR))
996 interval->month = (interval->month / MONTHS_PER_YEAR) * MONTHS_PER_YEAR;
1000 else if (range == INTERVAL_MASK(MONTH))
1006 else if (range == (INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH)))
1011 else if (range == INTERVAL_MASK(DAY))
1015 else if (range == INTERVAL_MASK(HOUR))
1017 #ifdef HAVE_INT64_TIMESTAMP
1018 interval->time = (interval->time / USECS_PER_HOUR) *
1021 interval->time = ((int) (interval->time / SECS_PER_HOUR)) * (double) SECS_PER_HOUR;
1024 else if (range == INTERVAL_MASK(MINUTE))
1026 #ifdef HAVE_INT64_TIMESTAMP
1027 interval->time = (interval->time / USECS_PER_MINUTE) *
1030 interval->time = ((int) (interval->time / SECS_PER_MINUTE)) * (double) SECS_PER_MINUTE;
1033 else if (range == INTERVAL_MASK(SECOND))
1035 /* fractional-second rounding will be dealt with below */
1038 else if (range == (INTERVAL_MASK(DAY) |
1039 INTERVAL_MASK(HOUR)))
1041 #ifdef HAVE_INT64_TIMESTAMP
1042 interval->time = (interval->time / USECS_PER_HOUR) *
1045 interval->time = ((int) (interval->time / SECS_PER_HOUR)) * (double) SECS_PER_HOUR;
1049 else if (range == (INTERVAL_MASK(DAY) |
1050 INTERVAL_MASK(HOUR) |
1051 INTERVAL_MASK(MINUTE)))
1053 #ifdef HAVE_INT64_TIMESTAMP
1054 interval->time = (interval->time / USECS_PER_MINUTE) *
1057 interval->time = ((int) (interval->time / SECS_PER_MINUTE)) * (double) SECS_PER_MINUTE;
1061 else if (range == (INTERVAL_MASK(DAY) |
1062 INTERVAL_MASK(HOUR) |
1063 INTERVAL_MASK(MINUTE) |
1064 INTERVAL_MASK(SECOND)))
1066 /* fractional-second rounding will be dealt with below */
1068 /* HOUR TO MINUTE */
1069 else if (range == (INTERVAL_MASK(HOUR) |
1070 INTERVAL_MASK(MINUTE)))
1072 #ifdef HAVE_INT64_TIMESTAMP
1073 interval->time = (interval->time / USECS_PER_MINUTE) *
1076 interval->time = ((int) (interval->time / SECS_PER_MINUTE)) * (double) SECS_PER_MINUTE;
1079 /* HOUR TO SECOND */
1080 else if (range == (INTERVAL_MASK(HOUR) |
1081 INTERVAL_MASK(MINUTE) |
1082 INTERVAL_MASK(SECOND)))
1084 /* fractional-second rounding will be dealt with below */
1086 /* MINUTE TO SECOND */
1087 else if (range == (INTERVAL_MASK(MINUTE) |
1088 INTERVAL_MASK(SECOND)))
1090 /* fractional-second rounding will be dealt with below */
1093 elog(ERROR, "unrecognized interval typmod: %d", typmod);
1095 /* Need to adjust subsecond precision? */
1096 if (precision != INTERVAL_FULL_PRECISION)
1098 if (precision < 0 || precision > MAX_INTERVAL_PRECISION)
1100 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1101 errmsg("interval(%d) precision must be between %d and %d",
1102 precision, 0, MAX_INTERVAL_PRECISION)));
1105 * Note: this round-to-nearest code is not completely consistent
1106 * about rounding values that are exactly halfway between integral
1107 * values. On most platforms, rint() will implement
1108 * round-to-nearest-even, but the integer code always rounds up
1109 * (away from zero). Is it worth trying to be consistent?
1111 #ifdef HAVE_INT64_TIMESTAMP
1112 if (interval->time >= INT64CONST(0))
1114 interval->time = ((interval->time +
1115 IntervalOffsets[precision]) /
1116 IntervalScales[precision]) *
1117 IntervalScales[precision];
1121 interval->time = -(((-interval->time +
1122 IntervalOffsets[precision]) /
1123 IntervalScales[precision]) *
1124 IntervalScales[precision]);
1127 interval->time = rint(((double) interval->time) *
1128 IntervalScales[precision]) /
1129 IntervalScales[precision];
1136 /* EncodeSpecialTimestamp()
1137 * Convert reserved timestamp data type to string.
1140 EncodeSpecialTimestamp(Timestamp dt, char *str)
1142 if (TIMESTAMP_IS_NOBEGIN(dt))
1144 else if (TIMESTAMP_IS_NOEND(dt))
1146 else /* shouldn't happen */
1147 elog(ERROR, "invalid argument for EncodeSpecialTimestamp");
1151 now(PG_FUNCTION_ARGS)
1153 PG_RETURN_TIMESTAMPTZ(GetCurrentTransactionStartTimestamp());
1157 statement_timestamp(PG_FUNCTION_ARGS)
1159 PG_RETURN_TIMESTAMPTZ(GetCurrentStatementStartTimestamp());
1163 clock_timestamp(PG_FUNCTION_ARGS)
1165 PG_RETURN_TIMESTAMPTZ(GetCurrentTimestamp());
1169 pg_postmaster_start_time(PG_FUNCTION_ARGS)
1171 PG_RETURN_TIMESTAMPTZ(PgStartTime);
1175 pg_conf_load_time(PG_FUNCTION_ARGS)
1177 PG_RETURN_TIMESTAMPTZ(PgReloadTime);
1181 * GetCurrentTimestamp -- get the current operating system time
1183 * Result is in the form of a TimestampTz value, and is expressed to the
1184 * full precision of the gettimeofday() syscall
1187 GetCurrentTimestamp(void)
1192 gettimeofday(&tp, NULL);
1194 result = (TimestampTz) tp.tv_sec -
1195 ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);
1197 #ifdef HAVE_INT64_TIMESTAMP
1198 result = (result * USECS_PER_SEC) + tp.tv_usec;
1200 result = result + (tp.tv_usec / 1000000.0);
1207 * TimestampDifference -- convert the difference between two timestamps
1208 * into integer seconds and microseconds
1210 * Both inputs must be ordinary finite timestamps (in current usage,
1211 * they'll be results from GetCurrentTimestamp()).
1213 * We expect start_time <= stop_time. If not, we return zeroes; for current
1214 * callers there is no need to be tense about which way division rounds on
1218 TimestampDifference(TimestampTz start_time, TimestampTz stop_time,
1219 long *secs, int *microsecs)
1221 TimestampTz diff = stop_time - start_time;
1230 #ifdef HAVE_INT64_TIMESTAMP
1231 *secs = (long) (diff / USECS_PER_SEC);
1232 *microsecs = (int) (diff % USECS_PER_SEC);
1234 *secs = (long) diff;
1235 *microsecs = (int) ((diff - *secs) * 1000000.0);
1241 * TimestampDifferenceExceeds -- report whether the difference between two
1242 * timestamps is >= a threshold (expressed in milliseconds)
1244 * Both inputs must be ordinary finite timestamps (in current usage,
1245 * they'll be results from GetCurrentTimestamp()).
1248 TimestampDifferenceExceeds(TimestampTz start_time,
1249 TimestampTz stop_time,
1252 TimestampTz diff = stop_time - start_time;
1254 #ifdef HAVE_INT64_TIMESTAMP
1255 return (diff >= msec * INT64CONST(1000));
1257 return (diff * 1000.0 >= msec);
1262 * Convert a time_t to TimestampTz.
1264 * We do not use time_t internally in Postgres, but this is provided for use
1265 * by functions that need to interpret, say, a stat(2) result.
1267 * To avoid having the function's ABI vary depending on the width of time_t,
1268 * we declare the argument as pg_time_t, which is cast-compatible with
1269 * time_t but always 64 bits wide (unless the platform has no 64-bit type).
1270 * This detail should be invisible to callers, at least at source code level.
1273 time_t_to_timestamptz(pg_time_t tm)
1277 result = (TimestampTz) tm -
1278 ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);
1280 #ifdef HAVE_INT64_TIMESTAMP
1281 result *= USECS_PER_SEC;
1288 * Convert a TimestampTz to time_t.
1290 * This too is just marginally useful, but some places need it.
1292 * To avoid having the function's ABI vary depending on the width of time_t,
1293 * we declare the result as pg_time_t, which is cast-compatible with
1294 * time_t but always 64 bits wide (unless the platform has no 64-bit type).
1295 * This detail should be invisible to callers, at least at source code level.
1298 timestamptz_to_time_t(TimestampTz t)
1302 #ifdef HAVE_INT64_TIMESTAMP
1303 result = (pg_time_t) (t / USECS_PER_SEC +
1304 ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY));
1306 result = (pg_time_t) (t +
1307 ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY));
1314 * Produce a C-string representation of a TimestampTz.
1316 * This is mostly for use in emitting messages. The primary difference
1317 * from timestamptz_out is that we force the output format to ISO. Note
1318 * also that the result is in a static buffer, not pstrdup'd.
1321 timestamptz_to_str(TimestampTz t)
1323 static char buf[MAXDATELEN + 1];
1330 if (TIMESTAMP_NOT_FINITE(t))
1331 EncodeSpecialTimestamp(t, buf);
1332 else if (timestamp2tm(t, &tz, tm, &fsec, &tzn, NULL) == 0)
1333 EncodeDateTime(tm, fsec, &tz, &tzn, USE_ISO_DATES, buf);
1335 strlcpy(buf, "(timestamp out of range)", sizeof(buf));
1342 dt2time(Timestamp jd, int *hour, int *min, int *sec, fsec_t *fsec)
1348 #ifdef HAVE_INT64_TIMESTAMP
1349 *hour = time / USECS_PER_HOUR;
1350 time -= (*hour) * USECS_PER_HOUR;
1351 *min = time / USECS_PER_MINUTE;
1352 time -= (*min) * USECS_PER_MINUTE;
1353 *sec = time / USECS_PER_SEC;
1354 *fsec = time - (*sec * USECS_PER_SEC);
1356 *hour = time / SECS_PER_HOUR;
1357 time -= (*hour) * SECS_PER_HOUR;
1358 *min = time / SECS_PER_MINUTE;
1359 time -= (*min) * SECS_PER_MINUTE;
1361 *fsec = time - *sec;
1367 * timestamp2tm() - Convert timestamp data type to POSIX time structure.
1369 * Note that year is _not_ 1900-based, but is an explicit full value.
1370 * Also, month is one-based, _not_ zero-based.
1373 * -1 on out of range
1375 * If attimezone is NULL, the global timezone (including possibly brute forced
1376 * timezone) will be used.
1379 timestamp2tm(Timestamp dt, int *tzp, struct pg_tm * tm, fsec_t *fsec, char **tzn, pg_tz *attimezone)
1386 * If HasCTZSet is true then we have a brute force time zone specified. Go
1387 * ahead and rotate to the local time zone since we will later bypass any
1388 * calls which adjust the tm fields.
1390 if (attimezone == NULL && HasCTZSet && tzp != NULL)
1392 #ifdef HAVE_INT64_TIMESTAMP
1393 dt -= CTimeZone * USECS_PER_SEC;
1399 #ifdef HAVE_INT64_TIMESTAMP
1401 TMODULO(time, date, USECS_PER_DAY);
1403 if (time < INT64CONST(0))
1405 time += USECS_PER_DAY;
1409 /* add offset to go from J2000 back to standard Julian date */
1410 date += POSTGRES_EPOCH_JDATE;
1412 /* Julian day routine does not work for negative Julian days */
1413 if (date < 0 || date > (Timestamp) INT_MAX)
1416 j2date((int) date, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1417 dt2time(time, &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1420 TMODULO(time, date, (double) SECS_PER_DAY);
1424 time += SECS_PER_DAY;
1428 /* add offset to go from J2000 back to standard Julian date */
1429 date += POSTGRES_EPOCH_JDATE;
1432 /* Julian day routine does not work for negative Julian days */
1433 if (date < 0 || date > (Timestamp) INT_MAX)
1436 j2date((int) date, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1438 dt2time(time, &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1440 *fsec = TSROUND(*fsec);
1441 /* roundoff may need to propagate to higher-order fields */
1445 if (time >= (double) SECS_PER_DAY)
1455 /* Done if no TZ conversion wanted */
1467 * We have a brute force time zone per SQL99? Then use it without change
1468 * since we have already rotated to the time zone.
1470 if (attimezone == NULL && HasCTZSet)
1474 tm->tm_gmtoff = CTimeZone;
1482 * If the time falls within the range of pg_time_t, use pg_localtime() to
1483 * rotate to the local time zone.
1485 * First, convert to an integral timestamp, avoiding possibly
1486 * platform-specific roundoff-in-wrong-direction errors, and adjust to
1487 * Unix epoch. Then see if we can convert to pg_time_t without loss. This
1488 * coding avoids hardwiring any assumptions about the width of pg_time_t,
1489 * so it should behave sanely on machines without int64.
1491 #ifdef HAVE_INT64_TIMESTAMP
1492 dt = (dt - *fsec) / USECS_PER_SEC +
1493 (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY;
1495 dt = rint(dt - *fsec +
1496 (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);
1498 utime = (pg_time_t) dt;
1499 if ((Timestamp) utime == dt)
1501 struct pg_tm *tx = pg_localtime(&utime,
1502 attimezone ? attimezone : session_timezone);
1504 tm->tm_year = tx->tm_year + 1900;
1505 tm->tm_mon = tx->tm_mon + 1;
1506 tm->tm_mday = tx->tm_mday;
1507 tm->tm_hour = tx->tm_hour;
1508 tm->tm_min = tx->tm_min;
1509 tm->tm_sec = tx->tm_sec;
1510 tm->tm_isdst = tx->tm_isdst;
1511 tm->tm_gmtoff = tx->tm_gmtoff;
1512 tm->tm_zone = tx->tm_zone;
1513 *tzp = -tm->tm_gmtoff;
1515 *tzn = (char *) tm->tm_zone;
1520 * When out of range of pg_time_t, treat as GMT
1523 /* Mark this as *no* time zone available */
1536 * Convert a tm structure to a timestamp data type.
1537 * Note that year is _not_ 1900-based, but is an explicit full value.
1538 * Also, month is one-based, _not_ zero-based.
1540 * Returns -1 on failure (value out of range).
1543 tm2timestamp(struct pg_tm * tm, fsec_t fsec, int *tzp, Timestamp *result)
1548 /* Julian day routines are not correct for negative Julian days */
1549 if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
1551 *result = 0; /* keep compiler quiet */
1555 date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - POSTGRES_EPOCH_JDATE;
1556 time = time2t(tm->tm_hour, tm->tm_min, tm->tm_sec, fsec);
1558 #ifdef HAVE_INT64_TIMESTAMP
1559 *result = date * USECS_PER_DAY + time;
1560 /* check for major overflow */
1561 if ((*result - time) / USECS_PER_DAY != date)
1563 *result = 0; /* keep compiler quiet */
1566 /* check for just-barely overflow (okay except time-of-day wraps) */
1567 if ((*result < 0 && date >= 0) ||
1568 (*result >= 0 && date < 0))
1570 *result = 0; /* keep compiler quiet */
1574 *result = date * SECS_PER_DAY + time;
1577 *result = dt2local(*result, -(*tzp));
1584 * Convert a interval data type to a tm structure.
1587 interval2tm(Interval span, struct pg_tm * tm, fsec_t *fsec)
1592 tm->tm_year = span.month / MONTHS_PER_YEAR;
1593 tm->tm_mon = span.month % MONTHS_PER_YEAR;
1594 tm->tm_mday = span.day;
1597 #ifdef HAVE_INT64_TIMESTAMP
1598 tfrac = time / USECS_PER_HOUR;
1599 time -= tfrac * USECS_PER_HOUR;
1600 tm->tm_hour = tfrac; /* could overflow ... */
1601 tfrac = time / USECS_PER_MINUTE;
1602 time -= tfrac * USECS_PER_MINUTE;
1604 tfrac = time / USECS_PER_SEC;
1605 *fsec = time - (tfrac * USECS_PER_SEC);
1609 TMODULO(time, tfrac, (double) SECS_PER_HOUR);
1610 tm->tm_hour = tfrac; /* could overflow ... */
1611 TMODULO(time, tfrac, (double) SECS_PER_MINUTE);
1613 TMODULO(time, tfrac, 1.0);
1615 time = TSROUND(time);
1616 /* roundoff may need to propagate to higher-order fields */
1619 time = ceil(span.time);
1629 tm2interval(struct pg_tm * tm, fsec_t fsec, Interval *span)
1631 span->month = tm->tm_year * MONTHS_PER_YEAR + tm->tm_mon;
1632 span->day = tm->tm_mday;
1633 #ifdef HAVE_INT64_TIMESTAMP
1634 span->time = (((((tm->tm_hour * INT64CONST(60)) +
1635 tm->tm_min) * INT64CONST(60)) +
1636 tm->tm_sec) * USECS_PER_SEC) + fsec;
1638 span->time = (((tm->tm_hour * (double) MINS_PER_HOUR) +
1639 tm->tm_min) * (double) SECS_PER_MINUTE) +
1647 time2t(const int hour, const int min, const int sec, const fsec_t fsec)
1649 #ifdef HAVE_INT64_TIMESTAMP
1650 return (((((hour * MINS_PER_HOUR) + min) * SECS_PER_MINUTE) + sec) * USECS_PER_SEC) + fsec;
1652 return (((hour * MINS_PER_HOUR) + min) * SECS_PER_MINUTE) + sec + fsec;
1657 dt2local(Timestamp dt, int tz)
1659 #ifdef HAVE_INT64_TIMESTAMP
1660 dt -= (tz * USECS_PER_SEC);
1668 /*****************************************************************************
1670 *****************************************************************************/
1674 timestamp_finite(PG_FUNCTION_ARGS)
1676 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
1678 PG_RETURN_BOOL(!TIMESTAMP_NOT_FINITE(timestamp));
1682 interval_finite(PG_FUNCTION_ARGS)
1684 PG_RETURN_BOOL(true);
1688 /*----------------------------------------------------------
1689 * Relational operators for timestamp.
1690 *---------------------------------------------------------*/
1693 GetEpochTime(struct pg_tm * tm)
1696 pg_time_t epoch = 0;
1698 t0 = pg_gmtime(&epoch);
1700 tm->tm_year = t0->tm_year;
1701 tm->tm_mon = t0->tm_mon;
1702 tm->tm_mday = t0->tm_mday;
1703 tm->tm_hour = t0->tm_hour;
1704 tm->tm_min = t0->tm_min;
1705 tm->tm_sec = t0->tm_sec;
1707 tm->tm_year += 1900;
1712 SetEpochTimestamp(void)
1719 /* we don't bother to test for failure ... */
1720 tm2timestamp(tm, 0, NULL, &dt);
1723 } /* SetEpochTimestamp() */
1726 * We are currently sharing some code between timestamp and timestamptz.
1727 * The comparison functions are among them. - thomas 2001-09-25
1729 * timestamp_relop - is timestamp1 relop timestamp2
1731 * collate invalid timestamp at the end
1734 timestamp_cmp_internal(Timestamp dt1, Timestamp dt2)
1736 #ifdef HAVE_INT64_TIMESTAMP
1737 return (dt1 < dt2) ? -1 : ((dt1 > dt2) ? 1 : 0);
1741 * When using float representation, we have to be wary of NaNs.
1743 * We consider all NANs to be equal and larger than any non-NAN. This is
1744 * somewhat arbitrary; the important thing is to have a consistent sort
1750 return 0; /* NAN = NAN */
1752 return 1; /* NAN > non-NAN */
1754 else if (isnan(dt2))
1756 return -1; /* non-NAN < NAN */
1771 timestamp_eq(PG_FUNCTION_ARGS)
1773 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
1774 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
1776 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
1780 timestamp_ne(PG_FUNCTION_ARGS)
1782 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
1783 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
1785 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
1789 timestamp_lt(PG_FUNCTION_ARGS)
1791 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
1792 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
1794 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
1798 timestamp_gt(PG_FUNCTION_ARGS)
1800 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
1801 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
1803 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
1807 timestamp_le(PG_FUNCTION_ARGS)
1809 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
1810 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
1812 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) <= 0);
1816 timestamp_ge(PG_FUNCTION_ARGS)
1818 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
1819 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
1821 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) >= 0);
1825 timestamp_cmp(PG_FUNCTION_ARGS)
1827 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
1828 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
1830 PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
1834 timestamp_hash(PG_FUNCTION_ARGS)
1836 /* We can use either hashint8 or hashfloat8 directly */
1837 #ifdef HAVE_INT64_TIMESTAMP
1838 return hashint8(fcinfo);
1840 return hashfloat8(fcinfo);
1846 * Crosstype comparison functions for timestamp vs timestamptz
1850 timestamp_eq_timestamptz(PG_FUNCTION_ARGS)
1852 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
1853 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
1856 dt1 = timestamp2timestamptz(timestampVal);
1858 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
1862 timestamp_ne_timestamptz(PG_FUNCTION_ARGS)
1864 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
1865 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
1868 dt1 = timestamp2timestamptz(timestampVal);
1870 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
1874 timestamp_lt_timestamptz(PG_FUNCTION_ARGS)
1876 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
1877 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
1880 dt1 = timestamp2timestamptz(timestampVal);
1882 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
1886 timestamp_gt_timestamptz(PG_FUNCTION_ARGS)
1888 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
1889 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
1892 dt1 = timestamp2timestamptz(timestampVal);
1894 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
1898 timestamp_le_timestamptz(PG_FUNCTION_ARGS)
1900 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
1901 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
1904 dt1 = timestamp2timestamptz(timestampVal);
1906 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) <= 0);
1910 timestamp_ge_timestamptz(PG_FUNCTION_ARGS)
1912 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
1913 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
1916 dt1 = timestamp2timestamptz(timestampVal);
1918 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) >= 0);
1922 timestamp_cmp_timestamptz(PG_FUNCTION_ARGS)
1924 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
1925 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
1928 dt1 = timestamp2timestamptz(timestampVal);
1930 PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
1934 timestamptz_eq_timestamp(PG_FUNCTION_ARGS)
1936 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
1937 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
1940 dt2 = timestamp2timestamptz(timestampVal);
1942 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
1946 timestamptz_ne_timestamp(PG_FUNCTION_ARGS)
1948 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
1949 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
1952 dt2 = timestamp2timestamptz(timestampVal);
1954 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
1958 timestamptz_lt_timestamp(PG_FUNCTION_ARGS)
1960 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
1961 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
1964 dt2 = timestamp2timestamptz(timestampVal);
1966 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
1970 timestamptz_gt_timestamp(PG_FUNCTION_ARGS)
1972 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
1973 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
1976 dt2 = timestamp2timestamptz(timestampVal);
1978 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
1982 timestamptz_le_timestamp(PG_FUNCTION_ARGS)
1984 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
1985 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
1988 dt2 = timestamp2timestamptz(timestampVal);
1990 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) <= 0);
1994 timestamptz_ge_timestamp(PG_FUNCTION_ARGS)
1996 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
1997 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2000 dt2 = timestamp2timestamptz(timestampVal);
2002 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) >= 0);
2006 timestamptz_cmp_timestamp(PG_FUNCTION_ARGS)
2008 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2009 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2012 dt2 = timestamp2timestamptz(timestampVal);
2014 PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
2019 * interval_relop - is interval1 relop interval2
2021 * collate invalid interval at the end
2023 static inline TimeOffset
2024 interval_cmp_value(const Interval *interval)
2028 span = interval->time;
2030 #ifdef HAVE_INT64_TIMESTAMP
2031 span += interval->month * INT64CONST(30) * USECS_PER_DAY;
2032 span += interval->day * INT64CONST(24) * USECS_PER_HOUR;
2034 span += interval->month * ((double) DAYS_PER_MONTH * SECS_PER_DAY);
2035 span += interval->day * ((double) HOURS_PER_DAY * SECS_PER_HOUR);
2042 interval_cmp_internal(Interval *interval1, Interval *interval2)
2044 TimeOffset span1 = interval_cmp_value(interval1);
2045 TimeOffset span2 = interval_cmp_value(interval2);
2047 return ((span1 < span2) ? -1 : (span1 > span2) ? 1 : 0);
2051 interval_eq(PG_FUNCTION_ARGS)
2053 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2054 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2056 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) == 0);
2060 interval_ne(PG_FUNCTION_ARGS)
2062 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2063 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2065 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) != 0);
2069 interval_lt(PG_FUNCTION_ARGS)
2071 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2072 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2074 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) < 0);
2078 interval_gt(PG_FUNCTION_ARGS)
2080 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2081 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2083 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) > 0);
2087 interval_le(PG_FUNCTION_ARGS)
2089 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2090 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2092 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) <= 0);
2096 interval_ge(PG_FUNCTION_ARGS)
2098 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2099 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2101 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) >= 0);
2105 interval_cmp(PG_FUNCTION_ARGS)
2107 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2108 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2110 PG_RETURN_INT32(interval_cmp_internal(interval1, interval2));
2114 * Hashing for intervals
2116 * We must produce equal hashvals for values that interval_cmp_internal()
2117 * considers equal. So, compute the net span the same way it does,
2118 * and then hash that, using either int64 or float8 hashing.
2121 interval_hash(PG_FUNCTION_ARGS)
2123 Interval *interval = PG_GETARG_INTERVAL_P(0);
2124 TimeOffset span = interval_cmp_value(interval);
2126 #ifdef HAVE_INT64_TIMESTAMP
2127 return DirectFunctionCall1(hashint8, Int64GetDatumFast(span));
2129 return DirectFunctionCall1(hashfloat8, Float8GetDatumFast(span));
2133 /* overlaps_timestamp() --- implements the SQL92 OVERLAPS operator.
2135 * Algorithm is per SQL92 spec. This is much harder than you'd think
2136 * because the spec requires us to deliver a non-null answer in some cases
2137 * where some of the inputs are null.
2140 overlaps_timestamp(PG_FUNCTION_ARGS)
2143 * The arguments are Timestamps, but we leave them as generic Datums to
2144 * avoid unnecessary conversions between value and reference forms --- not
2145 * to mention possible dereferences of null pointers.
2147 Datum ts1 = PG_GETARG_DATUM(0);
2148 Datum te1 = PG_GETARG_DATUM(1);
2149 Datum ts2 = PG_GETARG_DATUM(2);
2150 Datum te2 = PG_GETARG_DATUM(3);
2151 bool ts1IsNull = PG_ARGISNULL(0);
2152 bool te1IsNull = PG_ARGISNULL(1);
2153 bool ts2IsNull = PG_ARGISNULL(2);
2154 bool te2IsNull = PG_ARGISNULL(3);
2156 #define TIMESTAMP_GT(t1,t2) \
2157 DatumGetBool(DirectFunctionCall2(timestamp_gt,t1,t2))
2158 #define TIMESTAMP_LT(t1,t2) \
2159 DatumGetBool(DirectFunctionCall2(timestamp_lt,t1,t2))
2162 * If both endpoints of interval 1 are null, the result is null (unknown).
2163 * If just one endpoint is null, take ts1 as the non-null one. Otherwise,
2164 * take ts1 as the lesser endpoint.
2170 /* swap null for non-null */
2174 else if (!te1IsNull)
2176 if (TIMESTAMP_GT(ts1, te1))
2185 /* Likewise for interval 2. */
2190 /* swap null for non-null */
2194 else if (!te2IsNull)
2196 if (TIMESTAMP_GT(ts2, te2))
2206 * At this point neither ts1 nor ts2 is null, so we can consider three
2207 * cases: ts1 > ts2, ts1 < ts2, ts1 = ts2
2209 if (TIMESTAMP_GT(ts1, ts2))
2212 * This case is ts1 < te2 OR te1 < te2, which may look redundant but
2213 * in the presence of nulls it's not quite completely so.
2217 if (TIMESTAMP_LT(ts1, te2))
2218 PG_RETURN_BOOL(true);
2223 * If te1 is not null then we had ts1 <= te1 above, and we just found
2224 * ts1 >= te2, hence te1 >= te2.
2226 PG_RETURN_BOOL(false);
2228 else if (TIMESTAMP_LT(ts1, ts2))
2230 /* This case is ts2 < te1 OR te2 < te1 */
2233 if (TIMESTAMP_LT(ts2, te1))
2234 PG_RETURN_BOOL(true);
2239 * If te2 is not null then we had ts2 <= te2 above, and we just found
2240 * ts2 >= te1, hence te2 >= te1.
2242 PG_RETURN_BOOL(false);
2247 * For ts1 = ts2 the spec says te1 <> te2 OR te1 = te2, which is a
2248 * rather silly way of saying "true if both are nonnull, else null".
2250 if (te1IsNull || te2IsNull)
2252 PG_RETURN_BOOL(true);
2260 /*----------------------------------------------------------
2261 * "Arithmetic" operators on date/times.
2262 *---------------------------------------------------------*/
2265 timestamp_smaller(PG_FUNCTION_ARGS)
2267 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2268 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2271 /* use timestamp_cmp_internal to be sure this agrees with comparisons */
2272 if (timestamp_cmp_internal(dt1, dt2) < 0)
2276 PG_RETURN_TIMESTAMP(result);
2280 timestamp_larger(PG_FUNCTION_ARGS)
2282 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2283 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2286 if (timestamp_cmp_internal(dt1, dt2) > 0)
2290 PG_RETURN_TIMESTAMP(result);
2295 timestamp_mi(PG_FUNCTION_ARGS)
2297 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2298 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2301 result = (Interval *) palloc(sizeof(Interval));
2303 if (TIMESTAMP_NOT_FINITE(dt1) || TIMESTAMP_NOT_FINITE(dt2))
2305 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2306 errmsg("cannot subtract infinite timestamps")));
2308 result->time = dt1 - dt2;
2314 * This is wrong, but removing it breaks a lot of regression tests.
2317 * test=> SET timezone = 'EST5EDT';
2319 * test-> ('2005-10-30 13:22:00-05'::timestamptz -
2320 * test(> '2005-10-29 13:22:00-04'::timestamptz);
2326 * so adding that to the first timestamp gets:
2329 * test-> ('2005-10-29 13:22:00-04'::timestamptz +
2330 * test(> ('2005-10-30 13:22:00-05'::timestamptz -
2331 * test(> '2005-10-29 13:22:00-04'::timestamptz)) at time zone 'EST';
2333 * --------------------
2334 * 2005-10-30 14:22:00
2338 result = DatumGetIntervalP(DirectFunctionCall1(interval_justify_hours,
2339 IntervalPGetDatum(result)));
2341 PG_RETURN_INTERVAL_P(result);
2345 * interval_justify_interval()
2347 * Adjust interval so 'month', 'day', and 'time' portions are within
2348 * customary bounds. Specifically:
2350 * 0 <= abs(time) < 24 hours
2351 * 0 <= abs(day) < 30 days
2353 * Also, the sign bit on all three fields is made equal, so either
2354 * all three fields are negative or all are positive.
2357 interval_justify_interval(PG_FUNCTION_ARGS)
2359 Interval *span = PG_GETARG_INTERVAL_P(0);
2361 TimeOffset wholeday;
2364 result = (Interval *) palloc(sizeof(Interval));
2365 result->month = span->month;
2366 result->day = span->day;
2367 result->time = span->time;
2369 #ifdef HAVE_INT64_TIMESTAMP
2370 TMODULO(result->time, wholeday, USECS_PER_DAY);
2372 TMODULO(result->time, wholeday, (double) SECS_PER_DAY);
2374 result->day += wholeday; /* could overflow... */
2376 wholemonth = result->day / DAYS_PER_MONTH;
2377 result->day -= wholemonth * DAYS_PER_MONTH;
2378 result->month += wholemonth;
2380 if (result->month > 0 &&
2381 (result->day < 0 || (result->day == 0 && result->time < 0)))
2383 result->day += DAYS_PER_MONTH;
2386 else if (result->month < 0 &&
2387 (result->day > 0 || (result->day == 0 && result->time > 0)))
2389 result->day -= DAYS_PER_MONTH;
2393 if (result->day > 0 && result->time < 0)
2395 #ifdef HAVE_INT64_TIMESTAMP
2396 result->time += USECS_PER_DAY;
2398 result->time += (double) SECS_PER_DAY;
2402 else if (result->day < 0 && result->time > 0)
2404 #ifdef HAVE_INT64_TIMESTAMP
2405 result->time -= USECS_PER_DAY;
2407 result->time -= (double) SECS_PER_DAY;
2412 PG_RETURN_INTERVAL_P(result);
2416 * interval_justify_hours()
2418 * Adjust interval so 'time' contains less than a whole day, adding
2419 * the excess to 'day'. This is useful for
2420 * situations (such as non-TZ) where '1 day' = '24 hours' is valid,
2421 * e.g. interval subtraction and division.
2424 interval_justify_hours(PG_FUNCTION_ARGS)
2426 Interval *span = PG_GETARG_INTERVAL_P(0);
2428 TimeOffset wholeday;
2430 result = (Interval *) palloc(sizeof(Interval));
2431 result->month = span->month;
2432 result->day = span->day;
2433 result->time = span->time;
2435 #ifdef HAVE_INT64_TIMESTAMP
2436 TMODULO(result->time, wholeday, USECS_PER_DAY);
2438 TMODULO(result->time, wholeday, (double) SECS_PER_DAY);
2440 result->day += wholeday; /* could overflow... */
2442 if (result->day > 0 && result->time < 0)
2444 #ifdef HAVE_INT64_TIMESTAMP
2445 result->time += USECS_PER_DAY;
2447 result->time += (double) SECS_PER_DAY;
2451 else if (result->day < 0 && result->time > 0)
2453 #ifdef HAVE_INT64_TIMESTAMP
2454 result->time -= USECS_PER_DAY;
2456 result->time -= (double) SECS_PER_DAY;
2461 PG_RETURN_INTERVAL_P(result);
2465 * interval_justify_days()
2467 * Adjust interval so 'day' contains less than 30 days, adding
2468 * the excess to 'month'.
2471 interval_justify_days(PG_FUNCTION_ARGS)
2473 Interval *span = PG_GETARG_INTERVAL_P(0);
2477 result = (Interval *) palloc(sizeof(Interval));
2478 result->month = span->month;
2479 result->day = span->day;
2480 result->time = span->time;
2482 wholemonth = result->day / DAYS_PER_MONTH;
2483 result->day -= wholemonth * DAYS_PER_MONTH;
2484 result->month += wholemonth;
2486 if (result->month > 0 && result->day < 0)
2488 result->day += DAYS_PER_MONTH;
2491 else if (result->month < 0 && result->day > 0)
2493 result->day -= DAYS_PER_MONTH;
2497 PG_RETURN_INTERVAL_P(result);
2500 /* timestamp_pl_interval()
2501 * Add a interval to a timestamp data type.
2502 * Note that interval has provisions for qualitative year/month and day
2503 * units, so try to do the right thing with them.
2504 * To add a month, increment the month, and use the same day of month.
2505 * Then, if the next month has fewer days, set the day of month
2506 * to the last day of month.
2507 * To add a day, increment the mday, and use the same time of day.
2508 * Lastly, add in the "quantitative time".
2511 timestamp_pl_interval(PG_FUNCTION_ARGS)
2513 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
2514 Interval *span = PG_GETARG_INTERVAL_P(1);
2517 if (TIMESTAMP_NOT_FINITE(timestamp))
2521 if (span->month != 0)
2527 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
2529 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2530 errmsg("timestamp out of range")));
2532 tm->tm_mon += span->month;
2533 if (tm->tm_mon > MONTHS_PER_YEAR)
2535 tm->tm_year += (tm->tm_mon - 1) / MONTHS_PER_YEAR;
2536 tm->tm_mon = ((tm->tm_mon - 1) % MONTHS_PER_YEAR) + 1;
2538 else if (tm->tm_mon < 1)
2540 tm->tm_year += tm->tm_mon / MONTHS_PER_YEAR - 1;
2541 tm->tm_mon = tm->tm_mon % MONTHS_PER_YEAR + MONTHS_PER_YEAR;
2544 /* adjust for end of month boundary problems... */
2545 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2546 tm->tm_mday = (day_tab[isleap(tm->tm_year)][tm->tm_mon - 1]);
2548 if (tm2timestamp(tm, fsec, NULL, ×tamp) != 0)
2550 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2551 errmsg("timestamp out of range")));
2561 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
2563 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2564 errmsg("timestamp out of range")));
2566 /* Add days by converting to and from julian */
2567 julian = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + span->day;
2568 j2date(julian, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2570 if (tm2timestamp(tm, fsec, NULL, ×tamp) != 0)
2572 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2573 errmsg("timestamp out of range")));
2576 timestamp += span->time;
2580 PG_RETURN_TIMESTAMP(result);
2584 timestamp_mi_interval(PG_FUNCTION_ARGS)
2586 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
2587 Interval *span = PG_GETARG_INTERVAL_P(1);
2590 tspan.month = -span->month;
2591 tspan.day = -span->day;
2592 tspan.time = -span->time;
2594 return DirectFunctionCall2(timestamp_pl_interval,
2595 TimestampGetDatum(timestamp),
2596 PointerGetDatum(&tspan));
2600 /* timestamptz_pl_interval()
2601 * Add a interval to a timestamp with time zone data type.
2602 * Note that interval has provisions for qualitative year/month
2603 * units, so try to do the right thing with them.
2604 * To add a month, increment the month, and use the same day of month.
2605 * Then, if the next month has fewer days, set the day of month
2606 * to the last day of month.
2607 * Lastly, add in the "quantitative time".
2610 timestamptz_pl_interval(PG_FUNCTION_ARGS)
2612 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
2613 Interval *span = PG_GETARG_INTERVAL_P(1);
2618 if (TIMESTAMP_NOT_FINITE(timestamp))
2622 if (span->month != 0)
2628 if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
2630 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2631 errmsg("timestamp out of range")));
2633 tm->tm_mon += span->month;
2634 if (tm->tm_mon > MONTHS_PER_YEAR)
2636 tm->tm_year += (tm->tm_mon - 1) / MONTHS_PER_YEAR;
2637 tm->tm_mon = ((tm->tm_mon - 1) % MONTHS_PER_YEAR) + 1;
2639 else if (tm->tm_mon < 1)
2641 tm->tm_year += tm->tm_mon / MONTHS_PER_YEAR - 1;
2642 tm->tm_mon = tm->tm_mon % MONTHS_PER_YEAR + MONTHS_PER_YEAR;
2645 /* adjust for end of month boundary problems... */
2646 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2647 tm->tm_mday = (day_tab[isleap(tm->tm_year)][tm->tm_mon - 1]);
2649 tz = DetermineTimeZoneOffset(tm, session_timezone);
2651 if (tm2timestamp(tm, fsec, &tz, ×tamp) != 0)
2653 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2654 errmsg("timestamp out of range")));
2664 if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
2666 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2667 errmsg("timestamp out of range")));
2669 /* Add days by converting to and from julian */
2670 julian = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + span->day;
2671 j2date(julian, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2673 tz = DetermineTimeZoneOffset(tm, session_timezone);
2675 if (tm2timestamp(tm, fsec, &tz, ×tamp) != 0)
2677 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2678 errmsg("timestamp out of range")));
2681 timestamp += span->time;
2685 PG_RETURN_TIMESTAMP(result);
2689 timestamptz_mi_interval(PG_FUNCTION_ARGS)
2691 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
2692 Interval *span = PG_GETARG_INTERVAL_P(1);
2695 tspan.month = -span->month;
2696 tspan.day = -span->day;
2697 tspan.time = -span->time;
2699 return DirectFunctionCall2(timestamptz_pl_interval,
2700 TimestampGetDatum(timestamp),
2701 PointerGetDatum(&tspan));
2706 interval_um(PG_FUNCTION_ARGS)
2708 Interval *interval = PG_GETARG_INTERVAL_P(0);
2711 result = (Interval *) palloc(sizeof(Interval));
2713 result->time = -interval->time;
2714 result->day = -interval->day;
2715 result->month = -interval->month;
2717 PG_RETURN_INTERVAL_P(result);
2722 interval_smaller(PG_FUNCTION_ARGS)
2724 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2725 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2728 /* use interval_cmp_internal to be sure this agrees with comparisons */
2729 if (interval_cmp_internal(interval1, interval2) < 0)
2733 PG_RETURN_INTERVAL_P(result);
2737 interval_larger(PG_FUNCTION_ARGS)
2739 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2740 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2743 if (interval_cmp_internal(interval1, interval2) > 0)
2747 PG_RETURN_INTERVAL_P(result);
2751 interval_pl(PG_FUNCTION_ARGS)
2753 Interval *span1 = PG_GETARG_INTERVAL_P(0);
2754 Interval *span2 = PG_GETARG_INTERVAL_P(1);
2757 result = (Interval *) palloc(sizeof(Interval));
2759 result->month = span1->month + span2->month;
2760 result->day = span1->day + span2->day;
2761 result->time = span1->time + span2->time;
2763 PG_RETURN_INTERVAL_P(result);
2767 interval_mi(PG_FUNCTION_ARGS)
2769 Interval *span1 = PG_GETARG_INTERVAL_P(0);
2770 Interval *span2 = PG_GETARG_INTERVAL_P(1);
2773 result = (Interval *) palloc(sizeof(Interval));
2775 result->month = span1->month - span2->month;
2776 result->day = span1->day - span2->day;
2777 result->time = span1->time - span2->time;
2779 PG_RETURN_INTERVAL_P(result);
2783 * There is no interval_abs(): it is unclear what value to return:
2784 * http://archives.postgresql.org/pgsql-general/2009-10/msg01031.php
2785 * http://archives.postgresql.org/pgsql-general/2009-11/msg00041.php
2789 interval_mul(PG_FUNCTION_ARGS)
2791 Interval *span = PG_GETARG_INTERVAL_P(0);
2792 float8 factor = PG_GETARG_FLOAT8(1);
2793 double month_remainder_days,
2795 int32 orig_month = span->month,
2796 orig_day = span->day;
2799 result = (Interval *) palloc(sizeof(Interval));
2801 result->month = (int32) (span->month * factor);
2802 result->day = (int32) (span->day * factor);
2805 * The above correctly handles the whole-number part of the month and day
2806 * products, but we have to do something with any fractional part
2807 * resulting when the factor is nonintegral. We cascade the fractions
2808 * down to lower units using the conversion factors DAYS_PER_MONTH and
2809 * SECS_PER_DAY. Note we do NOT cascade up, since we are not forced to do
2810 * so by the representation. The user can choose to cascade up later,
2811 * using justify_hours and/or justify_days.
2815 * Fractional months full days into days.
2817 * Floating point calculation are inherently inprecise, so these
2818 * calculations are crafted to produce the most reliable result possible.
2819 * TSROUND() is needed to more accurately produce whole numbers where
2822 month_remainder_days = (orig_month * factor - result->month) * DAYS_PER_MONTH;
2823 month_remainder_days = TSROUND(month_remainder_days);
2824 sec_remainder = (orig_day * factor - result->day +
2825 month_remainder_days - (int) month_remainder_days) * SECS_PER_DAY;
2826 sec_remainder = TSROUND(sec_remainder);
2829 * Might have 24:00:00 hours due to rounding, or >24 hours because of time
2830 * cascade from months and days. It might still be >24 if the combination
2831 * of cascade and the seconds factor operation itself.
2833 if (Abs(sec_remainder) >= SECS_PER_DAY)
2835 result->day += (int) (sec_remainder / SECS_PER_DAY);
2836 sec_remainder -= (int) (sec_remainder / SECS_PER_DAY) * SECS_PER_DAY;
2839 /* cascade units down */
2840 result->day += (int32) month_remainder_days;
2841 #ifdef HAVE_INT64_TIMESTAMP
2842 result->time = rint(span->time * factor + sec_remainder * USECS_PER_SEC);
2844 result->time = span->time * factor + sec_remainder;
2847 PG_RETURN_INTERVAL_P(result);
2851 mul_d_interval(PG_FUNCTION_ARGS)
2853 /* Args are float8 and Interval *, but leave them as generic Datum */
2854 Datum factor = PG_GETARG_DATUM(0);
2855 Datum span = PG_GETARG_DATUM(1);
2857 return DirectFunctionCall2(interval_mul, span, factor);
2861 interval_div(PG_FUNCTION_ARGS)
2863 Interval *span = PG_GETARG_INTERVAL_P(0);
2864 float8 factor = PG_GETARG_FLOAT8(1);
2865 double month_remainder_days,
2867 int32 orig_month = span->month,
2868 orig_day = span->day;
2871 result = (Interval *) palloc(sizeof(Interval));
2875 (errcode(ERRCODE_DIVISION_BY_ZERO),
2876 errmsg("division by zero")));
2878 result->month = (int32) (span->month / factor);
2879 result->day = (int32) (span->day / factor);
2882 * Fractional months full days into days. See comment in interval_mul().
2884 month_remainder_days = (orig_month / factor - result->month) * DAYS_PER_MONTH;
2885 month_remainder_days = TSROUND(month_remainder_days);
2886 sec_remainder = (orig_day / factor - result->day +
2887 month_remainder_days - (int) month_remainder_days) * SECS_PER_DAY;
2888 sec_remainder = TSROUND(sec_remainder);
2889 if (Abs(sec_remainder) >= SECS_PER_DAY)
2891 result->day += (int) (sec_remainder / SECS_PER_DAY);
2892 sec_remainder -= (int) (sec_remainder / SECS_PER_DAY) * SECS_PER_DAY;
2895 /* cascade units down */
2896 result->day += (int32) month_remainder_days;
2897 #ifdef HAVE_INT64_TIMESTAMP
2898 result->time = rint(span->time / factor + sec_remainder * USECS_PER_SEC);
2900 /* See TSROUND comment in interval_mul(). */
2901 result->time = span->time / factor + sec_remainder;
2904 PG_RETURN_INTERVAL_P(result);
2908 * interval_accum and interval_avg implement the AVG(interval) aggregate.
2910 * The transition datatype for this aggregate is a 2-element array of
2911 * intervals, where the first is the running sum and the second contains
2912 * the number of values so far in its 'time' field. This is a bit ugly
2913 * but it beats inventing a specialized datatype for the purpose.
2917 interval_accum(PG_FUNCTION_ARGS)
2919 ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
2920 Interval *newval = PG_GETARG_INTERVAL_P(1);
2928 deconstruct_array(transarray,
2929 INTERVALOID, sizeof(Interval), false, 'd',
2930 &transdatums, NULL, &ndatums);
2932 elog(ERROR, "expected 2-element interval array");
2935 * XXX memcpy, instead of just extracting a pointer, to work around buggy
2936 * array code: it won't ensure proper alignment of Interval objects on
2937 * machines where double requires 8-byte alignment. That should be fixed,
2938 * but in the meantime...
2940 * Note: must use DatumGetPointer here, not DatumGetIntervalP, else some
2941 * compilers optimize into double-aligned load/store anyway.
2943 memcpy((void *) &sumX, DatumGetPointer(transdatums[0]), sizeof(Interval));
2944 memcpy((void *) &N, DatumGetPointer(transdatums[1]), sizeof(Interval));
2946 newsum = DatumGetIntervalP(DirectFunctionCall2(interval_pl,
2947 IntervalPGetDatum(&sumX),
2948 IntervalPGetDatum(newval)));
2951 transdatums[0] = IntervalPGetDatum(newsum);
2952 transdatums[1] = IntervalPGetDatum(&N);
2954 result = construct_array(transdatums, 2,
2955 INTERVALOID, sizeof(Interval), false, 'd');
2957 PG_RETURN_ARRAYTYPE_P(result);
2961 interval_avg(PG_FUNCTION_ARGS)
2963 ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
2969 deconstruct_array(transarray,
2970 INTERVALOID, sizeof(Interval), false, 'd',
2971 &transdatums, NULL, &ndatums);
2973 elog(ERROR, "expected 2-element interval array");
2976 * XXX memcpy, instead of just extracting a pointer, to work around buggy
2977 * array code: it won't ensure proper alignment of Interval objects on
2978 * machines where double requires 8-byte alignment. That should be fixed,
2979 * but in the meantime...
2981 * Note: must use DatumGetPointer here, not DatumGetIntervalP, else some
2982 * compilers optimize into double-aligned load/store anyway.
2984 memcpy((void *) &sumX, DatumGetPointer(transdatums[0]), sizeof(Interval));
2985 memcpy((void *) &N, DatumGetPointer(transdatums[1]), sizeof(Interval));
2987 /* SQL92 defines AVG of no values to be NULL */
2991 return DirectFunctionCall2(interval_div,
2992 IntervalPGetDatum(&sumX),
2993 Float8GetDatum(N.time));
2998 * Calculate time difference while retaining year/month fields.
2999 * Note that this does not result in an accurate absolute time span
3000 * since year and month are out of context once the arithmetic
3004 timestamp_age(PG_FUNCTION_ARGS)
3006 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
3007 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
3019 result = (Interval *) palloc(sizeof(Interval));
3021 if (timestamp2tm(dt1, NULL, tm1, &fsec1, NULL, NULL) == 0 &&
3022 timestamp2tm(dt2, NULL, tm2, &fsec2, NULL, NULL) == 0)
3024 /* form the symbolic difference */
3025 fsec = fsec1 - fsec2;
3026 tm->tm_sec = tm1->tm_sec - tm2->tm_sec;
3027 tm->tm_min = tm1->tm_min - tm2->tm_min;
3028 tm->tm_hour = tm1->tm_hour - tm2->tm_hour;
3029 tm->tm_mday = tm1->tm_mday - tm2->tm_mday;
3030 tm->tm_mon = tm1->tm_mon - tm2->tm_mon;
3031 tm->tm_year = tm1->tm_year - tm2->tm_year;
3033 /* flip sign if necessary... */
3037 tm->tm_sec = -tm->tm_sec;
3038 tm->tm_min = -tm->tm_min;
3039 tm->tm_hour = -tm->tm_hour;
3040 tm->tm_mday = -tm->tm_mday;
3041 tm->tm_mon = -tm->tm_mon;
3042 tm->tm_year = -tm->tm_year;
3045 /* propagate any negative fields into the next higher field */
3048 #ifdef HAVE_INT64_TIMESTAMP
3049 fsec += USECS_PER_SEC;
3056 while (tm->tm_sec < 0)
3058 tm->tm_sec += SECS_PER_MINUTE;
3062 while (tm->tm_min < 0)
3064 tm->tm_min += MINS_PER_HOUR;
3068 while (tm->tm_hour < 0)
3070 tm->tm_hour += HOURS_PER_DAY;
3074 while (tm->tm_mday < 0)
3078 tm->tm_mday += day_tab[isleap(tm1->tm_year)][tm1->tm_mon - 1];
3083 tm->tm_mday += day_tab[isleap(tm2->tm_year)][tm2->tm_mon - 1];
3088 while (tm->tm_mon < 0)
3090 tm->tm_mon += MONTHS_PER_YEAR;
3094 /* recover sign if necessary... */
3098 tm->tm_sec = -tm->tm_sec;
3099 tm->tm_min = -tm->tm_min;
3100 tm->tm_hour = -tm->tm_hour;
3101 tm->tm_mday = -tm->tm_mday;
3102 tm->tm_mon = -tm->tm_mon;
3103 tm->tm_year = -tm->tm_year;
3106 if (tm2interval(tm, fsec, result) != 0)
3108 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3109 errmsg("interval out of range")));
3113 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3114 errmsg("timestamp out of range")));
3116 PG_RETURN_INTERVAL_P(result);
3120 /* timestamptz_age()
3121 * Calculate time difference while retaining year/month fields.
3122 * Note that this does not result in an accurate absolute time span
3123 * since year and month are out of context once the arithmetic
3127 timestamptz_age(PG_FUNCTION_ARGS)
3129 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
3130 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
3145 result = (Interval *) palloc(sizeof(Interval));
3147 if (timestamp2tm(dt1, &tz1, tm1, &fsec1, &tzn, NULL) == 0 &&
3148 timestamp2tm(dt2, &tz2, tm2, &fsec2, &tzn, NULL) == 0)
3150 /* form the symbolic difference */
3151 fsec = fsec1 - fsec2;
3152 tm->tm_sec = tm1->tm_sec - tm2->tm_sec;
3153 tm->tm_min = tm1->tm_min - tm2->tm_min;
3154 tm->tm_hour = tm1->tm_hour - tm2->tm_hour;
3155 tm->tm_mday = tm1->tm_mday - tm2->tm_mday;
3156 tm->tm_mon = tm1->tm_mon - tm2->tm_mon;
3157 tm->tm_year = tm1->tm_year - tm2->tm_year;
3159 /* flip sign if necessary... */
3163 tm->tm_sec = -tm->tm_sec;
3164 tm->tm_min = -tm->tm_min;
3165 tm->tm_hour = -tm->tm_hour;
3166 tm->tm_mday = -tm->tm_mday;
3167 tm->tm_mon = -tm->tm_mon;
3168 tm->tm_year = -tm->tm_year;
3171 /* propagate any negative fields into the next higher field */
3174 #ifdef HAVE_INT64_TIMESTAMP
3175 fsec += USECS_PER_SEC;
3182 while (tm->tm_sec < 0)
3184 tm->tm_sec += SECS_PER_MINUTE;
3188 while (tm->tm_min < 0)
3190 tm->tm_min += MINS_PER_HOUR;
3194 while (tm->tm_hour < 0)
3196 tm->tm_hour += HOURS_PER_DAY;
3200 while (tm->tm_mday < 0)
3204 tm->tm_mday += day_tab[isleap(tm1->tm_year)][tm1->tm_mon - 1];
3209 tm->tm_mday += day_tab[isleap(tm2->tm_year)][tm2->tm_mon - 1];
3214 while (tm->tm_mon < 0)
3216 tm->tm_mon += MONTHS_PER_YEAR;
3221 * Note: we deliberately ignore any difference between tz1 and tz2.
3224 /* recover sign if necessary... */
3228 tm->tm_sec = -tm->tm_sec;
3229 tm->tm_min = -tm->tm_min;
3230 tm->tm_hour = -tm->tm_hour;
3231 tm->tm_mday = -tm->tm_mday;
3232 tm->tm_mon = -tm->tm_mon;
3233 tm->tm_year = -tm->tm_year;
3236 if (tm2interval(tm, fsec, result) != 0)
3238 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3239 errmsg("interval out of range")));
3243 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3244 errmsg("timestamp out of range")));
3246 PG_RETURN_INTERVAL_P(result);
3250 /*----------------------------------------------------------
3251 * Conversion operators.
3252 *---------------------------------------------------------*/
3255 /* timestamp_trunc()
3256 * Truncate timestamp to specified units.
3259 timestamp_trunc(PG_FUNCTION_ARGS)
3261 text *units = PG_GETARG_TEXT_PP(0);
3262 Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
3271 if (TIMESTAMP_NOT_FINITE(timestamp))
3272 PG_RETURN_TIMESTAMP(timestamp);
3274 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
3275 VARSIZE_ANY_EXHDR(units),
3278 type = DecodeUnits(0, lowunits, &val);
3282 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
3284 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3285 errmsg("timestamp out of range")));
3293 woy = date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
3296 * If it is week 52/53 and the month is January, then the
3297 * week must belong to the previous year. Also, some
3298 * December dates belong to the next year.
3300 if (woy >= 52 && tm->tm_mon == 1)
3302 if (woy <= 1 && tm->tm_mon == MONTHS_PER_YEAR)
3304 isoweek2date(woy, &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
3311 case DTK_MILLENNIUM:
3312 /* see comments in timestamptz_trunc */
3313 if (tm->tm_year > 0)
3314 tm->tm_year = ((tm->tm_year + 999) / 1000) * 1000 - 999;
3316 tm->tm_year = -((999 - (tm->tm_year - 1)) / 1000) * 1000 + 1;
3318 /* see comments in timestamptz_trunc */
3319 if (tm->tm_year > 0)
3320 tm->tm_year = ((tm->tm_year + 99) / 100) * 100 - 99;
3322 tm->tm_year = -((99 - (tm->tm_year - 1)) / 100) * 100 + 1;
3324 /* see comments in timestamptz_trunc */
3325 if (val != DTK_MILLENNIUM && val != DTK_CENTURY)
3327 if (tm->tm_year > 0)
3328 tm->tm_year = (tm->tm_year / 10) * 10;
3330 tm->tm_year = -((8 - (tm->tm_year - 1)) / 10) * 10;
3335 tm->tm_mon = (3 * ((tm->tm_mon - 1) / 3)) + 1;
3349 #ifdef HAVE_INT64_TIMESTAMP
3350 fsec = (fsec / 1000) * 1000;
3352 fsec = floor(fsec * 1000) / 1000;
3357 #ifndef HAVE_INT64_TIMESTAMP
3358 fsec = floor(fsec * 1000000) / 1000000;
3364 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3365 errmsg("timestamp units \"%s\" not supported",
3370 if (tm2timestamp(tm, fsec, NULL, &result) != 0)
3372 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3373 errmsg("timestamp out of range")));
3378 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3379 errmsg("timestamp units \"%s\" not recognized",
3384 PG_RETURN_TIMESTAMP(result);
3387 /* timestamptz_trunc()
3388 * Truncate timestamp to specified units.
3391 timestamptz_trunc(PG_FUNCTION_ARGS)
3393 text *units = PG_GETARG_TEXT_PP(0);
3394 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
3399 bool redotz = false;
3406 if (TIMESTAMP_NOT_FINITE(timestamp))
3407 PG_RETURN_TIMESTAMPTZ(timestamp);
3409 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
3410 VARSIZE_ANY_EXHDR(units),
3413 type = DecodeUnits(0, lowunits, &val);
3417 if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
3419 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3420 errmsg("timestamp out of range")));
3428 woy = date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
3431 * If it is week 52/53 and the month is January, then the
3432 * week must belong to the previous year. Also, some
3433 * December dates belong to the next year.
3435 if (woy >= 52 && tm->tm_mon == 1)
3437 if (woy <= 1 && tm->tm_mon == MONTHS_PER_YEAR)
3439 isoweek2date(woy, &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
3447 /* one may consider DTK_THOUSAND and DTK_HUNDRED... */
3448 case DTK_MILLENNIUM:
3451 * truncating to the millennium? what is this supposed to
3452 * mean? let us put the first year of the millennium... i.e.
3453 * -1000, 1, 1001, 2001...
3455 if (tm->tm_year > 0)
3456 tm->tm_year = ((tm->tm_year + 999) / 1000) * 1000 - 999;
3458 tm->tm_year = -((999 - (tm->tm_year - 1)) / 1000) * 1000 + 1;
3461 /* truncating to the century? as above: -100, 1, 101... */
3462 if (tm->tm_year > 0)
3463 tm->tm_year = ((tm->tm_year + 99) / 100) * 100 - 99;
3465 tm->tm_year = -((99 - (tm->tm_year - 1)) / 100) * 100 + 1;
3470 * truncating to the decade? first year of the decade. must
3471 * not be applied if year was truncated before!
3473 if (val != DTK_MILLENNIUM && val != DTK_CENTURY)
3475 if (tm->tm_year > 0)
3476 tm->tm_year = (tm->tm_year / 10) * 10;
3478 tm->tm_year = -((8 - (tm->tm_year - 1)) / 10) * 10;
3485 tm->tm_mon = (3 * ((tm->tm_mon - 1) / 3)) + 1;
3492 redotz = true; /* for all cases >= DAY */
3505 #ifdef HAVE_INT64_TIMESTAMP
3506 fsec = (fsec / 1000) * 1000;
3508 fsec = floor(fsec * 1000) / 1000;
3512 #ifndef HAVE_INT64_TIMESTAMP
3513 fsec = floor(fsec * 1000000) / 1000000;
3519 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3520 errmsg("timestamp with time zone units \"%s\" not "
3521 "supported", lowunits)));
3526 tz = DetermineTimeZoneOffset(tm, session_timezone);
3528 if (tm2timestamp(tm, fsec, &tz, &result) != 0)
3530 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3531 errmsg("timestamp out of range")));
3536 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3537 errmsg("timestamp with time zone units \"%s\" not recognized",
3542 PG_RETURN_TIMESTAMPTZ(result);
3546 * Extract specified field from interval.
3549 interval_trunc(PG_FUNCTION_ARGS)
3551 text *units = PG_GETARG_TEXT_PP(0);
3552 Interval *interval = PG_GETARG_INTERVAL_P(1);
3561 result = (Interval *) palloc(sizeof(Interval));
3563 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
3564 VARSIZE_ANY_EXHDR(units),
3567 type = DecodeUnits(0, lowunits, &val);
3571 if (interval2tm(*interval, tm, &fsec) == 0)
3576 case DTK_MILLENNIUM:
3577 /* caution: C division may have negative remainder */
3578 tm->tm_year = (tm->tm_year / 1000) * 1000;
3580 /* caution: C division may have negative remainder */
3581 tm->tm_year = (tm->tm_year / 100) * 100;
3583 /* caution: C division may have negative remainder */
3584 tm->tm_year = (tm->tm_year / 10) * 10;
3588 tm->tm_mon = 3 * (tm->tm_mon / 3);
3602 #ifdef HAVE_INT64_TIMESTAMP
3603 fsec = (fsec / 1000) * 1000;
3605 fsec = floor(fsec * 1000) / 1000;
3609 #ifndef HAVE_INT64_TIMESTAMP
3610 fsec = floor(fsec * 1000000) / 1000000;
3616 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3617 errmsg("interval units \"%s\" not supported",
3621 if (tm2interval(tm, fsec, result) != 0)
3623 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3624 errmsg("interval out of range")));
3627 elog(ERROR, "could not convert interval to tm");
3632 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3633 errmsg("interval units \"%s\" not recognized",
3637 PG_RETURN_INTERVAL_P(result);
3642 * Return the Julian day which corresponds to the first day (Monday) of the given ISO 8601 year and week.
3643 * Julian days are used to convert between ISO week dates and Gregorian dates.
3646 isoweek2j(int year, int week)
3651 /* fourth day of current year */
3652 day4 = date2j(year, 1, 4);
3654 /* day0 == offset to first day of week (Monday) */
3655 day0 = j2day(day4 - 1);
3657 return ((week - 1) * 7) + (day4 - day0);
3661 * Convert ISO week of year number to date.
3662 * The year field must be specified with the ISO year!
3666 isoweek2date(int woy, int *year, int *mon, int *mday)
3668 j2date(isoweek2j(*year, woy), year, mon, mday);
3671 /* isoweekdate2date()
3673 * Convert an ISO 8601 week date (ISO year, ISO week and day of week) into a Gregorian date.
3674 * Populates year, mon, and mday with the correct Gregorian values.
3675 * year must be passed in as the ISO year.
3678 isoweekdate2date(int isoweek, int isowday, int *year, int *mon, int *mday)
3682 jday = isoweek2j(*year, isoweek);
3683 jday += isowday - 1;
3685 j2date(jday, year, mon, mday);
3690 * Returns ISO week number of year.
3693 date2isoweek(int year, int mon, int mday)
3701 dayn = date2j(year, mon, mday);
3703 /* fourth day of current year */
3704 day4 = date2j(year, 1, 4);
3706 /* day0 == offset to first day of week (Monday) */
3707 day0 = j2day(day4 - 1);
3710 * We need the first week containing a Thursday, otherwise this day falls
3711 * into the previous year for purposes of counting weeks
3713 if (dayn < day4 - day0)
3715 day4 = date2j(year - 1, 1, 4);
3717 /* day0 == offset to first day of week (Monday) */
3718 day0 = j2day(day4 - 1);
3721 result = (dayn - (day4 - day0)) / 7 + 1;
3724 * Sometimes the last few days in a year will fall into the first week of
3725 * the next year, so check for this.
3729 day4 = date2j(year + 1, 1, 4);
3731 /* day0 == offset to first day of week (Monday) */
3732 day0 = j2day(day4 - 1);
3734 if (dayn >= day4 - day0)
3735 result = (dayn - (day4 - day0)) / 7 + 1;
3738 return (int) result;
3744 * Returns ISO 8601 year number.
3747 date2isoyear(int year, int mon, int mday)
3755 dayn = date2j(year, mon, mday);
3757 /* fourth day of current year */
3758 day4 = date2j(year, 1, 4);
3760 /* day0 == offset to first day of week (Monday) */
3761 day0 = j2day(day4 - 1);
3764 * We need the first week containing a Thursday, otherwise this day falls
3765 * into the previous year for purposes of counting weeks
3767 if (dayn < day4 - day0)
3769 day4 = date2j(year - 1, 1, 4);
3771 /* day0 == offset to first day of week (Monday) */
3772 day0 = j2day(day4 - 1);
3777 result = (dayn - (day4 - day0)) / 7 + 1;
3780 * Sometimes the last few days in a year will fall into the first week of
3781 * the next year, so check for this.
3785 day4 = date2j(year + 1, 1, 4);
3787 /* day0 == offset to first day of week (Monday) */
3788 day0 = j2day(day4 - 1);
3790 if (dayn >= day4 - day0)
3798 /* date2isoyearday()
3800 * Returns the ISO 8601 day-of-year, given a Gregorian year, month and day.
3801 * Possible return values are 1 through 371 (364 in non-leap years).
3804 date2isoyearday(int year, int mon, int mday)
3806 return date2j(year, mon, mday) - isoweek2j(date2isoyear(year, mon, mday), 1) + 1;
3810 * Extract specified field from timestamp.
3813 timestamp_part(PG_FUNCTION_ARGS)
3815 text *units = PG_GETARG_TEXT_PP(0);
3816 Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
3825 if (TIMESTAMP_NOT_FINITE(timestamp))
3828 PG_RETURN_FLOAT8(result);
3831 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
3832 VARSIZE_ANY_EXHDR(units),
3835 type = DecodeUnits(0, lowunits, &val);
3836 if (type == UNKNOWN_FIELD)
3837 type = DecodeSpecial(0, lowunits, &val);
3841 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
3843 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3844 errmsg("timestamp out of range")));
3849 #ifdef HAVE_INT64_TIMESTAMP
3850 result = tm->tm_sec * 1000000.0 + fsec;
3852 result = (tm->tm_sec + fsec) * 1000000;
3857 #ifdef HAVE_INT64_TIMESTAMP
3858 result = tm->tm_sec * 1000.0 + fsec / 1000.0;
3860 result = (tm->tm_sec + fsec) * 1000;
3865 #ifdef HAVE_INT64_TIMESTAMP
3866 result = tm->tm_sec + fsec / 1000000.0;
3868 result = tm->tm_sec + fsec;
3873 result = tm->tm_min;
3877 result = tm->tm_hour;
3881 result = tm->tm_mday;
3885 result = tm->tm_mon;
3889 result = (tm->tm_mon - 1) / 3 + 1;
3893 result = (float8) date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
3897 if (tm->tm_year > 0)
3898 result = tm->tm_year;
3900 /* there is no year 0, just 1 BC and 1 AD */
3901 result = tm->tm_year - 1;
3907 * what is a decade wrt dates? let us assume that decade 199
3908 * is 1990 thru 1999... decade 0 starts on year 1 BC, and -1
3909 * is 11 BC thru 2 BC...
3911 if (tm->tm_year >= 0)
3912 result = tm->tm_year / 10;
3914 result = -((8 - (tm->tm_year - 1)) / 10);
3920 * centuries AD, c>0: year in [ (c-1)* 100 + 1 : c*100 ]
3921 * centuries BC, c<0: year in [ c*100 : (c+1) * 100 - 1]
3922 * there is no number 0 century.
3925 if (tm->tm_year > 0)
3926 result = (tm->tm_year + 99) / 100;
3928 /* caution: C division may have negative remainder */
3929 result = -((99 - (tm->tm_year - 1)) / 100);
3932 case DTK_MILLENNIUM:
3933 /* see comments above. */
3934 if (tm->tm_year > 0)
3935 result = (tm->tm_year + 999) / 1000;
3937 result = -((999 - (tm->tm_year - 1)) / 1000);
3941 result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
3942 #ifdef HAVE_INT64_TIMESTAMP
3943 result += ((((tm->tm_hour * MINS_PER_HOUR) + tm->tm_min) * SECS_PER_MINUTE) +
3944 tm->tm_sec + (fsec / 1000000.0)) / (double) SECS_PER_DAY;
3946 result += ((((tm->tm_hour * MINS_PER_HOUR) + tm->tm_min) * SECS_PER_MINUTE) +
3947 tm->tm_sec + fsec) / (double) SECS_PER_DAY;
3952 result = date2isoyear(tm->tm_year, tm->tm_mon, tm->tm_mday);
3960 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3961 errmsg("timestamp units \"%s\" not supported",
3966 else if (type == RESERV)
3973 TimestampTz timestamptz;
3976 * convert to timestamptz to produce consistent results
3978 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
3980 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3981 errmsg("timestamp out of range")));
3983 tz = DetermineTimeZoneOffset(tm, session_timezone);
3985 if (tm2timestamp(tm, fsec, &tz, ×tamptz) != 0)
3987 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3988 errmsg("timestamp out of range")));
3990 #ifdef HAVE_INT64_TIMESTAMP
3991 result = (timestamptz - SetEpochTimestamp()) / 1000000.0;
3993 result = timestamptz - SetEpochTimestamp();
3999 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
4001 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4002 errmsg("timestamp out of range")));
4003 result = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
4004 if (val == DTK_ISODOW && result == 0)
4009 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
4011 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4012 errmsg("timestamp out of range")));
4013 result = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
4014 - date2j(tm->tm_year, 1, 1) + 1);
4019 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4020 errmsg("timestamp units \"%s\" not supported",
4029 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4030 errmsg("timestamp units \"%s\" not recognized", lowunits)));
4034 PG_RETURN_FLOAT8(result);
4037 /* timestamptz_part()
4038 * Extract specified field from timestamp with time zone.
4041 timestamptz_part(PG_FUNCTION_ARGS)
4043 text *units = PG_GETARG_TEXT_PP(0);
4044 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
4056 if (TIMESTAMP_NOT_FINITE(timestamp))
4059 PG_RETURN_FLOAT8(result);
4062 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
4063 VARSIZE_ANY_EXHDR(units),
4066 type = DecodeUnits(0, lowunits, &val);
4067 if (type == UNKNOWN_FIELD)
4068 type = DecodeSpecial(0, lowunits, &val);
4072 if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
4074 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4075 errmsg("timestamp out of range")));
4085 result /= MINS_PER_HOUR;
4086 FMODULO(result, dummy, (double) MINS_PER_HOUR);
4091 FMODULO(dummy, result, (double) SECS_PER_HOUR);
4095 #ifdef HAVE_INT64_TIMESTAMP
4096 result = tm->tm_sec * 1000000.0 + fsec;
4098 result = (tm->tm_sec + fsec) * 1000000;
4103 #ifdef HAVE_INT64_TIMESTAMP
4104 result = tm->tm_sec * 1000.0 + fsec / 1000.0;
4106 result = (tm->tm_sec + fsec) * 1000;
4111 #ifdef HAVE_INT64_TIMESTAMP
4112 result = tm->tm_sec + fsec / 1000000.0;
4114 result = tm->tm_sec + fsec;
4119 result = tm->tm_min;
4123 result = tm->tm_hour;
4127 result = tm->tm_mday;
4131 result = tm->tm_mon;
4135 result = (tm->tm_mon - 1) / 3 + 1;
4139 result = (float8) date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
4143 if (tm->tm_year > 0)
4144 result = tm->tm_year;
4146 /* there is no year 0, just 1 BC and 1 AD */
4147 result = tm->tm_year - 1;
4151 /* see comments in timestamp_part */
4152 if (tm->tm_year > 0)
4153 result = tm->tm_year / 10;
4155 result = -((8 - (tm->tm_year - 1)) / 10);
4159 /* see comments in timestamp_part */
4160 if (tm->tm_year > 0)
4161 result = (tm->tm_year + 99) / 100;
4163 result = -((99 - (tm->tm_year - 1)) / 100);
4166 case DTK_MILLENNIUM:
4167 /* see comments in timestamp_part */
4168 if (tm->tm_year > 0)
4169 result = (tm->tm_year + 999) / 1000;
4171 result = -((999 - (tm->tm_year - 1)) / 1000);
4175 result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
4176 #ifdef HAVE_INT64_TIMESTAMP
4177 result += ((((tm->tm_hour * MINS_PER_HOUR) + tm->tm_min) * SECS_PER_MINUTE) +
4178 tm->tm_sec + (fsec / 1000000.0)) / (double) SECS_PER_DAY;
4180 result += ((((tm->tm_hour * MINS_PER_HOUR) + tm->tm_min) * SECS_PER_MINUTE) +
4181 tm->tm_sec + fsec) / (double) SECS_PER_DAY;
4186 result = date2isoyear(tm->tm_year, tm->tm_mon, tm->tm_mday);
4191 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4192 errmsg("timestamp with time zone units \"%s\" not supported",
4198 else if (type == RESERV)
4203 #ifdef HAVE_INT64_TIMESTAMP
4204 result = (timestamp - SetEpochTimestamp()) / 1000000.0;
4206 result = timestamp - SetEpochTimestamp();
4212 if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
4214 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4215 errmsg("timestamp out of range")));
4216 result = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
4217 if (val == DTK_ISODOW && result == 0)
4222 if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
4224 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4225 errmsg("timestamp out of range")));
4226 result = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
4227 - date2j(tm->tm_year, 1, 1) + 1);
4232 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4233 errmsg("timestamp with time zone units \"%s\" not supported",
4241 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4242 errmsg("timestamp with time zone units \"%s\" not recognized",
4248 PG_RETURN_FLOAT8(result);
4253 * Extract specified field from interval.
4256 interval_part(PG_FUNCTION_ARGS)
4258 text *units = PG_GETARG_TEXT_PP(0);
4259 Interval *interval = PG_GETARG_INTERVAL_P(1);
4268 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
4269 VARSIZE_ANY_EXHDR(units),
4272 type = DecodeUnits(0, lowunits, &val);
4273 if (type == UNKNOWN_FIELD)
4274 type = DecodeSpecial(0, lowunits, &val);
4278 if (interval2tm(*interval, tm, &fsec) == 0)
4283 #ifdef HAVE_INT64_TIMESTAMP
4284 result = tm->tm_sec * 1000000.0 + fsec;
4286 result = (tm->tm_sec + fsec) * 1000000;
4291 #ifdef HAVE_INT64_TIMESTAMP
4292 result = tm->tm_sec * 1000.0 + fsec / 1000.0;
4294 result = (tm->tm_sec + fsec) * 1000;
4299 #ifdef HAVE_INT64_TIMESTAMP
4300 result = tm->tm_sec + fsec / 1000000.0;
4302 result = tm->tm_sec + fsec;
4307 result = tm->tm_min;
4311 result = tm->tm_hour;
4315 result = tm->tm_mday;
4319 result = tm->tm_mon;
4323 result = (tm->tm_mon / 3) + 1;
4327 result = tm->tm_year;
4331 /* caution: C division may have negative remainder */
4332 result = tm->tm_year / 10;
4336 /* caution: C division may have negative remainder */
4337 result = tm->tm_year / 100;
4340 case DTK_MILLENNIUM:
4341 /* caution: C division may have negative remainder */
4342 result = tm->tm_year / 1000;
4347 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4348 errmsg("interval units \"%s\" not supported",
4356 elog(ERROR, "could not convert interval to tm");
4360 else if (type == RESERV && val == DTK_EPOCH)
4362 #ifdef HAVE_INT64_TIMESTAMP
4363 result = interval->time / 1000000.0;
4365 result = interval->time;
4367 result += ((double) DAYS_PER_YEAR * SECS_PER_DAY) * (interval->month / MONTHS_PER_YEAR);
4368 result += ((double) DAYS_PER_MONTH * SECS_PER_DAY) * (interval->month % MONTHS_PER_YEAR);
4369 result += ((double) SECS_PER_DAY) * interval->day;
4374 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4375 errmsg("interval units \"%s\" not recognized",
4380 PG_RETURN_FLOAT8(result);
4385 * Encode timestamp type with specified time zone.
4386 * This function is just timestamp2timestamptz() except instead of
4387 * shifting to the global timezone, we shift to the specified timezone.
4388 * This is different from the other AT TIME ZONE cases because instead
4389 * of shifting to a _to_ a new time zone, it sets the time to _be_ the
4390 * specified timezone.
4393 timestamp_zone(PG_FUNCTION_ARGS)
4395 text *zone = PG_GETARG_TEXT_PP(0);
4396 Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
4399 char tzname[TZ_STRLEN_MAX + 1];
4405 if (TIMESTAMP_NOT_FINITE(timestamp))
4406 PG_RETURN_TIMESTAMPTZ(timestamp);
4409 * Look up the requested timezone. First we look in the date token table
4410 * (to handle cases like "EST"), and if that fails, we look in the
4411 * timezone database (to handle cases like "America/New_York"). (This
4412 * matches the order in which timestamp input checks the cases; it's
4413 * important because the timezone database unwisely uses a few zone names
4414 * that are identical to offset abbreviations.)
4416 text_to_cstring_buffer(zone, tzname, sizeof(tzname));
4417 lowzone = downcase_truncate_identifier(tzname,
4421 type = DecodeSpecial(0, lowzone, &val);
4423 if (type == TZ || type == DTZ)
4425 tz = -(val * MINS_PER_HOUR);
4426 result = dt2local(timestamp, tz);
4430 tzp = pg_tzset(tzname);
4433 /* Apply the timezone change */
4437 if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, tzp) != 0)
4439 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4440 errmsg("timestamp out of range")));
4441 tz = DetermineTimeZoneOffset(&tm, tzp);
4442 if (tm2timestamp(&tm, fsec, &tz, &result) != 0)
4444 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4445 errmsg("could not convert to time zone \"%s\"",
4451 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4452 errmsg("time zone \"%s\" not recognized", tzname)));
4453 result = 0; /* keep compiler quiet */
4457 PG_RETURN_TIMESTAMPTZ(result);
4460 /* timestamp_izone()
4461 * Encode timestamp type with specified time interval as time zone.
4464 timestamp_izone(PG_FUNCTION_ARGS)
4466 Interval *zone = PG_GETARG_INTERVAL_P(0);
4467 Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
4471 if (TIMESTAMP_NOT_FINITE(timestamp))
4472 PG_RETURN_TIMESTAMPTZ(timestamp);
4474 if (zone->month != 0)
4476 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4477 errmsg("interval time zone \"%s\" must not specify month",
4478 DatumGetCString(DirectFunctionCall1(interval_out,
4479 PointerGetDatum(zone))))));
4481 #ifdef HAVE_INT64_TIMESTAMP
4482 tz = zone->time / USECS_PER_SEC;
4487 result = dt2local(timestamp, tz);
4489 PG_RETURN_TIMESTAMPTZ(result);
4490 } /* timestamp_izone() */
4492 /* timestamp_timestamptz()
4493 * Convert local timestamp to timestamp at GMT
4496 timestamp_timestamptz(PG_FUNCTION_ARGS)
4498 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
4500 PG_RETURN_TIMESTAMPTZ(timestamp2timestamptz(timestamp));
4504 timestamp2timestamptz(Timestamp timestamp)
4512 if (TIMESTAMP_NOT_FINITE(timestamp))
4516 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
4518 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4519 errmsg("timestamp out of range")));
4521 tz = DetermineTimeZoneOffset(tm, session_timezone);
4523 if (tm2timestamp(tm, fsec, &tz, &result) != 0)
4525 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4526 errmsg("timestamp out of range")));
4532 /* timestamptz_timestamp()
4533 * Convert timestamp at GMT to local timestamp
4536 timestamptz_timestamp(PG_FUNCTION_ARGS)
4538 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
4546 if (TIMESTAMP_NOT_FINITE(timestamp))
4550 if (timestamp2tm(timestamp, &tz, tm, &fsec, &tzn, NULL) != 0)
4552 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4553 errmsg("timestamp out of range")));
4554 if (tm2timestamp(tm, fsec, NULL, &result) != 0)
4556 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4557 errmsg("timestamp out of range")));
4559 PG_RETURN_TIMESTAMP(result);
4562 /* timestamptz_zone()
4563 * Evaluate timestamp with time zone type at the specified time zone.
4564 * Returns a timestamp without time zone.
4567 timestamptz_zone(PG_FUNCTION_ARGS)
4569 text *zone = PG_GETARG_TEXT_PP(0);
4570 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
4573 char tzname[TZ_STRLEN_MAX + 1];
4579 if (TIMESTAMP_NOT_FINITE(timestamp))
4580 PG_RETURN_TIMESTAMP(timestamp);
4583 * Look up the requested timezone. First we look in the date token table
4584 * (to handle cases like "EST"), and if that fails, we look in the
4585 * timezone database (to handle cases like "America/New_York"). (This
4586 * matches the order in which timestamp input checks the cases; it's
4587 * important because the timezone database unwisely uses a few zone names
4588 * that are identical to offset abbreviations.)
4590 text_to_cstring_buffer(zone, tzname, sizeof(tzname));
4591 lowzone = downcase_truncate_identifier(tzname,
4595 type = DecodeSpecial(0, lowzone, &val);
4597 if (type == TZ || type == DTZ)
4599 tz = val * MINS_PER_HOUR;
4600 result = dt2local(timestamp, tz);
4604 tzp = pg_tzset(tzname);
4607 /* Apply the timezone change */
4611 if (timestamp2tm(timestamp, &tz, &tm, &fsec, NULL, tzp) != 0)
4613 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4614 errmsg("timestamp out of range")));
4615 if (tm2timestamp(&tm, fsec, NULL, &result) != 0)
4617 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4618 errmsg("could not convert to time zone \"%s\"",
4624 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4625 errmsg("time zone \"%s\" not recognized", tzname)));
4626 result = 0; /* keep compiler quiet */
4630 PG_RETURN_TIMESTAMP(result);
4633 /* timestamptz_izone()
4634 * Encode timestamp with time zone type with specified time interval as time zone.
4635 * Returns a timestamp without time zone.
4638 timestamptz_izone(PG_FUNCTION_ARGS)
4640 Interval *zone = PG_GETARG_INTERVAL_P(0);
4641 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
4645 if (TIMESTAMP_NOT_FINITE(timestamp))
4646 PG_RETURN_TIMESTAMP(timestamp);
4648 if (zone->month != 0)
4650 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4651 errmsg("interval time zone \"%s\" must not specify month",
4652 DatumGetCString(DirectFunctionCall1(interval_out,
4653 PointerGetDatum(zone))))));
4655 #ifdef HAVE_INT64_TIMESTAMP
4656 tz = -(zone->time / USECS_PER_SEC);
4661 result = dt2local(timestamp, tz);
4663 PG_RETURN_TIMESTAMP(result);
4666 /* generate_series_timestamp()
4667 * Generate the set of timestamps from start to finish by step
4670 generate_series_timestamp(PG_FUNCTION_ARGS)
4672 FuncCallContext *funcctx;
4673 generate_series_timestamp_fctx *fctx;
4676 /* stuff done only on the first call of the function */
4677 if (SRF_IS_FIRSTCALL())
4679 Timestamp start = PG_GETARG_TIMESTAMP(0);
4680 Timestamp finish = PG_GETARG_TIMESTAMP(1);
4681 Interval *step = PG_GETARG_INTERVAL_P(2);
4682 MemoryContext oldcontext;
4683 Interval interval_zero;
4685 /* create a function context for cross-call persistence */
4686 funcctx = SRF_FIRSTCALL_INIT();
4689 * switch to memory context appropriate for multiple function calls
4691 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4693 /* allocate memory for user context */
4694 fctx = (generate_series_timestamp_fctx *)
4695 palloc(sizeof(generate_series_timestamp_fctx));
4698 * Use fctx to keep state from call to call. Seed current with the
4699 * original start value
4701 fctx->current = start;
4702 fctx->finish = finish;
4705 /* Determine sign of the interval */
4706 MemSet(&interval_zero, 0, sizeof(Interval));
4707 fctx->step_sign = interval_cmp_internal(&fctx->step, &interval_zero);
4709 if (fctx->step_sign == 0)
4711 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4712 errmsg("step size cannot equal zero")));
4714 funcctx->user_fctx = fctx;
4715 MemoryContextSwitchTo(oldcontext);
4718 /* stuff done on every call of the function */
4719 funcctx = SRF_PERCALL_SETUP();
4722 * get the saved state and use current as the result for this iteration
4724 fctx = funcctx->user_fctx;
4725 result = fctx->current;
4727 if (fctx->step_sign > 0 ?
4728 timestamp_cmp_internal(result, fctx->finish) <= 0 :
4729 timestamp_cmp_internal(result, fctx->finish) >= 0)
4731 /* increment current in preparation for next iteration */
4732 fctx->current = DatumGetTimestamp(
4733 DirectFunctionCall2(timestamp_pl_interval,
4734 TimestampGetDatum(fctx->current),
4735 PointerGetDatum(&fctx->step)));
4737 /* do when there is more left to send */
4738 SRF_RETURN_NEXT(funcctx, TimestampGetDatum(result));
4742 /* do when there is no more left */
4743 SRF_RETURN_DONE(funcctx);
4747 /* generate_series_timestamptz()
4748 * Generate the set of timestamps from start to finish by step
4751 generate_series_timestamptz(PG_FUNCTION_ARGS)
4753 FuncCallContext *funcctx;
4754 generate_series_timestamptz_fctx *fctx;
4757 /* stuff done only on the first call of the function */
4758 if (SRF_IS_FIRSTCALL())
4760 TimestampTz start = PG_GETARG_TIMESTAMPTZ(0);
4761 TimestampTz finish = PG_GETARG_TIMESTAMPTZ(1);
4762 Interval *step = PG_GETARG_INTERVAL_P(2);
4763 MemoryContext oldcontext;
4764 Interval interval_zero;
4766 /* create a function context for cross-call persistence */
4767 funcctx = SRF_FIRSTCALL_INIT();
4770 * switch to memory context appropriate for multiple function calls
4772 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
4774 /* allocate memory for user context */
4775 fctx = (generate_series_timestamptz_fctx *)
4776 palloc(sizeof(generate_series_timestamptz_fctx));
4779 * Use fctx to keep state from call to call. Seed current with the
4780 * original start value
4782 fctx->current = start;
4783 fctx->finish = finish;
4786 /* Determine sign of the interval */
4787 MemSet(&interval_zero, 0, sizeof(Interval));
4788 fctx->step_sign = interval_cmp_internal(&fctx->step, &interval_zero);
4790 if (fctx->step_sign == 0)
4792 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4793 errmsg("step size cannot equal zero")));
4795 funcctx->user_fctx = fctx;
4796 MemoryContextSwitchTo(oldcontext);
4799 /* stuff done on every call of the function */
4800 funcctx = SRF_PERCALL_SETUP();
4803 * get the saved state and use current as the result for this iteration
4805 fctx = funcctx->user_fctx;
4806 result = fctx->current;
4808 if (fctx->step_sign > 0 ?
4809 timestamp_cmp_internal(result, fctx->finish) <= 0 :
4810 timestamp_cmp_internal(result, fctx->finish) >= 0)
4812 /* increment current in preparation for next iteration */
4813 fctx->current = DatumGetTimestampTz(
4814 DirectFunctionCall2(timestamptz_pl_interval,
4815 TimestampTzGetDatum(fctx->current),
4816 PointerGetDatum(&fctx->step)));
4818 /* do when there is more left to send */
4819 SRF_RETURN_NEXT(funcctx, TimestampTzGetDatum(result));
4823 /* do when there is no more left */
4824 SRF_RETURN_DONE(funcctx);