1 /*-------------------------------------------------------------------------
4 * Functions for the built-in SQL types "timestamp" and "interval".
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/utils/adt/timestamp.c
13 *-------------------------------------------------------------------------
23 #include "access/xact.h"
24 #include "catalog/pg_type.h"
25 #include "common/int.h"
26 #include "common/int128.h"
28 #include "libpq/pqformat.h"
29 #include "miscadmin.h"
30 #include "nodes/nodeFuncs.h"
31 #include "nodes/supportnodes.h"
32 #include "optimizer/optimizer.h"
33 #include "parser/scansup.h"
34 #include "utils/array.h"
35 #include "utils/builtins.h"
36 #include "utils/date.h"
37 #include "utils/datetime.h"
38 #include "utils/float.h"
39 #include "utils/numeric.h"
40 #include "utils/sortsupport.h"
43 * gcc's -ffast-math switch breaks routines that expect exact results from
44 * expressions like timeval / SECS_PER_HOUR, where timeval is double.
47 #error -ffast-math is known to break this code
50 #define SAMESIGN(a,b) (((a) < 0) == ((b) < 0))
52 /* Set at postmaster start */
53 TimestampTz PgStartTime
;
55 /* Set at configuration reload */
56 TimestampTz PgReloadTime
;
64 } generate_series_timestamp_fctx
;
73 } generate_series_timestamptz_fctx
;
76 * The transition datatype for interval aggregates is declared as internal.
77 * It's a pointer to an IntervalAggState allocated in the aggregate context.
79 typedef struct IntervalAggState
81 int64 N
; /* count of finite intervals processed */
82 Interval sumX
; /* sum of finite intervals processed */
83 /* These counts are *not* included in N! Use IA_TOTAL_COUNT() as needed */
84 int64 pInfcount
; /* count of +infinity intervals */
85 int64 nInfcount
; /* count of -infinity intervals */
88 #define IA_TOTAL_COUNT(ia) \
89 ((ia)->N + (ia)->pInfcount + (ia)->nInfcount)
91 static TimeOffset
time2t(const int hour
, const int min
, const int sec
, const fsec_t fsec
);
92 static Timestamp
dt2local(Timestamp dt
, int timezone
);
93 static bool AdjustIntervalForTypmod(Interval
*interval
, int32 typmod
,
95 static TimestampTz
timestamp2timestamptz(Timestamp timestamp
);
96 static Timestamp
timestamptz2timestamp(TimestampTz timestamp
);
98 static void EncodeSpecialInterval(const Interval
*interval
, char *str
);
99 static void interval_um_internal(const Interval
*interval
, Interval
*result
);
101 /* common code for timestamptypmodin and timestamptztypmodin */
103 anytimestamp_typmodin(bool istz
, ArrayType
*ta
)
108 tl
= ArrayGetIntegerTypmods(ta
, &n
);
111 * we're not too tense about good error message here because grammar
112 * shouldn't allow wrong number of modifiers for TIMESTAMP
116 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
117 errmsg("invalid type modifier")));
119 return anytimestamp_typmod_check(istz
, tl
[0]);
122 /* exported so parse_expr.c can use it */
124 anytimestamp_typmod_check(bool istz
, int32 typmod
)
128 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
129 errmsg("TIMESTAMP(%d)%s precision must not be negative",
130 typmod
, (istz
? " WITH TIME ZONE" : ""))));
131 if (typmod
> MAX_TIMESTAMP_PRECISION
)
134 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
135 errmsg("TIMESTAMP(%d)%s precision reduced to maximum allowed, %d",
136 typmod
, (istz
? " WITH TIME ZONE" : ""),
137 MAX_TIMESTAMP_PRECISION
)));
138 typmod
= MAX_TIMESTAMP_PRECISION
;
144 /* common code for timestamptypmodout and timestamptztypmodout */
146 anytimestamp_typmodout(bool istz
, int32 typmod
)
148 const char *tz
= istz
? " with time zone" : " without time zone";
151 return psprintf("(%d)%s", (int) typmod
, tz
);
157 /*****************************************************************************
158 * USER I/O ROUTINES *
159 *****************************************************************************/
162 * Convert a string to internal form.
165 timestamp_in(PG_FUNCTION_ARGS
)
167 char *str
= PG_GETARG_CSTRING(0);
169 Oid typelem
= PG_GETARG_OID(1);
171 int32 typmod
= PG_GETARG_INT32(2);
172 Node
*escontext
= fcinfo
->context
;
181 char *field
[MAXDATEFIELDS
];
182 int ftype
[MAXDATEFIELDS
];
183 char workbuf
[MAXDATELEN
+ MAXDATEFIELDS
];
184 DateTimeErrorExtra extra
;
186 dterr
= ParseDateTime(str
, workbuf
, sizeof(workbuf
),
187 field
, ftype
, MAXDATEFIELDS
, &nf
);
189 dterr
= DecodeDateTime(field
, ftype
, nf
,
190 &dtype
, tm
, &fsec
, &tz
, &extra
);
193 DateTimeParseError(dterr
, &extra
, str
, "timestamp", escontext
);
200 if (tm2timestamp(tm
, fsec
, NULL
, &result
) != 0)
201 ereturn(escontext
, (Datum
) 0,
202 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
203 errmsg("timestamp out of range: \"%s\"", str
)));
207 result
= SetEpochTimestamp();
211 TIMESTAMP_NOEND(result
);
215 TIMESTAMP_NOBEGIN(result
);
219 elog(ERROR
, "unexpected dtype %d while parsing timestamp \"%s\"",
221 TIMESTAMP_NOEND(result
);
224 AdjustTimestampForTypmod(&result
, typmod
, escontext
);
226 PG_RETURN_TIMESTAMP(result
);
230 * Convert a timestamp to external form.
233 timestamp_out(PG_FUNCTION_ARGS
)
235 Timestamp timestamp
= PG_GETARG_TIMESTAMP(0);
240 char buf
[MAXDATELEN
+ 1];
242 if (TIMESTAMP_NOT_FINITE(timestamp
))
243 EncodeSpecialTimestamp(timestamp
, buf
);
244 else if (timestamp2tm(timestamp
, NULL
, tm
, &fsec
, NULL
, NULL
) == 0)
245 EncodeDateTime(tm
, fsec
, false, 0, NULL
, DateStyle
, buf
);
248 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
249 errmsg("timestamp out of range")));
251 result
= pstrdup(buf
);
252 PG_RETURN_CSTRING(result
);
256 * timestamp_recv - converts external binary format to timestamp
259 timestamp_recv(PG_FUNCTION_ARGS
)
261 StringInfo buf
= (StringInfo
) PG_GETARG_POINTER(0);
264 Oid typelem
= PG_GETARG_OID(1);
266 int32 typmod
= PG_GETARG_INT32(2);
272 timestamp
= (Timestamp
) pq_getmsgint64(buf
);
274 /* range check: see if timestamp_out would like it */
275 if (TIMESTAMP_NOT_FINITE(timestamp
))
277 else if (timestamp2tm(timestamp
, NULL
, tm
, &fsec
, NULL
, NULL
) != 0 ||
278 !IS_VALID_TIMESTAMP(timestamp
))
280 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
281 errmsg("timestamp out of range")));
283 AdjustTimestampForTypmod(×tamp
, typmod
, NULL
);
285 PG_RETURN_TIMESTAMP(timestamp
);
289 * timestamp_send - converts timestamp to binary format
292 timestamp_send(PG_FUNCTION_ARGS
)
294 Timestamp timestamp
= PG_GETARG_TIMESTAMP(0);
297 pq_begintypsend(&buf
);
298 pq_sendint64(&buf
, timestamp
);
299 PG_RETURN_BYTEA_P(pq_endtypsend(&buf
));
303 timestamptypmodin(PG_FUNCTION_ARGS
)
305 ArrayType
*ta
= PG_GETARG_ARRAYTYPE_P(0);
307 PG_RETURN_INT32(anytimestamp_typmodin(false, ta
));
311 timestamptypmodout(PG_FUNCTION_ARGS
)
313 int32 typmod
= PG_GETARG_INT32(0);
315 PG_RETURN_CSTRING(anytimestamp_typmodout(false, typmod
));
320 * timestamp_support()
322 * Planner support function for the timestamp_scale() and timestamptz_scale()
323 * length coercion functions (we need not distinguish them here).
326 timestamp_support(PG_FUNCTION_ARGS
)
328 Node
*rawreq
= (Node
*) PG_GETARG_POINTER(0);
331 if (IsA(rawreq
, SupportRequestSimplify
))
333 SupportRequestSimplify
*req
= (SupportRequestSimplify
*) rawreq
;
335 ret
= TemporalSimplify(MAX_TIMESTAMP_PRECISION
, (Node
*) req
->fcall
);
338 PG_RETURN_POINTER(ret
);
342 * Adjust time type for specified scale factor.
343 * Used by PostgreSQL type system to stuff columns.
346 timestamp_scale(PG_FUNCTION_ARGS
)
348 Timestamp timestamp
= PG_GETARG_TIMESTAMP(0);
349 int32 typmod
= PG_GETARG_INT32(1);
354 AdjustTimestampForTypmod(&result
, typmod
, NULL
);
356 PG_RETURN_TIMESTAMP(result
);
360 * AdjustTimestampForTypmod --- round off a timestamp to suit given typmod
361 * Works for either timestamp or timestamptz.
363 * Returns true on success, false on failure (if escontext points to an
364 * ErrorSaveContext; otherwise errors are thrown).
367 AdjustTimestampForTypmod(Timestamp
*time
, int32 typmod
, Node
*escontext
)
369 static const int64 TimestampScales
[MAX_TIMESTAMP_PRECISION
+ 1] = {
379 static const int64 TimestampOffsets
[MAX_TIMESTAMP_PRECISION
+ 1] = {
389 if (!TIMESTAMP_NOT_FINITE(*time
)
390 && (typmod
!= -1) && (typmod
!= MAX_TIMESTAMP_PRECISION
))
392 if (typmod
< 0 || typmod
> MAX_TIMESTAMP_PRECISION
)
393 ereturn(escontext
, false,
394 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
395 errmsg("timestamp(%d) precision must be between %d and %d",
396 typmod
, 0, MAX_TIMESTAMP_PRECISION
)));
398 if (*time
>= INT64CONST(0))
400 *time
= ((*time
+ TimestampOffsets
[typmod
]) / TimestampScales
[typmod
]) *
401 TimestampScales
[typmod
];
405 *time
= -((((-*time
) + TimestampOffsets
[typmod
]) / TimestampScales
[typmod
])
406 * TimestampScales
[typmod
]);
414 * Convert a string to internal form.
417 timestamptz_in(PG_FUNCTION_ARGS
)
419 char *str
= PG_GETARG_CSTRING(0);
421 Oid typelem
= PG_GETARG_OID(1);
423 int32 typmod
= PG_GETARG_INT32(2);
424 Node
*escontext
= fcinfo
->context
;
433 char *field
[MAXDATEFIELDS
];
434 int ftype
[MAXDATEFIELDS
];
435 char workbuf
[MAXDATELEN
+ MAXDATEFIELDS
];
436 DateTimeErrorExtra extra
;
438 dterr
= ParseDateTime(str
, workbuf
, sizeof(workbuf
),
439 field
, ftype
, MAXDATEFIELDS
, &nf
);
441 dterr
= DecodeDateTime(field
, ftype
, nf
,
442 &dtype
, tm
, &fsec
, &tz
, &extra
);
445 DateTimeParseError(dterr
, &extra
, str
, "timestamp with time zone",
453 if (tm2timestamp(tm
, fsec
, &tz
, &result
) != 0)
454 ereturn(escontext
, (Datum
) 0,
455 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
456 errmsg("timestamp out of range: \"%s\"", str
)));
460 result
= SetEpochTimestamp();
464 TIMESTAMP_NOEND(result
);
468 TIMESTAMP_NOBEGIN(result
);
472 elog(ERROR
, "unexpected dtype %d while parsing timestamptz \"%s\"",
474 TIMESTAMP_NOEND(result
);
477 AdjustTimestampForTypmod(&result
, typmod
, escontext
);
479 PG_RETURN_TIMESTAMPTZ(result
);
483 * Try to parse a timezone specification, and return its timezone offset value
484 * if it's acceptable. Otherwise, an error is thrown.
486 * Note: some code paths update tm->tm_isdst, and some don't; current callers
487 * don't care, so we don't bother being consistent.
490 parse_sane_timezone(struct pg_tm
*tm
, text
*zone
)
492 char tzname
[TZ_STRLEN_MAX
+ 1];
496 text_to_cstring_buffer(zone
, tzname
, sizeof(tzname
));
499 * Look up the requested timezone. First we try to interpret it as a
500 * numeric timezone specification; if DecodeTimezone decides it doesn't
501 * like the format, we try timezone abbreviations and names.
503 * Note pg_tzset happily parses numeric input that DecodeTimezone would
504 * reject. To avoid having it accept input that would otherwise be seen
505 * as invalid, it's enough to disallow having a digit in the first
506 * position of our input string.
508 if (isdigit((unsigned char) *tzname
))
510 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
511 errmsg("invalid input syntax for type %s: \"%s\"",
512 "numeric time zone", tzname
),
513 errhint("Numeric time zones must have \"-\" or \"+\" as first character.")));
515 dterr
= DecodeTimezone(tzname
, &tz
);
522 if (dterr
== DTERR_TZDISP_OVERFLOW
)
524 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
525 errmsg("numeric time zone \"%s\" out of range", tzname
)));
526 else if (dterr
!= DTERR_BAD_FORMAT
)
528 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
529 errmsg("time zone \"%s\" not recognized", tzname
)));
531 type
= DecodeTimezoneName(tzname
, &val
, &tzp
);
533 if (type
== TZNAME_FIXED_OFFSET
)
535 /* fixed-offset abbreviation */
538 else if (type
== TZNAME_DYNTZ
)
540 /* dynamic-offset abbreviation, resolve using specified time */
541 tz
= DetermineTimeZoneAbbrevOffset(tm
, tzname
, tzp
);
546 tz
= DetermineTimeZoneOffset(tm
, tzp
);
554 * Look up the requested timezone, returning a pg_tz struct.
556 * This is the same as DecodeTimezoneNameToTz, but starting with a text Datum.
559 lookup_timezone(text
*zone
)
561 char tzname
[TZ_STRLEN_MAX
+ 1];
563 text_to_cstring_buffer(zone
, tzname
, sizeof(tzname
));
565 return DecodeTimezoneNameToTz(tzname
);
569 * make_timestamp_internal
570 * workhorse for make_timestamp and make_timestamptz
573 make_timestamp_internal(int year
, int month
, int day
,
574 int hour
, int min
, double sec
)
587 /* Handle negative years as BC */
591 tm
.tm_year
= -tm
.tm_year
;
594 dterr
= ValidateDate(DTK_DATE_M
, false, false, bc
, &tm
);
598 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW
),
599 errmsg("date field value out of range: %d-%02d-%02d",
602 if (!IS_VALID_JULIAN(tm
.tm_year
, tm
.tm_mon
, tm
.tm_mday
))
604 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
605 errmsg("date out of range: %d-%02d-%02d",
608 date
= date2j(tm
.tm_year
, tm
.tm_mon
, tm
.tm_mday
) - POSTGRES_EPOCH_JDATE
;
610 /* Check for time overflow */
611 if (float_time_overflows(hour
, min
, sec
))
613 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW
),
614 errmsg("time field value out of range: %d:%02d:%02g",
617 /* This should match tm2time */
618 time
= (((hour
* MINS_PER_HOUR
+ min
) * SECS_PER_MINUTE
)
619 * USECS_PER_SEC
) + (int64
) rint(sec
* USECS_PER_SEC
);
621 if (unlikely(pg_mul_s64_overflow(date
, USECS_PER_DAY
, &result
) ||
622 pg_add_s64_overflow(result
, time
, &result
)))
624 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
625 errmsg("timestamp out of range: %d-%02d-%02d %d:%02d:%02g",
629 /* final range check catches just-out-of-range timestamps */
630 if (!IS_VALID_TIMESTAMP(result
))
632 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
633 errmsg("timestamp out of range: %d-%02d-%02d %d:%02d:%02g",
641 * make_timestamp() - timestamp constructor
644 make_timestamp(PG_FUNCTION_ARGS
)
646 int32 year
= PG_GETARG_INT32(0);
647 int32 month
= PG_GETARG_INT32(1);
648 int32 mday
= PG_GETARG_INT32(2);
649 int32 hour
= PG_GETARG_INT32(3);
650 int32 min
= PG_GETARG_INT32(4);
651 float8 sec
= PG_GETARG_FLOAT8(5);
654 result
= make_timestamp_internal(year
, month
, mday
,
657 PG_RETURN_TIMESTAMP(result
);
661 * make_timestamptz() - timestamp with time zone constructor
664 make_timestamptz(PG_FUNCTION_ARGS
)
666 int32 year
= PG_GETARG_INT32(0);
667 int32 month
= PG_GETARG_INT32(1);
668 int32 mday
= PG_GETARG_INT32(2);
669 int32 hour
= PG_GETARG_INT32(3);
670 int32 min
= PG_GETARG_INT32(4);
671 float8 sec
= PG_GETARG_FLOAT8(5);
674 result
= make_timestamp_internal(year
, month
, mday
,
677 PG_RETURN_TIMESTAMPTZ(timestamp2timestamptz(result
));
681 * Construct a timestamp with time zone.
682 * As above, but the time zone is specified as seventh argument.
685 make_timestamptz_at_timezone(PG_FUNCTION_ARGS
)
687 int32 year
= PG_GETARG_INT32(0);
688 int32 month
= PG_GETARG_INT32(1);
689 int32 mday
= PG_GETARG_INT32(2);
690 int32 hour
= PG_GETARG_INT32(3);
691 int32 min
= PG_GETARG_INT32(4);
692 float8 sec
= PG_GETARG_FLOAT8(5);
693 text
*zone
= PG_GETARG_TEXT_PP(6);
700 timestamp
= make_timestamp_internal(year
, month
, mday
,
703 if (timestamp2tm(timestamp
, NULL
, &tt
, &fsec
, NULL
, NULL
) != 0)
705 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
706 errmsg("timestamp out of range")));
708 tz
= parse_sane_timezone(&tt
, zone
);
710 result
= dt2local(timestamp
, -tz
);
712 if (!IS_VALID_TIMESTAMP(result
))
714 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
715 errmsg("timestamp out of range")));
717 PG_RETURN_TIMESTAMPTZ(result
);
721 * to_timestamp(double precision)
722 * Convert UNIX epoch to timestamptz.
725 float8_timestamptz(PG_FUNCTION_ARGS
)
727 float8 seconds
= PG_GETARG_FLOAT8(0);
730 /* Deal with NaN and infinite inputs ... */
733 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
734 errmsg("timestamp cannot be NaN")));
739 TIMESTAMP_NOBEGIN(result
);
741 TIMESTAMP_NOEND(result
);
747 (float8
) SECS_PER_DAY
* (DATETIME_MIN_JULIAN
- UNIX_EPOCH_JDATE
)
749 (float8
) SECS_PER_DAY
* (TIMESTAMP_END_JULIAN
- UNIX_EPOCH_JDATE
))
751 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
752 errmsg("timestamp out of range: \"%g\"", seconds
)));
754 /* Convert UNIX epoch to Postgres epoch */
755 seconds
-= ((POSTGRES_EPOCH_JDATE
- UNIX_EPOCH_JDATE
) * SECS_PER_DAY
);
757 seconds
= rint(seconds
* USECS_PER_SEC
);
758 result
= (int64
) seconds
;
760 /* Recheck in case roundoff produces something just out of range */
761 if (!IS_VALID_TIMESTAMP(result
))
763 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
764 errmsg("timestamp out of range: \"%g\"",
765 PG_GETARG_FLOAT8(0))));
768 PG_RETURN_TIMESTAMP(result
);
772 * Convert a timestamp to external form.
775 timestamptz_out(PG_FUNCTION_ARGS
)
777 TimestampTz dt
= PG_GETARG_TIMESTAMPTZ(0);
784 char buf
[MAXDATELEN
+ 1];
786 if (TIMESTAMP_NOT_FINITE(dt
))
787 EncodeSpecialTimestamp(dt
, buf
);
788 else if (timestamp2tm(dt
, &tz
, tm
, &fsec
, &tzn
, NULL
) == 0)
789 EncodeDateTime(tm
, fsec
, true, tz
, tzn
, DateStyle
, buf
);
792 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
793 errmsg("timestamp out of range")));
795 result
= pstrdup(buf
);
796 PG_RETURN_CSTRING(result
);
800 * timestamptz_recv - converts external binary format to timestamptz
803 timestamptz_recv(PG_FUNCTION_ARGS
)
805 StringInfo buf
= (StringInfo
) PG_GETARG_POINTER(0);
808 Oid typelem
= PG_GETARG_OID(1);
810 int32 typmod
= PG_GETARG_INT32(2);
811 TimestampTz timestamp
;
817 timestamp
= (TimestampTz
) pq_getmsgint64(buf
);
819 /* range check: see if timestamptz_out would like it */
820 if (TIMESTAMP_NOT_FINITE(timestamp
))
822 else if (timestamp2tm(timestamp
, &tz
, tm
, &fsec
, NULL
, NULL
) != 0 ||
823 !IS_VALID_TIMESTAMP(timestamp
))
825 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
826 errmsg("timestamp out of range")));
828 AdjustTimestampForTypmod(×tamp
, typmod
, NULL
);
830 PG_RETURN_TIMESTAMPTZ(timestamp
);
834 * timestamptz_send - converts timestamptz to binary format
837 timestamptz_send(PG_FUNCTION_ARGS
)
839 TimestampTz timestamp
= PG_GETARG_TIMESTAMPTZ(0);
842 pq_begintypsend(&buf
);
843 pq_sendint64(&buf
, timestamp
);
844 PG_RETURN_BYTEA_P(pq_endtypsend(&buf
));
848 timestamptztypmodin(PG_FUNCTION_ARGS
)
850 ArrayType
*ta
= PG_GETARG_ARRAYTYPE_P(0);
852 PG_RETURN_INT32(anytimestamp_typmodin(true, ta
));
856 timestamptztypmodout(PG_FUNCTION_ARGS
)
858 int32 typmod
= PG_GETARG_INT32(0);
860 PG_RETURN_CSTRING(anytimestamp_typmodout(true, typmod
));
864 /* timestamptz_scale()
865 * Adjust time type for specified scale factor.
866 * Used by PostgreSQL type system to stuff columns.
869 timestamptz_scale(PG_FUNCTION_ARGS
)
871 TimestampTz timestamp
= PG_GETARG_TIMESTAMPTZ(0);
872 int32 typmod
= PG_GETARG_INT32(1);
877 AdjustTimestampForTypmod(&result
, typmod
, NULL
);
879 PG_RETURN_TIMESTAMPTZ(result
);
884 * Convert a string to internal form.
886 * External format(s):
887 * Uses the generic date/time parsing and decoding routines.
890 interval_in(PG_FUNCTION_ARGS
)
892 char *str
= PG_GETARG_CSTRING(0);
894 Oid typelem
= PG_GETARG_OID(1);
896 int32 typmod
= PG_GETARG_INT32(2);
897 Node
*escontext
= fcinfo
->context
;
905 char *field
[MAXDATEFIELDS
];
906 int ftype
[MAXDATEFIELDS
];
908 DateTimeErrorExtra extra
;
916 range
= INTERVAL_RANGE(typmod
);
918 range
= INTERVAL_FULL_RANGE
;
920 dterr
= ParseDateTime(str
, workbuf
, sizeof(workbuf
), field
,
921 ftype
, MAXDATEFIELDS
, &nf
);
923 dterr
= DecodeInterval(field
, ftype
, nf
, range
,
926 /* if those functions think it's a bad format, try ISO8601 style */
927 if (dterr
== DTERR_BAD_FORMAT
)
928 dterr
= DecodeISO8601Interval(str
,
933 if (dterr
== DTERR_FIELD_OVERFLOW
)
934 dterr
= DTERR_INTERVAL_OVERFLOW
;
935 DateTimeParseError(dterr
, &extra
, str
, "interval", escontext
);
939 result
= (Interval
*) palloc(sizeof(Interval
));
944 if (itmin2interval(itm_in
, result
) != 0)
945 ereturn(escontext
, (Datum
) 0,
946 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
947 errmsg("interval out of range")));
951 INTERVAL_NOEND(result
);
955 INTERVAL_NOBEGIN(result
);
959 elog(ERROR
, "unexpected dtype %d while parsing interval \"%s\"",
963 AdjustIntervalForTypmod(result
, typmod
, escontext
);
965 PG_RETURN_INTERVAL_P(result
);
969 * Convert a time span to external form.
972 interval_out(PG_FUNCTION_ARGS
)
974 Interval
*span
= PG_GETARG_INTERVAL_P(0);
978 char buf
[MAXDATELEN
+ 1];
980 if (INTERVAL_NOT_FINITE(span
))
981 EncodeSpecialInterval(span
, buf
);
984 interval2itm(*span
, itm
);
985 EncodeInterval(itm
, IntervalStyle
, buf
);
988 result
= pstrdup(buf
);
989 PG_RETURN_CSTRING(result
);
993 * interval_recv - converts external binary format to interval
996 interval_recv(PG_FUNCTION_ARGS
)
998 StringInfo buf
= (StringInfo
) PG_GETARG_POINTER(0);
1001 Oid typelem
= PG_GETARG_OID(1);
1003 int32 typmod
= PG_GETARG_INT32(2);
1006 interval
= (Interval
*) palloc(sizeof(Interval
));
1008 interval
->time
= pq_getmsgint64(buf
);
1009 interval
->day
= pq_getmsgint(buf
, sizeof(interval
->day
));
1010 interval
->month
= pq_getmsgint(buf
, sizeof(interval
->month
));
1012 AdjustIntervalForTypmod(interval
, typmod
, NULL
);
1014 PG_RETURN_INTERVAL_P(interval
);
1018 * interval_send - converts interval to binary format
1021 interval_send(PG_FUNCTION_ARGS
)
1023 Interval
*interval
= PG_GETARG_INTERVAL_P(0);
1026 pq_begintypsend(&buf
);
1027 pq_sendint64(&buf
, interval
->time
);
1028 pq_sendint32(&buf
, interval
->day
);
1029 pq_sendint32(&buf
, interval
->month
);
1030 PG_RETURN_BYTEA_P(pq_endtypsend(&buf
));
1034 * The interval typmod stores a "range" in its high 16 bits and a "precision"
1035 * in its low 16 bits. Both contribute to defining the resolution of the
1036 * type. Range addresses resolution granules larger than one second, and
1037 * precision specifies resolution below one second. This representation can
1038 * express all SQL standard resolutions, but we implement them all in terms of
1039 * truncating rightward from some position. Range is a bitmap of permitted
1040 * fields, but only the temporally-smallest such field is significant to our
1041 * calculations. Precision is a count of sub-second decimal places to retain.
1042 * Setting all bits (INTERVAL_FULL_PRECISION) gives the same truncation
1043 * semantics as choosing MAX_INTERVAL_PRECISION.
1046 intervaltypmodin(PG_FUNCTION_ARGS
)
1048 ArrayType
*ta
= PG_GETARG_ARRAYTYPE_P(0);
1053 tl
= ArrayGetIntegerTypmods(ta
, &n
);
1056 * tl[0] - interval range (fields bitmask) tl[1] - precision (optional)
1058 * Note we must validate tl[0] even though it's normally guaranteed
1059 * correct by the grammar --- consider SELECT 'foo'::"interval"(1000).
1065 case INTERVAL_MASK(YEAR
):
1066 case INTERVAL_MASK(MONTH
):
1067 case INTERVAL_MASK(DAY
):
1068 case INTERVAL_MASK(HOUR
):
1069 case INTERVAL_MASK(MINUTE
):
1070 case INTERVAL_MASK(SECOND
):
1071 case INTERVAL_MASK(YEAR
) | INTERVAL_MASK(MONTH
):
1072 case INTERVAL_MASK(DAY
) | INTERVAL_MASK(HOUR
):
1073 case INTERVAL_MASK(DAY
) | INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
):
1074 case INTERVAL_MASK(DAY
) | INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
) | INTERVAL_MASK(SECOND
):
1075 case INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
):
1076 case INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
) | INTERVAL_MASK(SECOND
):
1077 case INTERVAL_MASK(MINUTE
) | INTERVAL_MASK(SECOND
):
1078 case INTERVAL_FULL_RANGE
:
1083 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
1084 errmsg("invalid INTERVAL type modifier")));
1090 if (tl
[0] != INTERVAL_FULL_RANGE
)
1091 typmod
= INTERVAL_TYPMOD(INTERVAL_FULL_PRECISION
, tl
[0]);
1099 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
1100 errmsg("INTERVAL(%d) precision must not be negative",
1102 if (tl
[1] > MAX_INTERVAL_PRECISION
)
1105 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
1106 errmsg("INTERVAL(%d) precision reduced to maximum allowed, %d",
1107 tl
[1], MAX_INTERVAL_PRECISION
)));
1108 typmod
= INTERVAL_TYPMOD(MAX_INTERVAL_PRECISION
, tl
[0]);
1111 typmod
= INTERVAL_TYPMOD(tl
[1], tl
[0]);
1116 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
1117 errmsg("invalid INTERVAL type modifier")));
1118 typmod
= 0; /* keep compiler quiet */
1121 PG_RETURN_INT32(typmod
);
1125 intervaltypmodout(PG_FUNCTION_ARGS
)
1127 int32 typmod
= PG_GETARG_INT32(0);
1128 char *res
= (char *) palloc(64);
1131 const char *fieldstr
;
1136 PG_RETURN_CSTRING(res
);
1139 fields
= INTERVAL_RANGE(typmod
);
1140 precision
= INTERVAL_PRECISION(typmod
);
1144 case INTERVAL_MASK(YEAR
):
1147 case INTERVAL_MASK(MONTH
):
1148 fieldstr
= " month";
1150 case INTERVAL_MASK(DAY
):
1153 case INTERVAL_MASK(HOUR
):
1156 case INTERVAL_MASK(MINUTE
):
1157 fieldstr
= " minute";
1159 case INTERVAL_MASK(SECOND
):
1160 fieldstr
= " second";
1162 case INTERVAL_MASK(YEAR
) | INTERVAL_MASK(MONTH
):
1163 fieldstr
= " year to month";
1165 case INTERVAL_MASK(DAY
) | INTERVAL_MASK(HOUR
):
1166 fieldstr
= " day to hour";
1168 case INTERVAL_MASK(DAY
) | INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
):
1169 fieldstr
= " day to minute";
1171 case INTERVAL_MASK(DAY
) | INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
) | INTERVAL_MASK(SECOND
):
1172 fieldstr
= " day to second";
1174 case INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
):
1175 fieldstr
= " hour to minute";
1177 case INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
) | INTERVAL_MASK(SECOND
):
1178 fieldstr
= " hour to second";
1180 case INTERVAL_MASK(MINUTE
) | INTERVAL_MASK(SECOND
):
1181 fieldstr
= " minute to second";
1183 case INTERVAL_FULL_RANGE
:
1187 elog(ERROR
, "invalid INTERVAL typmod: 0x%x", typmod
);
1192 if (precision
!= INTERVAL_FULL_PRECISION
)
1193 snprintf(res
, 64, "%s(%d)", fieldstr
, precision
);
1195 snprintf(res
, 64, "%s", fieldstr
);
1197 PG_RETURN_CSTRING(res
);
1201 * Given an interval typmod value, return a code for the least-significant
1202 * field that the typmod allows to be nonzero, for instance given
1203 * INTERVAL DAY TO HOUR we want to identify "hour".
1205 * The results should be ordered by field significance, which means
1206 * we can't use the dt.h macros YEAR etc, because for some odd reason
1207 * they aren't ordered that way. Instead, arbitrarily represent
1208 * SECOND = 0, MINUTE = 1, HOUR = 2, DAY = 3, MONTH = 4, YEAR = 5.
1211 intervaltypmodleastfield(int32 typmod
)
1214 return 0; /* SECOND */
1216 switch (INTERVAL_RANGE(typmod
))
1218 case INTERVAL_MASK(YEAR
):
1219 return 5; /* YEAR */
1220 case INTERVAL_MASK(MONTH
):
1221 return 4; /* MONTH */
1222 case INTERVAL_MASK(DAY
):
1224 case INTERVAL_MASK(HOUR
):
1225 return 2; /* HOUR */
1226 case INTERVAL_MASK(MINUTE
):
1227 return 1; /* MINUTE */
1228 case INTERVAL_MASK(SECOND
):
1229 return 0; /* SECOND */
1230 case INTERVAL_MASK(YEAR
) | INTERVAL_MASK(MONTH
):
1231 return 4; /* MONTH */
1232 case INTERVAL_MASK(DAY
) | INTERVAL_MASK(HOUR
):
1233 return 2; /* HOUR */
1234 case INTERVAL_MASK(DAY
) | INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
):
1235 return 1; /* MINUTE */
1236 case INTERVAL_MASK(DAY
) | INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
) | INTERVAL_MASK(SECOND
):
1237 return 0; /* SECOND */
1238 case INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
):
1239 return 1; /* MINUTE */
1240 case INTERVAL_MASK(HOUR
) | INTERVAL_MASK(MINUTE
) | INTERVAL_MASK(SECOND
):
1241 return 0; /* SECOND */
1242 case INTERVAL_MASK(MINUTE
) | INTERVAL_MASK(SECOND
):
1243 return 0; /* SECOND */
1244 case INTERVAL_FULL_RANGE
:
1245 return 0; /* SECOND */
1247 elog(ERROR
, "invalid INTERVAL typmod: 0x%x", typmod
);
1250 return 0; /* can't get here, but keep compiler quiet */
1255 * interval_support()
1257 * Planner support function for interval_scale().
1259 * Flatten superfluous calls to interval_scale(). The interval typmod is
1260 * complex to permit accepting and regurgitating all SQL standard variations.
1261 * For truncation purposes, it boils down to a single, simple granularity.
1264 interval_support(PG_FUNCTION_ARGS
)
1266 Node
*rawreq
= (Node
*) PG_GETARG_POINTER(0);
1269 if (IsA(rawreq
, SupportRequestSimplify
))
1271 SupportRequestSimplify
*req
= (SupportRequestSimplify
*) rawreq
;
1272 FuncExpr
*expr
= req
->fcall
;
1275 Assert(list_length(expr
->args
) >= 2);
1277 typmod
= (Node
*) lsecond(expr
->args
);
1279 if (IsA(typmod
, Const
) && !((Const
*) typmod
)->constisnull
)
1281 Node
*source
= (Node
*) linitial(expr
->args
);
1282 int32 new_typmod
= DatumGetInt32(((Const
*) typmod
)->constvalue
);
1289 int32 old_typmod
= exprTypmod(source
);
1290 int old_least_field
;
1291 int new_least_field
;
1295 old_least_field
= intervaltypmodleastfield(old_typmod
);
1296 new_least_field
= intervaltypmodleastfield(new_typmod
);
1298 old_precis
= INTERVAL_FULL_PRECISION
;
1300 old_precis
= INTERVAL_PRECISION(old_typmod
);
1301 new_precis
= INTERVAL_PRECISION(new_typmod
);
1304 * Cast is a no-op if least field stays the same or decreases
1305 * while precision stays the same or increases. But
1306 * precision, which is to say, sub-second precision, only
1307 * affects ranges that include SECOND.
1309 noop
= (new_least_field
<= old_least_field
) &&
1310 (old_least_field
> 0 /* SECOND */ ||
1311 new_precis
>= MAX_INTERVAL_PRECISION
||
1312 new_precis
>= old_precis
);
1315 ret
= relabel_to_typmod(source
, new_typmod
);
1319 PG_RETURN_POINTER(ret
);
1323 * Adjust interval type for specified fields.
1324 * Used by PostgreSQL type system to stuff columns.
1327 interval_scale(PG_FUNCTION_ARGS
)
1329 Interval
*interval
= PG_GETARG_INTERVAL_P(0);
1330 int32 typmod
= PG_GETARG_INT32(1);
1333 result
= palloc(sizeof(Interval
));
1334 *result
= *interval
;
1336 AdjustIntervalForTypmod(result
, typmod
, NULL
);
1338 PG_RETURN_INTERVAL_P(result
);
1342 * Adjust interval for specified precision, in both YEAR to SECOND
1343 * range and sub-second precision.
1345 * Returns true on success, false on failure (if escontext points to an
1346 * ErrorSaveContext; otherwise errors are thrown).
1349 AdjustIntervalForTypmod(Interval
*interval
, int32 typmod
,
1352 static const int64 IntervalScales
[MAX_INTERVAL_PRECISION
+ 1] = {
1353 INT64CONST(1000000),
1362 static const int64 IntervalOffsets
[MAX_INTERVAL_PRECISION
+ 1] = {
1372 /* Typmod has no effect on infinite intervals */
1373 if (INTERVAL_NOT_FINITE(interval
))
1377 * Unspecified range and precision? Then not necessary to adjust. Setting
1378 * typmod to -1 is the convention for all data types.
1382 int range
= INTERVAL_RANGE(typmod
);
1383 int precision
= INTERVAL_PRECISION(typmod
);
1386 * Our interpretation of intervals with a limited set of fields is
1387 * that fields to the right of the last one specified are zeroed out,
1388 * but those to the left of it remain valid. Thus for example there
1389 * is no operational difference between INTERVAL YEAR TO MONTH and
1390 * INTERVAL MONTH. In some cases we could meaningfully enforce that
1391 * higher-order fields are zero; for example INTERVAL DAY could reject
1392 * nonzero "month" field. However that seems a bit pointless when we
1393 * can't do it consistently. (We cannot enforce a range limit on the
1394 * highest expected field, since we do not have any equivalent of
1395 * SQL's <interval leading field precision>.) If we ever decide to
1396 * revisit this, interval_support will likely require adjusting.
1398 * Note: before PG 8.4 we interpreted a limited set of fields as
1399 * actually causing a "modulo" operation on a given value, potentially
1400 * losing high-order as well as low-order information. But there is
1401 * no support for such behavior in the standard, and it seems fairly
1402 * undesirable on data consistency grounds anyway. Now we only
1403 * perform truncation or rounding of low-order fields.
1405 if (range
== INTERVAL_FULL_RANGE
)
1409 else if (range
== INTERVAL_MASK(YEAR
))
1411 interval
->month
= (interval
->month
/ MONTHS_PER_YEAR
) * MONTHS_PER_YEAR
;
1415 else if (range
== INTERVAL_MASK(MONTH
))
1421 else if (range
== (INTERVAL_MASK(YEAR
) | INTERVAL_MASK(MONTH
)))
1426 else if (range
== INTERVAL_MASK(DAY
))
1430 else if (range
== INTERVAL_MASK(HOUR
))
1432 interval
->time
= (interval
->time
/ USECS_PER_HOUR
) *
1435 else if (range
== INTERVAL_MASK(MINUTE
))
1437 interval
->time
= (interval
->time
/ USECS_PER_MINUTE
) *
1440 else if (range
== INTERVAL_MASK(SECOND
))
1442 /* fractional-second rounding will be dealt with below */
1445 else if (range
== (INTERVAL_MASK(DAY
) |
1446 INTERVAL_MASK(HOUR
)))
1448 interval
->time
= (interval
->time
/ USECS_PER_HOUR
) *
1452 else if (range
== (INTERVAL_MASK(DAY
) |
1453 INTERVAL_MASK(HOUR
) |
1454 INTERVAL_MASK(MINUTE
)))
1456 interval
->time
= (interval
->time
/ USECS_PER_MINUTE
) *
1460 else if (range
== (INTERVAL_MASK(DAY
) |
1461 INTERVAL_MASK(HOUR
) |
1462 INTERVAL_MASK(MINUTE
) |
1463 INTERVAL_MASK(SECOND
)))
1465 /* fractional-second rounding will be dealt with below */
1467 /* HOUR TO MINUTE */
1468 else if (range
== (INTERVAL_MASK(HOUR
) |
1469 INTERVAL_MASK(MINUTE
)))
1471 interval
->time
= (interval
->time
/ USECS_PER_MINUTE
) *
1474 /* HOUR TO SECOND */
1475 else if (range
== (INTERVAL_MASK(HOUR
) |
1476 INTERVAL_MASK(MINUTE
) |
1477 INTERVAL_MASK(SECOND
)))
1479 /* fractional-second rounding will be dealt with below */
1481 /* MINUTE TO SECOND */
1482 else if (range
== (INTERVAL_MASK(MINUTE
) |
1483 INTERVAL_MASK(SECOND
)))
1485 /* fractional-second rounding will be dealt with below */
1488 elog(ERROR
, "unrecognized interval typmod: %d", typmod
);
1490 /* Need to adjust sub-second precision? */
1491 if (precision
!= INTERVAL_FULL_PRECISION
)
1493 if (precision
< 0 || precision
> MAX_INTERVAL_PRECISION
)
1494 ereturn(escontext
, false,
1495 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
1496 errmsg("interval(%d) precision must be between %d and %d",
1497 precision
, 0, MAX_INTERVAL_PRECISION
)));
1499 if (interval
->time
>= INT64CONST(0))
1501 if (pg_add_s64_overflow(interval
->time
,
1502 IntervalOffsets
[precision
],
1504 ereturn(escontext
, false,
1505 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
1506 errmsg("interval out of range")));
1507 interval
->time
-= interval
->time
% IntervalScales
[precision
];
1511 if (pg_sub_s64_overflow(interval
->time
,
1512 IntervalOffsets
[precision
],
1514 ereturn(escontext
, false,
1515 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
1516 errmsg("interval out of range")));
1517 interval
->time
-= interval
->time
% IntervalScales
[precision
];
1526 * make_interval - numeric Interval constructor
1529 make_interval(PG_FUNCTION_ARGS
)
1531 int32 years
= PG_GETARG_INT32(0);
1532 int32 months
= PG_GETARG_INT32(1);
1533 int32 weeks
= PG_GETARG_INT32(2);
1534 int32 days
= PG_GETARG_INT32(3);
1535 int32 hours
= PG_GETARG_INT32(4);
1536 int32 mins
= PG_GETARG_INT32(5);
1537 double secs
= PG_GETARG_FLOAT8(6);
1541 * Reject out-of-range inputs. We reject any input values that cause
1542 * integer overflow of the corresponding interval fields.
1544 if (isinf(secs
) || isnan(secs
))
1547 result
= (Interval
*) palloc(sizeof(Interval
));
1549 /* years and months -> months */
1550 if (pg_mul_s32_overflow(years
, MONTHS_PER_YEAR
, &result
->month
) ||
1551 pg_add_s32_overflow(result
->month
, months
, &result
->month
))
1554 /* weeks and days -> days */
1555 if (pg_mul_s32_overflow(weeks
, DAYS_PER_WEEK
, &result
->day
) ||
1556 pg_add_s32_overflow(result
->day
, days
, &result
->day
))
1559 /* hours and mins -> usecs (cannot overflow 64-bit) */
1560 result
->time
= hours
* USECS_PER_HOUR
+ mins
* USECS_PER_MINUTE
;
1563 secs
= rint(float8_mul(secs
, USECS_PER_SEC
));
1564 if (!FLOAT8_FITS_IN_INT64(secs
) ||
1565 pg_add_s64_overflow(result
->time
, (int64
) secs
, &result
->time
))
1568 /* make sure that the result is finite */
1569 if (INTERVAL_NOT_FINITE(result
))
1572 PG_RETURN_INTERVAL_P(result
);
1576 errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
1577 errmsg("interval out of range"));
1579 PG_RETURN_NULL(); /* keep compiler quiet */
1582 /* EncodeSpecialTimestamp()
1583 * Convert reserved timestamp data type to string.
1586 EncodeSpecialTimestamp(Timestamp dt
, char *str
)
1588 if (TIMESTAMP_IS_NOBEGIN(dt
))
1590 else if (TIMESTAMP_IS_NOEND(dt
))
1592 else /* shouldn't happen */
1593 elog(ERROR
, "invalid argument for EncodeSpecialTimestamp");
1597 EncodeSpecialInterval(const Interval
*interval
, char *str
)
1599 if (INTERVAL_IS_NOBEGIN(interval
))
1601 else if (INTERVAL_IS_NOEND(interval
))
1603 else /* shouldn't happen */
1604 elog(ERROR
, "invalid argument for EncodeSpecialInterval");
1608 now(PG_FUNCTION_ARGS
)
1610 PG_RETURN_TIMESTAMPTZ(GetCurrentTransactionStartTimestamp());
1614 statement_timestamp(PG_FUNCTION_ARGS
)
1616 PG_RETURN_TIMESTAMPTZ(GetCurrentStatementStartTimestamp());
1620 clock_timestamp(PG_FUNCTION_ARGS
)
1622 PG_RETURN_TIMESTAMPTZ(GetCurrentTimestamp());
1626 pg_postmaster_start_time(PG_FUNCTION_ARGS
)
1628 PG_RETURN_TIMESTAMPTZ(PgStartTime
);
1632 pg_conf_load_time(PG_FUNCTION_ARGS
)
1634 PG_RETURN_TIMESTAMPTZ(PgReloadTime
);
1638 * GetCurrentTimestamp -- get the current operating system time
1640 * Result is in the form of a TimestampTz value, and is expressed to the
1641 * full precision of the gettimeofday() syscall
1644 GetCurrentTimestamp(void)
1649 gettimeofday(&tp
, NULL
);
1651 result
= (TimestampTz
) tp
.tv_sec
-
1652 ((POSTGRES_EPOCH_JDATE
- UNIX_EPOCH_JDATE
) * SECS_PER_DAY
);
1653 result
= (result
* USECS_PER_SEC
) + tp
.tv_usec
;
1659 * GetSQLCurrentTimestamp -- implements CURRENT_TIMESTAMP, CURRENT_TIMESTAMP(n)
1662 GetSQLCurrentTimestamp(int32 typmod
)
1666 ts
= GetCurrentTransactionStartTimestamp();
1668 AdjustTimestampForTypmod(&ts
, typmod
, NULL
);
1673 * GetSQLLocalTimestamp -- implements LOCALTIMESTAMP, LOCALTIMESTAMP(n)
1676 GetSQLLocalTimestamp(int32 typmod
)
1680 ts
= timestamptz2timestamp(GetCurrentTransactionStartTimestamp());
1682 AdjustTimestampForTypmod(&ts
, typmod
, NULL
);
1687 * timeofday(*) -- returns the current time as a text.
1690 timeofday(PG_FUNCTION_ARGS
)
1697 gettimeofday(&tp
, NULL
);
1698 tt
= (pg_time_t
) tp
.tv_sec
;
1699 pg_strftime(templ
, sizeof(templ
), "%a %b %d %H:%M:%S.%%06d %Y %Z",
1700 pg_localtime(&tt
, session_timezone
));
1701 snprintf(buf
, sizeof(buf
), templ
, tp
.tv_usec
);
1703 PG_RETURN_TEXT_P(cstring_to_text(buf
));
1707 * TimestampDifference -- convert the difference between two timestamps
1708 * into integer seconds and microseconds
1710 * This is typically used to calculate a wait timeout for select(2),
1711 * which explains the otherwise-odd choice of output format.
1713 * Both inputs must be ordinary finite timestamps (in current usage,
1714 * they'll be results from GetCurrentTimestamp()).
1716 * We expect start_time <= stop_time. If not, we return zeros,
1717 * since then we're already past the previously determined stop_time.
1720 TimestampDifference(TimestampTz start_time
, TimestampTz stop_time
,
1721 long *secs
, int *microsecs
)
1723 TimestampTz diff
= stop_time
- start_time
;
1732 *secs
= (long) (diff
/ USECS_PER_SEC
);
1733 *microsecs
= (int) (diff
% USECS_PER_SEC
);
1738 * TimestampDifferenceMilliseconds -- convert the difference between two
1739 * timestamps into integer milliseconds
1741 * This is typically used to calculate a wait timeout for WaitLatch()
1742 * or a related function. The choice of "long" as the result type
1743 * is to harmonize with that; furthermore, we clamp the result to at most
1744 * INT_MAX milliseconds, because that's all that WaitLatch() allows.
1746 * We expect start_time <= stop_time. If not, we return zero,
1747 * since then we're already past the previously determined stop_time.
1749 * Subtracting finite and infinite timestamps works correctly, returning
1750 * zero or INT_MAX as appropriate.
1752 * Note we round up any fractional millisecond, since waiting for just
1753 * less than the intended timeout is undesirable.
1756 TimestampDifferenceMilliseconds(TimestampTz start_time
, TimestampTz stop_time
)
1760 /* Deal with zero or negative elapsed time quickly. */
1761 if (start_time
>= stop_time
)
1763 /* To not fail with timestamp infinities, we must detect overflow. */
1764 if (pg_sub_s64_overflow(stop_time
, start_time
, &diff
))
1765 return (long) INT_MAX
;
1766 if (diff
>= (INT_MAX
* INT64CONST(1000) - 999))
1767 return (long) INT_MAX
;
1769 return (long) ((diff
+ 999) / 1000);
1773 * TimestampDifferenceExceeds -- report whether the difference between two
1774 * timestamps is >= a threshold (expressed in milliseconds)
1776 * Both inputs must be ordinary finite timestamps (in current usage,
1777 * they'll be results from GetCurrentTimestamp()).
1780 TimestampDifferenceExceeds(TimestampTz start_time
,
1781 TimestampTz stop_time
,
1784 TimestampTz diff
= stop_time
- start_time
;
1786 return (diff
>= msec
* INT64CONST(1000));
1790 * Convert a time_t to TimestampTz.
1792 * We do not use time_t internally in Postgres, but this is provided for use
1793 * by functions that need to interpret, say, a stat(2) result.
1795 * To avoid having the function's ABI vary depending on the width of time_t,
1796 * we declare the argument as pg_time_t, which is cast-compatible with
1797 * time_t but always 64 bits wide (unless the platform has no 64-bit type).
1798 * This detail should be invisible to callers, at least at source code level.
1801 time_t_to_timestamptz(pg_time_t tm
)
1805 result
= (TimestampTz
) tm
-
1806 ((POSTGRES_EPOCH_JDATE
- UNIX_EPOCH_JDATE
) * SECS_PER_DAY
);
1807 result
*= USECS_PER_SEC
;
1813 * Convert a TimestampTz to time_t.
1815 * This too is just marginally useful, but some places need it.
1817 * To avoid having the function's ABI vary depending on the width of time_t,
1818 * we declare the result as pg_time_t, which is cast-compatible with
1819 * time_t but always 64 bits wide (unless the platform has no 64-bit type).
1820 * This detail should be invisible to callers, at least at source code level.
1823 timestamptz_to_time_t(TimestampTz t
)
1827 result
= (pg_time_t
) (t
/ USECS_PER_SEC
+
1828 ((POSTGRES_EPOCH_JDATE
- UNIX_EPOCH_JDATE
) * SECS_PER_DAY
));
1834 * Produce a C-string representation of a TimestampTz.
1836 * This is mostly for use in emitting messages. The primary difference
1837 * from timestamptz_out is that we force the output format to ISO. Note
1838 * also that the result is in a static buffer, not pstrdup'd.
1840 * See also pg_strftime.
1843 timestamptz_to_str(TimestampTz t
)
1845 static char buf
[MAXDATELEN
+ 1];
1852 if (TIMESTAMP_NOT_FINITE(t
))
1853 EncodeSpecialTimestamp(t
, buf
);
1854 else if (timestamp2tm(t
, &tz
, tm
, &fsec
, &tzn
, NULL
) == 0)
1855 EncodeDateTime(tm
, fsec
, true, tz
, tzn
, USE_ISO_DATES
, buf
);
1857 strlcpy(buf
, "(timestamp out of range)", sizeof(buf
));
1864 dt2time(Timestamp jd
, int *hour
, int *min
, int *sec
, fsec_t
*fsec
)
1870 *hour
= time
/ USECS_PER_HOUR
;
1871 time
-= (*hour
) * USECS_PER_HOUR
;
1872 *min
= time
/ USECS_PER_MINUTE
;
1873 time
-= (*min
) * USECS_PER_MINUTE
;
1874 *sec
= time
/ USECS_PER_SEC
;
1875 *fsec
= time
- (*sec
* USECS_PER_SEC
);
1880 * timestamp2tm() - Convert timestamp data type to POSIX time structure.
1882 * Note that year is _not_ 1900-based, but is an explicit full value.
1883 * Also, month is one-based, _not_ zero-based.
1886 * -1 on out of range
1888 * If attimezone is NULL, the global timezone setting will be used.
1891 timestamp2tm(Timestamp dt
, int *tzp
, struct pg_tm
*tm
, fsec_t
*fsec
, const char **tzn
, pg_tz
*attimezone
)
1897 /* Use session timezone if caller asks for default */
1898 if (attimezone
== NULL
)
1899 attimezone
= session_timezone
;
1902 TMODULO(time
, date
, USECS_PER_DAY
);
1904 if (time
< INT64CONST(0))
1906 time
+= USECS_PER_DAY
;
1910 /* add offset to go from J2000 back to standard Julian date */
1911 date
+= POSTGRES_EPOCH_JDATE
;
1913 /* Julian day routine does not work for negative Julian days */
1914 if (date
< 0 || date
> (Timestamp
) INT_MAX
)
1917 j2date((int) date
, &tm
->tm_year
, &tm
->tm_mon
, &tm
->tm_mday
);
1918 dt2time(time
, &tm
->tm_hour
, &tm
->tm_min
, &tm
->tm_sec
, fsec
);
1920 /* Done if no TZ conversion wanted */
1932 * If the time falls within the range of pg_time_t, use pg_localtime() to
1933 * rotate to the local time zone.
1935 * First, convert to an integral timestamp, avoiding possibly
1936 * platform-specific roundoff-in-wrong-direction errors, and adjust to
1937 * Unix epoch. Then see if we can convert to pg_time_t without loss. This
1938 * coding avoids hardwiring any assumptions about the width of pg_time_t,
1939 * so it should behave sanely on machines without int64.
1941 dt
= (dt
- *fsec
) / USECS_PER_SEC
+
1942 (POSTGRES_EPOCH_JDATE
- UNIX_EPOCH_JDATE
) * SECS_PER_DAY
;
1943 utime
= (pg_time_t
) dt
;
1944 if ((Timestamp
) utime
== dt
)
1946 struct pg_tm
*tx
= pg_localtime(&utime
, attimezone
);
1948 tm
->tm_year
= tx
->tm_year
+ 1900;
1949 tm
->tm_mon
= tx
->tm_mon
+ 1;
1950 tm
->tm_mday
= tx
->tm_mday
;
1951 tm
->tm_hour
= tx
->tm_hour
;
1952 tm
->tm_min
= tx
->tm_min
;
1953 tm
->tm_sec
= tx
->tm_sec
;
1954 tm
->tm_isdst
= tx
->tm_isdst
;
1955 tm
->tm_gmtoff
= tx
->tm_gmtoff
;
1956 tm
->tm_zone
= tx
->tm_zone
;
1957 *tzp
= -tm
->tm_gmtoff
;
1964 * When out of range of pg_time_t, treat as GMT
1967 /* Mark this as *no* time zone available */
1980 * Convert a tm structure to a timestamp data type.
1981 * Note that year is _not_ 1900-based, but is an explicit full value.
1982 * Also, month is one-based, _not_ zero-based.
1984 * Returns -1 on failure (value out of range).
1987 tm2timestamp(struct pg_tm
*tm
, fsec_t fsec
, int *tzp
, Timestamp
*result
)
1992 /* Prevent overflow in Julian-day routines */
1993 if (!IS_VALID_JULIAN(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
))
1995 *result
= 0; /* keep compiler quiet */
1999 date
= date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
) - POSTGRES_EPOCH_JDATE
;
2000 time
= time2t(tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
, fsec
);
2002 if (unlikely(pg_mul_s64_overflow(date
, USECS_PER_DAY
, result
) ||
2003 pg_add_s64_overflow(*result
, time
, result
)))
2005 *result
= 0; /* keep compiler quiet */
2009 *result
= dt2local(*result
, -(*tzp
));
2011 /* final range check catches just-out-of-range timestamps */
2012 if (!IS_VALID_TIMESTAMP(*result
))
2014 *result
= 0; /* keep compiler quiet */
2023 * Convert an Interval to a pg_itm structure.
2024 * Note: overflow is not possible, because the pg_itm fields are
2025 * wide enough for all possible conversion results.
2028 interval2itm(Interval span
, struct pg_itm
*itm
)
2033 itm
->tm_year
= span
.month
/ MONTHS_PER_YEAR
;
2034 itm
->tm_mon
= span
.month
% MONTHS_PER_YEAR
;
2035 itm
->tm_mday
= span
.day
;
2038 tfrac
= time
/ USECS_PER_HOUR
;
2039 time
-= tfrac
* USECS_PER_HOUR
;
2040 itm
->tm_hour
= tfrac
;
2041 tfrac
= time
/ USECS_PER_MINUTE
;
2042 time
-= tfrac
* USECS_PER_MINUTE
;
2043 itm
->tm_min
= (int) tfrac
;
2044 tfrac
= time
/ USECS_PER_SEC
;
2045 time
-= tfrac
* USECS_PER_SEC
;
2046 itm
->tm_sec
= (int) tfrac
;
2047 itm
->tm_usec
= (int) time
;
2051 * Convert a pg_itm structure to an Interval.
2052 * Returns 0 if OK, -1 on overflow.
2054 * This is for use in computations expected to produce finite results. Any
2055 * inputs that lead to infinite results are treated as overflows.
2058 itm2interval(struct pg_itm
*itm
, Interval
*span
)
2060 int64 total_months
= (int64
) itm
->tm_year
* MONTHS_PER_YEAR
+ itm
->tm_mon
;
2062 if (total_months
> INT_MAX
|| total_months
< INT_MIN
)
2064 span
->month
= (int32
) total_months
;
2065 span
->day
= itm
->tm_mday
;
2066 if (pg_mul_s64_overflow(itm
->tm_hour
, USECS_PER_HOUR
,
2069 /* tm_min, tm_sec are 32 bits, so intermediate products can't overflow */
2070 if (pg_add_s64_overflow(span
->time
, itm
->tm_min
* USECS_PER_MINUTE
,
2073 if (pg_add_s64_overflow(span
->time
, itm
->tm_sec
* USECS_PER_SEC
,
2076 if (pg_add_s64_overflow(span
->time
, itm
->tm_usec
,
2079 if (INTERVAL_NOT_FINITE(span
))
2085 * Convert a pg_itm_in structure to an Interval.
2086 * Returns 0 if OK, -1 on overflow.
2088 * Note: if the result is infinite, it is not treated as an overflow. This
2089 * avoids any dump/reload hazards from pre-17 databases that do not support
2090 * infinite intervals, but do allow finite intervals with all fields set to
2091 * INT_MIN/INT_MAX (outside the documented range). Such intervals will be
2092 * silently converted to +/-infinity. This may not be ideal, but seems
2093 * preferable to failure, and ought to be pretty unlikely in practice.
2096 itmin2interval(struct pg_itm_in
*itm_in
, Interval
*span
)
2098 int64 total_months
= (int64
) itm_in
->tm_year
* MONTHS_PER_YEAR
+ itm_in
->tm_mon
;
2100 if (total_months
> INT_MAX
|| total_months
< INT_MIN
)
2102 span
->month
= (int32
) total_months
;
2103 span
->day
= itm_in
->tm_mday
;
2104 span
->time
= itm_in
->tm_usec
;
2109 time2t(const int hour
, const int min
, const int sec
, const fsec_t fsec
)
2111 return (((((hour
* MINS_PER_HOUR
) + min
) * SECS_PER_MINUTE
) + sec
) * USECS_PER_SEC
) + fsec
;
2115 dt2local(Timestamp dt
, int timezone
)
2117 dt
-= (timezone
* USECS_PER_SEC
);
2122 /*****************************************************************************
2124 *****************************************************************************/
2128 timestamp_finite(PG_FUNCTION_ARGS
)
2130 Timestamp timestamp
= PG_GETARG_TIMESTAMP(0);
2132 PG_RETURN_BOOL(!TIMESTAMP_NOT_FINITE(timestamp
));
2136 interval_finite(PG_FUNCTION_ARGS
)
2138 Interval
*interval
= PG_GETARG_INTERVAL_P(0);
2140 PG_RETURN_BOOL(!INTERVAL_NOT_FINITE(interval
));
2144 /*----------------------------------------------------------
2145 * Relational operators for timestamp.
2146 *---------------------------------------------------------*/
2149 GetEpochTime(struct pg_tm
*tm
)
2152 pg_time_t epoch
= 0;
2154 t0
= pg_gmtime(&epoch
);
2157 elog(ERROR
, "could not convert epoch to timestamp: %m");
2159 tm
->tm_year
= t0
->tm_year
;
2160 tm
->tm_mon
= t0
->tm_mon
;
2161 tm
->tm_mday
= t0
->tm_mday
;
2162 tm
->tm_hour
= t0
->tm_hour
;
2163 tm
->tm_min
= t0
->tm_min
;
2164 tm
->tm_sec
= t0
->tm_sec
;
2166 tm
->tm_year
+= 1900;
2171 SetEpochTimestamp(void)
2178 /* we don't bother to test for failure ... */
2179 tm2timestamp(tm
, 0, NULL
, &dt
);
2182 } /* SetEpochTimestamp() */
2185 * We are currently sharing some code between timestamp and timestamptz.
2186 * The comparison functions are among them. - thomas 2001-09-25
2188 * timestamp_relop - is timestamp1 relop timestamp2
2191 timestamp_cmp_internal(Timestamp dt1
, Timestamp dt2
)
2193 return (dt1
< dt2
) ? -1 : ((dt1
> dt2
) ? 1 : 0);
2197 timestamp_eq(PG_FUNCTION_ARGS
)
2199 Timestamp dt1
= PG_GETARG_TIMESTAMP(0);
2200 Timestamp dt2
= PG_GETARG_TIMESTAMP(1);
2202 PG_RETURN_BOOL(timestamp_cmp_internal(dt1
, dt2
) == 0);
2206 timestamp_ne(PG_FUNCTION_ARGS
)
2208 Timestamp dt1
= PG_GETARG_TIMESTAMP(0);
2209 Timestamp dt2
= PG_GETARG_TIMESTAMP(1);
2211 PG_RETURN_BOOL(timestamp_cmp_internal(dt1
, dt2
) != 0);
2215 timestamp_lt(PG_FUNCTION_ARGS
)
2217 Timestamp dt1
= PG_GETARG_TIMESTAMP(0);
2218 Timestamp dt2
= PG_GETARG_TIMESTAMP(1);
2220 PG_RETURN_BOOL(timestamp_cmp_internal(dt1
, dt2
) < 0);
2224 timestamp_gt(PG_FUNCTION_ARGS
)
2226 Timestamp dt1
= PG_GETARG_TIMESTAMP(0);
2227 Timestamp dt2
= PG_GETARG_TIMESTAMP(1);
2229 PG_RETURN_BOOL(timestamp_cmp_internal(dt1
, dt2
) > 0);
2233 timestamp_le(PG_FUNCTION_ARGS
)
2235 Timestamp dt1
= PG_GETARG_TIMESTAMP(0);
2236 Timestamp dt2
= PG_GETARG_TIMESTAMP(1);
2238 PG_RETURN_BOOL(timestamp_cmp_internal(dt1
, dt2
) <= 0);
2242 timestamp_ge(PG_FUNCTION_ARGS
)
2244 Timestamp dt1
= PG_GETARG_TIMESTAMP(0);
2245 Timestamp dt2
= PG_GETARG_TIMESTAMP(1);
2247 PG_RETURN_BOOL(timestamp_cmp_internal(dt1
, dt2
) >= 0);
2251 timestamp_cmp(PG_FUNCTION_ARGS
)
2253 Timestamp dt1
= PG_GETARG_TIMESTAMP(0);
2254 Timestamp dt2
= PG_GETARG_TIMESTAMP(1);
2256 PG_RETURN_INT32(timestamp_cmp_internal(dt1
, dt2
));
2259 #if SIZEOF_DATUM < 8
2260 /* note: this is used for timestamptz also */
2262 timestamp_fastcmp(Datum x
, Datum y
, SortSupport ssup
)
2264 Timestamp a
= DatumGetTimestamp(x
);
2265 Timestamp b
= DatumGetTimestamp(y
);
2267 return timestamp_cmp_internal(a
, b
);
2272 timestamp_sortsupport(PG_FUNCTION_ARGS
)
2274 SortSupport ssup
= (SortSupport
) PG_GETARG_POINTER(0);
2276 #if SIZEOF_DATUM >= 8
2279 * If this build has pass-by-value timestamps, then we can use a standard
2280 * comparator function.
2282 ssup
->comparator
= ssup_datum_signed_cmp
;
2284 ssup
->comparator
= timestamp_fastcmp
;
2290 timestamp_hash(PG_FUNCTION_ARGS
)
2292 return hashint8(fcinfo
);
2296 timestamp_hash_extended(PG_FUNCTION_ARGS
)
2298 return hashint8extended(fcinfo
);
2302 timestamptz_hash(PG_FUNCTION_ARGS
)
2304 return hashint8(fcinfo
);
2308 timestamptz_hash_extended(PG_FUNCTION_ARGS
)
2310 return hashint8extended(fcinfo
);
2314 * Cross-type comparison functions for timestamp vs timestamptz
2318 timestamp_cmp_timestamptz_internal(Timestamp timestampVal
, TimestampTz dt2
)
2323 dt1
= timestamp2timestamptz_opt_overflow(timestampVal
, &overflow
);
2326 /* dt1 is larger than any finite timestamp, but less than infinity */
2327 return TIMESTAMP_IS_NOEND(dt2
) ? -1 : +1;
2331 /* dt1 is less than any finite timestamp, but more than -infinity */
2332 return TIMESTAMP_IS_NOBEGIN(dt2
) ? +1 : -1;
2335 return timestamptz_cmp_internal(dt1
, dt2
);
2339 timestamp_eq_timestamptz(PG_FUNCTION_ARGS
)
2341 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(0);
2342 TimestampTz dt2
= PG_GETARG_TIMESTAMPTZ(1);
2344 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal
, dt2
) == 0);
2348 timestamp_ne_timestamptz(PG_FUNCTION_ARGS
)
2350 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(0);
2351 TimestampTz dt2
= PG_GETARG_TIMESTAMPTZ(1);
2353 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal
, dt2
) != 0);
2357 timestamp_lt_timestamptz(PG_FUNCTION_ARGS
)
2359 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(0);
2360 TimestampTz dt2
= PG_GETARG_TIMESTAMPTZ(1);
2362 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal
, dt2
) < 0);
2366 timestamp_gt_timestamptz(PG_FUNCTION_ARGS
)
2368 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(0);
2369 TimestampTz dt2
= PG_GETARG_TIMESTAMPTZ(1);
2371 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal
, dt2
) > 0);
2375 timestamp_le_timestamptz(PG_FUNCTION_ARGS
)
2377 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(0);
2378 TimestampTz dt2
= PG_GETARG_TIMESTAMPTZ(1);
2380 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal
, dt2
) <= 0);
2384 timestamp_ge_timestamptz(PG_FUNCTION_ARGS
)
2386 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(0);
2387 TimestampTz dt2
= PG_GETARG_TIMESTAMPTZ(1);
2389 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal
, dt2
) >= 0);
2393 timestamp_cmp_timestamptz(PG_FUNCTION_ARGS
)
2395 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(0);
2396 TimestampTz dt2
= PG_GETARG_TIMESTAMPTZ(1);
2398 PG_RETURN_INT32(timestamp_cmp_timestamptz_internal(timestampVal
, dt2
));
2402 timestamptz_eq_timestamp(PG_FUNCTION_ARGS
)
2404 TimestampTz dt1
= PG_GETARG_TIMESTAMPTZ(0);
2405 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(1);
2407 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal
, dt1
) == 0);
2411 timestamptz_ne_timestamp(PG_FUNCTION_ARGS
)
2413 TimestampTz dt1
= PG_GETARG_TIMESTAMPTZ(0);
2414 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(1);
2416 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal
, dt1
) != 0);
2420 timestamptz_lt_timestamp(PG_FUNCTION_ARGS
)
2422 TimestampTz dt1
= PG_GETARG_TIMESTAMPTZ(0);
2423 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(1);
2425 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal
, dt1
) > 0);
2429 timestamptz_gt_timestamp(PG_FUNCTION_ARGS
)
2431 TimestampTz dt1
= PG_GETARG_TIMESTAMPTZ(0);
2432 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(1);
2434 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal
, dt1
) < 0);
2438 timestamptz_le_timestamp(PG_FUNCTION_ARGS
)
2440 TimestampTz dt1
= PG_GETARG_TIMESTAMPTZ(0);
2441 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(1);
2443 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal
, dt1
) >= 0);
2447 timestamptz_ge_timestamp(PG_FUNCTION_ARGS
)
2449 TimestampTz dt1
= PG_GETARG_TIMESTAMPTZ(0);
2450 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(1);
2452 PG_RETURN_BOOL(timestamp_cmp_timestamptz_internal(timestampVal
, dt1
) <= 0);
2456 timestamptz_cmp_timestamp(PG_FUNCTION_ARGS
)
2458 TimestampTz dt1
= PG_GETARG_TIMESTAMPTZ(0);
2459 Timestamp timestampVal
= PG_GETARG_TIMESTAMP(1);
2461 PG_RETURN_INT32(-timestamp_cmp_timestamptz_internal(timestampVal
, dt1
));
2466 * interval_relop - is interval1 relop interval2
2468 * Interval comparison is based on converting interval values to a linear
2469 * representation expressed in the units of the time field (microseconds,
2470 * in the case of integer timestamps) with days assumed to be always 24 hours
2471 * and months assumed to be always 30 days. To avoid overflow, we need a
2472 * wider-than-int64 datatype for the linear representation, so use INT128.
2475 static inline INT128
2476 interval_cmp_value(const Interval
*interval
)
2482 * Combine the month and day fields into an integral number of days.
2483 * Because the inputs are int32, int64 arithmetic suffices here.
2485 days
= interval
->month
* INT64CONST(30);
2486 days
+= interval
->day
;
2488 /* Widen time field to 128 bits */
2489 span
= int64_to_int128(interval
->time
);
2491 /* Scale up days to microseconds, forming a 128-bit product */
2492 int128_add_int64_mul_int64(&span
, days
, USECS_PER_DAY
);
2498 interval_cmp_internal(const Interval
*interval1
, const Interval
*interval2
)
2500 INT128 span1
= interval_cmp_value(interval1
);
2501 INT128 span2
= interval_cmp_value(interval2
);
2503 return int128_compare(span1
, span2
);
2507 interval_sign(const Interval
*interval
)
2509 INT128 span
= interval_cmp_value(interval
);
2510 INT128 zero
= int64_to_int128(0);
2512 return int128_compare(span
, zero
);
2516 interval_eq(PG_FUNCTION_ARGS
)
2518 Interval
*interval1
= PG_GETARG_INTERVAL_P(0);
2519 Interval
*interval2
= PG_GETARG_INTERVAL_P(1);
2521 PG_RETURN_BOOL(interval_cmp_internal(interval1
, interval2
) == 0);
2525 interval_ne(PG_FUNCTION_ARGS
)
2527 Interval
*interval1
= PG_GETARG_INTERVAL_P(0);
2528 Interval
*interval2
= PG_GETARG_INTERVAL_P(1);
2530 PG_RETURN_BOOL(interval_cmp_internal(interval1
, interval2
) != 0);
2534 interval_lt(PG_FUNCTION_ARGS
)
2536 Interval
*interval1
= PG_GETARG_INTERVAL_P(0);
2537 Interval
*interval2
= PG_GETARG_INTERVAL_P(1);
2539 PG_RETURN_BOOL(interval_cmp_internal(interval1
, interval2
) < 0);
2543 interval_gt(PG_FUNCTION_ARGS
)
2545 Interval
*interval1
= PG_GETARG_INTERVAL_P(0);
2546 Interval
*interval2
= PG_GETARG_INTERVAL_P(1);
2548 PG_RETURN_BOOL(interval_cmp_internal(interval1
, interval2
) > 0);
2552 interval_le(PG_FUNCTION_ARGS
)
2554 Interval
*interval1
= PG_GETARG_INTERVAL_P(0);
2555 Interval
*interval2
= PG_GETARG_INTERVAL_P(1);
2557 PG_RETURN_BOOL(interval_cmp_internal(interval1
, interval2
) <= 0);
2561 interval_ge(PG_FUNCTION_ARGS
)
2563 Interval
*interval1
= PG_GETARG_INTERVAL_P(0);
2564 Interval
*interval2
= PG_GETARG_INTERVAL_P(1);
2566 PG_RETURN_BOOL(interval_cmp_internal(interval1
, interval2
) >= 0);
2570 interval_cmp(PG_FUNCTION_ARGS
)
2572 Interval
*interval1
= PG_GETARG_INTERVAL_P(0);
2573 Interval
*interval2
= PG_GETARG_INTERVAL_P(1);
2575 PG_RETURN_INT32(interval_cmp_internal(interval1
, interval2
));
2579 * Hashing for intervals
2581 * We must produce equal hashvals for values that interval_cmp_internal()
2582 * considers equal. So, compute the net span the same way it does,
2583 * and then hash that.
2586 interval_hash(PG_FUNCTION_ARGS
)
2588 Interval
*interval
= PG_GETARG_INTERVAL_P(0);
2589 INT128 span
= interval_cmp_value(interval
);
2593 * Use only the least significant 64 bits for hashing. The upper 64 bits
2594 * seldom add any useful information, and besides we must do it like this
2595 * for compatibility with hashes calculated before use of INT128 was
2598 span64
= int128_to_int64(span
);
2600 return DirectFunctionCall1(hashint8
, Int64GetDatumFast(span64
));
2604 interval_hash_extended(PG_FUNCTION_ARGS
)
2606 Interval
*interval
= PG_GETARG_INTERVAL_P(0);
2607 INT128 span
= interval_cmp_value(interval
);
2610 /* Same approach as interval_hash */
2611 span64
= int128_to_int64(span
);
2613 return DirectFunctionCall2(hashint8extended
, Int64GetDatumFast(span64
),
2614 PG_GETARG_DATUM(1));
2617 /* overlaps_timestamp() --- implements the SQL OVERLAPS operator.
2619 * Algorithm is per SQL spec. This is much harder than you'd think
2620 * because the spec requires us to deliver a non-null answer in some cases
2621 * where some of the inputs are null.
2624 overlaps_timestamp(PG_FUNCTION_ARGS
)
2627 * The arguments are Timestamps, but we leave them as generic Datums to
2628 * avoid unnecessary conversions between value and reference forms --- not
2629 * to mention possible dereferences of null pointers.
2631 Datum ts1
= PG_GETARG_DATUM(0);
2632 Datum te1
= PG_GETARG_DATUM(1);
2633 Datum ts2
= PG_GETARG_DATUM(2);
2634 Datum te2
= PG_GETARG_DATUM(3);
2635 bool ts1IsNull
= PG_ARGISNULL(0);
2636 bool te1IsNull
= PG_ARGISNULL(1);
2637 bool ts2IsNull
= PG_ARGISNULL(2);
2638 bool te2IsNull
= PG_ARGISNULL(3);
2640 #define TIMESTAMP_GT(t1,t2) \
2641 DatumGetBool(DirectFunctionCall2(timestamp_gt,t1,t2))
2642 #define TIMESTAMP_LT(t1,t2) \
2643 DatumGetBool(DirectFunctionCall2(timestamp_lt,t1,t2))
2646 * If both endpoints of interval 1 are null, the result is null (unknown).
2647 * If just one endpoint is null, take ts1 as the non-null one. Otherwise,
2648 * take ts1 as the lesser endpoint.
2654 /* swap null for non-null */
2658 else if (!te1IsNull
)
2660 if (TIMESTAMP_GT(ts1
, te1
))
2669 /* Likewise for interval 2. */
2674 /* swap null for non-null */
2678 else if (!te2IsNull
)
2680 if (TIMESTAMP_GT(ts2
, te2
))
2690 * At this point neither ts1 nor ts2 is null, so we can consider three
2691 * cases: ts1 > ts2, ts1 < ts2, ts1 = ts2
2693 if (TIMESTAMP_GT(ts1
, ts2
))
2696 * This case is ts1 < te2 OR te1 < te2, which may look redundant but
2697 * in the presence of nulls it's not quite completely so.
2701 if (TIMESTAMP_LT(ts1
, te2
))
2702 PG_RETURN_BOOL(true);
2707 * If te1 is not null then we had ts1 <= te1 above, and we just found
2708 * ts1 >= te2, hence te1 >= te2.
2710 PG_RETURN_BOOL(false);
2712 else if (TIMESTAMP_LT(ts1
, ts2
))
2714 /* This case is ts2 < te1 OR te2 < te1 */
2717 if (TIMESTAMP_LT(ts2
, te1
))
2718 PG_RETURN_BOOL(true);
2723 * If te2 is not null then we had ts2 <= te2 above, and we just found
2724 * ts2 >= te1, hence te2 >= te1.
2726 PG_RETURN_BOOL(false);
2731 * For ts1 = ts2 the spec says te1 <> te2 OR te1 = te2, which is a
2732 * rather silly way of saying "true if both are non-null, else null".
2734 if (te1IsNull
|| te2IsNull
)
2736 PG_RETURN_BOOL(true);
2744 /*----------------------------------------------------------
2745 * "Arithmetic" operators on date/times.
2746 *---------------------------------------------------------*/
2749 timestamp_smaller(PG_FUNCTION_ARGS
)
2751 Timestamp dt1
= PG_GETARG_TIMESTAMP(0);
2752 Timestamp dt2
= PG_GETARG_TIMESTAMP(1);
2755 /* use timestamp_cmp_internal to be sure this agrees with comparisons */
2756 if (timestamp_cmp_internal(dt1
, dt2
) < 0)
2760 PG_RETURN_TIMESTAMP(result
);
2764 timestamp_larger(PG_FUNCTION_ARGS
)
2766 Timestamp dt1
= PG_GETARG_TIMESTAMP(0);
2767 Timestamp dt2
= PG_GETARG_TIMESTAMP(1);
2770 if (timestamp_cmp_internal(dt1
, dt2
) > 0)
2774 PG_RETURN_TIMESTAMP(result
);
2779 timestamp_mi(PG_FUNCTION_ARGS
)
2781 Timestamp dt1
= PG_GETARG_TIMESTAMP(0);
2782 Timestamp dt2
= PG_GETARG_TIMESTAMP(1);
2785 result
= (Interval
*) palloc(sizeof(Interval
));
2788 * Handle infinities.
2790 * We treat anything that amounts to "infinity - infinity" as an error,
2791 * since the interval type has nothing equivalent to NaN.
2793 if (TIMESTAMP_NOT_FINITE(dt1
) || TIMESTAMP_NOT_FINITE(dt2
))
2795 if (TIMESTAMP_IS_NOBEGIN(dt1
))
2797 if (TIMESTAMP_IS_NOBEGIN(dt2
))
2799 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
2800 errmsg("interval out of range")));
2802 INTERVAL_NOBEGIN(result
);
2804 else if (TIMESTAMP_IS_NOEND(dt1
))
2806 if (TIMESTAMP_IS_NOEND(dt2
))
2808 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
2809 errmsg("interval out of range")));
2811 INTERVAL_NOEND(result
);
2813 else if (TIMESTAMP_IS_NOBEGIN(dt2
))
2814 INTERVAL_NOEND(result
);
2815 else /* TIMESTAMP_IS_NOEND(dt2) */
2816 INTERVAL_NOBEGIN(result
);
2818 PG_RETURN_INTERVAL_P(result
);
2821 if (unlikely(pg_sub_s64_overflow(dt1
, dt2
, &result
->time
)))
2823 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
2824 errmsg("interval out of range")));
2830 * This is wrong, but removing it breaks a lot of regression tests.
2833 * test=> SET timezone = 'EST5EDT';
2835 * test-> ('2005-10-30 13:22:00-05'::timestamptz -
2836 * test(> '2005-10-29 13:22:00-04'::timestamptz);
2842 * so adding that to the first timestamp gets:
2845 * test-> ('2005-10-29 13:22:00-04'::timestamptz +
2846 * test(> ('2005-10-30 13:22:00-05'::timestamptz -
2847 * test(> '2005-10-29 13:22:00-04'::timestamptz)) at time zone 'EST';
2849 * --------------------
2850 * 2005-10-30 14:22:00
2854 result
= DatumGetIntervalP(DirectFunctionCall1(interval_justify_hours
,
2855 IntervalPGetDatum(result
)));
2857 PG_RETURN_INTERVAL_P(result
);
2861 * interval_justify_interval()
2863 * Adjust interval so 'month', 'day', and 'time' portions are within
2864 * customary bounds. Specifically:
2866 * 0 <= abs(time) < 24 hours
2867 * 0 <= abs(day) < 30 days
2869 * Also, the sign bit on all three fields is made equal, so either
2870 * all three fields are negative or all are positive.
2873 interval_justify_interval(PG_FUNCTION_ARGS
)
2875 Interval
*span
= PG_GETARG_INTERVAL_P(0);
2877 TimeOffset wholeday
;
2880 result
= (Interval
*) palloc(sizeof(Interval
));
2881 result
->month
= span
->month
;
2882 result
->day
= span
->day
;
2883 result
->time
= span
->time
;
2885 /* do nothing for infinite intervals */
2886 if (INTERVAL_NOT_FINITE(result
))
2887 PG_RETURN_INTERVAL_P(result
);
2889 /* pre-justify days if it might prevent overflow */
2890 if ((result
->day
> 0 && result
->time
> 0) ||
2891 (result
->day
< 0 && result
->time
< 0))
2893 wholemonth
= result
->day
/ DAYS_PER_MONTH
;
2894 result
->day
-= wholemonth
* DAYS_PER_MONTH
;
2895 if (pg_add_s32_overflow(result
->month
, wholemonth
, &result
->month
))
2897 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
2898 errmsg("interval out of range")));
2902 * Since TimeOffset is int64, abs(wholeday) can't exceed about 1.07e8. If
2903 * we pre-justified then abs(result->day) is less than DAYS_PER_MONTH, so
2904 * this addition can't overflow. If we didn't pre-justify, then day and
2905 * time are of different signs, so it still can't overflow.
2907 TMODULO(result
->time
, wholeday
, USECS_PER_DAY
);
2908 result
->day
+= wholeday
;
2910 wholemonth
= result
->day
/ DAYS_PER_MONTH
;
2911 result
->day
-= wholemonth
* DAYS_PER_MONTH
;
2912 if (pg_add_s32_overflow(result
->month
, wholemonth
, &result
->month
))
2914 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
2915 errmsg("interval out of range")));
2917 if (result
->month
> 0 &&
2918 (result
->day
< 0 || (result
->day
== 0 && result
->time
< 0)))
2920 result
->day
+= DAYS_PER_MONTH
;
2923 else if (result
->month
< 0 &&
2924 (result
->day
> 0 || (result
->day
== 0 && result
->time
> 0)))
2926 result
->day
-= DAYS_PER_MONTH
;
2930 if (result
->day
> 0 && result
->time
< 0)
2932 result
->time
+= USECS_PER_DAY
;
2935 else if (result
->day
< 0 && result
->time
> 0)
2937 result
->time
-= USECS_PER_DAY
;
2941 PG_RETURN_INTERVAL_P(result
);
2945 * interval_justify_hours()
2947 * Adjust interval so 'time' contains less than a whole day, adding
2948 * the excess to 'day'. This is useful for
2949 * situations (such as non-TZ) where '1 day' = '24 hours' is valid,
2950 * e.g. interval subtraction and division.
2953 interval_justify_hours(PG_FUNCTION_ARGS
)
2955 Interval
*span
= PG_GETARG_INTERVAL_P(0);
2957 TimeOffset wholeday
;
2959 result
= (Interval
*) palloc(sizeof(Interval
));
2960 result
->month
= span
->month
;
2961 result
->day
= span
->day
;
2962 result
->time
= span
->time
;
2964 /* do nothing for infinite intervals */
2965 if (INTERVAL_NOT_FINITE(result
))
2966 PG_RETURN_INTERVAL_P(result
);
2968 TMODULO(result
->time
, wholeday
, USECS_PER_DAY
);
2969 if (pg_add_s32_overflow(result
->day
, wholeday
, &result
->day
))
2971 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
2972 errmsg("interval out of range")));
2974 if (result
->day
> 0 && result
->time
< 0)
2976 result
->time
+= USECS_PER_DAY
;
2979 else if (result
->day
< 0 && result
->time
> 0)
2981 result
->time
-= USECS_PER_DAY
;
2985 PG_RETURN_INTERVAL_P(result
);
2989 * interval_justify_days()
2991 * Adjust interval so 'day' contains less than 30 days, adding
2992 * the excess to 'month'.
2995 interval_justify_days(PG_FUNCTION_ARGS
)
2997 Interval
*span
= PG_GETARG_INTERVAL_P(0);
3001 result
= (Interval
*) palloc(sizeof(Interval
));
3002 result
->month
= span
->month
;
3003 result
->day
= span
->day
;
3004 result
->time
= span
->time
;
3006 /* do nothing for infinite intervals */
3007 if (INTERVAL_NOT_FINITE(result
))
3008 PG_RETURN_INTERVAL_P(result
);
3010 wholemonth
= result
->day
/ DAYS_PER_MONTH
;
3011 result
->day
-= wholemonth
* DAYS_PER_MONTH
;
3012 if (pg_add_s32_overflow(result
->month
, wholemonth
, &result
->month
))
3014 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3015 errmsg("interval out of range")));
3017 if (result
->month
> 0 && result
->day
< 0)
3019 result
->day
+= DAYS_PER_MONTH
;
3022 else if (result
->month
< 0 && result
->day
> 0)
3024 result
->day
-= DAYS_PER_MONTH
;
3028 PG_RETURN_INTERVAL_P(result
);
3031 /* timestamp_pl_interval()
3032 * Add an interval to a timestamp data type.
3033 * Note that interval has provisions for qualitative year/month and day
3034 * units, so try to do the right thing with them.
3035 * To add a month, increment the month, and use the same day of month.
3036 * Then, if the next month has fewer days, set the day of month
3037 * to the last day of month.
3038 * To add a day, increment the mday, and use the same time of day.
3039 * Lastly, add in the "quantitative time".
3042 timestamp_pl_interval(PG_FUNCTION_ARGS
)
3044 Timestamp timestamp
= PG_GETARG_TIMESTAMP(0);
3045 Interval
*span
= PG_GETARG_INTERVAL_P(1);
3049 * Handle infinities.
3051 * We treat anything that amounts to "infinity - infinity" as an error,
3052 * since the timestamp type has nothing equivalent to NaN.
3054 if (INTERVAL_IS_NOBEGIN(span
))
3056 if (TIMESTAMP_IS_NOEND(timestamp
))
3058 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3059 errmsg("timestamp out of range")));
3061 TIMESTAMP_NOBEGIN(result
);
3063 else if (INTERVAL_IS_NOEND(span
))
3065 if (TIMESTAMP_IS_NOBEGIN(timestamp
))
3067 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3068 errmsg("timestamp out of range")));
3070 TIMESTAMP_NOEND(result
);
3072 else if (TIMESTAMP_NOT_FINITE(timestamp
))
3076 if (span
->month
!= 0)
3082 if (timestamp2tm(timestamp
, NULL
, tm
, &fsec
, NULL
, NULL
) != 0)
3084 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3085 errmsg("timestamp out of range")));
3087 if (pg_add_s32_overflow(tm
->tm_mon
, span
->month
, &tm
->tm_mon
))
3089 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3090 errmsg("timestamp out of range")));
3091 if (tm
->tm_mon
> MONTHS_PER_YEAR
)
3093 tm
->tm_year
+= (tm
->tm_mon
- 1) / MONTHS_PER_YEAR
;
3094 tm
->tm_mon
= ((tm
->tm_mon
- 1) % MONTHS_PER_YEAR
) + 1;
3096 else if (tm
->tm_mon
< 1)
3098 tm
->tm_year
+= tm
->tm_mon
/ MONTHS_PER_YEAR
- 1;
3099 tm
->tm_mon
= tm
->tm_mon
% MONTHS_PER_YEAR
+ MONTHS_PER_YEAR
;
3102 /* adjust for end of month boundary problems... */
3103 if (tm
->tm_mday
> day_tab
[isleap(tm
->tm_year
)][tm
->tm_mon
- 1])
3104 tm
->tm_mday
= (day_tab
[isleap(tm
->tm_year
)][tm
->tm_mon
- 1]);
3106 if (tm2timestamp(tm
, fsec
, NULL
, ×tamp
) != 0)
3108 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3109 errmsg("timestamp out of range")));
3119 if (timestamp2tm(timestamp
, NULL
, tm
, &fsec
, NULL
, NULL
) != 0)
3121 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3122 errmsg("timestamp out of range")));
3125 * Add days by converting to and from Julian. We need an overflow
3126 * check here since j2date expects a non-negative integer input.
3128 julian
= date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
);
3129 if (pg_add_s32_overflow(julian
, span
->day
, &julian
) ||
3132 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3133 errmsg("timestamp out of range")));
3134 j2date(julian
, &tm
->tm_year
, &tm
->tm_mon
, &tm
->tm_mday
);
3136 if (tm2timestamp(tm
, fsec
, NULL
, ×tamp
) != 0)
3138 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3139 errmsg("timestamp out of range")));
3142 if (pg_add_s64_overflow(timestamp
, span
->time
, ×tamp
))
3144 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3145 errmsg("timestamp out of range")));
3147 if (!IS_VALID_TIMESTAMP(timestamp
))
3149 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3150 errmsg("timestamp out of range")));
3155 PG_RETURN_TIMESTAMP(result
);
3159 timestamp_mi_interval(PG_FUNCTION_ARGS
)
3161 Timestamp timestamp
= PG_GETARG_TIMESTAMP(0);
3162 Interval
*span
= PG_GETARG_INTERVAL_P(1);
3165 interval_um_internal(span
, &tspan
);
3167 return DirectFunctionCall2(timestamp_pl_interval
,
3168 TimestampGetDatum(timestamp
),
3169 PointerGetDatum(&tspan
));
3173 /* timestamptz_pl_interval_internal()
3174 * Add an interval to a timestamptz, in the given (or session) timezone.
3176 * Note that interval has provisions for qualitative year/month and day
3177 * units, so try to do the right thing with them.
3178 * To add a month, increment the month, and use the same day of month.
3179 * Then, if the next month has fewer days, set the day of month
3180 * to the last day of month.
3181 * To add a day, increment the mday, and use the same time of day.
3182 * Lastly, add in the "quantitative time".
3185 timestamptz_pl_interval_internal(TimestampTz timestamp
,
3193 * Handle infinities.
3195 * We treat anything that amounts to "infinity - infinity" as an error,
3196 * since the timestamptz type has nothing equivalent to NaN.
3198 if (INTERVAL_IS_NOBEGIN(span
))
3200 if (TIMESTAMP_IS_NOEND(timestamp
))
3202 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3203 errmsg("timestamp out of range")));
3205 TIMESTAMP_NOBEGIN(result
);
3207 else if (INTERVAL_IS_NOEND(span
))
3209 if (TIMESTAMP_IS_NOBEGIN(timestamp
))
3211 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3212 errmsg("timestamp out of range")));
3214 TIMESTAMP_NOEND(result
);
3216 else if (TIMESTAMP_NOT_FINITE(timestamp
))
3220 /* Use session timezone if caller asks for default */
3221 if (attimezone
== NULL
)
3222 attimezone
= session_timezone
;
3224 if (span
->month
!= 0)
3230 if (timestamp2tm(timestamp
, &tz
, tm
, &fsec
, NULL
, attimezone
) != 0)
3232 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3233 errmsg("timestamp out of range")));
3235 if (pg_add_s32_overflow(tm
->tm_mon
, span
->month
, &tm
->tm_mon
))
3237 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3238 errmsg("timestamp out of range")));
3239 if (tm
->tm_mon
> MONTHS_PER_YEAR
)
3241 tm
->tm_year
+= (tm
->tm_mon
- 1) / MONTHS_PER_YEAR
;
3242 tm
->tm_mon
= ((tm
->tm_mon
- 1) % MONTHS_PER_YEAR
) + 1;
3244 else if (tm
->tm_mon
< 1)
3246 tm
->tm_year
+= tm
->tm_mon
/ MONTHS_PER_YEAR
- 1;
3247 tm
->tm_mon
= tm
->tm_mon
% MONTHS_PER_YEAR
+ MONTHS_PER_YEAR
;
3250 /* adjust for end of month boundary problems... */
3251 if (tm
->tm_mday
> day_tab
[isleap(tm
->tm_year
)][tm
->tm_mon
- 1])
3252 tm
->tm_mday
= (day_tab
[isleap(tm
->tm_year
)][tm
->tm_mon
- 1]);
3254 tz
= DetermineTimeZoneOffset(tm
, attimezone
);
3256 if (tm2timestamp(tm
, fsec
, &tz
, ×tamp
) != 0)
3258 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3259 errmsg("timestamp out of range")));
3269 if (timestamp2tm(timestamp
, &tz
, tm
, &fsec
, NULL
, attimezone
) != 0)
3271 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3272 errmsg("timestamp out of range")));
3275 * Add days by converting to and from Julian. We need an overflow
3276 * check here since j2date expects a non-negative integer input.
3277 * In practice though, it will give correct answers for small
3278 * negative Julian dates; we should allow -1 to avoid
3279 * timezone-dependent failures, as discussed in timestamp.h.
3281 julian
= date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
);
3282 if (pg_add_s32_overflow(julian
, span
->day
, &julian
) ||
3285 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3286 errmsg("timestamp out of range")));
3287 j2date(julian
, &tm
->tm_year
, &tm
->tm_mon
, &tm
->tm_mday
);
3289 tz
= DetermineTimeZoneOffset(tm
, attimezone
);
3291 if (tm2timestamp(tm
, fsec
, &tz
, ×tamp
) != 0)
3293 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3294 errmsg("timestamp out of range")));
3297 if (pg_add_s64_overflow(timestamp
, span
->time
, ×tamp
))
3299 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3300 errmsg("timestamp out of range")));
3302 if (!IS_VALID_TIMESTAMP(timestamp
))
3304 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3305 errmsg("timestamp out of range")));
3313 /* timestamptz_mi_interval_internal()
3314 * As above, but subtract the interval.
3317 timestamptz_mi_interval_internal(TimestampTz timestamp
,
3323 interval_um_internal(span
, &tspan
);
3325 return timestamptz_pl_interval_internal(timestamp
, &tspan
, attimezone
);
3328 /* timestamptz_pl_interval()
3329 * Add an interval to a timestamptz, in the session timezone.
3332 timestamptz_pl_interval(PG_FUNCTION_ARGS
)
3334 TimestampTz timestamp
= PG_GETARG_TIMESTAMPTZ(0);
3335 Interval
*span
= PG_GETARG_INTERVAL_P(1);
3337 PG_RETURN_TIMESTAMP(timestamptz_pl_interval_internal(timestamp
, span
, NULL
));
3341 timestamptz_mi_interval(PG_FUNCTION_ARGS
)
3343 TimestampTz timestamp
= PG_GETARG_TIMESTAMPTZ(0);
3344 Interval
*span
= PG_GETARG_INTERVAL_P(1);
3346 PG_RETURN_TIMESTAMP(timestamptz_mi_interval_internal(timestamp
, span
, NULL
));
3349 /* timestamptz_pl_interval_at_zone()
3350 * Add an interval to a timestamptz, in the specified timezone.
3353 timestamptz_pl_interval_at_zone(PG_FUNCTION_ARGS
)
3355 TimestampTz timestamp
= PG_GETARG_TIMESTAMPTZ(0);
3356 Interval
*span
= PG_GETARG_INTERVAL_P(1);
3357 text
*zone
= PG_GETARG_TEXT_PP(2);
3358 pg_tz
*attimezone
= lookup_timezone(zone
);
3360 PG_RETURN_TIMESTAMP(timestamptz_pl_interval_internal(timestamp
, span
, attimezone
));
3364 timestamptz_mi_interval_at_zone(PG_FUNCTION_ARGS
)
3366 TimestampTz timestamp
= PG_GETARG_TIMESTAMPTZ(0);
3367 Interval
*span
= PG_GETARG_INTERVAL_P(1);
3368 text
*zone
= PG_GETARG_TEXT_PP(2);
3369 pg_tz
*attimezone
= lookup_timezone(zone
);
3371 PG_RETURN_TIMESTAMP(timestamptz_mi_interval_internal(timestamp
, span
, attimezone
));
3374 /* interval_um_internal()
3375 * Negate an interval.
3378 interval_um_internal(const Interval
*interval
, Interval
*result
)
3380 if (INTERVAL_IS_NOBEGIN(interval
))
3381 INTERVAL_NOEND(result
);
3382 else if (INTERVAL_IS_NOEND(interval
))
3383 INTERVAL_NOBEGIN(result
);
3386 /* Negate each field, guarding against overflow */
3387 if (pg_sub_s64_overflow(INT64CONST(0), interval
->time
, &result
->time
) ||
3388 pg_sub_s32_overflow(0, interval
->day
, &result
->day
) ||
3389 pg_sub_s32_overflow(0, interval
->month
, &result
->month
) ||
3390 INTERVAL_NOT_FINITE(result
))
3392 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3393 errmsg("interval out of range")));
3398 interval_um(PG_FUNCTION_ARGS
)
3400 Interval
*interval
= PG_GETARG_INTERVAL_P(0);
3403 result
= (Interval
*) palloc(sizeof(Interval
));
3404 interval_um_internal(interval
, result
);
3406 PG_RETURN_INTERVAL_P(result
);
3411 interval_smaller(PG_FUNCTION_ARGS
)
3413 Interval
*interval1
= PG_GETARG_INTERVAL_P(0);
3414 Interval
*interval2
= PG_GETARG_INTERVAL_P(1);
3417 /* use interval_cmp_internal to be sure this agrees with comparisons */
3418 if (interval_cmp_internal(interval1
, interval2
) < 0)
3422 PG_RETURN_INTERVAL_P(result
);
3426 interval_larger(PG_FUNCTION_ARGS
)
3428 Interval
*interval1
= PG_GETARG_INTERVAL_P(0);
3429 Interval
*interval2
= PG_GETARG_INTERVAL_P(1);
3432 if (interval_cmp_internal(interval1
, interval2
) > 0)
3436 PG_RETURN_INTERVAL_P(result
);
3440 finite_interval_pl(const Interval
*span1
, const Interval
*span2
, Interval
*result
)
3442 Assert(!INTERVAL_NOT_FINITE(span1
));
3443 Assert(!INTERVAL_NOT_FINITE(span2
));
3445 if (pg_add_s32_overflow(span1
->month
, span2
->month
, &result
->month
) ||
3446 pg_add_s32_overflow(span1
->day
, span2
->day
, &result
->day
) ||
3447 pg_add_s64_overflow(span1
->time
, span2
->time
, &result
->time
) ||
3448 INTERVAL_NOT_FINITE(result
))
3450 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3451 errmsg("interval out of range")));
3455 interval_pl(PG_FUNCTION_ARGS
)
3457 Interval
*span1
= PG_GETARG_INTERVAL_P(0);
3458 Interval
*span2
= PG_GETARG_INTERVAL_P(1);
3461 result
= (Interval
*) palloc(sizeof(Interval
));
3464 * Handle infinities.
3466 * We treat anything that amounts to "infinity - infinity" as an error,
3467 * since the interval type has nothing equivalent to NaN.
3469 if (INTERVAL_IS_NOBEGIN(span1
))
3471 if (INTERVAL_IS_NOEND(span2
))
3473 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3474 errmsg("interval out of range")));
3476 INTERVAL_NOBEGIN(result
);
3478 else if (INTERVAL_IS_NOEND(span1
))
3480 if (INTERVAL_IS_NOBEGIN(span2
))
3482 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3483 errmsg("interval out of range")));
3485 INTERVAL_NOEND(result
);
3487 else if (INTERVAL_NOT_FINITE(span2
))
3488 memcpy(result
, span2
, sizeof(Interval
));
3490 finite_interval_pl(span1
, span2
, result
);
3492 PG_RETURN_INTERVAL_P(result
);
3496 finite_interval_mi(const Interval
*span1
, const Interval
*span2
, Interval
*result
)
3498 Assert(!INTERVAL_NOT_FINITE(span1
));
3499 Assert(!INTERVAL_NOT_FINITE(span2
));
3501 if (pg_sub_s32_overflow(span1
->month
, span2
->month
, &result
->month
) ||
3502 pg_sub_s32_overflow(span1
->day
, span2
->day
, &result
->day
) ||
3503 pg_sub_s64_overflow(span1
->time
, span2
->time
, &result
->time
) ||
3504 INTERVAL_NOT_FINITE(result
))
3506 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3507 errmsg("interval out of range")));
3511 interval_mi(PG_FUNCTION_ARGS
)
3513 Interval
*span1
= PG_GETARG_INTERVAL_P(0);
3514 Interval
*span2
= PG_GETARG_INTERVAL_P(1);
3517 result
= (Interval
*) palloc(sizeof(Interval
));
3520 * Handle infinities.
3522 * We treat anything that amounts to "infinity - infinity" as an error,
3523 * since the interval type has nothing equivalent to NaN.
3525 if (INTERVAL_IS_NOBEGIN(span1
))
3527 if (INTERVAL_IS_NOBEGIN(span2
))
3529 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3530 errmsg("interval out of range")));
3532 INTERVAL_NOBEGIN(result
);
3534 else if (INTERVAL_IS_NOEND(span1
))
3536 if (INTERVAL_IS_NOEND(span2
))
3538 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3539 errmsg("interval out of range")));
3541 INTERVAL_NOEND(result
);
3543 else if (INTERVAL_IS_NOBEGIN(span2
))
3544 INTERVAL_NOEND(result
);
3545 else if (INTERVAL_IS_NOEND(span2
))
3546 INTERVAL_NOBEGIN(result
);
3548 finite_interval_mi(span1
, span2
, result
);
3550 PG_RETURN_INTERVAL_P(result
);
3554 * There is no interval_abs(): it is unclear what value to return:
3555 * http://archives.postgresql.org/pgsql-general/2009-10/msg01031.php
3556 * http://archives.postgresql.org/pgsql-general/2009-11/msg00041.php
3560 interval_mul(PG_FUNCTION_ARGS
)
3562 Interval
*span
= PG_GETARG_INTERVAL_P(0);
3563 float8 factor
= PG_GETARG_FLOAT8(1);
3564 double month_remainder_days
,
3567 int32 orig_month
= span
->month
,
3568 orig_day
= span
->day
;
3571 result
= (Interval
*) palloc(sizeof(Interval
));
3574 * Handle NaN and infinities.
3576 * We treat "0 * infinity" and "infinity * 0" as errors, since the
3577 * interval type has nothing equivalent to NaN.
3582 if (INTERVAL_NOT_FINITE(span
))
3588 interval_um_internal(span
, result
);
3590 memcpy(result
, span
, sizeof(Interval
));
3592 PG_RETURN_INTERVAL_P(result
);
3596 int isign
= interval_sign(span
);
3601 if (factor
* isign
< 0)
3602 INTERVAL_NOBEGIN(result
);
3604 INTERVAL_NOEND(result
);
3606 PG_RETURN_INTERVAL_P(result
);
3609 result_double
= span
->month
* factor
;
3610 if (isnan(result_double
) || !FLOAT8_FITS_IN_INT32(result_double
))
3612 result
->month
= (int32
) result_double
;
3614 result_double
= span
->day
* factor
;
3615 if (isnan(result_double
) || !FLOAT8_FITS_IN_INT32(result_double
))
3617 result
->day
= (int32
) result_double
;
3620 * The above correctly handles the whole-number part of the month and day
3621 * products, but we have to do something with any fractional part
3622 * resulting when the factor is non-integral. We cascade the fractions
3623 * down to lower units using the conversion factors DAYS_PER_MONTH and
3624 * SECS_PER_DAY. Note we do NOT cascade up, since we are not forced to do
3625 * so by the representation. The user can choose to cascade up later,
3626 * using justify_hours and/or justify_days.
3630 * Fractional months full days into days.
3632 * Floating point calculation are inherently imprecise, so these
3633 * calculations are crafted to produce the most reliable result possible.
3634 * TSROUND() is needed to more accurately produce whole numbers where
3637 month_remainder_days
= (orig_month
* factor
- result
->month
) * DAYS_PER_MONTH
;
3638 month_remainder_days
= TSROUND(month_remainder_days
);
3639 sec_remainder
= (orig_day
* factor
- result
->day
+
3640 month_remainder_days
- (int) month_remainder_days
) * SECS_PER_DAY
;
3641 sec_remainder
= TSROUND(sec_remainder
);
3644 * Might have 24:00:00 hours due to rounding, or >24 hours because of time
3645 * cascade from months and days. It might still be >24 if the combination
3646 * of cascade and the seconds factor operation itself.
3648 if (fabs(sec_remainder
) >= SECS_PER_DAY
)
3650 if (pg_add_s32_overflow(result
->day
,
3651 (int) (sec_remainder
/ SECS_PER_DAY
),
3654 sec_remainder
-= (int) (sec_remainder
/ SECS_PER_DAY
) * SECS_PER_DAY
;
3657 /* cascade units down */
3658 if (pg_add_s32_overflow(result
->day
, (int32
) month_remainder_days
,
3661 result_double
= rint(span
->time
* factor
+ sec_remainder
* USECS_PER_SEC
);
3662 if (isnan(result_double
) || !FLOAT8_FITS_IN_INT64(result_double
))
3664 result
->time
= (int64
) result_double
;
3666 if (INTERVAL_NOT_FINITE(result
))
3669 PG_RETURN_INTERVAL_P(result
);
3673 errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3674 errmsg("interval out of range"));
3676 PG_RETURN_NULL(); /* keep compiler quiet */
3680 mul_d_interval(PG_FUNCTION_ARGS
)
3682 /* Args are float8 and Interval *, but leave them as generic Datum */
3683 Datum factor
= PG_GETARG_DATUM(0);
3684 Datum span
= PG_GETARG_DATUM(1);
3686 return DirectFunctionCall2(interval_mul
, span
, factor
);
3690 interval_div(PG_FUNCTION_ARGS
)
3692 Interval
*span
= PG_GETARG_INTERVAL_P(0);
3693 float8 factor
= PG_GETARG_FLOAT8(1);
3694 double month_remainder_days
,
3697 int32 orig_month
= span
->month
,
3698 orig_day
= span
->day
;
3701 result
= (Interval
*) palloc(sizeof(Interval
));
3705 (errcode(ERRCODE_DIVISION_BY_ZERO
),
3706 errmsg("division by zero")));
3709 * Handle NaN and infinities.
3711 * We treat "infinity / infinity" as an error, since the interval type has
3712 * nothing equivalent to NaN. Otherwise, dividing by infinity is handled
3713 * by the regular division code, causing all fields to be set to zero.
3718 if (INTERVAL_NOT_FINITE(span
))
3724 interval_um_internal(span
, result
);
3726 memcpy(result
, span
, sizeof(Interval
));
3728 PG_RETURN_INTERVAL_P(result
);
3731 result_double
= span
->month
/ factor
;
3732 if (isnan(result_double
) || !FLOAT8_FITS_IN_INT32(result_double
))
3734 result
->month
= (int32
) result_double
;
3736 result_double
= span
->day
/ factor
;
3737 if (isnan(result_double
) || !FLOAT8_FITS_IN_INT32(result_double
))
3739 result
->day
= (int32
) result_double
;
3742 * Fractional months full days into days. See comment in interval_mul().
3744 month_remainder_days
= (orig_month
/ factor
- result
->month
) * DAYS_PER_MONTH
;
3745 month_remainder_days
= TSROUND(month_remainder_days
);
3746 sec_remainder
= (orig_day
/ factor
- result
->day
+
3747 month_remainder_days
- (int) month_remainder_days
) * SECS_PER_DAY
;
3748 sec_remainder
= TSROUND(sec_remainder
);
3749 if (fabs(sec_remainder
) >= SECS_PER_DAY
)
3751 if (pg_add_s32_overflow(result
->day
,
3752 (int) (sec_remainder
/ SECS_PER_DAY
),
3755 sec_remainder
-= (int) (sec_remainder
/ SECS_PER_DAY
) * SECS_PER_DAY
;
3758 /* cascade units down */
3759 if (pg_add_s32_overflow(result
->day
, (int32
) month_remainder_days
,
3762 result_double
= rint(span
->time
/ factor
+ sec_remainder
* USECS_PER_SEC
);
3763 if (isnan(result_double
) || !FLOAT8_FITS_IN_INT64(result_double
))
3765 result
->time
= (int64
) result_double
;
3767 if (INTERVAL_NOT_FINITE(result
))
3770 PG_RETURN_INTERVAL_P(result
);
3774 errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
3775 errmsg("interval out of range"));
3777 PG_RETURN_NULL(); /* keep compiler quiet */
3782 * in_range support functions for timestamps and intervals.
3784 * Per SQL spec, we support these with interval as the offset type.
3785 * The spec's restriction that the offset not be negative is a bit hard to
3786 * decipher for intervals, but we choose to interpret it the same as our
3787 * interval comparison operators would.
3791 in_range_timestamptz_interval(PG_FUNCTION_ARGS
)
3793 TimestampTz val
= PG_GETARG_TIMESTAMPTZ(0);
3794 TimestampTz base
= PG_GETARG_TIMESTAMPTZ(1);
3795 Interval
*offset
= PG_GETARG_INTERVAL_P(2);
3796 bool sub
= PG_GETARG_BOOL(3);
3797 bool less
= PG_GETARG_BOOL(4);
3800 if (interval_sign(offset
) < 0)
3802 (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE
),
3803 errmsg("invalid preceding or following size in window function")));
3806 * Deal with cases where both base and offset are infinite, and computing
3807 * base +/- offset would cause an error. As for float and numeric types,
3808 * we assume that all values infinitely precede +infinity and infinitely
3809 * follow -infinity. See in_range_float8_float8() for reasoning.
3811 if (INTERVAL_IS_NOEND(offset
) &&
3812 (sub
? TIMESTAMP_IS_NOEND(base
) : TIMESTAMP_IS_NOBEGIN(base
)))
3813 PG_RETURN_BOOL(true);
3815 /* We don't currently bother to avoid overflow hazards here */
3817 sum
= timestamptz_mi_interval_internal(base
, offset
, NULL
);
3819 sum
= timestamptz_pl_interval_internal(base
, offset
, NULL
);
3822 PG_RETURN_BOOL(val
<= sum
);
3824 PG_RETURN_BOOL(val
>= sum
);
3828 in_range_timestamp_interval(PG_FUNCTION_ARGS
)
3830 Timestamp val
= PG_GETARG_TIMESTAMP(0);
3831 Timestamp base
= PG_GETARG_TIMESTAMP(1);
3832 Interval
*offset
= PG_GETARG_INTERVAL_P(2);
3833 bool sub
= PG_GETARG_BOOL(3);
3834 bool less
= PG_GETARG_BOOL(4);
3837 if (interval_sign(offset
) < 0)
3839 (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE
),
3840 errmsg("invalid preceding or following size in window function")));
3843 * Deal with cases where both base and offset are infinite, and computing
3844 * base +/- offset would cause an error. As for float and numeric types,
3845 * we assume that all values infinitely precede +infinity and infinitely
3846 * follow -infinity. See in_range_float8_float8() for reasoning.
3848 if (INTERVAL_IS_NOEND(offset
) &&
3849 (sub
? TIMESTAMP_IS_NOEND(base
) : TIMESTAMP_IS_NOBEGIN(base
)))
3850 PG_RETURN_BOOL(true);
3852 /* We don't currently bother to avoid overflow hazards here */
3854 sum
= DatumGetTimestamp(DirectFunctionCall2(timestamp_mi_interval
,
3855 TimestampGetDatum(base
),
3856 IntervalPGetDatum(offset
)));
3858 sum
= DatumGetTimestamp(DirectFunctionCall2(timestamp_pl_interval
,
3859 TimestampGetDatum(base
),
3860 IntervalPGetDatum(offset
)));
3863 PG_RETURN_BOOL(val
<= sum
);
3865 PG_RETURN_BOOL(val
>= sum
);
3869 in_range_interval_interval(PG_FUNCTION_ARGS
)
3871 Interval
*val
= PG_GETARG_INTERVAL_P(0);
3872 Interval
*base
= PG_GETARG_INTERVAL_P(1);
3873 Interval
*offset
= PG_GETARG_INTERVAL_P(2);
3874 bool sub
= PG_GETARG_BOOL(3);
3875 bool less
= PG_GETARG_BOOL(4);
3878 if (interval_sign(offset
) < 0)
3880 (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE
),
3881 errmsg("invalid preceding or following size in window function")));
3884 * Deal with cases where both base and offset are infinite, and computing
3885 * base +/- offset would cause an error. As for float and numeric types,
3886 * we assume that all values infinitely precede +infinity and infinitely
3887 * follow -infinity. See in_range_float8_float8() for reasoning.
3889 if (INTERVAL_IS_NOEND(offset
) &&
3890 (sub
? INTERVAL_IS_NOEND(base
) : INTERVAL_IS_NOBEGIN(base
)))
3891 PG_RETURN_BOOL(true);
3893 /* We don't currently bother to avoid overflow hazards here */
3895 sum
= DatumGetIntervalP(DirectFunctionCall2(interval_mi
,
3896 IntervalPGetDatum(base
),
3897 IntervalPGetDatum(offset
)));
3899 sum
= DatumGetIntervalP(DirectFunctionCall2(interval_pl
,
3900 IntervalPGetDatum(base
),
3901 IntervalPGetDatum(offset
)));
3904 PG_RETURN_BOOL(interval_cmp_internal(val
, sum
) <= 0);
3906 PG_RETURN_BOOL(interval_cmp_internal(val
, sum
) >= 0);
3911 * Prepare state data for an interval aggregate function, that needs to compute
3912 * sum and count, in the aggregate's memory context.
3914 * The function is used when the state data needs to be allocated in aggregate's
3915 * context. When the state data needs to be allocated in the current memory
3916 * context, we use palloc0 directly e.g. interval_avg_deserialize().
3918 static IntervalAggState
*
3919 makeIntervalAggState(FunctionCallInfo fcinfo
)
3921 IntervalAggState
*state
;
3922 MemoryContext agg_context
;
3923 MemoryContext old_context
;
3925 if (!AggCheckCallContext(fcinfo
, &agg_context
))
3926 elog(ERROR
, "aggregate function called in non-aggregate context");
3928 old_context
= MemoryContextSwitchTo(agg_context
);
3930 state
= (IntervalAggState
*) palloc0(sizeof(IntervalAggState
));
3932 MemoryContextSwitchTo(old_context
);
3938 * Accumulate a new input value for interval aggregate functions.
3941 do_interval_accum(IntervalAggState
*state
, Interval
*newval
)
3943 /* Infinite inputs are counted separately, and do not affect "N" */
3944 if (INTERVAL_IS_NOBEGIN(newval
))
3950 if (INTERVAL_IS_NOEND(newval
))
3956 finite_interval_pl(&state
->sumX
, newval
, &state
->sumX
);
3961 * Remove the given interval value from the aggregated state.
3964 do_interval_discard(IntervalAggState
*state
, Interval
*newval
)
3966 /* Infinite inputs are counted separately, and do not affect "N" */
3967 if (INTERVAL_IS_NOBEGIN(newval
))
3973 if (INTERVAL_IS_NOEND(newval
))
3979 /* Handle the to-be-discarded finite value. */
3982 finite_interval_mi(&state
->sumX
, newval
, &state
->sumX
);
3985 /* All values discarded, reset the state */
3986 Assert(state
->N
== 0);
3987 memset(&state
->sumX
, 0, sizeof(state
->sumX
));
3992 * Transition function for sum() and avg() interval aggregates.
3995 interval_avg_accum(PG_FUNCTION_ARGS
)
3997 IntervalAggState
*state
;
3999 state
= PG_ARGISNULL(0) ? NULL
: (IntervalAggState
*) PG_GETARG_POINTER(0);
4001 /* Create the state data on the first call */
4003 state
= makeIntervalAggState(fcinfo
);
4005 if (!PG_ARGISNULL(1))
4006 do_interval_accum(state
, PG_GETARG_INTERVAL_P(1));
4008 PG_RETURN_POINTER(state
);
4012 * Combine function for sum() and avg() interval aggregates.
4014 * Combine the given internal aggregate states and place the combination in
4015 * the first argument.
4018 interval_avg_combine(PG_FUNCTION_ARGS
)
4020 IntervalAggState
*state1
;
4021 IntervalAggState
*state2
;
4023 state1
= PG_ARGISNULL(0) ? NULL
: (IntervalAggState
*) PG_GETARG_POINTER(0);
4024 state2
= PG_ARGISNULL(1) ? NULL
: (IntervalAggState
*) PG_GETARG_POINTER(1);
4027 PG_RETURN_POINTER(state1
);
4031 /* manually copy all fields from state2 to state1 */
4032 state1
= makeIntervalAggState(fcinfo
);
4034 state1
->N
= state2
->N
;
4035 state1
->pInfcount
= state2
->pInfcount
;
4036 state1
->nInfcount
= state2
->nInfcount
;
4038 state1
->sumX
.day
= state2
->sumX
.day
;
4039 state1
->sumX
.month
= state2
->sumX
.month
;
4040 state1
->sumX
.time
= state2
->sumX
.time
;
4042 PG_RETURN_POINTER(state1
);
4045 state1
->N
+= state2
->N
;
4046 state1
->pInfcount
+= state2
->pInfcount
;
4047 state1
->nInfcount
+= state2
->nInfcount
;
4049 /* Accumulate finite interval values, if any. */
4051 finite_interval_pl(&state1
->sumX
, &state2
->sumX
, &state1
->sumX
);
4053 PG_RETURN_POINTER(state1
);
4057 * interval_avg_serialize
4058 * Serialize IntervalAggState for interval aggregates.
4061 interval_avg_serialize(PG_FUNCTION_ARGS
)
4063 IntervalAggState
*state
;
4067 /* Ensure we disallow calling when not in aggregate context */
4068 if (!AggCheckCallContext(fcinfo
, NULL
))
4069 elog(ERROR
, "aggregate function called in non-aggregate context");
4071 state
= (IntervalAggState
*) PG_GETARG_POINTER(0);
4073 pq_begintypsend(&buf
);
4076 pq_sendint64(&buf
, state
->N
);
4079 pq_sendint64(&buf
, state
->sumX
.time
);
4080 pq_sendint32(&buf
, state
->sumX
.day
);
4081 pq_sendint32(&buf
, state
->sumX
.month
);
4084 pq_sendint64(&buf
, state
->pInfcount
);
4087 pq_sendint64(&buf
, state
->nInfcount
);
4089 result
= pq_endtypsend(&buf
);
4091 PG_RETURN_BYTEA_P(result
);
4095 * interval_avg_deserialize
4096 * Deserialize bytea into IntervalAggState for interval aggregates.
4099 interval_avg_deserialize(PG_FUNCTION_ARGS
)
4102 IntervalAggState
*result
;
4105 if (!AggCheckCallContext(fcinfo
, NULL
))
4106 elog(ERROR
, "aggregate function called in non-aggregate context");
4108 sstate
= PG_GETARG_BYTEA_PP(0);
4111 * Initialize a StringInfo so that we can "receive" it using the standard
4112 * recv-function infrastructure.
4114 initReadOnlyStringInfo(&buf
, VARDATA_ANY(sstate
),
4115 VARSIZE_ANY_EXHDR(sstate
));
4117 result
= (IntervalAggState
*) palloc0(sizeof(IntervalAggState
));
4120 result
->N
= pq_getmsgint64(&buf
);
4123 result
->sumX
.time
= pq_getmsgint64(&buf
);
4124 result
->sumX
.day
= pq_getmsgint(&buf
, 4);
4125 result
->sumX
.month
= pq_getmsgint(&buf
, 4);
4128 result
->pInfcount
= pq_getmsgint64(&buf
);
4131 result
->nInfcount
= pq_getmsgint64(&buf
);
4135 PG_RETURN_POINTER(result
);
4139 * Inverse transition function for sum() and avg() interval aggregates.
4142 interval_avg_accum_inv(PG_FUNCTION_ARGS
)
4144 IntervalAggState
*state
;
4146 state
= PG_ARGISNULL(0) ? NULL
: (IntervalAggState
*) PG_GETARG_POINTER(0);
4148 /* Should not get here with no state */
4150 elog(ERROR
, "interval_avg_accum_inv called with NULL state");
4152 if (!PG_ARGISNULL(1))
4153 do_interval_discard(state
, PG_GETARG_INTERVAL_P(1));
4155 PG_RETURN_POINTER(state
);
4158 /* avg(interval) aggregate final function */
4160 interval_avg(PG_FUNCTION_ARGS
)
4162 IntervalAggState
*state
;
4164 state
= PG_ARGISNULL(0) ? NULL
: (IntervalAggState
*) PG_GETARG_POINTER(0);
4166 /* If there were no non-null inputs, return NULL */
4167 if (state
== NULL
|| IA_TOTAL_COUNT(state
) == 0)
4171 * Aggregating infinities that all have the same sign produces infinity
4172 * with that sign. Aggregating infinities with different signs results in
4175 if (state
->pInfcount
> 0 || state
->nInfcount
> 0)
4179 if (state
->pInfcount
> 0 && state
->nInfcount
> 0)
4181 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4182 errmsg("interval out of range")));
4184 result
= (Interval
*) palloc(sizeof(Interval
));
4185 if (state
->pInfcount
> 0)
4186 INTERVAL_NOEND(result
);
4188 INTERVAL_NOBEGIN(result
);
4190 PG_RETURN_INTERVAL_P(result
);
4193 return DirectFunctionCall2(interval_div
,
4194 IntervalPGetDatum(&state
->sumX
),
4195 Float8GetDatum((double) state
->N
));
4198 /* sum(interval) aggregate final function */
4200 interval_sum(PG_FUNCTION_ARGS
)
4202 IntervalAggState
*state
;
4205 state
= PG_ARGISNULL(0) ? NULL
: (IntervalAggState
*) PG_GETARG_POINTER(0);
4207 /* If there were no non-null inputs, return NULL */
4208 if (state
== NULL
|| IA_TOTAL_COUNT(state
) == 0)
4212 * Aggregating infinities that all have the same sign produces infinity
4213 * with that sign. Aggregating infinities with different signs results in
4216 if (state
->pInfcount
> 0 && state
->nInfcount
> 0)
4218 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4219 errmsg("interval out of range")));
4221 result
= (Interval
*) palloc(sizeof(Interval
));
4223 if (state
->pInfcount
> 0)
4224 INTERVAL_NOEND(result
);
4225 else if (state
->nInfcount
> 0)
4226 INTERVAL_NOBEGIN(result
);
4228 memcpy(result
, &state
->sumX
, sizeof(Interval
));
4230 PG_RETURN_INTERVAL_P(result
);
4234 * Calculate time difference while retaining year/month fields.
4235 * Note that this does not result in an accurate absolute time span
4236 * since year and month are out of context once the arithmetic
4240 timestamp_age(PG_FUNCTION_ARGS
)
4242 Timestamp dt1
= PG_GETARG_TIMESTAMP(0);
4243 Timestamp dt2
= PG_GETARG_TIMESTAMP(1);
4254 result
= (Interval
*) palloc(sizeof(Interval
));
4257 * Handle infinities.
4259 * We treat anything that amounts to "infinity - infinity" as an error,
4260 * since the interval type has nothing equivalent to NaN.
4262 if (TIMESTAMP_IS_NOBEGIN(dt1
))
4264 if (TIMESTAMP_IS_NOBEGIN(dt2
))
4266 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4267 errmsg("interval out of range")));
4269 INTERVAL_NOBEGIN(result
);
4271 else if (TIMESTAMP_IS_NOEND(dt1
))
4273 if (TIMESTAMP_IS_NOEND(dt2
))
4275 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4276 errmsg("interval out of range")));
4278 INTERVAL_NOEND(result
);
4280 else if (TIMESTAMP_IS_NOBEGIN(dt2
))
4281 INTERVAL_NOEND(result
);
4282 else if (TIMESTAMP_IS_NOEND(dt2
))
4283 INTERVAL_NOBEGIN(result
);
4284 else if (timestamp2tm(dt1
, NULL
, tm1
, &fsec1
, NULL
, NULL
) == 0 &&
4285 timestamp2tm(dt2
, NULL
, tm2
, &fsec2
, NULL
, NULL
) == 0)
4287 /* form the symbolic difference */
4288 tm
->tm_usec
= fsec1
- fsec2
;
4289 tm
->tm_sec
= tm1
->tm_sec
- tm2
->tm_sec
;
4290 tm
->tm_min
= tm1
->tm_min
- tm2
->tm_min
;
4291 tm
->tm_hour
= tm1
->tm_hour
- tm2
->tm_hour
;
4292 tm
->tm_mday
= tm1
->tm_mday
- tm2
->tm_mday
;
4293 tm
->tm_mon
= tm1
->tm_mon
- tm2
->tm_mon
;
4294 tm
->tm_year
= tm1
->tm_year
- tm2
->tm_year
;
4296 /* flip sign if necessary... */
4299 tm
->tm_usec
= -tm
->tm_usec
;
4300 tm
->tm_sec
= -tm
->tm_sec
;
4301 tm
->tm_min
= -tm
->tm_min
;
4302 tm
->tm_hour
= -tm
->tm_hour
;
4303 tm
->tm_mday
= -tm
->tm_mday
;
4304 tm
->tm_mon
= -tm
->tm_mon
;
4305 tm
->tm_year
= -tm
->tm_year
;
4308 /* propagate any negative fields into the next higher field */
4309 while (tm
->tm_usec
< 0)
4311 tm
->tm_usec
+= USECS_PER_SEC
;
4315 while (tm
->tm_sec
< 0)
4317 tm
->tm_sec
+= SECS_PER_MINUTE
;
4321 while (tm
->tm_min
< 0)
4323 tm
->tm_min
+= MINS_PER_HOUR
;
4327 while (tm
->tm_hour
< 0)
4329 tm
->tm_hour
+= HOURS_PER_DAY
;
4333 while (tm
->tm_mday
< 0)
4337 tm
->tm_mday
+= day_tab
[isleap(tm1
->tm_year
)][tm1
->tm_mon
- 1];
4342 tm
->tm_mday
+= day_tab
[isleap(tm2
->tm_year
)][tm2
->tm_mon
- 1];
4347 while (tm
->tm_mon
< 0)
4349 tm
->tm_mon
+= MONTHS_PER_YEAR
;
4353 /* recover sign if necessary... */
4356 tm
->tm_usec
= -tm
->tm_usec
;
4357 tm
->tm_sec
= -tm
->tm_sec
;
4358 tm
->tm_min
= -tm
->tm_min
;
4359 tm
->tm_hour
= -tm
->tm_hour
;
4360 tm
->tm_mday
= -tm
->tm_mday
;
4361 tm
->tm_mon
= -tm
->tm_mon
;
4362 tm
->tm_year
= -tm
->tm_year
;
4365 if (itm2interval(tm
, result
) != 0)
4367 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4368 errmsg("interval out of range")));
4372 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4373 errmsg("timestamp out of range")));
4375 PG_RETURN_INTERVAL_P(result
);
4379 /* timestamptz_age()
4380 * Calculate time difference while retaining year/month fields.
4381 * Note that this does not result in an accurate absolute time span
4382 * since year and month are out of context once the arithmetic
4386 timestamptz_age(PG_FUNCTION_ARGS
)
4388 TimestampTz dt1
= PG_GETARG_TIMESTAMPTZ(0);
4389 TimestampTz dt2
= PG_GETARG_TIMESTAMPTZ(1);
4402 result
= (Interval
*) palloc(sizeof(Interval
));
4405 * Handle infinities.
4407 * We treat anything that amounts to "infinity - infinity" as an error,
4408 * since the interval type has nothing equivalent to NaN.
4410 if (TIMESTAMP_IS_NOBEGIN(dt1
))
4412 if (TIMESTAMP_IS_NOBEGIN(dt2
))
4414 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4415 errmsg("interval out of range")));
4417 INTERVAL_NOBEGIN(result
);
4419 else if (TIMESTAMP_IS_NOEND(dt1
))
4421 if (TIMESTAMP_IS_NOEND(dt2
))
4423 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4424 errmsg("interval out of range")));
4426 INTERVAL_NOEND(result
);
4428 else if (TIMESTAMP_IS_NOBEGIN(dt2
))
4429 INTERVAL_NOEND(result
);
4430 else if (TIMESTAMP_IS_NOEND(dt2
))
4431 INTERVAL_NOBEGIN(result
);
4432 else if (timestamp2tm(dt1
, &tz1
, tm1
, &fsec1
, NULL
, NULL
) == 0 &&
4433 timestamp2tm(dt2
, &tz2
, tm2
, &fsec2
, NULL
, NULL
) == 0)
4435 /* form the symbolic difference */
4436 tm
->tm_usec
= fsec1
- fsec2
;
4437 tm
->tm_sec
= tm1
->tm_sec
- tm2
->tm_sec
;
4438 tm
->tm_min
= tm1
->tm_min
- tm2
->tm_min
;
4439 tm
->tm_hour
= tm1
->tm_hour
- tm2
->tm_hour
;
4440 tm
->tm_mday
= tm1
->tm_mday
- tm2
->tm_mday
;
4441 tm
->tm_mon
= tm1
->tm_mon
- tm2
->tm_mon
;
4442 tm
->tm_year
= tm1
->tm_year
- tm2
->tm_year
;
4444 /* flip sign if necessary... */
4447 tm
->tm_usec
= -tm
->tm_usec
;
4448 tm
->tm_sec
= -tm
->tm_sec
;
4449 tm
->tm_min
= -tm
->tm_min
;
4450 tm
->tm_hour
= -tm
->tm_hour
;
4451 tm
->tm_mday
= -tm
->tm_mday
;
4452 tm
->tm_mon
= -tm
->tm_mon
;
4453 tm
->tm_year
= -tm
->tm_year
;
4456 /* propagate any negative fields into the next higher field */
4457 while (tm
->tm_usec
< 0)
4459 tm
->tm_usec
+= USECS_PER_SEC
;
4463 while (tm
->tm_sec
< 0)
4465 tm
->tm_sec
+= SECS_PER_MINUTE
;
4469 while (tm
->tm_min
< 0)
4471 tm
->tm_min
+= MINS_PER_HOUR
;
4475 while (tm
->tm_hour
< 0)
4477 tm
->tm_hour
+= HOURS_PER_DAY
;
4481 while (tm
->tm_mday
< 0)
4485 tm
->tm_mday
+= day_tab
[isleap(tm1
->tm_year
)][tm1
->tm_mon
- 1];
4490 tm
->tm_mday
+= day_tab
[isleap(tm2
->tm_year
)][tm2
->tm_mon
- 1];
4495 while (tm
->tm_mon
< 0)
4497 tm
->tm_mon
+= MONTHS_PER_YEAR
;
4502 * Note: we deliberately ignore any difference between tz1 and tz2.
4505 /* recover sign if necessary... */
4508 tm
->tm_usec
= -tm
->tm_usec
;
4509 tm
->tm_sec
= -tm
->tm_sec
;
4510 tm
->tm_min
= -tm
->tm_min
;
4511 tm
->tm_hour
= -tm
->tm_hour
;
4512 tm
->tm_mday
= -tm
->tm_mday
;
4513 tm
->tm_mon
= -tm
->tm_mon
;
4514 tm
->tm_year
= -tm
->tm_year
;
4517 if (itm2interval(tm
, result
) != 0)
4519 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4520 errmsg("interval out of range")));
4524 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4525 errmsg("timestamp out of range")));
4527 PG_RETURN_INTERVAL_P(result
);
4531 /*----------------------------------------------------------
4532 * Conversion operators.
4533 *---------------------------------------------------------*/
4537 * Bin timestamp into specified interval.
4540 timestamp_bin(PG_FUNCTION_ARGS
)
4542 Interval
*stride
= PG_GETARG_INTERVAL_P(0);
4543 Timestamp timestamp
= PG_GETARG_TIMESTAMP(1);
4544 Timestamp origin
= PG_GETARG_TIMESTAMP(2);
4551 if (TIMESTAMP_NOT_FINITE(timestamp
))
4552 PG_RETURN_TIMESTAMP(timestamp
);
4554 if (TIMESTAMP_NOT_FINITE(origin
))
4556 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4557 errmsg("origin out of range")));
4559 if (INTERVAL_NOT_FINITE(stride
))
4561 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4562 errmsg("timestamps cannot be binned into infinite intervals")));
4564 if (stride
->month
!= 0)
4566 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
4567 errmsg("timestamps cannot be binned into intervals containing months or years")));
4569 if (unlikely(pg_mul_s64_overflow(stride
->day
, USECS_PER_DAY
, &stride_usecs
)) ||
4570 unlikely(pg_add_s64_overflow(stride_usecs
, stride
->time
, &stride_usecs
)))
4572 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4573 errmsg("interval out of range")));
4575 if (stride_usecs
<= 0)
4577 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4578 errmsg("stride must be greater than zero")));
4580 if (unlikely(pg_sub_s64_overflow(timestamp
, origin
, &tm_diff
)))
4582 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4583 errmsg("interval out of range")));
4585 /* These calculations cannot overflow */
4586 tm_modulo
= tm_diff
% stride_usecs
;
4587 tm_delta
= tm_diff
- tm_modulo
;
4588 result
= origin
+ tm_delta
;
4591 * We want to round towards -infinity, not 0, when tm_diff is negative and
4592 * not a multiple of stride_usecs. This adjustment *can* cause overflow,
4593 * since the result might now be out of the range origin .. timestamp.
4597 if (unlikely(pg_sub_s64_overflow(result
, stride_usecs
, &result
)) ||
4598 !IS_VALID_TIMESTAMP(result
))
4600 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4601 errmsg("timestamp out of range")));
4604 PG_RETURN_TIMESTAMP(result
);
4607 /* timestamp_trunc()
4608 * Truncate timestamp to specified units.
4611 timestamp_trunc(PG_FUNCTION_ARGS
)
4613 text
*units
= PG_GETARG_TEXT_PP(0);
4614 Timestamp timestamp
= PG_GETARG_TIMESTAMP(1);
4623 lowunits
= downcase_truncate_identifier(VARDATA_ANY(units
),
4624 VARSIZE_ANY_EXHDR(units
),
4627 type
= DecodeUnits(0, lowunits
, &val
);
4631 if (TIMESTAMP_NOT_FINITE(timestamp
))
4634 * Errors thrown here for invalid units should exactly match those
4635 * below, else there will be unexpected discrepancies between
4636 * finite- and infinite-input cases.
4641 case DTK_MILLENNIUM
:
4653 PG_RETURN_TIMESTAMP(timestamp
);
4657 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
4658 errmsg("unit \"%s\" not supported for type %s",
4659 lowunits
, format_type_be(TIMESTAMPOID
))));
4664 if (timestamp2tm(timestamp
, NULL
, tm
, &fsec
, NULL
, NULL
) != 0)
4666 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4667 errmsg("timestamp out of range")));
4675 woy
= date2isoweek(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
);
4678 * If it is week 52/53 and the month is January, then the
4679 * week must belong to the previous year. Also, some
4680 * December dates belong to the next year.
4682 if (woy
>= 52 && tm
->tm_mon
== 1)
4684 if (woy
<= 1 && tm
->tm_mon
== MONTHS_PER_YEAR
)
4686 isoweek2date(woy
, &(tm
->tm_year
), &(tm
->tm_mon
), &(tm
->tm_mday
));
4693 case DTK_MILLENNIUM
:
4694 /* see comments in timestamptz_trunc */
4695 if (tm
->tm_year
> 0)
4696 tm
->tm_year
= ((tm
->tm_year
+ 999) / 1000) * 1000 - 999;
4698 tm
->tm_year
= -((999 - (tm
->tm_year
- 1)) / 1000) * 1000 + 1;
4701 /* see comments in timestamptz_trunc */
4702 if (tm
->tm_year
> 0)
4703 tm
->tm_year
= ((tm
->tm_year
+ 99) / 100) * 100 - 99;
4705 tm
->tm_year
= -((99 - (tm
->tm_year
- 1)) / 100) * 100 + 1;
4708 /* see comments in timestamptz_trunc */
4709 if (val
!= DTK_MILLENNIUM
&& val
!= DTK_CENTURY
)
4711 if (tm
->tm_year
> 0)
4712 tm
->tm_year
= (tm
->tm_year
/ 10) * 10;
4714 tm
->tm_year
= -((8 - (tm
->tm_year
- 1)) / 10) * 10;
4721 tm
->tm_mon
= (3 * ((tm
->tm_mon
- 1) / 3)) + 1;
4740 fsec
= (fsec
/ 1000) * 1000;
4748 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
4749 errmsg("unit \"%s\" not supported for type %s",
4750 lowunits
, format_type_be(TIMESTAMPOID
))));
4754 if (tm2timestamp(tm
, fsec
, NULL
, &result
) != 0)
4756 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4757 errmsg("timestamp out of range")));
4762 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
4763 errmsg("unit \"%s\" not recognized for type %s",
4764 lowunits
, format_type_be(TIMESTAMPOID
))));
4768 PG_RETURN_TIMESTAMP(result
);
4771 /* timestamptz_bin()
4772 * Bin timestamptz into specified interval using specified origin.
4775 timestamptz_bin(PG_FUNCTION_ARGS
)
4777 Interval
*stride
= PG_GETARG_INTERVAL_P(0);
4778 TimestampTz timestamp
= PG_GETARG_TIMESTAMPTZ(1);
4779 TimestampTz origin
= PG_GETARG_TIMESTAMPTZ(2);
4786 if (TIMESTAMP_NOT_FINITE(timestamp
))
4787 PG_RETURN_TIMESTAMPTZ(timestamp
);
4789 if (TIMESTAMP_NOT_FINITE(origin
))
4791 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4792 errmsg("origin out of range")));
4794 if (INTERVAL_NOT_FINITE(stride
))
4796 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4797 errmsg("timestamps cannot be binned into infinite intervals")));
4799 if (stride
->month
!= 0)
4801 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
4802 errmsg("timestamps cannot be binned into intervals containing months or years")));
4804 if (unlikely(pg_mul_s64_overflow(stride
->day
, USECS_PER_DAY
, &stride_usecs
)) ||
4805 unlikely(pg_add_s64_overflow(stride_usecs
, stride
->time
, &stride_usecs
)))
4807 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4808 errmsg("interval out of range")));
4810 if (stride_usecs
<= 0)
4812 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4813 errmsg("stride must be greater than zero")));
4815 if (unlikely(pg_sub_s64_overflow(timestamp
, origin
, &tm_diff
)))
4817 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4818 errmsg("interval out of range")));
4820 /* These calculations cannot overflow */
4821 tm_modulo
= tm_diff
% stride_usecs
;
4822 tm_delta
= tm_diff
- tm_modulo
;
4823 result
= origin
+ tm_delta
;
4826 * We want to round towards -infinity, not 0, when tm_diff is negative and
4827 * not a multiple of stride_usecs. This adjustment *can* cause overflow,
4828 * since the result might now be out of the range origin .. timestamp.
4832 if (unlikely(pg_sub_s64_overflow(result
, stride_usecs
, &result
)) ||
4833 !IS_VALID_TIMESTAMP(result
))
4835 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4836 errmsg("timestamp out of range")));
4839 PG_RETURN_TIMESTAMPTZ(result
);
4843 * Common code for timestamptz_trunc() and timestamptz_trunc_zone().
4845 * tzp identifies the zone to truncate with respect to. We assume
4846 * infinite timestamps have already been rejected.
4849 timestamptz_trunc_internal(text
*units
, TimestampTz timestamp
, pg_tz
*tzp
)
4855 bool redotz
= false;
4861 lowunits
= downcase_truncate_identifier(VARDATA_ANY(units
),
4862 VARSIZE_ANY_EXHDR(units
),
4865 type
= DecodeUnits(0, lowunits
, &val
);
4869 if (TIMESTAMP_NOT_FINITE(timestamp
))
4872 * Errors thrown here for invalid units should exactly match those
4873 * below, else there will be unexpected discrepancies between
4874 * finite- and infinite-input cases.
4879 case DTK_MILLENNIUM
:
4891 PG_RETURN_TIMESTAMPTZ(timestamp
);
4896 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
4897 errmsg("unit \"%s\" not supported for type %s",
4898 lowunits
, format_type_be(TIMESTAMPTZOID
))));
4903 if (timestamp2tm(timestamp
, &tz
, tm
, &fsec
, NULL
, tzp
) != 0)
4905 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
4906 errmsg("timestamp out of range")));
4914 woy
= date2isoweek(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
);
4917 * If it is week 52/53 and the month is January, then the
4918 * week must belong to the previous year. Also, some
4919 * December dates belong to the next year.
4921 if (woy
>= 52 && tm
->tm_mon
== 1)
4923 if (woy
<= 1 && tm
->tm_mon
== MONTHS_PER_YEAR
)
4925 isoweek2date(woy
, &(tm
->tm_year
), &(tm
->tm_mon
), &(tm
->tm_mday
));
4933 /* one may consider DTK_THOUSAND and DTK_HUNDRED... */
4934 case DTK_MILLENNIUM
:
4937 * truncating to the millennium? what is this supposed to
4938 * mean? let us put the first year of the millennium... i.e.
4939 * -1000, 1, 1001, 2001...
4941 if (tm
->tm_year
> 0)
4942 tm
->tm_year
= ((tm
->tm_year
+ 999) / 1000) * 1000 - 999;
4944 tm
->tm_year
= -((999 - (tm
->tm_year
- 1)) / 1000) * 1000 + 1;
4947 /* truncating to the century? as above: -100, 1, 101... */
4948 if (tm
->tm_year
> 0)
4949 tm
->tm_year
= ((tm
->tm_year
+ 99) / 100) * 100 - 99;
4951 tm
->tm_year
= -((99 - (tm
->tm_year
- 1)) / 100) * 100 + 1;
4956 * truncating to the decade? first year of the decade. must
4957 * not be applied if year was truncated before!
4959 if (val
!= DTK_MILLENNIUM
&& val
!= DTK_CENTURY
)
4961 if (tm
->tm_year
> 0)
4962 tm
->tm_year
= (tm
->tm_year
/ 10) * 10;
4964 tm
->tm_year
= -((8 - (tm
->tm_year
- 1)) / 10) * 10;
4971 tm
->tm_mon
= (3 * ((tm
->tm_mon
- 1) / 3)) + 1;
4978 redotz
= true; /* for all cases >= DAY */
4990 fsec
= (fsec
/ 1000) * 1000;
4997 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
4998 errmsg("unit \"%s\" not supported for type %s",
4999 lowunits
, format_type_be(TIMESTAMPTZOID
))));
5004 tz
= DetermineTimeZoneOffset(tm
, tzp
);
5006 if (tm2timestamp(tm
, fsec
, &tz
, &result
) != 0)
5008 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
5009 errmsg("timestamp out of range")));
5014 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
5015 errmsg("unit \"%s\" not recognized for type %s",
5016 lowunits
, format_type_be(TIMESTAMPTZOID
))));
5023 /* timestamptz_trunc()
5024 * Truncate timestamptz to specified units in session timezone.
5027 timestamptz_trunc(PG_FUNCTION_ARGS
)
5029 text
*units
= PG_GETARG_TEXT_PP(0);
5030 TimestampTz timestamp
= PG_GETARG_TIMESTAMPTZ(1);
5033 result
= timestamptz_trunc_internal(units
, timestamp
, session_timezone
);
5035 PG_RETURN_TIMESTAMPTZ(result
);
5038 /* timestamptz_trunc_zone()
5039 * Truncate timestamptz to specified units in specified timezone.
5042 timestamptz_trunc_zone(PG_FUNCTION_ARGS
)
5044 text
*units
= PG_GETARG_TEXT_PP(0);
5045 TimestampTz timestamp
= PG_GETARG_TIMESTAMPTZ(1);
5046 text
*zone
= PG_GETARG_TEXT_PP(2);
5051 * Look up the requested timezone.
5053 tzp
= lookup_timezone(zone
);
5055 result
= timestamptz_trunc_internal(units
, timestamp
, tzp
);
5057 PG_RETURN_TIMESTAMPTZ(result
);
5061 * Extract specified field from interval.
5064 interval_trunc(PG_FUNCTION_ARGS
)
5066 text
*units
= PG_GETARG_TEXT_PP(0);
5067 Interval
*interval
= PG_GETARG_INTERVAL_P(1);
5075 result
= (Interval
*) palloc(sizeof(Interval
));
5077 lowunits
= downcase_truncate_identifier(VARDATA_ANY(units
),
5078 VARSIZE_ANY_EXHDR(units
),
5081 type
= DecodeUnits(0, lowunits
, &val
);
5085 if (INTERVAL_NOT_FINITE(interval
))
5088 * Errors thrown here for invalid units should exactly match those
5089 * below, else there will be unexpected discrepancies between
5090 * finite- and infinite-input cases.
5094 case DTK_MILLENNIUM
:
5106 memcpy(result
, interval
, sizeof(Interval
));
5107 PG_RETURN_INTERVAL_P(result
);
5112 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
5113 errmsg("unit \"%s\" not supported for type %s",
5114 lowunits
, format_type_be(INTERVALOID
)),
5115 (val
== DTK_WEEK
) ? errdetail("Months usually have fractional weeks.") : 0));
5120 interval2itm(*interval
, tm
);
5123 case DTK_MILLENNIUM
:
5124 /* caution: C division may have negative remainder */
5125 tm
->tm_year
= (tm
->tm_year
/ 1000) * 1000;
5128 /* caution: C division may have negative remainder */
5129 tm
->tm_year
= (tm
->tm_year
/ 100) * 100;
5132 /* caution: C division may have negative remainder */
5133 tm
->tm_year
= (tm
->tm_year
/ 10) * 10;
5139 tm
->tm_mon
= 3 * (tm
->tm_mon
/ 3);
5157 tm
->tm_usec
= (tm
->tm_usec
/ 1000) * 1000;
5164 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
5165 errmsg("unit \"%s\" not supported for type %s",
5166 lowunits
, format_type_be(INTERVALOID
)),
5167 (val
== DTK_WEEK
) ? errdetail("Months usually have fractional weeks.") : 0));
5170 if (itm2interval(tm
, result
) != 0)
5172 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
5173 errmsg("interval out of range")));
5178 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
5179 errmsg("unit \"%s\" not recognized for type %s",
5180 lowunits
, format_type_be(INTERVALOID
))));
5183 PG_RETURN_INTERVAL_P(result
);
5188 * Return the Julian day which corresponds to the first day (Monday) of the given ISO 8601 year and week.
5189 * Julian days are used to convert between ISO week dates and Gregorian dates.
5191 * XXX: This function has integer overflow hazards, but restructuring it to
5192 * work with the soft-error handling that its callers do is likely more
5193 * trouble than it's worth.
5196 isoweek2j(int year
, int week
)
5201 /* fourth day of current year */
5202 day4
= date2j(year
, 1, 4);
5204 /* day0 == offset to first day of week (Monday) */
5205 day0
= j2day(day4
- 1);
5207 return ((week
- 1) * 7) + (day4
- day0
);
5211 * Convert ISO week of year number to date.
5212 * The year field must be specified with the ISO year!
5216 isoweek2date(int woy
, int *year
, int *mon
, int *mday
)
5218 j2date(isoweek2j(*year
, woy
), year
, mon
, mday
);
5221 /* isoweekdate2date()
5223 * Convert an ISO 8601 week date (ISO year, ISO week) into a Gregorian date.
5224 * Gregorian day of week sent so weekday strings can be supplied.
5225 * Populates year, mon, and mday with the correct Gregorian values.
5226 * year must be passed in as the ISO year.
5229 isoweekdate2date(int isoweek
, int wday
, int *year
, int *mon
, int *mday
)
5233 jday
= isoweek2j(*year
, isoweek
);
5234 /* convert Gregorian week start (Sunday=1) to ISO week start (Monday=1) */
5239 j2date(jday
, year
, mon
, mday
);
5244 * Returns ISO week number of year.
5247 date2isoweek(int year
, int mon
, int mday
)
5255 dayn
= date2j(year
, mon
, mday
);
5257 /* fourth day of current year */
5258 day4
= date2j(year
, 1, 4);
5260 /* day0 == offset to first day of week (Monday) */
5261 day0
= j2day(day4
- 1);
5264 * We need the first week containing a Thursday, otherwise this day falls
5265 * into the previous year for purposes of counting weeks
5267 if (dayn
< day4
- day0
)
5269 day4
= date2j(year
- 1, 1, 4);
5271 /* day0 == offset to first day of week (Monday) */
5272 day0
= j2day(day4
- 1);
5275 result
= (dayn
- (day4
- day0
)) / 7 + 1;
5278 * Sometimes the last few days in a year will fall into the first week of
5279 * the next year, so check for this.
5283 day4
= date2j(year
+ 1, 1, 4);
5285 /* day0 == offset to first day of week (Monday) */
5286 day0
= j2day(day4
- 1);
5288 if (dayn
>= day4
- day0
)
5289 result
= (dayn
- (day4
- day0
)) / 7 + 1;
5292 return (int) result
;
5298 * Returns ISO 8601 year number.
5299 * Note: zero or negative results follow the year-zero-exists convention.
5302 date2isoyear(int year
, int mon
, int mday
)
5310 dayn
= date2j(year
, mon
, mday
);
5312 /* fourth day of current year */
5313 day4
= date2j(year
, 1, 4);
5315 /* day0 == offset to first day of week (Monday) */
5316 day0
= j2day(day4
- 1);
5319 * We need the first week containing a Thursday, otherwise this day falls
5320 * into the previous year for purposes of counting weeks
5322 if (dayn
< day4
- day0
)
5324 day4
= date2j(year
- 1, 1, 4);
5326 /* day0 == offset to first day of week (Monday) */
5327 day0
= j2day(day4
- 1);
5332 result
= (dayn
- (day4
- day0
)) / 7 + 1;
5335 * Sometimes the last few days in a year will fall into the first week of
5336 * the next year, so check for this.
5340 day4
= date2j(year
+ 1, 1, 4);
5342 /* day0 == offset to first day of week (Monday) */
5343 day0
= j2day(day4
- 1);
5345 if (dayn
>= day4
- day0
)
5353 /* date2isoyearday()
5355 * Returns the ISO 8601 day-of-year, given a Gregorian year, month and day.
5356 * Possible return values are 1 through 371 (364 in non-leap years).
5359 date2isoyearday(int year
, int mon
, int mday
)
5361 return date2j(year
, mon
, mday
) - isoweek2j(date2isoyear(year
, mon
, mday
), 1) + 1;
5365 * NonFiniteTimestampTzPart
5367 * Used by timestamp_part and timestamptz_part when extracting from infinite
5368 * timestamp[tz]. Returns +/-Infinity if that is the appropriate result,
5369 * otherwise returns zero (which should be taken as meaning to return NULL).
5371 * Errors thrown here for invalid units should exactly match those that
5372 * would be thrown in the calling functions, else there will be unexpected
5373 * discrepancies between finite- and infinite-input cases.
5376 NonFiniteTimestampTzPart(int type
, int unit
, char *lowunits
,
5377 bool isNegative
, bool isTz
)
5379 if ((type
!= UNITS
) && (type
!= RESERV
))
5381 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
5382 errmsg("unit \"%s\" not recognized for type %s",
5384 format_type_be(isTz
? TIMESTAMPTZOID
: TIMESTAMPOID
))));
5388 /* Oscillating units */
5406 /* Monotonically-increasing units */
5410 case DTK_MILLENNIUM
:
5415 return -get_float8_infinity();
5417 return get_float8_infinity();
5421 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
5422 errmsg("unit \"%s\" not supported for type %s",
5424 format_type_be(isTz
? TIMESTAMPTZOID
: TIMESTAMPOID
))));
5425 return 0.0; /* keep compiler quiet */
5429 /* timestamp_part() and extract_timestamp()
5430 * Extract specified field from timestamp.
5433 timestamp_part_common(PG_FUNCTION_ARGS
, bool retnumeric
)
5435 text
*units
= PG_GETARG_TEXT_PP(0);
5436 Timestamp timestamp
= PG_GETARG_TIMESTAMP(1);
5446 lowunits
= downcase_truncate_identifier(VARDATA_ANY(units
),
5447 VARSIZE_ANY_EXHDR(units
),
5450 type
= DecodeUnits(0, lowunits
, &val
);
5451 if (type
== UNKNOWN_FIELD
)
5452 type
= DecodeSpecial(0, lowunits
, &val
);
5454 if (TIMESTAMP_NOT_FINITE(timestamp
))
5456 double r
= NonFiniteTimestampTzPart(type
, val
, lowunits
,
5457 TIMESTAMP_IS_NOBEGIN(timestamp
),
5465 return DirectFunctionCall3(numeric_in
,
5466 CStringGetDatum("-Infinity"),
5467 ObjectIdGetDatum(InvalidOid
),
5470 return DirectFunctionCall3(numeric_in
,
5471 CStringGetDatum("Infinity"),
5472 ObjectIdGetDatum(InvalidOid
),
5476 PG_RETURN_FLOAT8(r
);
5484 if (timestamp2tm(timestamp
, NULL
, tm
, &fsec
, NULL
, NULL
) != 0)
5486 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
5487 errmsg("timestamp out of range")));
5492 intresult
= tm
->tm_sec
* INT64CONST(1000000) + fsec
;
5498 * tm->tm_sec * 1000 + fsec / 1000
5499 * = (tm->tm_sec * 1'000'000 + fsec) / 1000
5501 PG_RETURN_NUMERIC(int64_div_fast_to_numeric(tm
->tm_sec
* INT64CONST(1000000) + fsec
, 3));
5503 PG_RETURN_FLOAT8(tm
->tm_sec
* 1000.0 + fsec
/ 1000.0);
5509 * tm->tm_sec + fsec / 1'000'000
5510 * = (tm->tm_sec * 1'000'000 + fsec) / 1'000'000
5512 PG_RETURN_NUMERIC(int64_div_fast_to_numeric(tm
->tm_sec
* INT64CONST(1000000) + fsec
, 6));
5514 PG_RETURN_FLOAT8(tm
->tm_sec
+ fsec
/ 1000000.0);
5518 intresult
= tm
->tm_min
;
5522 intresult
= tm
->tm_hour
;
5526 intresult
= tm
->tm_mday
;
5530 intresult
= tm
->tm_mon
;
5534 intresult
= (tm
->tm_mon
- 1) / 3 + 1;
5538 intresult
= date2isoweek(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
);
5542 if (tm
->tm_year
> 0)
5543 intresult
= tm
->tm_year
;
5545 /* there is no year 0, just 1 BC and 1 AD */
5546 intresult
= tm
->tm_year
- 1;
5552 * what is a decade wrt dates? let us assume that decade 199
5553 * is 1990 thru 1999... decade 0 starts on year 1 BC, and -1
5554 * is 11 BC thru 2 BC...
5556 if (tm
->tm_year
>= 0)
5557 intresult
= tm
->tm_year
/ 10;
5559 intresult
= -((8 - (tm
->tm_year
- 1)) / 10);
5565 * centuries AD, c>0: year in [ (c-1)* 100 + 1 : c*100 ]
5566 * centuries BC, c<0: year in [ c*100 : (c+1) * 100 - 1]
5567 * there is no number 0 century.
5570 if (tm
->tm_year
> 0)
5571 intresult
= (tm
->tm_year
+ 99) / 100;
5573 /* caution: C division may have negative remainder */
5574 intresult
= -((99 - (tm
->tm_year
- 1)) / 100);
5577 case DTK_MILLENNIUM
:
5578 /* see comments above. */
5579 if (tm
->tm_year
> 0)
5580 intresult
= (tm
->tm_year
+ 999) / 1000;
5582 intresult
= -((999 - (tm
->tm_year
- 1)) / 1000);
5587 PG_RETURN_NUMERIC(numeric_add_opt_error(int64_to_numeric(date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
)),
5588 numeric_div_opt_error(int64_to_numeric(((((tm
->tm_hour
* MINS_PER_HOUR
) + tm
->tm_min
) * SECS_PER_MINUTE
) + tm
->tm_sec
) * INT64CONST(1000000) + fsec
),
5589 int64_to_numeric(SECS_PER_DAY
* INT64CONST(1000000)),
5593 PG_RETURN_FLOAT8(date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
) +
5594 ((((tm
->tm_hour
* MINS_PER_HOUR
) + tm
->tm_min
) * SECS_PER_MINUTE
) +
5595 tm
->tm_sec
+ (fsec
/ 1000000.0)) / (double) SECS_PER_DAY
);
5599 intresult
= date2isoyear(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
);
5600 /* Adjust BC years */
5607 intresult
= j2day(date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
));
5608 if (val
== DTK_ISODOW
&& intresult
== 0)
5613 intresult
= (date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
)
5614 - date2j(tm
->tm_year
, 1, 1) + 1);
5622 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
5623 errmsg("unit \"%s\" not supported for type %s",
5624 lowunits
, format_type_be(TIMESTAMPOID
))));
5628 else if (type
== RESERV
)
5633 epoch
= SetEpochTimestamp();
5634 /* (timestamp - epoch) / 1000000 */
5639 if (timestamp
< (PG_INT64_MAX
+ epoch
))
5640 result
= int64_div_fast_to_numeric(timestamp
- epoch
, 6);
5643 result
= numeric_div_opt_error(numeric_sub_opt_error(int64_to_numeric(timestamp
),
5644 int64_to_numeric(epoch
),
5646 int64_to_numeric(1000000),
5648 result
= DatumGetNumeric(DirectFunctionCall2(numeric_round
,
5649 NumericGetDatum(result
),
5652 PG_RETURN_NUMERIC(result
);
5658 /* try to avoid precision loss in subtraction */
5659 if (timestamp
< (PG_INT64_MAX
+ epoch
))
5660 result
= (timestamp
- epoch
) / 1000000.0;
5662 result
= ((float8
) timestamp
- epoch
) / 1000000.0;
5663 PG_RETURN_FLOAT8(result
);
5669 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
5670 errmsg("unit \"%s\" not supported for type %s",
5671 lowunits
, format_type_be(TIMESTAMPOID
))));
5678 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
5679 errmsg("unit \"%s\" not recognized for type %s",
5680 lowunits
, format_type_be(TIMESTAMPOID
))));
5685 PG_RETURN_NUMERIC(int64_to_numeric(intresult
));
5687 PG_RETURN_FLOAT8(intresult
);
5691 timestamp_part(PG_FUNCTION_ARGS
)
5693 return timestamp_part_common(fcinfo
, false);
5697 extract_timestamp(PG_FUNCTION_ARGS
)
5699 return timestamp_part_common(fcinfo
, true);
5702 /* timestamptz_part() and extract_timestamptz()
5703 * Extract specified field from timestamp with time zone.
5706 timestamptz_part_common(PG_FUNCTION_ARGS
, bool retnumeric
)
5708 text
*units
= PG_GETARG_TEXT_PP(0);
5709 TimestampTz timestamp
= PG_GETARG_TIMESTAMPTZ(1);
5720 lowunits
= downcase_truncate_identifier(VARDATA_ANY(units
),
5721 VARSIZE_ANY_EXHDR(units
),
5724 type
= DecodeUnits(0, lowunits
, &val
);
5725 if (type
== UNKNOWN_FIELD
)
5726 type
= DecodeSpecial(0, lowunits
, &val
);
5728 if (TIMESTAMP_NOT_FINITE(timestamp
))
5730 double r
= NonFiniteTimestampTzPart(type
, val
, lowunits
,
5731 TIMESTAMP_IS_NOBEGIN(timestamp
),
5739 return DirectFunctionCall3(numeric_in
,
5740 CStringGetDatum("-Infinity"),
5741 ObjectIdGetDatum(InvalidOid
),
5744 return DirectFunctionCall3(numeric_in
,
5745 CStringGetDatum("Infinity"),
5746 ObjectIdGetDatum(InvalidOid
),
5750 PG_RETURN_FLOAT8(r
);
5758 if (timestamp2tm(timestamp
, &tz
, tm
, &fsec
, NULL
, NULL
) != 0)
5760 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
5761 errmsg("timestamp out of range")));
5770 intresult
= (-tz
/ SECS_PER_MINUTE
) % MINS_PER_HOUR
;
5774 intresult
= -tz
/ SECS_PER_HOUR
;
5778 intresult
= tm
->tm_sec
* INT64CONST(1000000) + fsec
;
5784 * tm->tm_sec * 1000 + fsec / 1000
5785 * = (tm->tm_sec * 1'000'000 + fsec) / 1000
5787 PG_RETURN_NUMERIC(int64_div_fast_to_numeric(tm
->tm_sec
* INT64CONST(1000000) + fsec
, 3));
5789 PG_RETURN_FLOAT8(tm
->tm_sec
* 1000.0 + fsec
/ 1000.0);
5795 * tm->tm_sec + fsec / 1'000'000
5796 * = (tm->tm_sec * 1'000'000 + fsec) / 1'000'000
5798 PG_RETURN_NUMERIC(int64_div_fast_to_numeric(tm
->tm_sec
* INT64CONST(1000000) + fsec
, 6));
5800 PG_RETURN_FLOAT8(tm
->tm_sec
+ fsec
/ 1000000.0);
5804 intresult
= tm
->tm_min
;
5808 intresult
= tm
->tm_hour
;
5812 intresult
= tm
->tm_mday
;
5816 intresult
= tm
->tm_mon
;
5820 intresult
= (tm
->tm_mon
- 1) / 3 + 1;
5824 intresult
= date2isoweek(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
);
5828 if (tm
->tm_year
> 0)
5829 intresult
= tm
->tm_year
;
5831 /* there is no year 0, just 1 BC and 1 AD */
5832 intresult
= tm
->tm_year
- 1;
5836 /* see comments in timestamp_part */
5837 if (tm
->tm_year
> 0)
5838 intresult
= tm
->tm_year
/ 10;
5840 intresult
= -((8 - (tm
->tm_year
- 1)) / 10);
5844 /* see comments in timestamp_part */
5845 if (tm
->tm_year
> 0)
5846 intresult
= (tm
->tm_year
+ 99) / 100;
5848 intresult
= -((99 - (tm
->tm_year
- 1)) / 100);
5851 case DTK_MILLENNIUM
:
5852 /* see comments in timestamp_part */
5853 if (tm
->tm_year
> 0)
5854 intresult
= (tm
->tm_year
+ 999) / 1000;
5856 intresult
= -((999 - (tm
->tm_year
- 1)) / 1000);
5861 PG_RETURN_NUMERIC(numeric_add_opt_error(int64_to_numeric(date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
)),
5862 numeric_div_opt_error(int64_to_numeric(((((tm
->tm_hour
* MINS_PER_HOUR
) + tm
->tm_min
) * SECS_PER_MINUTE
) + tm
->tm_sec
) * INT64CONST(1000000) + fsec
),
5863 int64_to_numeric(SECS_PER_DAY
* INT64CONST(1000000)),
5867 PG_RETURN_FLOAT8(date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
) +
5868 ((((tm
->tm_hour
* MINS_PER_HOUR
) + tm
->tm_min
) * SECS_PER_MINUTE
) +
5869 tm
->tm_sec
+ (fsec
/ 1000000.0)) / (double) SECS_PER_DAY
);
5873 intresult
= date2isoyear(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
);
5874 /* Adjust BC years */
5881 intresult
= j2day(date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
));
5882 if (val
== DTK_ISODOW
&& intresult
== 0)
5887 intresult
= (date2j(tm
->tm_year
, tm
->tm_mon
, tm
->tm_mday
)
5888 - date2j(tm
->tm_year
, 1, 1) + 1);
5893 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
5894 errmsg("unit \"%s\" not supported for type %s",
5895 lowunits
, format_type_be(TIMESTAMPTZOID
))));
5899 else if (type
== RESERV
)
5904 epoch
= SetEpochTimestamp();
5905 /* (timestamp - epoch) / 1000000 */
5910 if (timestamp
< (PG_INT64_MAX
+ epoch
))
5911 result
= int64_div_fast_to_numeric(timestamp
- epoch
, 6);
5914 result
= numeric_div_opt_error(numeric_sub_opt_error(int64_to_numeric(timestamp
),
5915 int64_to_numeric(epoch
),
5917 int64_to_numeric(1000000),
5919 result
= DatumGetNumeric(DirectFunctionCall2(numeric_round
,
5920 NumericGetDatum(result
),
5923 PG_RETURN_NUMERIC(result
);
5929 /* try to avoid precision loss in subtraction */
5930 if (timestamp
< (PG_INT64_MAX
+ epoch
))
5931 result
= (timestamp
- epoch
) / 1000000.0;
5933 result
= ((float8
) timestamp
- epoch
) / 1000000.0;
5934 PG_RETURN_FLOAT8(result
);
5940 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
5941 errmsg("unit \"%s\" not supported for type %s",
5942 lowunits
, format_type_be(TIMESTAMPTZOID
))));
5949 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
5950 errmsg("unit \"%s\" not recognized for type %s",
5951 lowunits
, format_type_be(TIMESTAMPTZOID
))));
5957 PG_RETURN_NUMERIC(int64_to_numeric(intresult
));
5959 PG_RETURN_FLOAT8(intresult
);
5963 timestamptz_part(PG_FUNCTION_ARGS
)
5965 return timestamptz_part_common(fcinfo
, false);
5969 extract_timestamptz(PG_FUNCTION_ARGS
)
5971 return timestamptz_part_common(fcinfo
, true);
5975 * NonFiniteIntervalPart
5977 * Used by interval_part when extracting from infinite interval. Returns
5978 * +/-Infinity if that is the appropriate result, otherwise returns zero
5979 * (which should be taken as meaning to return NULL).
5981 * Errors thrown here for invalid units should exactly match those that
5982 * would be thrown in the calling functions, else there will be unexpected
5983 * discrepancies between finite- and infinite-input cases.
5986 NonFiniteIntervalPart(int type
, int unit
, char *lowunits
, bool isNegative
)
5988 if ((type
!= UNITS
) && (type
!= RESERV
))
5990 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
5991 errmsg("unit \"%s\" not recognized for type %s",
5992 lowunits
, format_type_be(INTERVALOID
))));
5996 /* Oscillating units */
6006 /* Monotonically-increasing units */
6012 case DTK_MILLENNIUM
:
6015 return -get_float8_infinity();
6017 return get_float8_infinity();
6021 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
6022 errmsg("unit \"%s\" not supported for type %s",
6023 lowunits
, format_type_be(INTERVALOID
))));
6024 return 0.0; /* keep compiler quiet */
6028 /* interval_part() and extract_interval()
6029 * Extract specified field from interval.
6032 interval_part_common(PG_FUNCTION_ARGS
, bool retnumeric
)
6034 text
*units
= PG_GETARG_TEXT_PP(0);
6035 Interval
*interval
= PG_GETARG_INTERVAL_P(1);
6043 lowunits
= downcase_truncate_identifier(VARDATA_ANY(units
),
6044 VARSIZE_ANY_EXHDR(units
),
6047 type
= DecodeUnits(0, lowunits
, &val
);
6048 if (type
== UNKNOWN_FIELD
)
6049 type
= DecodeSpecial(0, lowunits
, &val
);
6051 if (INTERVAL_NOT_FINITE(interval
))
6053 double r
= NonFiniteIntervalPart(type
, val
, lowunits
,
6054 INTERVAL_IS_NOBEGIN(interval
));
6061 return DirectFunctionCall3(numeric_in
,
6062 CStringGetDatum("-Infinity"),
6063 ObjectIdGetDatum(InvalidOid
),
6066 return DirectFunctionCall3(numeric_in
,
6067 CStringGetDatum("Infinity"),
6068 ObjectIdGetDatum(InvalidOid
),
6072 PG_RETURN_FLOAT8(r
);
6080 interval2itm(*interval
, tm
);
6084 intresult
= tm
->tm_sec
* INT64CONST(1000000) + tm
->tm_usec
;
6090 * tm->tm_sec * 1000 + fsec / 1000
6091 * = (tm->tm_sec * 1'000'000 + fsec) / 1000
6093 PG_RETURN_NUMERIC(int64_div_fast_to_numeric(tm
->tm_sec
* INT64CONST(1000000) + tm
->tm_usec
, 3));
6095 PG_RETURN_FLOAT8(tm
->tm_sec
* 1000.0 + tm
->tm_usec
/ 1000.0);
6101 * tm->tm_sec + fsec / 1'000'000
6102 * = (tm->tm_sec * 1'000'000 + fsec) / 1'000'000
6104 PG_RETURN_NUMERIC(int64_div_fast_to_numeric(tm
->tm_sec
* INT64CONST(1000000) + tm
->tm_usec
, 6));
6106 PG_RETURN_FLOAT8(tm
->tm_sec
+ tm
->tm_usec
/ 1000000.0);
6110 intresult
= tm
->tm_min
;
6114 intresult
= tm
->tm_hour
;
6118 intresult
= tm
->tm_mday
;
6122 intresult
= tm
->tm_mday
/ 7;
6126 intresult
= tm
->tm_mon
;
6132 * We want to maintain the rule that a field extracted from a
6133 * negative interval is the negative of the field's value for
6134 * the sign-reversed interval. The broken-down tm_year and
6135 * tm_mon aren't very helpful for that, so work from
6138 if (interval
->month
>= 0)
6139 intresult
= (tm
->tm_mon
/ 3) + 1;
6141 intresult
= -(((-interval
->month
% MONTHS_PER_YEAR
) / 3) + 1);
6145 intresult
= tm
->tm_year
;
6149 /* caution: C division may have negative remainder */
6150 intresult
= tm
->tm_year
/ 10;
6154 /* caution: C division may have negative remainder */
6155 intresult
= tm
->tm_year
/ 100;
6158 case DTK_MILLENNIUM
:
6159 /* caution: C division may have negative remainder */
6160 intresult
= tm
->tm_year
/ 1000;
6165 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
6166 errmsg("unit \"%s\" not supported for type %s",
6167 lowunits
, format_type_be(INTERVALOID
))));
6171 else if (type
== RESERV
&& val
== DTK_EPOCH
)
6176 int64 secs_from_day_month
;
6180 * To do this calculation in integer arithmetic even though
6181 * DAYS_PER_YEAR is fractional, multiply everything by 4 and then
6182 * divide by 4 again at the end. This relies on DAYS_PER_YEAR
6183 * being a multiple of 0.25 and on SECS_PER_DAY being a multiple
6186 secs_from_day_month
= ((int64
) (4 * DAYS_PER_YEAR
) * (interval
->month
/ MONTHS_PER_YEAR
) +
6187 (int64
) (4 * DAYS_PER_MONTH
) * (interval
->month
% MONTHS_PER_YEAR
) +
6188 (int64
) 4 * interval
->day
) * (SECS_PER_DAY
/ 4);
6191 * result = secs_from_day_month + interval->time / 1'000'000
6192 * = (secs_from_day_month * 1'000'000 + interval->time) / 1'000'000
6196 * Try the computation inside int64; if it overflows, do it in
6197 * numeric (slower). This overflow happens around 10^9 days, so
6198 * not common in practice.
6200 if (!pg_mul_s64_overflow(secs_from_day_month
, 1000000, &val
) &&
6201 !pg_add_s64_overflow(val
, interval
->time
, &val
))
6202 result
= int64_div_fast_to_numeric(val
, 6);
6205 numeric_add_opt_error(int64_div_fast_to_numeric(interval
->time
, 6),
6206 int64_to_numeric(secs_from_day_month
),
6209 PG_RETURN_NUMERIC(result
);
6215 result
= interval
->time
/ 1000000.0;
6216 result
+= ((double) DAYS_PER_YEAR
* SECS_PER_DAY
) * (interval
->month
/ MONTHS_PER_YEAR
);
6217 result
+= ((double) DAYS_PER_MONTH
* SECS_PER_DAY
) * (interval
->month
% MONTHS_PER_YEAR
);
6218 result
+= ((double) SECS_PER_DAY
) * interval
->day
;
6220 PG_RETURN_FLOAT8(result
);
6226 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
6227 errmsg("unit \"%s\" not recognized for type %s",
6228 lowunits
, format_type_be(INTERVALOID
))));
6233 PG_RETURN_NUMERIC(int64_to_numeric(intresult
));
6235 PG_RETURN_FLOAT8(intresult
);
6239 interval_part(PG_FUNCTION_ARGS
)
6241 return interval_part_common(fcinfo
, false);
6245 extract_interval(PG_FUNCTION_ARGS
)
6247 return interval_part_common(fcinfo
, true);
6252 * Encode timestamp type with specified time zone.
6253 * This function is just timestamp2timestamptz() except instead of
6254 * shifting to the global timezone, we shift to the specified timezone.
6255 * This is different from the other AT TIME ZONE cases because instead
6256 * of shifting _to_ a new time zone, it sets the time to _be_ the
6257 * specified timezone.
6260 timestamp_zone(PG_FUNCTION_ARGS
)
6262 text
*zone
= PG_GETARG_TEXT_PP(0);
6263 Timestamp timestamp
= PG_GETARG_TIMESTAMP(1);
6266 char tzname
[TZ_STRLEN_MAX
+ 1];
6273 if (TIMESTAMP_NOT_FINITE(timestamp
))
6274 PG_RETURN_TIMESTAMPTZ(timestamp
);
6277 * Look up the requested timezone.
6279 text_to_cstring_buffer(zone
, tzname
, sizeof(tzname
));
6281 type
= DecodeTimezoneName(tzname
, &val
, &tzp
);
6283 if (type
== TZNAME_FIXED_OFFSET
)
6285 /* fixed-offset abbreviation */
6287 result
= dt2local(timestamp
, tz
);
6289 else if (type
== TZNAME_DYNTZ
)
6291 /* dynamic-offset abbreviation, resolve using specified time */
6292 if (timestamp2tm(timestamp
, NULL
, &tm
, &fsec
, NULL
, tzp
) != 0)
6294 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
6295 errmsg("timestamp out of range")));
6296 tz
= -DetermineTimeZoneAbbrevOffset(&tm
, tzname
, tzp
);
6297 result
= dt2local(timestamp
, tz
);
6301 /* full zone name, rotate to that zone */
6302 if (timestamp2tm(timestamp
, NULL
, &tm
, &fsec
, NULL
, tzp
) != 0)
6304 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
6305 errmsg("timestamp out of range")));
6306 tz
= DetermineTimeZoneOffset(&tm
, tzp
);
6307 if (tm2timestamp(&tm
, fsec
, &tz
, &result
) != 0)
6309 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
6310 errmsg("timestamp out of range")));
6313 if (!IS_VALID_TIMESTAMP(result
))
6315 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
6316 errmsg("timestamp out of range")));
6318 PG_RETURN_TIMESTAMPTZ(result
);
6321 /* timestamp_izone()
6322 * Encode timestamp type with specified time interval as time zone.
6325 timestamp_izone(PG_FUNCTION_ARGS
)
6327 Interval
*zone
= PG_GETARG_INTERVAL_P(0);
6328 Timestamp timestamp
= PG_GETARG_TIMESTAMP(1);
6332 if (TIMESTAMP_NOT_FINITE(timestamp
))
6333 PG_RETURN_TIMESTAMPTZ(timestamp
);
6335 if (INTERVAL_NOT_FINITE(zone
))
6337 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
6338 errmsg("interval time zone \"%s\" must be finite",
6339 DatumGetCString(DirectFunctionCall1(interval_out
,
6340 PointerGetDatum(zone
))))));
6342 if (zone
->month
!= 0 || zone
->day
!= 0)
6344 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
6345 errmsg("interval time zone \"%s\" must not include months or days",
6346 DatumGetCString(DirectFunctionCall1(interval_out
,
6347 PointerGetDatum(zone
))))));
6349 tz
= zone
->time
/ USECS_PER_SEC
;
6351 result
= dt2local(timestamp
, tz
);
6353 if (!IS_VALID_TIMESTAMP(result
))
6355 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
6356 errmsg("timestamp out of range")));
6358 PG_RETURN_TIMESTAMPTZ(result
);
6359 } /* timestamp_izone() */
6361 /* TimestampTimestampTzRequiresRewrite()
6363 * Returns false if the TimeZone GUC setting causes timestamp_timestamptz and
6364 * timestamptz_timestamp to be no-ops, where the return value has the same
6365 * bits as the argument. Since project convention is to assume a GUC changes
6366 * no more often than STABLE functions change, the answer is valid that long.
6369 TimestampTimestampTzRequiresRewrite(void)
6373 if (pg_get_timezone_offset(session_timezone
, &offset
) && offset
== 0)
6378 /* timestamp_timestamptz()
6379 * Convert local timestamp to timestamp at GMT
6382 timestamp_timestamptz(PG_FUNCTION_ARGS
)
6384 Timestamp timestamp
= PG_GETARG_TIMESTAMP(0);
6386 PG_RETURN_TIMESTAMPTZ(timestamp2timestamptz(timestamp
));
6390 * Convert timestamp to timestamp with time zone.
6392 * On successful conversion, *overflow is set to zero if it's not NULL.
6394 * If the timestamp is finite but out of the valid range for timestamptz, then:
6395 * if overflow is NULL, we throw an out-of-range error.
6396 * if overflow is not NULL, we store +1 or -1 there to indicate the sign
6397 * of the overflow, and return the appropriate timestamptz infinity.
6400 timestamp2timestamptz_opt_overflow(Timestamp timestamp
, int *overflow
)
6411 if (TIMESTAMP_NOT_FINITE(timestamp
))
6414 /* We don't expect this to fail, but check it pro forma */
6415 if (timestamp2tm(timestamp
, NULL
, tm
, &fsec
, NULL
, NULL
) == 0)
6417 tz
= DetermineTimeZoneOffset(tm
, session_timezone
);
6419 result
= dt2local(timestamp
, -tz
);
6421 if (IS_VALID_TIMESTAMP(result
))
6427 if (result
< MIN_TIMESTAMP
)
6430 TIMESTAMP_NOBEGIN(result
);
6435 TIMESTAMP_NOEND(result
);
6442 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
6443 errmsg("timestamp out of range")));
6449 * Promote timestamp to timestamptz, throwing error for overflow.
6452 timestamp2timestamptz(Timestamp timestamp
)
6454 return timestamp2timestamptz_opt_overflow(timestamp
, NULL
);
6457 /* timestamptz_timestamp()
6458 * Convert timestamp at GMT to local timestamp
6461 timestamptz_timestamp(PG_FUNCTION_ARGS
)
6463 TimestampTz timestamp
= PG_GETARG_TIMESTAMPTZ(0);
6465 PG_RETURN_TIMESTAMP(timestamptz2timestamp(timestamp
));
6469 timestamptz2timestamp(TimestampTz timestamp
)
6477 if (TIMESTAMP_NOT_FINITE(timestamp
))
6481 if (timestamp2tm(timestamp
, &tz
, tm
, &fsec
, NULL
, NULL
) != 0)
6483 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
6484 errmsg("timestamp out of range")));
6485 if (tm2timestamp(tm
, fsec
, NULL
, &result
) != 0)
6487 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
6488 errmsg("timestamp out of range")));
6493 /* timestamptz_zone()
6494 * Evaluate timestamp with time zone type at the specified time zone.
6495 * Returns a timestamp without time zone.
6498 timestamptz_zone(PG_FUNCTION_ARGS
)
6500 text
*zone
= PG_GETARG_TEXT_PP(0);
6501 TimestampTz timestamp
= PG_GETARG_TIMESTAMPTZ(1);
6504 char tzname
[TZ_STRLEN_MAX
+ 1];
6509 if (TIMESTAMP_NOT_FINITE(timestamp
))
6510 PG_RETURN_TIMESTAMP(timestamp
);
6513 * Look up the requested timezone.
6515 text_to_cstring_buffer(zone
, tzname
, sizeof(tzname
));
6517 type
= DecodeTimezoneName(tzname
, &val
, &tzp
);
6519 if (type
== TZNAME_FIXED_OFFSET
)
6521 /* fixed-offset abbreviation */
6523 result
= dt2local(timestamp
, tz
);
6525 else if (type
== TZNAME_DYNTZ
)
6527 /* dynamic-offset abbreviation, resolve using specified time */
6530 tz
= DetermineTimeZoneAbbrevOffsetTS(timestamp
, tzname
, tzp
, &isdst
);
6531 result
= dt2local(timestamp
, tz
);
6535 /* full zone name, rotate from that zone */
6539 if (timestamp2tm(timestamp
, &tz
, &tm
, &fsec
, NULL
, tzp
) != 0)
6541 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
6542 errmsg("timestamp out of range")));
6543 if (tm2timestamp(&tm
, fsec
, NULL
, &result
) != 0)
6545 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
6546 errmsg("timestamp out of range")));
6549 if (!IS_VALID_TIMESTAMP(result
))
6551 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
6552 errmsg("timestamp out of range")));
6554 PG_RETURN_TIMESTAMP(result
);
6557 /* timestamptz_izone()
6558 * Encode timestamp with time zone type with specified time interval as time zone.
6559 * Returns a timestamp without time zone.
6562 timestamptz_izone(PG_FUNCTION_ARGS
)
6564 Interval
*zone
= PG_GETARG_INTERVAL_P(0);
6565 TimestampTz timestamp
= PG_GETARG_TIMESTAMPTZ(1);
6569 if (TIMESTAMP_NOT_FINITE(timestamp
))
6570 PG_RETURN_TIMESTAMP(timestamp
);
6572 if (INTERVAL_NOT_FINITE(zone
))
6574 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
6575 errmsg("interval time zone \"%s\" must be finite",
6576 DatumGetCString(DirectFunctionCall1(interval_out
,
6577 PointerGetDatum(zone
))))));
6579 if (zone
->month
!= 0 || zone
->day
!= 0)
6581 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
6582 errmsg("interval time zone \"%s\" must not include months or days",
6583 DatumGetCString(DirectFunctionCall1(interval_out
,
6584 PointerGetDatum(zone
))))));
6586 tz
= -(zone
->time
/ USECS_PER_SEC
);
6588 result
= dt2local(timestamp
, tz
);
6590 if (!IS_VALID_TIMESTAMP(result
))
6592 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE
),
6593 errmsg("timestamp out of range")));
6595 PG_RETURN_TIMESTAMP(result
);
6598 /* generate_series_timestamp()
6599 * Generate the set of timestamps from start to finish by step
6602 generate_series_timestamp(PG_FUNCTION_ARGS
)
6604 FuncCallContext
*funcctx
;
6605 generate_series_timestamp_fctx
*fctx
;
6608 /* stuff done only on the first call of the function */
6609 if (SRF_IS_FIRSTCALL())
6611 Timestamp start
= PG_GETARG_TIMESTAMP(0);
6612 Timestamp finish
= PG_GETARG_TIMESTAMP(1);
6613 Interval
*step
= PG_GETARG_INTERVAL_P(2);
6614 MemoryContext oldcontext
;
6616 /* create a function context for cross-call persistence */
6617 funcctx
= SRF_FIRSTCALL_INIT();
6620 * switch to memory context appropriate for multiple function calls
6622 oldcontext
= MemoryContextSwitchTo(funcctx
->multi_call_memory_ctx
);
6624 /* allocate memory for user context */
6625 fctx
= (generate_series_timestamp_fctx
*)
6626 palloc(sizeof(generate_series_timestamp_fctx
));
6629 * Use fctx to keep state from call to call. Seed current with the
6630 * original start value
6632 fctx
->current
= start
;
6633 fctx
->finish
= finish
;
6636 /* Determine sign of the interval */
6637 fctx
->step_sign
= interval_sign(&fctx
->step
);
6639 if (fctx
->step_sign
== 0)
6641 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
6642 errmsg("step size cannot equal zero")));
6644 if (INTERVAL_NOT_FINITE((&fctx
->step
)))
6646 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
6647 errmsg("step size cannot be infinite")));
6649 funcctx
->user_fctx
= fctx
;
6650 MemoryContextSwitchTo(oldcontext
);
6653 /* stuff done on every call of the function */
6654 funcctx
= SRF_PERCALL_SETUP();
6657 * get the saved state and use current as the result for this iteration
6659 fctx
= funcctx
->user_fctx
;
6660 result
= fctx
->current
;
6662 if (fctx
->step_sign
> 0 ?
6663 timestamp_cmp_internal(result
, fctx
->finish
) <= 0 :
6664 timestamp_cmp_internal(result
, fctx
->finish
) >= 0)
6666 /* increment current in preparation for next iteration */
6667 fctx
->current
= DatumGetTimestamp(DirectFunctionCall2(timestamp_pl_interval
,
6668 TimestampGetDatum(fctx
->current
),
6669 PointerGetDatum(&fctx
->step
)));
6671 /* do when there is more left to send */
6672 SRF_RETURN_NEXT(funcctx
, TimestampGetDatum(result
));
6676 /* do when there is no more left */
6677 SRF_RETURN_DONE(funcctx
);
6681 /* generate_series_timestamptz()
6682 * Generate the set of timestamps from start to finish by step,
6683 * doing arithmetic in the specified or session timezone.
6686 generate_series_timestamptz_internal(FunctionCallInfo fcinfo
)
6688 FuncCallContext
*funcctx
;
6689 generate_series_timestamptz_fctx
*fctx
;
6692 /* stuff done only on the first call of the function */
6693 if (SRF_IS_FIRSTCALL())
6695 TimestampTz start
= PG_GETARG_TIMESTAMPTZ(0);
6696 TimestampTz finish
= PG_GETARG_TIMESTAMPTZ(1);
6697 Interval
*step
= PG_GETARG_INTERVAL_P(2);
6698 text
*zone
= (PG_NARGS() == 4) ? PG_GETARG_TEXT_PP(3) : NULL
;
6699 MemoryContext oldcontext
;
6701 /* create a function context for cross-call persistence */
6702 funcctx
= SRF_FIRSTCALL_INIT();
6705 * switch to memory context appropriate for multiple function calls
6707 oldcontext
= MemoryContextSwitchTo(funcctx
->multi_call_memory_ctx
);
6709 /* allocate memory for user context */
6710 fctx
= (generate_series_timestamptz_fctx
*)
6711 palloc(sizeof(generate_series_timestamptz_fctx
));
6714 * Use fctx to keep state from call to call. Seed current with the
6715 * original start value
6717 fctx
->current
= start
;
6718 fctx
->finish
= finish
;
6720 fctx
->attimezone
= zone
? lookup_timezone(zone
) : session_timezone
;
6722 /* Determine sign of the interval */
6723 fctx
->step_sign
= interval_sign(&fctx
->step
);
6725 if (fctx
->step_sign
== 0)
6727 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
6728 errmsg("step size cannot equal zero")));
6730 if (INTERVAL_NOT_FINITE((&fctx
->step
)))
6732 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
6733 errmsg("step size cannot be infinite")));
6735 funcctx
->user_fctx
= fctx
;
6736 MemoryContextSwitchTo(oldcontext
);
6739 /* stuff done on every call of the function */
6740 funcctx
= SRF_PERCALL_SETUP();
6743 * get the saved state and use current as the result for this iteration
6745 fctx
= funcctx
->user_fctx
;
6746 result
= fctx
->current
;
6748 if (fctx
->step_sign
> 0 ?
6749 timestamp_cmp_internal(result
, fctx
->finish
) <= 0 :
6750 timestamp_cmp_internal(result
, fctx
->finish
) >= 0)
6752 /* increment current in preparation for next iteration */
6753 fctx
->current
= timestamptz_pl_interval_internal(fctx
->current
,
6757 /* do when there is more left to send */
6758 SRF_RETURN_NEXT(funcctx
, TimestampTzGetDatum(result
));
6762 /* do when there is no more left */
6763 SRF_RETURN_DONE(funcctx
);
6768 generate_series_timestamptz(PG_FUNCTION_ARGS
)
6770 return generate_series_timestamptz_internal(fcinfo
);
6774 generate_series_timestamptz_at_zone(PG_FUNCTION_ARGS
)
6776 return generate_series_timestamptz_internal(fcinfo
);
6780 * Planner support function for generate_series(timestamp, timestamp, interval)
6783 generate_series_timestamp_support(PG_FUNCTION_ARGS
)
6785 Node
*rawreq
= (Node
*) PG_GETARG_POINTER(0);
6788 if (IsA(rawreq
, SupportRequestRows
))
6790 /* Try to estimate the number of rows returned */
6791 SupportRequestRows
*req
= (SupportRequestRows
*) rawreq
;
6793 if (is_funcclause(req
->node
)) /* be paranoid */
6795 List
*args
= ((FuncExpr
*) req
->node
)->args
;
6800 /* We can use estimated argument values here */
6801 arg1
= estimate_expression_value(req
->root
, linitial(args
));
6802 arg2
= estimate_expression_value(req
->root
, lsecond(args
));
6803 arg3
= estimate_expression_value(req
->root
, lthird(args
));
6806 * If any argument is constant NULL, we can safely assume that
6807 * zero rows are returned. Otherwise, if they're all non-NULL
6808 * constants, we can calculate the number of rows that will be
6811 if ((IsA(arg1
, Const
) && ((Const
*) arg1
)->constisnull
) ||
6812 (IsA(arg2
, Const
) && ((Const
*) arg2
)->constisnull
) ||
6813 (IsA(arg3
, Const
) && ((Const
*) arg3
)->constisnull
))
6818 else if (IsA(arg1
, Const
) && IsA(arg2
, Const
) && IsA(arg3
, Const
))
6827 start
= DatumGetTimestamp(((Const
*) arg1
)->constvalue
);
6828 finish
= DatumGetTimestamp(((Const
*) arg2
)->constvalue
);
6829 step
= DatumGetIntervalP(((Const
*) arg3
)->constvalue
);
6832 * Perform some prechecks which could cause timestamp_mi to
6833 * raise an ERROR. It's much better to just return some
6834 * default estimate than error out in a support function.
6836 if (!TIMESTAMP_NOT_FINITE(start
) && !TIMESTAMP_NOT_FINITE(finish
) &&
6837 !pg_sub_s64_overflow(finish
, start
, &dummy
))
6839 diff
= DirectFunctionCall2(timestamp_mi
,
6840 TimestampGetDatum(finish
),
6841 TimestampGetDatum(start
));
6843 #define INTERVAL_TO_MICROSECONDS(i) ((((double) (i)->month * DAYS_PER_MONTH + (i)->day)) * USECS_PER_DAY + (i)->time)
6845 dstep
= INTERVAL_TO_MICROSECONDS(step
);
6847 /* This equation works for either sign of step */
6850 Interval
*idiff
= DatumGetIntervalP(diff
);
6851 double ddiff
= INTERVAL_TO_MICROSECONDS(idiff
);
6853 req
->rows
= floor(ddiff
/ dstep
+ 1.0);
6856 #undef INTERVAL_TO_MICROSECONDS
6862 PG_RETURN_POINTER(ret
);
6866 /* timestamp_at_local()
6867 * timestamptz_at_local()
6869 * The regression tests do not like two functions with the same proargs and
6870 * prosrc but different proname, but the grammar for AT LOCAL needs an
6871 * overloaded name to handle both types of timestamp, so we make simple
6875 timestamp_at_local(PG_FUNCTION_ARGS
)
6877 return timestamp_timestamptz(fcinfo
);
6881 timestamptz_at_local(PG_FUNCTION_ARGS
)
6883 return timestamptz_timestamp(fcinfo
);