1 /*-------------------------------------------------------------------------
2 *
3 * timestamp.c
4 * Functions for the built-in SQL types "timestamp" and "interval".
5 *
6 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/utils/adt/timestamp.c
12 *
13 *-------------------------------------------------------------------------
14 */
15
16 #include "postgres.h"
17
18 #include <ctype.h>
19 #include <math.h>
20 #include <float.h>
21 #include <limits.h>
22 #include <sys/time.h>
23
24 #include "access/hash.h"
25 #include "access/xact.h"
26 #include "catalog/pg_type.h"
27 #include "common/int128.h"
28 #include "funcapi.h"
29 #include "libpq/pqformat.h"
30 #include "miscadmin.h"
31 #include "nodes/makefuncs.h"
32 #include "nodes/nodeFuncs.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
39 /*
40 * gcc's -ffast-math switch breaks routines that expect exact results from
41 * expressions like timeval / SECS_PER_HOUR, where timeval is double.
42 */
43 #ifdef __FAST_MATH__
44 #error -ffast-math is known to break this code
45 #endif
46
47 #define SAMESIGN(a,b) (((a) < 0) == ((b) < 0))
48
49 /* Set at postmaster start */
50 TimestampTz PgStartTime;
51
52 /* Set at configuration reload */
53 TimestampTz PgReloadTime;
54
55 typedef struct
56 {
57 Timestamp current;
58 Timestamp finish;
59 Interval step;
60 int step_sign;
61 } generate_series_timestamp_fctx;
62
63 typedef struct
64 {
65 TimestampTz current;
66 TimestampTz finish;
67 Interval step;
68 int step_sign;
69 } generate_series_timestamptz_fctx;
70
71
72 static TimeOffset time2t(const int hour, const int min, const int sec, const fsec_t fsec);
73 static Timestamp dt2local(Timestamp dt, int timezone);
74 static void AdjustTimestampForTypmod(Timestamp *time, int32 typmod);
75 static void AdjustIntervalForTypmod(Interval *interval, int32 typmod);
76 static TimestampTz timestamp2timestamptz(Timestamp timestamp);
77 static Timestamp timestamptz2timestamp(TimestampTz timestamp);
78
79
80 /* common code for timestamptypmodin and timestamptztypmodin */
81 static int32
anytimestamp_typmodin(bool istz,ArrayType * ta)82 anytimestamp_typmodin(bool istz, ArrayType *ta)
83 {
84 int32 *tl;
85 int n;
86
87 tl = ArrayGetIntegerTypmods(ta, &n);
88
89 /*
90 * we're not too tense about good error message here because grammar
91 * shouldn't allow wrong number of modifiers for TIMESTAMP
92 */
93 if (n != 1)
94 ereport(ERROR,
95 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
96 errmsg("invalid type modifier")));
97
98 return anytimestamp_typmod_check(istz, tl[0]);
99 }
100
101 /* exported so parse_expr.c can use it */
102 int32
anytimestamp_typmod_check(bool istz,int32 typmod)103 anytimestamp_typmod_check(bool istz, int32 typmod)
104 {
105 if (typmod < 0)
106 ereport(ERROR,
107 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
108 errmsg("TIMESTAMP(%d)%s precision must not be negative",
109 typmod, (istz ? " WITH TIME ZONE" : ""))));
110 if (typmod > MAX_TIMESTAMP_PRECISION)
111 {
112 ereport(WARNING,
113 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
114 errmsg("TIMESTAMP(%d)%s precision reduced to maximum allowed, %d",
115 typmod, (istz ? " WITH TIME ZONE" : ""),
116 MAX_TIMESTAMP_PRECISION)));
117 typmod = MAX_TIMESTAMP_PRECISION;
118 }
119
120 return typmod;
121 }
122
123 /* common code for timestamptypmodout and timestamptztypmodout */
124 static char *
anytimestamp_typmodout(bool istz,int32 typmod)125 anytimestamp_typmodout(bool istz, int32 typmod)
126 {
127 const char *tz = istz ? " with time zone" : " without time zone";
128
129 if (typmod >= 0)
130 return psprintf("(%d)%s", (int) typmod, tz);
131 else
132 return psprintf("%s", tz);
133 }
134
135
136 /*****************************************************************************
137 * USER I/O ROUTINES *
138 *****************************************************************************/
139
140 /* timestamp_in()
141 * Convert a string to internal form.
142 */
143 Datum
timestamp_in(PG_FUNCTION_ARGS)144 timestamp_in(PG_FUNCTION_ARGS)
145 {
146 char *str = PG_GETARG_CSTRING(0);
147
148 #ifdef NOT_USED
149 Oid typelem = PG_GETARG_OID(1);
150 #endif
151 int32 typmod = PG_GETARG_INT32(2);
152 Timestamp result;
153 fsec_t fsec;
154 struct pg_tm tt,
155 *tm = &tt;
156 int tz;
157 int dtype;
158 int nf;
159 int dterr;
160 char *field[MAXDATEFIELDS];
161 int ftype[MAXDATEFIELDS];
162 char workbuf[MAXDATELEN + MAXDATEFIELDS];
163
164 dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
165 field, ftype, MAXDATEFIELDS, &nf);
166 if (dterr == 0)
167 dterr = DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz);
168 if (dterr != 0)
169 DateTimeParseError(dterr, str, "timestamp");
170
171 switch (dtype)
172 {
173 case DTK_DATE:
174 if (tm2timestamp(tm, fsec, NULL, &result) != 0)
175 ereport(ERROR,
176 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
177 errmsg("timestamp out of range: \"%s\"", str)));
178 break;
179
180 case DTK_EPOCH:
181 result = SetEpochTimestamp();
182 break;
183
184 case DTK_LATE:
185 TIMESTAMP_NOEND(result);
186 break;
187
188 case DTK_EARLY:
189 TIMESTAMP_NOBEGIN(result);
190 break;
191
192 case DTK_INVALID:
193 ereport(ERROR,
194 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
195 errmsg("date/time value \"%s\" is no longer supported", str)));
196
197 TIMESTAMP_NOEND(result);
198 break;
199
200 default:
201 elog(ERROR, "unexpected dtype %d while parsing timestamp \"%s\"",
202 dtype, str);
203 TIMESTAMP_NOEND(result);
204 }
205
206 AdjustTimestampForTypmod(&result, typmod);
207
208 PG_RETURN_TIMESTAMP(result);
209 }
210
211 /* timestamp_out()
212 * Convert a timestamp to external form.
213 */
214 Datum
timestamp_out(PG_FUNCTION_ARGS)215 timestamp_out(PG_FUNCTION_ARGS)
216 {
217 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
218 char *result;
219 struct pg_tm tt,
220 *tm = &tt;
221 fsec_t fsec;
222 char buf[MAXDATELEN + 1];
223
224 if (TIMESTAMP_NOT_FINITE(timestamp))
225 EncodeSpecialTimestamp(timestamp, buf);
226 else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) == 0)
227 EncodeDateTime(tm, fsec, false, 0, NULL, DateStyle, buf);
228 else
229 ereport(ERROR,
230 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
231 errmsg("timestamp out of range")));
232
233 result = pstrdup(buf);
234 PG_RETURN_CSTRING(result);
235 }
236
237 /*
238 * timestamp_recv - converts external binary format to timestamp
239 */
240 Datum
timestamp_recv(PG_FUNCTION_ARGS)241 timestamp_recv(PG_FUNCTION_ARGS)
242 {
243 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
244
245 #ifdef NOT_USED
246 Oid typelem = PG_GETARG_OID(1);
247 #endif
248 int32 typmod = PG_GETARG_INT32(2);
249 Timestamp timestamp;
250 struct pg_tm tt,
251 *tm = &tt;
252 fsec_t fsec;
253
254 timestamp = (Timestamp) pq_getmsgint64(buf);
255
256 /* range check: see if timestamp_out would like it */
257 if (TIMESTAMP_NOT_FINITE(timestamp))
258 /* ok */ ;
259 else if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0 ||
260 !IS_VALID_TIMESTAMP(timestamp))
261 ereport(ERROR,
262 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
263 errmsg("timestamp out of range")));
264
265 AdjustTimestampForTypmod(×tamp, typmod);
266
267 PG_RETURN_TIMESTAMP(timestamp);
268 }
269
270 /*
271 * timestamp_send - converts timestamp to binary format
272 */
273 Datum
timestamp_send(PG_FUNCTION_ARGS)274 timestamp_send(PG_FUNCTION_ARGS)
275 {
276 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
277 StringInfoData buf;
278
279 pq_begintypsend(&buf);
280 pq_sendint64(&buf, timestamp);
281 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
282 }
283
284 Datum
timestamptypmodin(PG_FUNCTION_ARGS)285 timestamptypmodin(PG_FUNCTION_ARGS)
286 {
287 ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
288
289 PG_RETURN_INT32(anytimestamp_typmodin(false, ta));
290 }
291
292 Datum
timestamptypmodout(PG_FUNCTION_ARGS)293 timestamptypmodout(PG_FUNCTION_ARGS)
294 {
295 int32 typmod = PG_GETARG_INT32(0);
296
297 PG_RETURN_CSTRING(anytimestamp_typmodout(false, typmod));
298 }
299
300
301 /* timestamp_transform()
302 * Flatten calls to timestamp_scale() and timestamptz_scale() that solely
303 * represent increases in allowed precision.
304 */
305 Datum
timestamp_transform(PG_FUNCTION_ARGS)306 timestamp_transform(PG_FUNCTION_ARGS)
307 {
308 PG_RETURN_POINTER(TemporalTransform(MAX_TIMESTAMP_PRECISION,
309 (Node *) PG_GETARG_POINTER(0)));
310 }
311
312 /* timestamp_scale()
313 * Adjust time type for specified scale factor.
314 * Used by PostgreSQL type system to stuff columns.
315 */
316 Datum
timestamp_scale(PG_FUNCTION_ARGS)317 timestamp_scale(PG_FUNCTION_ARGS)
318 {
319 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
320 int32 typmod = PG_GETARG_INT32(1);
321 Timestamp result;
322
323 result = timestamp;
324
325 AdjustTimestampForTypmod(&result, typmod);
326
327 PG_RETURN_TIMESTAMP(result);
328 }
329
330 /*
331 * AdjustTimestampForTypmod --- round off a timestamp to suit given typmod
332 * Works for either timestamp or timestamptz.
333 */
334 static void
AdjustTimestampForTypmod(Timestamp * time,int32 typmod)335 AdjustTimestampForTypmod(Timestamp *time, int32 typmod)
336 {
337 static const int64 TimestampScales[MAX_TIMESTAMP_PRECISION + 1] = {
338 INT64CONST(1000000),
339 INT64CONST(100000),
340 INT64CONST(10000),
341 INT64CONST(1000),
342 INT64CONST(100),
343 INT64CONST(10),
344 INT64CONST(1)
345 };
346
347 static const int64 TimestampOffsets[MAX_TIMESTAMP_PRECISION + 1] = {
348 INT64CONST(500000),
349 INT64CONST(50000),
350 INT64CONST(5000),
351 INT64CONST(500),
352 INT64CONST(50),
353 INT64CONST(5),
354 INT64CONST(0)
355 };
356
357 if (!TIMESTAMP_NOT_FINITE(*time)
358 && (typmod != -1) && (typmod != MAX_TIMESTAMP_PRECISION))
359 {
360 if (typmod < 0 || typmod > MAX_TIMESTAMP_PRECISION)
361 ereport(ERROR,
362 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
363 errmsg("timestamp(%d) precision must be between %d and %d",
364 typmod, 0, MAX_TIMESTAMP_PRECISION)));
365
366 if (*time >= INT64CONST(0))
367 {
368 *time = ((*time + TimestampOffsets[typmod]) / TimestampScales[typmod]) *
369 TimestampScales[typmod];
370 }
371 else
372 {
373 *time = -((((-*time) + TimestampOffsets[typmod]) / TimestampScales[typmod])
374 * TimestampScales[typmod]);
375 }
376 }
377 }
378
379
380 /* timestamptz_in()
381 * Convert a string to internal form.
382 */
383 Datum
timestamptz_in(PG_FUNCTION_ARGS)384 timestamptz_in(PG_FUNCTION_ARGS)
385 {
386 char *str = PG_GETARG_CSTRING(0);
387
388 #ifdef NOT_USED
389 Oid typelem = PG_GETARG_OID(1);
390 #endif
391 int32 typmod = PG_GETARG_INT32(2);
392 TimestampTz result;
393 fsec_t fsec;
394 struct pg_tm tt,
395 *tm = &tt;
396 int tz;
397 int dtype;
398 int nf;
399 int dterr;
400 char *field[MAXDATEFIELDS];
401 int ftype[MAXDATEFIELDS];
402 char workbuf[MAXDATELEN + MAXDATEFIELDS];
403
404 dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
405 field, ftype, MAXDATEFIELDS, &nf);
406 if (dterr == 0)
407 dterr = DecodeDateTime(field, ftype, nf, &dtype, tm, &fsec, &tz);
408 if (dterr != 0)
409 DateTimeParseError(dterr, str, "timestamp with time zone");
410
411 switch (dtype)
412 {
413 case DTK_DATE:
414 if (tm2timestamp(tm, fsec, &tz, &result) != 0)
415 ereport(ERROR,
416 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
417 errmsg("timestamp out of range: \"%s\"", str)));
418 break;
419
420 case DTK_EPOCH:
421 result = SetEpochTimestamp();
422 break;
423
424 case DTK_LATE:
425 TIMESTAMP_NOEND(result);
426 break;
427
428 case DTK_EARLY:
429 TIMESTAMP_NOBEGIN(result);
430 break;
431
432 case DTK_INVALID:
433 ereport(ERROR,
434 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
435 errmsg("date/time value \"%s\" is no longer supported", str)));
436
437 TIMESTAMP_NOEND(result);
438 break;
439
440 default:
441 elog(ERROR, "unexpected dtype %d while parsing timestamptz \"%s\"",
442 dtype, str);
443 TIMESTAMP_NOEND(result);
444 }
445
446 AdjustTimestampForTypmod(&result, typmod);
447
448 PG_RETURN_TIMESTAMPTZ(result);
449 }
450
451 /*
452 * Try to parse a timezone specification, and return its timezone offset value
453 * if it's acceptable. Otherwise, an error is thrown.
454 *
455 * Note: some code paths update tm->tm_isdst, and some don't; current callers
456 * don't care, so we don't bother being consistent.
457 */
458 static int
parse_sane_timezone(struct pg_tm * tm,text * zone)459 parse_sane_timezone(struct pg_tm *tm, text *zone)
460 {
461 char tzname[TZ_STRLEN_MAX + 1];
462 int rt;
463 int tz;
464
465 text_to_cstring_buffer(zone, tzname, sizeof(tzname));
466
467 /*
468 * Look up the requested timezone. First we try to interpret it as a
469 * numeric timezone specification; if DecodeTimezone decides it doesn't
470 * like the format, we look in the timezone abbreviation table (to handle
471 * cases like "EST"), and if that also fails, we look in the timezone
472 * database (to handle cases like "America/New_York"). (This matches the
473 * order in which timestamp input checks the cases; it's important because
474 * the timezone database unwisely uses a few zone names that are identical
475 * to offset abbreviations.)
476 *
477 * Note pg_tzset happily parses numeric input that DecodeTimezone would
478 * reject. To avoid having it accept input that would otherwise be seen
479 * as invalid, it's enough to disallow having a digit in the first
480 * position of our input string.
481 */
482 if (isdigit((unsigned char) *tzname))
483 ereport(ERROR,
484 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
485 errmsg("invalid input syntax for numeric time zone: \"%s\"",
486 tzname),
487 errhint("Numeric time zones must have \"-\" or \"+\" as first character.")));
488
489 rt = DecodeTimezone(tzname, &tz);
490 if (rt != 0)
491 {
492 char *lowzone;
493 int type,
494 val;
495 pg_tz *tzp;
496
497 if (rt == DTERR_TZDISP_OVERFLOW)
498 ereport(ERROR,
499 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
500 errmsg("numeric time zone \"%s\" out of range", tzname)));
501 else if (rt != DTERR_BAD_FORMAT)
502 ereport(ERROR,
503 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
504 errmsg("time zone \"%s\" not recognized", tzname)));
505
506 /* DecodeTimezoneAbbrev requires lowercase input */
507 lowzone = downcase_truncate_identifier(tzname,
508 strlen(tzname),
509 false);
510 type = DecodeTimezoneAbbrev(0, lowzone, &val, &tzp);
511
512 if (type == TZ || type == DTZ)
513 {
514 /* fixed-offset abbreviation */
515 tz = -val;
516 }
517 else if (type == DYNTZ)
518 {
519 /* dynamic-offset abbreviation, resolve using specified time */
520 tz = DetermineTimeZoneAbbrevOffset(tm, tzname, tzp);
521 }
522 else
523 {
524 /* try it as a full zone name */
525 tzp = pg_tzset(tzname);
526 if (tzp)
527 tz = DetermineTimeZoneOffset(tm, tzp);
528 else
529 ereport(ERROR,
530 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
531 errmsg("time zone \"%s\" not recognized", tzname)));
532 }
533 }
534
535 return tz;
536 }
537
538 /*
539 * make_timestamp_internal
540 * workhorse for make_timestamp and make_timestamptz
541 */
542 static Timestamp
make_timestamp_internal(int year,int month,int day,int hour,int min,double sec)543 make_timestamp_internal(int year, int month, int day,
544 int hour, int min, double sec)
545 {
546 struct pg_tm tm;
547 TimeOffset date;
548 TimeOffset time;
549 int dterr;
550 Timestamp result;
551
552 tm.tm_year = year;
553 tm.tm_mon = month;
554 tm.tm_mday = day;
555
556 /*
557 * Note: we'll reject zero or negative year values. Perhaps negatives
558 * should be allowed to represent BC years?
559 */
560 dterr = ValidateDate(DTK_DATE_M, false, false, false, &tm);
561
562 if (dterr != 0)
563 ereport(ERROR,
564 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
565 errmsg("date field value out of range: %d-%02d-%02d",
566 year, month, day)));
567
568 if (!IS_VALID_JULIAN(tm.tm_year, tm.tm_mon, tm.tm_mday))
569 ereport(ERROR,
570 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
571 errmsg("date out of range: %d-%02d-%02d",
572 year, month, day)));
573
574 date = date2j(tm.tm_year, tm.tm_mon, tm.tm_mday) - POSTGRES_EPOCH_JDATE;
575
576 /* Check for time overflow */
577 if (float_time_overflows(hour, min, sec))
578 ereport(ERROR,
579 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
580 errmsg("time field value out of range: %d:%02d:%02g",
581 hour, min, sec)));
582
583 /* This should match tm2time */
584 time = (((hour * MINS_PER_HOUR + min) * SECS_PER_MINUTE)
585 * USECS_PER_SEC) + (int64) rint(sec * USECS_PER_SEC);
586
587 result = date * USECS_PER_DAY + time;
588 /* check for major overflow */
589 if ((result - time) / USECS_PER_DAY != date)
590 ereport(ERROR,
591 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
592 errmsg("timestamp out of range: %d-%02d-%02d %d:%02d:%02g",
593 year, month, day,
594 hour, min, sec)));
595
596 /* check for just-barely overflow (okay except time-of-day wraps) */
597 /* caution: we want to allow 1999-12-31 24:00:00 */
598 if ((result < 0 && date > 0) ||
599 (result > 0 && date < -1))
600 ereport(ERROR,
601 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
602 errmsg("timestamp out of range: %d-%02d-%02d %d:%02d:%02g",
603 year, month, day,
604 hour, min, sec)));
605
606 /* final range check catches just-out-of-range timestamps */
607 if (!IS_VALID_TIMESTAMP(result))
608 ereport(ERROR,
609 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
610 errmsg("timestamp out of range: %d-%02d-%02d %d:%02d:%02g",
611 year, month, day,
612 hour, min, sec)));
613
614 return result;
615 }
616
617 /*
618 * make_timestamp() - timestamp constructor
619 */
620 Datum
make_timestamp(PG_FUNCTION_ARGS)621 make_timestamp(PG_FUNCTION_ARGS)
622 {
623 int32 year = PG_GETARG_INT32(0);
624 int32 month = PG_GETARG_INT32(1);
625 int32 mday = PG_GETARG_INT32(2);
626 int32 hour = PG_GETARG_INT32(3);
627 int32 min = PG_GETARG_INT32(4);
628 float8 sec = PG_GETARG_FLOAT8(5);
629 Timestamp result;
630
631 result = make_timestamp_internal(year, month, mday,
632 hour, min, sec);
633
634 PG_RETURN_TIMESTAMP(result);
635 }
636
637 /*
638 * make_timestamptz() - timestamp with time zone constructor
639 */
640 Datum
make_timestamptz(PG_FUNCTION_ARGS)641 make_timestamptz(PG_FUNCTION_ARGS)
642 {
643 int32 year = PG_GETARG_INT32(0);
644 int32 month = PG_GETARG_INT32(1);
645 int32 mday = PG_GETARG_INT32(2);
646 int32 hour = PG_GETARG_INT32(3);
647 int32 min = PG_GETARG_INT32(4);
648 float8 sec = PG_GETARG_FLOAT8(5);
649 Timestamp result;
650
651 result = make_timestamp_internal(year, month, mday,
652 hour, min, sec);
653
654 PG_RETURN_TIMESTAMPTZ(timestamp2timestamptz(result));
655 }
656
657 /*
658 * Construct a timestamp with time zone.
659 * As above, but the time zone is specified as seventh argument.
660 */
661 Datum
make_timestamptz_at_timezone(PG_FUNCTION_ARGS)662 make_timestamptz_at_timezone(PG_FUNCTION_ARGS)
663 {
664 int32 year = PG_GETARG_INT32(0);
665 int32 month = PG_GETARG_INT32(1);
666 int32 mday = PG_GETARG_INT32(2);
667 int32 hour = PG_GETARG_INT32(3);
668 int32 min = PG_GETARG_INT32(4);
669 float8 sec = PG_GETARG_FLOAT8(5);
670 text *zone = PG_GETARG_TEXT_PP(6);
671 TimestampTz result;
672 Timestamp timestamp;
673 struct pg_tm tt;
674 int tz;
675 fsec_t fsec;
676
677 timestamp = make_timestamp_internal(year, month, mday,
678 hour, min, sec);
679
680 if (timestamp2tm(timestamp, NULL, &tt, &fsec, NULL, NULL) != 0)
681 ereport(ERROR,
682 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
683 errmsg("timestamp out of range")));
684
685 tz = parse_sane_timezone(&tt, zone);
686
687 result = dt2local(timestamp, -tz);
688
689 if (!IS_VALID_TIMESTAMP(result))
690 ereport(ERROR,
691 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
692 errmsg("timestamp out of range")));
693
694 PG_RETURN_TIMESTAMPTZ(result);
695 }
696
697 /*
698 * to_timestamp(double precision)
699 * Convert UNIX epoch to timestamptz.
700 */
701 Datum
float8_timestamptz(PG_FUNCTION_ARGS)702 float8_timestamptz(PG_FUNCTION_ARGS)
703 {
704 float8 seconds = PG_GETARG_FLOAT8(0);
705 TimestampTz result;
706
707 /* Deal with NaN and infinite inputs ... */
708 if (isnan(seconds))
709 ereport(ERROR,
710 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
711 errmsg("timestamp cannot be NaN")));
712
713 if (isinf(seconds))
714 {
715 if (seconds < 0)
716 TIMESTAMP_NOBEGIN(result);
717 else
718 TIMESTAMP_NOEND(result);
719 }
720 else
721 {
722 /* Out of range? */
723 if (seconds <
724 (float8) SECS_PER_DAY * (DATETIME_MIN_JULIAN - UNIX_EPOCH_JDATE)
725 || seconds >=
726 (float8) SECS_PER_DAY * (TIMESTAMP_END_JULIAN - UNIX_EPOCH_JDATE))
727 ereport(ERROR,
728 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
729 errmsg("timestamp out of range: \"%g\"", seconds)));
730
731 /* Convert UNIX epoch to Postgres epoch */
732 seconds -= ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);
733
734 seconds = rint(seconds * USECS_PER_SEC);
735 result = (int64) seconds;
736
737 /* Recheck in case roundoff produces something just out of range */
738 if (!IS_VALID_TIMESTAMP(result))
739 ereport(ERROR,
740 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
741 errmsg("timestamp out of range: \"%g\"",
742 PG_GETARG_FLOAT8(0))));
743 }
744
745 PG_RETURN_TIMESTAMP(result);
746 }
747
748 /* timestamptz_out()
749 * Convert a timestamp to external form.
750 */
751 Datum
timestamptz_out(PG_FUNCTION_ARGS)752 timestamptz_out(PG_FUNCTION_ARGS)
753 {
754 TimestampTz dt = PG_GETARG_TIMESTAMPTZ(0);
755 char *result;
756 int tz;
757 struct pg_tm tt,
758 *tm = &tt;
759 fsec_t fsec;
760 const char *tzn;
761 char buf[MAXDATELEN + 1];
762
763 if (TIMESTAMP_NOT_FINITE(dt))
764 EncodeSpecialTimestamp(dt, buf);
765 else if (timestamp2tm(dt, &tz, tm, &fsec, &tzn, NULL) == 0)
766 EncodeDateTime(tm, fsec, true, tz, tzn, DateStyle, buf);
767 else
768 ereport(ERROR,
769 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
770 errmsg("timestamp out of range")));
771
772 result = pstrdup(buf);
773 PG_RETURN_CSTRING(result);
774 }
775
776 /*
777 * timestamptz_recv - converts external binary format to timestamptz
778 */
779 Datum
timestamptz_recv(PG_FUNCTION_ARGS)780 timestamptz_recv(PG_FUNCTION_ARGS)
781 {
782 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
783
784 #ifdef NOT_USED
785 Oid typelem = PG_GETARG_OID(1);
786 #endif
787 int32 typmod = PG_GETARG_INT32(2);
788 TimestampTz timestamp;
789 int tz;
790 struct pg_tm tt,
791 *tm = &tt;
792 fsec_t fsec;
793
794 timestamp = (TimestampTz) pq_getmsgint64(buf);
795
796 /* range check: see if timestamptz_out would like it */
797 if (TIMESTAMP_NOT_FINITE(timestamp))
798 /* ok */ ;
799 else if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, NULL) != 0 ||
800 !IS_VALID_TIMESTAMP(timestamp))
801 ereport(ERROR,
802 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
803 errmsg("timestamp out of range")));
804
805 AdjustTimestampForTypmod(×tamp, typmod);
806
807 PG_RETURN_TIMESTAMPTZ(timestamp);
808 }
809
810 /*
811 * timestamptz_send - converts timestamptz to binary format
812 */
813 Datum
timestamptz_send(PG_FUNCTION_ARGS)814 timestamptz_send(PG_FUNCTION_ARGS)
815 {
816 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
817 StringInfoData buf;
818
819 pq_begintypsend(&buf);
820 pq_sendint64(&buf, timestamp);
821 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
822 }
823
824 Datum
timestamptztypmodin(PG_FUNCTION_ARGS)825 timestamptztypmodin(PG_FUNCTION_ARGS)
826 {
827 ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
828
829 PG_RETURN_INT32(anytimestamp_typmodin(true, ta));
830 }
831
832 Datum
timestamptztypmodout(PG_FUNCTION_ARGS)833 timestamptztypmodout(PG_FUNCTION_ARGS)
834 {
835 int32 typmod = PG_GETARG_INT32(0);
836
837 PG_RETURN_CSTRING(anytimestamp_typmodout(true, typmod));
838 }
839
840
841 /* timestamptz_scale()
842 * Adjust time type for specified scale factor.
843 * Used by PostgreSQL type system to stuff columns.
844 */
845 Datum
timestamptz_scale(PG_FUNCTION_ARGS)846 timestamptz_scale(PG_FUNCTION_ARGS)
847 {
848 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
849 int32 typmod = PG_GETARG_INT32(1);
850 TimestampTz result;
851
852 result = timestamp;
853
854 AdjustTimestampForTypmod(&result, typmod);
855
856 PG_RETURN_TIMESTAMPTZ(result);
857 }
858
859
860 /* interval_in()
861 * Convert a string to internal form.
862 *
863 * External format(s):
864 * Uses the generic date/time parsing and decoding routines.
865 */
866 Datum
interval_in(PG_FUNCTION_ARGS)867 interval_in(PG_FUNCTION_ARGS)
868 {
869 char *str = PG_GETARG_CSTRING(0);
870
871 #ifdef NOT_USED
872 Oid typelem = PG_GETARG_OID(1);
873 #endif
874 int32 typmod = PG_GETARG_INT32(2);
875 Interval *result;
876 fsec_t fsec;
877 struct pg_tm tt,
878 *tm = &tt;
879 int dtype;
880 int nf;
881 int range;
882 int dterr;
883 char *field[MAXDATEFIELDS];
884 int ftype[MAXDATEFIELDS];
885 char workbuf[256];
886
887 tm->tm_year = 0;
888 tm->tm_mon = 0;
889 tm->tm_mday = 0;
890 tm->tm_hour = 0;
891 tm->tm_min = 0;
892 tm->tm_sec = 0;
893 fsec = 0;
894
895 if (typmod >= 0)
896 range = INTERVAL_RANGE(typmod);
897 else
898 range = INTERVAL_FULL_RANGE;
899
900 dterr = ParseDateTime(str, workbuf, sizeof(workbuf), field,
901 ftype, MAXDATEFIELDS, &nf);
902 if (dterr == 0)
903 dterr = DecodeInterval(field, ftype, nf, range,
904 &dtype, tm, &fsec);
905
906 /* if those functions think it's a bad format, try ISO8601 style */
907 if (dterr == DTERR_BAD_FORMAT)
908 dterr = DecodeISO8601Interval(str,
909 &dtype, tm, &fsec);
910
911 if (dterr != 0)
912 {
913 if (dterr == DTERR_FIELD_OVERFLOW)
914 dterr = DTERR_INTERVAL_OVERFLOW;
915 DateTimeParseError(dterr, str, "interval");
916 }
917
918 result = (Interval *) palloc(sizeof(Interval));
919
920 switch (dtype)
921 {
922 case DTK_DELTA:
923 if (tm2interval(tm, fsec, result) != 0)
924 ereport(ERROR,
925 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
926 errmsg("interval out of range")));
927 break;
928
929 case DTK_INVALID:
930 ereport(ERROR,
931 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
932 errmsg("date/time value \"%s\" is no longer supported", str)));
933 break;
934
935 default:
936 elog(ERROR, "unexpected dtype %d while parsing interval \"%s\"",
937 dtype, str);
938 }
939
940 AdjustIntervalForTypmod(result, typmod);
941
942 PG_RETURN_INTERVAL_P(result);
943 }
944
945 /* interval_out()
946 * Convert a time span to external form.
947 */
948 Datum
interval_out(PG_FUNCTION_ARGS)949 interval_out(PG_FUNCTION_ARGS)
950 {
951 Interval *span = PG_GETARG_INTERVAL_P(0);
952 char *result;
953 struct pg_tm tt,
954 *tm = &tt;
955 fsec_t fsec;
956 char buf[MAXDATELEN + 1];
957
958 if (interval2tm(*span, tm, &fsec) != 0)
959 elog(ERROR, "could not convert interval to tm");
960
961 EncodeInterval(tm, fsec, IntervalStyle, buf);
962
963 result = pstrdup(buf);
964 PG_RETURN_CSTRING(result);
965 }
966
967 /*
968 * interval_recv - converts external binary format to interval
969 */
970 Datum
interval_recv(PG_FUNCTION_ARGS)971 interval_recv(PG_FUNCTION_ARGS)
972 {
973 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
974
975 #ifdef NOT_USED
976 Oid typelem = PG_GETARG_OID(1);
977 #endif
978 int32 typmod = PG_GETARG_INT32(2);
979 Interval *interval;
980
981 interval = (Interval *) palloc(sizeof(Interval));
982
983 interval->time = pq_getmsgint64(buf);
984 interval->day = pq_getmsgint(buf, sizeof(interval->day));
985 interval->month = pq_getmsgint(buf, sizeof(interval->month));
986
987 AdjustIntervalForTypmod(interval, typmod);
988
989 PG_RETURN_INTERVAL_P(interval);
990 }
991
992 /*
993 * interval_send - converts interval to binary format
994 */
995 Datum
interval_send(PG_FUNCTION_ARGS)996 interval_send(PG_FUNCTION_ARGS)
997 {
998 Interval *interval = PG_GETARG_INTERVAL_P(0);
999 StringInfoData buf;
1000
1001 pq_begintypsend(&buf);
1002 pq_sendint64(&buf, interval->time);
1003 pq_sendint(&buf, interval->day, sizeof(interval->day));
1004 pq_sendint(&buf, interval->month, sizeof(interval->month));
1005 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
1006 }
1007
1008 /*
1009 * The interval typmod stores a "range" in its high 16 bits and a "precision"
1010 * in its low 16 bits. Both contribute to defining the resolution of the
1011 * type. Range addresses resolution granules larger than one second, and
1012 * precision specifies resolution below one second. This representation can
1013 * express all SQL standard resolutions, but we implement them all in terms of
1014 * truncating rightward from some position. Range is a bitmap of permitted
1015 * fields, but only the temporally-smallest such field is significant to our
1016 * calculations. Precision is a count of sub-second decimal places to retain.
1017 * Setting all bits (INTERVAL_FULL_PRECISION) gives the same truncation
1018 * semantics as choosing MAX_INTERVAL_PRECISION.
1019 */
1020 Datum
intervaltypmodin(PG_FUNCTION_ARGS)1021 intervaltypmodin(PG_FUNCTION_ARGS)
1022 {
1023 ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
1024 int32 *tl;
1025 int n;
1026 int32 typmod;
1027
1028 tl = ArrayGetIntegerTypmods(ta, &n);
1029
1030 /*
1031 * tl[0] - interval range (fields bitmask) tl[1] - precision (optional)
1032 *
1033 * Note we must validate tl[0] even though it's normally guaranteed
1034 * correct by the grammar --- consider SELECT 'foo'::"interval"(1000).
1035 */
1036 if (n > 0)
1037 {
1038 switch (tl[0])
1039 {
1040 case INTERVAL_MASK(YEAR):
1041 case INTERVAL_MASK(MONTH):
1042 case INTERVAL_MASK(DAY):
1043 case INTERVAL_MASK(HOUR):
1044 case INTERVAL_MASK(MINUTE):
1045 case INTERVAL_MASK(SECOND):
1046 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
1047 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
1048 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
1049 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1050 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
1051 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1052 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1053 case INTERVAL_FULL_RANGE:
1054 /* all OK */
1055 break;
1056 default:
1057 ereport(ERROR,
1058 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1059 errmsg("invalid INTERVAL type modifier")));
1060 }
1061 }
1062
1063 if (n == 1)
1064 {
1065 if (tl[0] != INTERVAL_FULL_RANGE)
1066 typmod = INTERVAL_TYPMOD(INTERVAL_FULL_PRECISION, tl[0]);
1067 else
1068 typmod = -1;
1069 }
1070 else if (n == 2)
1071 {
1072 if (tl[1] < 0)
1073 ereport(ERROR,
1074 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1075 errmsg("INTERVAL(%d) precision must not be negative",
1076 tl[1])));
1077 if (tl[1] > MAX_INTERVAL_PRECISION)
1078 {
1079 ereport(WARNING,
1080 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1081 errmsg("INTERVAL(%d) precision reduced to maximum allowed, %d",
1082 tl[1], MAX_INTERVAL_PRECISION)));
1083 typmod = INTERVAL_TYPMOD(MAX_INTERVAL_PRECISION, tl[0]);
1084 }
1085 else
1086 typmod = INTERVAL_TYPMOD(tl[1], tl[0]);
1087 }
1088 else
1089 {
1090 ereport(ERROR,
1091 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1092 errmsg("invalid INTERVAL type modifier")));
1093 typmod = 0; /* keep compiler quiet */
1094 }
1095
1096 PG_RETURN_INT32(typmod);
1097 }
1098
1099 Datum
intervaltypmodout(PG_FUNCTION_ARGS)1100 intervaltypmodout(PG_FUNCTION_ARGS)
1101 {
1102 int32 typmod = PG_GETARG_INT32(0);
1103 char *res = (char *) palloc(64);
1104 int fields;
1105 int precision;
1106 const char *fieldstr;
1107
1108 if (typmod < 0)
1109 {
1110 *res = '\0';
1111 PG_RETURN_CSTRING(res);
1112 }
1113
1114 fields = INTERVAL_RANGE(typmod);
1115 precision = INTERVAL_PRECISION(typmod);
1116
1117 switch (fields)
1118 {
1119 case INTERVAL_MASK(YEAR):
1120 fieldstr = " year";
1121 break;
1122 case INTERVAL_MASK(MONTH):
1123 fieldstr = " month";
1124 break;
1125 case INTERVAL_MASK(DAY):
1126 fieldstr = " day";
1127 break;
1128 case INTERVAL_MASK(HOUR):
1129 fieldstr = " hour";
1130 break;
1131 case INTERVAL_MASK(MINUTE):
1132 fieldstr = " minute";
1133 break;
1134 case INTERVAL_MASK(SECOND):
1135 fieldstr = " second";
1136 break;
1137 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
1138 fieldstr = " year to month";
1139 break;
1140 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
1141 fieldstr = " day to hour";
1142 break;
1143 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
1144 fieldstr = " day to minute";
1145 break;
1146 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1147 fieldstr = " day to second";
1148 break;
1149 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
1150 fieldstr = " hour to minute";
1151 break;
1152 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1153 fieldstr = " hour to second";
1154 break;
1155 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1156 fieldstr = " minute to second";
1157 break;
1158 case INTERVAL_FULL_RANGE:
1159 fieldstr = "";
1160 break;
1161 default:
1162 elog(ERROR, "invalid INTERVAL typmod: 0x%x", typmod);
1163 fieldstr = "";
1164 break;
1165 }
1166
1167 if (precision != INTERVAL_FULL_PRECISION)
1168 snprintf(res, 64, "%s(%d)", fieldstr, precision);
1169 else
1170 snprintf(res, 64, "%s", fieldstr);
1171
1172 PG_RETURN_CSTRING(res);
1173 }
1174
1175 /*
1176 * Given an interval typmod value, return a code for the least-significant
1177 * field that the typmod allows to be nonzero, for instance given
1178 * INTERVAL DAY TO HOUR we want to identify "hour".
1179 *
1180 * The results should be ordered by field significance, which means
1181 * we can't use the dt.h macros YEAR etc, because for some odd reason
1182 * they aren't ordered that way. Instead, arbitrarily represent
1183 * SECOND = 0, MINUTE = 1, HOUR = 2, DAY = 3, MONTH = 4, YEAR = 5.
1184 */
1185 static int
intervaltypmodleastfield(int32 typmod)1186 intervaltypmodleastfield(int32 typmod)
1187 {
1188 if (typmod < 0)
1189 return 0; /* SECOND */
1190
1191 switch (INTERVAL_RANGE(typmod))
1192 {
1193 case INTERVAL_MASK(YEAR):
1194 return 5; /* YEAR */
1195 case INTERVAL_MASK(MONTH):
1196 return 4; /* MONTH */
1197 case INTERVAL_MASK(DAY):
1198 return 3; /* DAY */
1199 case INTERVAL_MASK(HOUR):
1200 return 2; /* HOUR */
1201 case INTERVAL_MASK(MINUTE):
1202 return 1; /* MINUTE */
1203 case INTERVAL_MASK(SECOND):
1204 return 0; /* SECOND */
1205 case INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH):
1206 return 4; /* MONTH */
1207 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR):
1208 return 2; /* HOUR */
1209 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
1210 return 1; /* MINUTE */
1211 case INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1212 return 0; /* SECOND */
1213 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE):
1214 return 1; /* MINUTE */
1215 case INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1216 return 0; /* SECOND */
1217 case INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND):
1218 return 0; /* SECOND */
1219 case INTERVAL_FULL_RANGE:
1220 return 0; /* SECOND */
1221 default:
1222 elog(ERROR, "invalid INTERVAL typmod: 0x%x", typmod);
1223 break;
1224 }
1225 return 0; /* can't get here, but keep compiler quiet */
1226 }
1227
1228
1229 /* interval_transform()
1230 * Flatten superfluous calls to interval_scale(). The interval typmod is
1231 * complex to permit accepting and regurgitating all SQL standard variations.
1232 * For truncation purposes, it boils down to a single, simple granularity.
1233 */
1234 Datum
interval_transform(PG_FUNCTION_ARGS)1235 interval_transform(PG_FUNCTION_ARGS)
1236 {
1237 FuncExpr *expr = castNode(FuncExpr, PG_GETARG_POINTER(0));
1238 Node *ret = NULL;
1239 Node *typmod;
1240
1241 Assert(list_length(expr->args) >= 2);
1242
1243 typmod = (Node *) lsecond(expr->args);
1244
1245 if (IsA(typmod, Const) &&!((Const *) typmod)->constisnull)
1246 {
1247 Node *source = (Node *) linitial(expr->args);
1248 int32 new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
1249 bool noop;
1250
1251 if (new_typmod < 0)
1252 noop = true;
1253 else
1254 {
1255 int32 old_typmod = exprTypmod(source);
1256 int old_least_field;
1257 int new_least_field;
1258 int old_precis;
1259 int new_precis;
1260
1261 old_least_field = intervaltypmodleastfield(old_typmod);
1262 new_least_field = intervaltypmodleastfield(new_typmod);
1263 if (old_typmod < 0)
1264 old_precis = INTERVAL_FULL_PRECISION;
1265 else
1266 old_precis = INTERVAL_PRECISION(old_typmod);
1267 new_precis = INTERVAL_PRECISION(new_typmod);
1268
1269 /*
1270 * Cast is a no-op if least field stays the same or decreases
1271 * while precision stays the same or increases. But precision,
1272 * which is to say, sub-second precision, only affects ranges that
1273 * include SECOND.
1274 */
1275 noop = (new_least_field <= old_least_field) &&
1276 (old_least_field > 0 /* SECOND */ ||
1277 new_precis >= MAX_INTERVAL_PRECISION ||
1278 new_precis >= old_precis);
1279 }
1280 if (noop)
1281 ret = relabel_to_typmod(source, new_typmod);
1282 }
1283
1284 PG_RETURN_POINTER(ret);
1285 }
1286
1287 /* interval_scale()
1288 * Adjust interval type for specified fields.
1289 * Used by PostgreSQL type system to stuff columns.
1290 */
1291 Datum
interval_scale(PG_FUNCTION_ARGS)1292 interval_scale(PG_FUNCTION_ARGS)
1293 {
1294 Interval *interval = PG_GETARG_INTERVAL_P(0);
1295 int32 typmod = PG_GETARG_INT32(1);
1296 Interval *result;
1297
1298 result = palloc(sizeof(Interval));
1299 *result = *interval;
1300
1301 AdjustIntervalForTypmod(result, typmod);
1302
1303 PG_RETURN_INTERVAL_P(result);
1304 }
1305
1306 /*
1307 * Adjust interval for specified precision, in both YEAR to SECOND
1308 * range and sub-second precision.
1309 */
1310 static void
AdjustIntervalForTypmod(Interval * interval,int32 typmod)1311 AdjustIntervalForTypmod(Interval *interval, int32 typmod)
1312 {
1313 static const int64 IntervalScales[MAX_INTERVAL_PRECISION + 1] = {
1314 INT64CONST(1000000),
1315 INT64CONST(100000),
1316 INT64CONST(10000),
1317 INT64CONST(1000),
1318 INT64CONST(100),
1319 INT64CONST(10),
1320 INT64CONST(1)
1321 };
1322
1323 static const int64 IntervalOffsets[MAX_INTERVAL_PRECISION + 1] = {
1324 INT64CONST(500000),
1325 INT64CONST(50000),
1326 INT64CONST(5000),
1327 INT64CONST(500),
1328 INT64CONST(50),
1329 INT64CONST(5),
1330 INT64CONST(0)
1331 };
1332
1333 /*
1334 * Unspecified range and precision? Then not necessary to adjust. Setting
1335 * typmod to -1 is the convention for all data types.
1336 */
1337 if (typmod >= 0)
1338 {
1339 int range = INTERVAL_RANGE(typmod);
1340 int precision = INTERVAL_PRECISION(typmod);
1341
1342 /*
1343 * Our interpretation of intervals with a limited set of fields is
1344 * that fields to the right of the last one specified are zeroed out,
1345 * but those to the left of it remain valid. Thus for example there
1346 * is no operational difference between INTERVAL YEAR TO MONTH and
1347 * INTERVAL MONTH. In some cases we could meaningfully enforce that
1348 * higher-order fields are zero; for example INTERVAL DAY could reject
1349 * nonzero "month" field. However that seems a bit pointless when we
1350 * can't do it consistently. (We cannot enforce a range limit on the
1351 * highest expected field, since we do not have any equivalent of
1352 * SQL's <interval leading field precision>.) If we ever decide to
1353 * revisit this, interval_transform will likely require adjusting.
1354 *
1355 * Note: before PG 8.4 we interpreted a limited set of fields as
1356 * actually causing a "modulo" operation on a given value, potentially
1357 * losing high-order as well as low-order information. But there is
1358 * no support for such behavior in the standard, and it seems fairly
1359 * undesirable on data consistency grounds anyway. Now we only
1360 * perform truncation or rounding of low-order fields.
1361 */
1362 if (range == INTERVAL_FULL_RANGE)
1363 {
1364 /* Do nothing... */
1365 }
1366 else if (range == INTERVAL_MASK(YEAR))
1367 {
1368 interval->month = (interval->month / MONTHS_PER_YEAR) * MONTHS_PER_YEAR;
1369 interval->day = 0;
1370 interval->time = 0;
1371 }
1372 else if (range == INTERVAL_MASK(MONTH))
1373 {
1374 interval->day = 0;
1375 interval->time = 0;
1376 }
1377 /* YEAR TO MONTH */
1378 else if (range == (INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH)))
1379 {
1380 interval->day = 0;
1381 interval->time = 0;
1382 }
1383 else if (range == INTERVAL_MASK(DAY))
1384 {
1385 interval->time = 0;
1386 }
1387 else if (range == INTERVAL_MASK(HOUR))
1388 {
1389 interval->time = (interval->time / USECS_PER_HOUR) *
1390 USECS_PER_HOUR;
1391 }
1392 else if (range == INTERVAL_MASK(MINUTE))
1393 {
1394 interval->time = (interval->time / USECS_PER_MINUTE) *
1395 USECS_PER_MINUTE;
1396 }
1397 else if (range == INTERVAL_MASK(SECOND))
1398 {
1399 /* fractional-second rounding will be dealt with below */
1400 }
1401 /* DAY TO HOUR */
1402 else if (range == (INTERVAL_MASK(DAY) |
1403 INTERVAL_MASK(HOUR)))
1404 {
1405 interval->time = (interval->time / USECS_PER_HOUR) *
1406 USECS_PER_HOUR;
1407 }
1408 /* DAY TO MINUTE */
1409 else if (range == (INTERVAL_MASK(DAY) |
1410 INTERVAL_MASK(HOUR) |
1411 INTERVAL_MASK(MINUTE)))
1412 {
1413 interval->time = (interval->time / USECS_PER_MINUTE) *
1414 USECS_PER_MINUTE;
1415 }
1416 /* DAY TO SECOND */
1417 else if (range == (INTERVAL_MASK(DAY) |
1418 INTERVAL_MASK(HOUR) |
1419 INTERVAL_MASK(MINUTE) |
1420 INTERVAL_MASK(SECOND)))
1421 {
1422 /* fractional-second rounding will be dealt with below */
1423 }
1424 /* HOUR TO MINUTE */
1425 else if (range == (INTERVAL_MASK(HOUR) |
1426 INTERVAL_MASK(MINUTE)))
1427 {
1428 interval->time = (interval->time / USECS_PER_MINUTE) *
1429 USECS_PER_MINUTE;
1430 }
1431 /* HOUR TO SECOND */
1432 else if (range == (INTERVAL_MASK(HOUR) |
1433 INTERVAL_MASK(MINUTE) |
1434 INTERVAL_MASK(SECOND)))
1435 {
1436 /* fractional-second rounding will be dealt with below */
1437 }
1438 /* MINUTE TO SECOND */
1439 else if (range == (INTERVAL_MASK(MINUTE) |
1440 INTERVAL_MASK(SECOND)))
1441 {
1442 /* fractional-second rounding will be dealt with below */
1443 }
1444 else
1445 elog(ERROR, "unrecognized interval typmod: %d", typmod);
1446
1447 /* Need to adjust sub-second precision? */
1448 if (precision != INTERVAL_FULL_PRECISION)
1449 {
1450 if (precision < 0 || precision > MAX_INTERVAL_PRECISION)
1451 ereport(ERROR,
1452 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1453 errmsg("interval(%d) precision must be between %d and %d",
1454 precision, 0, MAX_INTERVAL_PRECISION)));
1455
1456 if (interval->time >= INT64CONST(0))
1457 {
1458 interval->time = ((interval->time +
1459 IntervalOffsets[precision]) /
1460 IntervalScales[precision]) *
1461 IntervalScales[precision];
1462 }
1463 else
1464 {
1465 interval->time = -(((-interval->time +
1466 IntervalOffsets[precision]) /
1467 IntervalScales[precision]) *
1468 IntervalScales[precision]);
1469 }
1470 }
1471 }
1472 }
1473
1474 /*
1475 * make_interval - numeric Interval constructor
1476 */
1477 Datum
make_interval(PG_FUNCTION_ARGS)1478 make_interval(PG_FUNCTION_ARGS)
1479 {
1480 int32 years = PG_GETARG_INT32(0);
1481 int32 months = PG_GETARG_INT32(1);
1482 int32 weeks = PG_GETARG_INT32(2);
1483 int32 days = PG_GETARG_INT32(3);
1484 int32 hours = PG_GETARG_INT32(4);
1485 int32 mins = PG_GETARG_INT32(5);
1486 double secs = PG_GETARG_FLOAT8(6);
1487 Interval *result;
1488
1489 /*
1490 * Reject out-of-range inputs. We really ought to check the integer
1491 * inputs as well, but it's not entirely clear what limits to apply.
1492 */
1493 if (isinf(secs) || isnan(secs))
1494 ereport(ERROR,
1495 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1496 errmsg("interval out of range")));
1497
1498 result = (Interval *) palloc(sizeof(Interval));
1499 result->month = years * MONTHS_PER_YEAR + months;
1500 result->day = weeks * 7 + days;
1501
1502 secs = rint(secs * USECS_PER_SEC);
1503 result->time = hours * ((int64) SECS_PER_HOUR * USECS_PER_SEC) +
1504 mins * ((int64) SECS_PER_MINUTE * USECS_PER_SEC) +
1505 (int64) secs;
1506
1507 PG_RETURN_INTERVAL_P(result);
1508 }
1509
1510 /* EncodeSpecialTimestamp()
1511 * Convert reserved timestamp data type to string.
1512 */
1513 void
EncodeSpecialTimestamp(Timestamp dt,char * str)1514 EncodeSpecialTimestamp(Timestamp dt, char *str)
1515 {
1516 if (TIMESTAMP_IS_NOBEGIN(dt))
1517 strcpy(str, EARLY);
1518 else if (TIMESTAMP_IS_NOEND(dt))
1519 strcpy(str, LATE);
1520 else /* shouldn't happen */
1521 elog(ERROR, "invalid argument for EncodeSpecialTimestamp");
1522 }
1523
1524 Datum
now(PG_FUNCTION_ARGS)1525 now(PG_FUNCTION_ARGS)
1526 {
1527 PG_RETURN_TIMESTAMPTZ(GetCurrentTransactionStartTimestamp());
1528 }
1529
1530 Datum
statement_timestamp(PG_FUNCTION_ARGS)1531 statement_timestamp(PG_FUNCTION_ARGS)
1532 {
1533 PG_RETURN_TIMESTAMPTZ(GetCurrentStatementStartTimestamp());
1534 }
1535
1536 Datum
clock_timestamp(PG_FUNCTION_ARGS)1537 clock_timestamp(PG_FUNCTION_ARGS)
1538 {
1539 PG_RETURN_TIMESTAMPTZ(GetCurrentTimestamp());
1540 }
1541
1542 Datum
pg_postmaster_start_time(PG_FUNCTION_ARGS)1543 pg_postmaster_start_time(PG_FUNCTION_ARGS)
1544 {
1545 PG_RETURN_TIMESTAMPTZ(PgStartTime);
1546 }
1547
1548 Datum
pg_conf_load_time(PG_FUNCTION_ARGS)1549 pg_conf_load_time(PG_FUNCTION_ARGS)
1550 {
1551 PG_RETURN_TIMESTAMPTZ(PgReloadTime);
1552 }
1553
1554 /*
1555 * GetCurrentTimestamp -- get the current operating system time
1556 *
1557 * Result is in the form of a TimestampTz value, and is expressed to the
1558 * full precision of the gettimeofday() syscall
1559 */
1560 TimestampTz
GetCurrentTimestamp(void)1561 GetCurrentTimestamp(void)
1562 {
1563 TimestampTz result;
1564 struct timeval tp;
1565
1566 gettimeofday(&tp, NULL);
1567
1568 result = (TimestampTz) tp.tv_sec -
1569 ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);
1570 result = (result * USECS_PER_SEC) + tp.tv_usec;
1571
1572 return result;
1573 }
1574
1575 /*
1576 * GetSQLCurrentTimestamp -- implements CURRENT_TIMESTAMP, CURRENT_TIMESTAMP(n)
1577 */
1578 TimestampTz
GetSQLCurrentTimestamp(int32 typmod)1579 GetSQLCurrentTimestamp(int32 typmod)
1580 {
1581 TimestampTz ts;
1582
1583 ts = GetCurrentTransactionStartTimestamp();
1584 if (typmod >= 0)
1585 AdjustTimestampForTypmod(&ts, typmod);
1586 return ts;
1587 }
1588
1589 /*
1590 * GetSQLLocalTimestamp -- implements LOCALTIMESTAMP, LOCALTIMESTAMP(n)
1591 */
1592 Timestamp
GetSQLLocalTimestamp(int32 typmod)1593 GetSQLLocalTimestamp(int32 typmod)
1594 {
1595 Timestamp ts;
1596
1597 ts = timestamptz2timestamp(GetCurrentTransactionStartTimestamp());
1598 if (typmod >= 0)
1599 AdjustTimestampForTypmod(&ts, typmod);
1600 return ts;
1601 }
1602
1603 /*
1604 * TimestampDifference -- convert the difference between two timestamps
1605 * into integer seconds and microseconds
1606 *
1607 * This is typically used to calculate a wait timeout for select(2),
1608 * which explains the otherwise-odd choice of output format.
1609 *
1610 * Both inputs must be ordinary finite timestamps (in current usage,
1611 * they'll be results from GetCurrentTimestamp()).
1612 *
1613 * We expect start_time <= stop_time. If not, we return zeros,
1614 * since then we're already past the previously determined stop_time.
1615 */
1616 void
TimestampDifference(TimestampTz start_time,TimestampTz stop_time,long * secs,int * microsecs)1617 TimestampDifference(TimestampTz start_time, TimestampTz stop_time,
1618 long *secs, int *microsecs)
1619 {
1620 TimestampTz diff = stop_time - start_time;
1621
1622 if (diff <= 0)
1623 {
1624 *secs = 0;
1625 *microsecs = 0;
1626 }
1627 else
1628 {
1629 *secs = (long) (diff / USECS_PER_SEC);
1630 *microsecs = (int) (diff % USECS_PER_SEC);
1631 }
1632 }
1633
1634 /*
1635 * TimestampDifferenceMilliseconds -- convert the difference between two
1636 * timestamps into integer milliseconds
1637 *
1638 * This is typically used to calculate a wait timeout for WaitLatch()
1639 * or a related function. The choice of "long" as the result type
1640 * is to harmonize with that. It is caller's responsibility that the
1641 * input timestamps not be so far apart as to risk overflow of "long"
1642 * (which'd happen at about 25 days on machines with 32-bit "long").
1643 *
1644 * Both inputs must be ordinary finite timestamps (in current usage,
1645 * they'll be results from GetCurrentTimestamp()).
1646 *
1647 * We expect start_time <= stop_time. If not, we return zero,
1648 * since then we're already past the previously determined stop_time.
1649 *
1650 * Note we round up any fractional millisecond, since waiting for just
1651 * less than the intended timeout is undesirable.
1652 */
1653 long
TimestampDifferenceMilliseconds(TimestampTz start_time,TimestampTz stop_time)1654 TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
1655 {
1656 TimestampTz diff = stop_time - start_time;
1657
1658 if (diff <= 0)
1659 return 0;
1660 else
1661 return (long) ((diff + 999) / 1000);
1662 }
1663
1664 /*
1665 * TimestampDifferenceExceeds -- report whether the difference between two
1666 * timestamps is >= a threshold (expressed in milliseconds)
1667 *
1668 * Both inputs must be ordinary finite timestamps (in current usage,
1669 * they'll be results from GetCurrentTimestamp()).
1670 */
1671 bool
TimestampDifferenceExceeds(TimestampTz start_time,TimestampTz stop_time,int msec)1672 TimestampDifferenceExceeds(TimestampTz start_time,
1673 TimestampTz stop_time,
1674 int msec)
1675 {
1676 TimestampTz diff = stop_time - start_time;
1677
1678 return (diff >= msec * INT64CONST(1000));
1679 }
1680
1681 /*
1682 * Convert a time_t to TimestampTz.
1683 *
1684 * We do not use time_t internally in Postgres, but this is provided for use
1685 * by functions that need to interpret, say, a stat(2) result.
1686 *
1687 * To avoid having the function's ABI vary depending on the width of time_t,
1688 * we declare the argument as pg_time_t, which is cast-compatible with
1689 * time_t but always 64 bits wide (unless the platform has no 64-bit type).
1690 * This detail should be invisible to callers, at least at source code level.
1691 */
1692 TimestampTz
time_t_to_timestamptz(pg_time_t tm)1693 time_t_to_timestamptz(pg_time_t tm)
1694 {
1695 TimestampTz result;
1696
1697 result = (TimestampTz) tm -
1698 ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);
1699 result *= USECS_PER_SEC;
1700
1701 return result;
1702 }
1703
1704 /*
1705 * Convert a TimestampTz to time_t.
1706 *
1707 * This too is just marginally useful, but some places need it.
1708 *
1709 * To avoid having the function's ABI vary depending on the width of time_t,
1710 * we declare the result as pg_time_t, which is cast-compatible with
1711 * time_t but always 64 bits wide (unless the platform has no 64-bit type).
1712 * This detail should be invisible to callers, at least at source code level.
1713 */
1714 pg_time_t
timestamptz_to_time_t(TimestampTz t)1715 timestamptz_to_time_t(TimestampTz t)
1716 {
1717 pg_time_t result;
1718
1719 result = (pg_time_t) (t / USECS_PER_SEC +
1720 ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY));
1721
1722 return result;
1723 }
1724
1725 /*
1726 * Produce a C-string representation of a TimestampTz.
1727 *
1728 * This is mostly for use in emitting messages. The primary difference
1729 * from timestamptz_out is that we force the output format to ISO. Note
1730 * also that the result is in a static buffer, not pstrdup'd.
1731 */
1732 const char *
timestamptz_to_str(TimestampTz t)1733 timestamptz_to_str(TimestampTz t)
1734 {
1735 static char buf[MAXDATELEN + 1];
1736 int tz;
1737 struct pg_tm tt,
1738 *tm = &tt;
1739 fsec_t fsec;
1740 const char *tzn;
1741
1742 if (TIMESTAMP_NOT_FINITE(t))
1743 EncodeSpecialTimestamp(t, buf);
1744 else if (timestamp2tm(t, &tz, tm, &fsec, &tzn, NULL) == 0)
1745 EncodeDateTime(tm, fsec, true, tz, tzn, USE_ISO_DATES, buf);
1746 else
1747 strlcpy(buf, "(timestamp out of range)", sizeof(buf));
1748
1749 return buf;
1750 }
1751
1752
1753 void
dt2time(Timestamp jd,int * hour,int * min,int * sec,fsec_t * fsec)1754 dt2time(Timestamp jd, int *hour, int *min, int *sec, fsec_t *fsec)
1755 {
1756 TimeOffset time;
1757
1758 time = jd;
1759
1760 *hour = time / USECS_PER_HOUR;
1761 time -= (*hour) * USECS_PER_HOUR;
1762 *min = time / USECS_PER_MINUTE;
1763 time -= (*min) * USECS_PER_MINUTE;
1764 *sec = time / USECS_PER_SEC;
1765 *fsec = time - (*sec * USECS_PER_SEC);
1766 } /* dt2time() */
1767
1768
1769 /*
1770 * timestamp2tm() - Convert timestamp data type to POSIX time structure.
1771 *
1772 * Note that year is _not_ 1900-based, but is an explicit full value.
1773 * Also, month is one-based, _not_ zero-based.
1774 * Returns:
1775 * 0 on success
1776 * -1 on out of range
1777 *
1778 * If attimezone is NULL, the global timezone setting will be used.
1779 */
1780 int
timestamp2tm(Timestamp dt,int * tzp,struct pg_tm * tm,fsec_t * fsec,const char ** tzn,pg_tz * attimezone)1781 timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm, fsec_t *fsec, const char **tzn, pg_tz *attimezone)
1782 {
1783 Timestamp date;
1784 Timestamp time;
1785 pg_time_t utime;
1786
1787 /* Use session timezone if caller asks for default */
1788 if (attimezone == NULL)
1789 attimezone = session_timezone;
1790
1791 time = dt;
1792 TMODULO(time, date, USECS_PER_DAY);
1793
1794 if (time < INT64CONST(0))
1795 {
1796 time += USECS_PER_DAY;
1797 date -= 1;
1798 }
1799
1800 /* add offset to go from J2000 back to standard Julian date */
1801 date += POSTGRES_EPOCH_JDATE;
1802
1803 /* Julian day routine does not work for negative Julian days */
1804 if (date < 0 || date > (Timestamp) INT_MAX)
1805 return -1;
1806
1807 j2date((int) date, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1808 dt2time(time, &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
1809
1810 /* Done if no TZ conversion wanted */
1811 if (tzp == NULL)
1812 {
1813 tm->tm_isdst = -1;
1814 tm->tm_gmtoff = 0;
1815 tm->tm_zone = NULL;
1816 if (tzn != NULL)
1817 *tzn = NULL;
1818 return 0;
1819 }
1820
1821 /*
1822 * If the time falls within the range of pg_time_t, use pg_localtime() to
1823 * rotate to the local time zone.
1824 *
1825 * First, convert to an integral timestamp, avoiding possibly
1826 * platform-specific roundoff-in-wrong-direction errors, and adjust to
1827 * Unix epoch. Then see if we can convert to pg_time_t without loss. This
1828 * coding avoids hardwiring any assumptions about the width of pg_time_t,
1829 * so it should behave sanely on machines without int64.
1830 */
1831 dt = (dt - *fsec) / USECS_PER_SEC +
1832 (POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY;
1833 utime = (pg_time_t) dt;
1834 if ((Timestamp) utime == dt)
1835 {
1836 struct pg_tm *tx = pg_localtime(&utime, attimezone);
1837
1838 tm->tm_year = tx->tm_year + 1900;
1839 tm->tm_mon = tx->tm_mon + 1;
1840 tm->tm_mday = tx->tm_mday;
1841 tm->tm_hour = tx->tm_hour;
1842 tm->tm_min = tx->tm_min;
1843 tm->tm_sec = tx->tm_sec;
1844 tm->tm_isdst = tx->tm_isdst;
1845 tm->tm_gmtoff = tx->tm_gmtoff;
1846 tm->tm_zone = tx->tm_zone;
1847 *tzp = -tm->tm_gmtoff;
1848 if (tzn != NULL)
1849 *tzn = tm->tm_zone;
1850 }
1851 else
1852 {
1853 /*
1854 * When out of range of pg_time_t, treat as GMT
1855 */
1856 *tzp = 0;
1857 /* Mark this as *no* time zone available */
1858 tm->tm_isdst = -1;
1859 tm->tm_gmtoff = 0;
1860 tm->tm_zone = NULL;
1861 if (tzn != NULL)
1862 *tzn = NULL;
1863 }
1864
1865 return 0;
1866 }
1867
1868
1869 /* tm2timestamp()
1870 * Convert a tm structure to a timestamp data type.
1871 * Note that year is _not_ 1900-based, but is an explicit full value.
1872 * Also, month is one-based, _not_ zero-based.
1873 *
1874 * Returns -1 on failure (value out of range).
1875 */
1876 int
tm2timestamp(struct pg_tm * tm,fsec_t fsec,int * tzp,Timestamp * result)1877 tm2timestamp(struct pg_tm *tm, fsec_t fsec, int *tzp, Timestamp *result)
1878 {
1879 TimeOffset date;
1880 TimeOffset time;
1881
1882 /* Prevent overflow in Julian-day routines */
1883 if (!IS_VALID_JULIAN(tm->tm_year, tm->tm_mon, tm->tm_mday))
1884 {
1885 *result = 0; /* keep compiler quiet */
1886 return -1;
1887 }
1888
1889 date = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - POSTGRES_EPOCH_JDATE;
1890 time = time2t(tm->tm_hour, tm->tm_min, tm->tm_sec, fsec);
1891
1892 *result = date * USECS_PER_DAY + time;
1893 /* check for major overflow */
1894 if ((*result - time) / USECS_PER_DAY != date)
1895 {
1896 *result = 0; /* keep compiler quiet */
1897 return -1;
1898 }
1899 /* check for just-barely overflow (okay except time-of-day wraps) */
1900 /* caution: we want to allow 1999-12-31 24:00:00 */
1901 if ((*result < 0 && date > 0) ||
1902 (*result > 0 && date < -1))
1903 {
1904 *result = 0; /* keep compiler quiet */
1905 return -1;
1906 }
1907 if (tzp != NULL)
1908 *result = dt2local(*result, -(*tzp));
1909
1910 /* final range check catches just-out-of-range timestamps */
1911 if (!IS_VALID_TIMESTAMP(*result))
1912 {
1913 *result = 0; /* keep compiler quiet */
1914 return -1;
1915 }
1916
1917 return 0;
1918 }
1919
1920
1921 /* interval2tm()
1922 * Convert an interval data type to a tm structure.
1923 */
1924 int
interval2tm(Interval span,struct pg_tm * tm,fsec_t * fsec)1925 interval2tm(Interval span, struct pg_tm *tm, fsec_t *fsec)
1926 {
1927 TimeOffset time;
1928 TimeOffset tfrac;
1929
1930 tm->tm_year = span.month / MONTHS_PER_YEAR;
1931 tm->tm_mon = span.month % MONTHS_PER_YEAR;
1932 tm->tm_mday = span.day;
1933 time = span.time;
1934
1935 tfrac = time / USECS_PER_HOUR;
1936 time -= tfrac * USECS_PER_HOUR;
1937 tm->tm_hour = tfrac;
1938 if (!SAMESIGN(tm->tm_hour, tfrac))
1939 ereport(ERROR,
1940 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1941 errmsg("interval out of range")));
1942 tfrac = time / USECS_PER_MINUTE;
1943 time -= tfrac * USECS_PER_MINUTE;
1944 tm->tm_min = tfrac;
1945 tfrac = time / USECS_PER_SEC;
1946 *fsec = time - (tfrac * USECS_PER_SEC);
1947 tm->tm_sec = tfrac;
1948
1949 return 0;
1950 }
1951
1952 int
tm2interval(struct pg_tm * tm,fsec_t fsec,Interval * span)1953 tm2interval(struct pg_tm *tm, fsec_t fsec, Interval *span)
1954 {
1955 double total_months = (double) tm->tm_year * MONTHS_PER_YEAR + tm->tm_mon;
1956
1957 if (total_months > INT_MAX || total_months < INT_MIN)
1958 return -1;
1959 span->month = total_months;
1960 span->day = tm->tm_mday;
1961 span->time = (((((tm->tm_hour * INT64CONST(60)) +
1962 tm->tm_min) * INT64CONST(60)) +
1963 tm->tm_sec) * USECS_PER_SEC) + fsec;
1964
1965 return 0;
1966 }
1967
1968 static TimeOffset
time2t(const int hour,const int min,const int sec,const fsec_t fsec)1969 time2t(const int hour, const int min, const int sec, const fsec_t fsec)
1970 {
1971 return (((((hour * MINS_PER_HOUR) + min) * SECS_PER_MINUTE) + sec) * USECS_PER_SEC) + fsec;
1972 }
1973
1974 static Timestamp
dt2local(Timestamp dt,int tz)1975 dt2local(Timestamp dt, int tz)
1976 {
1977 dt -= (tz * USECS_PER_SEC);
1978 return dt;
1979 }
1980
1981
1982 /*****************************************************************************
1983 * PUBLIC ROUTINES *
1984 *****************************************************************************/
1985
1986
1987 Datum
timestamp_finite(PG_FUNCTION_ARGS)1988 timestamp_finite(PG_FUNCTION_ARGS)
1989 {
1990 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
1991
1992 PG_RETURN_BOOL(!TIMESTAMP_NOT_FINITE(timestamp));
1993 }
1994
1995 Datum
interval_finite(PG_FUNCTION_ARGS)1996 interval_finite(PG_FUNCTION_ARGS)
1997 {
1998 PG_RETURN_BOOL(true);
1999 }
2000
2001
2002 /*----------------------------------------------------------
2003 * Relational operators for timestamp.
2004 *---------------------------------------------------------*/
2005
2006 void
GetEpochTime(struct pg_tm * tm)2007 GetEpochTime(struct pg_tm *tm)
2008 {
2009 struct pg_tm *t0;
2010 pg_time_t epoch = 0;
2011
2012 t0 = pg_gmtime(&epoch);
2013
2014 if (t0 == NULL)
2015 elog(ERROR, "could not convert epoch to timestamp: %m");
2016
2017 tm->tm_year = t0->tm_year;
2018 tm->tm_mon = t0->tm_mon;
2019 tm->tm_mday = t0->tm_mday;
2020 tm->tm_hour = t0->tm_hour;
2021 tm->tm_min = t0->tm_min;
2022 tm->tm_sec = t0->tm_sec;
2023
2024 tm->tm_year += 1900;
2025 tm->tm_mon++;
2026 }
2027
2028 Timestamp
SetEpochTimestamp(void)2029 SetEpochTimestamp(void)
2030 {
2031 Timestamp dt;
2032 struct pg_tm tt,
2033 *tm = &tt;
2034
2035 GetEpochTime(tm);
2036 /* we don't bother to test for failure ... */
2037 tm2timestamp(tm, 0, NULL, &dt);
2038
2039 return dt;
2040 } /* SetEpochTimestamp() */
2041
2042 /*
2043 * We are currently sharing some code between timestamp and timestamptz.
2044 * The comparison functions are among them. - thomas 2001-09-25
2045 *
2046 * timestamp_relop - is timestamp1 relop timestamp2
2047 */
2048 int
timestamp_cmp_internal(Timestamp dt1,Timestamp dt2)2049 timestamp_cmp_internal(Timestamp dt1, Timestamp dt2)
2050 {
2051 return (dt1 < dt2) ? -1 : ((dt1 > dt2) ? 1 : 0);
2052 }
2053
2054 Datum
timestamp_eq(PG_FUNCTION_ARGS)2055 timestamp_eq(PG_FUNCTION_ARGS)
2056 {
2057 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2058 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2059
2060 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
2061 }
2062
2063 Datum
timestamp_ne(PG_FUNCTION_ARGS)2064 timestamp_ne(PG_FUNCTION_ARGS)
2065 {
2066 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2067 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2068
2069 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
2070 }
2071
2072 Datum
timestamp_lt(PG_FUNCTION_ARGS)2073 timestamp_lt(PG_FUNCTION_ARGS)
2074 {
2075 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2076 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2077
2078 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
2079 }
2080
2081 Datum
timestamp_gt(PG_FUNCTION_ARGS)2082 timestamp_gt(PG_FUNCTION_ARGS)
2083 {
2084 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2085 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2086
2087 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
2088 }
2089
2090 Datum
timestamp_le(PG_FUNCTION_ARGS)2091 timestamp_le(PG_FUNCTION_ARGS)
2092 {
2093 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2094 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2095
2096 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) <= 0);
2097 }
2098
2099 Datum
timestamp_ge(PG_FUNCTION_ARGS)2100 timestamp_ge(PG_FUNCTION_ARGS)
2101 {
2102 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2103 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2104
2105 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) >= 0);
2106 }
2107
2108 Datum
timestamp_cmp(PG_FUNCTION_ARGS)2109 timestamp_cmp(PG_FUNCTION_ARGS)
2110 {
2111 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2112 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2113
2114 PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
2115 }
2116
2117 /* note: this is used for timestamptz also */
2118 static int
timestamp_fastcmp(Datum x,Datum y,SortSupport ssup)2119 timestamp_fastcmp(Datum x, Datum y, SortSupport ssup)
2120 {
2121 Timestamp a = DatumGetTimestamp(x);
2122 Timestamp b = DatumGetTimestamp(y);
2123
2124 return timestamp_cmp_internal(a, b);
2125 }
2126
2127 Datum
timestamp_sortsupport(PG_FUNCTION_ARGS)2128 timestamp_sortsupport(PG_FUNCTION_ARGS)
2129 {
2130 SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
2131
2132 ssup->comparator = timestamp_fastcmp;
2133 PG_RETURN_VOID();
2134 }
2135
2136 Datum
timestamp_hash(PG_FUNCTION_ARGS)2137 timestamp_hash(PG_FUNCTION_ARGS)
2138 {
2139 return hashint8(fcinfo);
2140 }
2141
2142
2143 /*
2144 * Cross-type comparison functions for timestamp vs timestamptz
2145 */
2146
2147 Datum
timestamp_eq_timestamptz(PG_FUNCTION_ARGS)2148 timestamp_eq_timestamptz(PG_FUNCTION_ARGS)
2149 {
2150 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2151 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2152 TimestampTz dt1;
2153
2154 dt1 = timestamp2timestamptz(timestampVal);
2155
2156 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
2157 }
2158
2159 Datum
timestamp_ne_timestamptz(PG_FUNCTION_ARGS)2160 timestamp_ne_timestamptz(PG_FUNCTION_ARGS)
2161 {
2162 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2163 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2164 TimestampTz dt1;
2165
2166 dt1 = timestamp2timestamptz(timestampVal);
2167
2168 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
2169 }
2170
2171 Datum
timestamp_lt_timestamptz(PG_FUNCTION_ARGS)2172 timestamp_lt_timestamptz(PG_FUNCTION_ARGS)
2173 {
2174 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2175 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2176 TimestampTz dt1;
2177
2178 dt1 = timestamp2timestamptz(timestampVal);
2179
2180 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
2181 }
2182
2183 Datum
timestamp_gt_timestamptz(PG_FUNCTION_ARGS)2184 timestamp_gt_timestamptz(PG_FUNCTION_ARGS)
2185 {
2186 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2187 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2188 TimestampTz dt1;
2189
2190 dt1 = timestamp2timestamptz(timestampVal);
2191
2192 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
2193 }
2194
2195 Datum
timestamp_le_timestamptz(PG_FUNCTION_ARGS)2196 timestamp_le_timestamptz(PG_FUNCTION_ARGS)
2197 {
2198 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2199 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2200 TimestampTz dt1;
2201
2202 dt1 = timestamp2timestamptz(timestampVal);
2203
2204 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) <= 0);
2205 }
2206
2207 Datum
timestamp_ge_timestamptz(PG_FUNCTION_ARGS)2208 timestamp_ge_timestamptz(PG_FUNCTION_ARGS)
2209 {
2210 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2211 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2212 TimestampTz dt1;
2213
2214 dt1 = timestamp2timestamptz(timestampVal);
2215
2216 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) >= 0);
2217 }
2218
2219 Datum
timestamp_cmp_timestamptz(PG_FUNCTION_ARGS)2220 timestamp_cmp_timestamptz(PG_FUNCTION_ARGS)
2221 {
2222 Timestamp timestampVal = PG_GETARG_TIMESTAMP(0);
2223 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
2224 TimestampTz dt1;
2225
2226 dt1 = timestamp2timestamptz(timestampVal);
2227
2228 PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
2229 }
2230
2231 Datum
timestamptz_eq_timestamp(PG_FUNCTION_ARGS)2232 timestamptz_eq_timestamp(PG_FUNCTION_ARGS)
2233 {
2234 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2235 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2236 TimestampTz dt2;
2237
2238 dt2 = timestamp2timestamptz(timestampVal);
2239
2240 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) == 0);
2241 }
2242
2243 Datum
timestamptz_ne_timestamp(PG_FUNCTION_ARGS)2244 timestamptz_ne_timestamp(PG_FUNCTION_ARGS)
2245 {
2246 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2247 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2248 TimestampTz dt2;
2249
2250 dt2 = timestamp2timestamptz(timestampVal);
2251
2252 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) != 0);
2253 }
2254
2255 Datum
timestamptz_lt_timestamp(PG_FUNCTION_ARGS)2256 timestamptz_lt_timestamp(PG_FUNCTION_ARGS)
2257 {
2258 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2259 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2260 TimestampTz dt2;
2261
2262 dt2 = timestamp2timestamptz(timestampVal);
2263
2264 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) < 0);
2265 }
2266
2267 Datum
timestamptz_gt_timestamp(PG_FUNCTION_ARGS)2268 timestamptz_gt_timestamp(PG_FUNCTION_ARGS)
2269 {
2270 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2271 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2272 TimestampTz dt2;
2273
2274 dt2 = timestamp2timestamptz(timestampVal);
2275
2276 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) > 0);
2277 }
2278
2279 Datum
timestamptz_le_timestamp(PG_FUNCTION_ARGS)2280 timestamptz_le_timestamp(PG_FUNCTION_ARGS)
2281 {
2282 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2283 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2284 TimestampTz dt2;
2285
2286 dt2 = timestamp2timestamptz(timestampVal);
2287
2288 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) <= 0);
2289 }
2290
2291 Datum
timestamptz_ge_timestamp(PG_FUNCTION_ARGS)2292 timestamptz_ge_timestamp(PG_FUNCTION_ARGS)
2293 {
2294 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2295 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2296 TimestampTz dt2;
2297
2298 dt2 = timestamp2timestamptz(timestampVal);
2299
2300 PG_RETURN_BOOL(timestamp_cmp_internal(dt1, dt2) >= 0);
2301 }
2302
2303 Datum
timestamptz_cmp_timestamp(PG_FUNCTION_ARGS)2304 timestamptz_cmp_timestamp(PG_FUNCTION_ARGS)
2305 {
2306 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
2307 Timestamp timestampVal = PG_GETARG_TIMESTAMP(1);
2308 TimestampTz dt2;
2309
2310 dt2 = timestamp2timestamptz(timestampVal);
2311
2312 PG_RETURN_INT32(timestamp_cmp_internal(dt1, dt2));
2313 }
2314
2315
2316 /*
2317 * interval_relop - is interval1 relop interval2
2318 *
2319 * Interval comparison is based on converting interval values to a linear
2320 * representation expressed in the units of the time field (microseconds,
2321 * in the case of integer timestamps) with days assumed to be always 24 hours
2322 * and months assumed to be always 30 days. To avoid overflow, we need a
2323 * wider-than-int64 datatype for the linear representation, so use INT128.
2324 */
2325
2326 static inline INT128
interval_cmp_value(const Interval * interval)2327 interval_cmp_value(const Interval *interval)
2328 {
2329 INT128 span;
2330 int64 dayfraction;
2331 int64 days;
2332
2333 /*
2334 * Separate time field into days and dayfraction, then add the month and
2335 * day fields to the days part. We cannot overflow int64 days here.
2336 */
2337 dayfraction = interval->time % USECS_PER_DAY;
2338 days = interval->time / USECS_PER_DAY;
2339 days += interval->month * INT64CONST(30);
2340 days += interval->day;
2341
2342 /* Widen dayfraction to 128 bits */
2343 span = int64_to_int128(dayfraction);
2344
2345 /* Scale up days to microseconds, forming a 128-bit product */
2346 int128_add_int64_mul_int64(&span, days, USECS_PER_DAY);
2347
2348 return span;
2349 }
2350
2351 static int
interval_cmp_internal(Interval * interval1,Interval * interval2)2352 interval_cmp_internal(Interval *interval1, Interval *interval2)
2353 {
2354 INT128 span1 = interval_cmp_value(interval1);
2355 INT128 span2 = interval_cmp_value(interval2);
2356
2357 return int128_compare(span1, span2);
2358 }
2359
2360 Datum
interval_eq(PG_FUNCTION_ARGS)2361 interval_eq(PG_FUNCTION_ARGS)
2362 {
2363 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2364 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2365
2366 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) == 0);
2367 }
2368
2369 Datum
interval_ne(PG_FUNCTION_ARGS)2370 interval_ne(PG_FUNCTION_ARGS)
2371 {
2372 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2373 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2374
2375 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) != 0);
2376 }
2377
2378 Datum
interval_lt(PG_FUNCTION_ARGS)2379 interval_lt(PG_FUNCTION_ARGS)
2380 {
2381 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2382 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2383
2384 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) < 0);
2385 }
2386
2387 Datum
interval_gt(PG_FUNCTION_ARGS)2388 interval_gt(PG_FUNCTION_ARGS)
2389 {
2390 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2391 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2392
2393 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) > 0);
2394 }
2395
2396 Datum
interval_le(PG_FUNCTION_ARGS)2397 interval_le(PG_FUNCTION_ARGS)
2398 {
2399 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2400 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2401
2402 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) <= 0);
2403 }
2404
2405 Datum
interval_ge(PG_FUNCTION_ARGS)2406 interval_ge(PG_FUNCTION_ARGS)
2407 {
2408 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2409 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2410
2411 PG_RETURN_BOOL(interval_cmp_internal(interval1, interval2) >= 0);
2412 }
2413
2414 Datum
interval_cmp(PG_FUNCTION_ARGS)2415 interval_cmp(PG_FUNCTION_ARGS)
2416 {
2417 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
2418 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
2419
2420 PG_RETURN_INT32(interval_cmp_internal(interval1, interval2));
2421 }
2422
2423 /*
2424 * Hashing for intervals
2425 *
2426 * We must produce equal hashvals for values that interval_cmp_internal()
2427 * considers equal. So, compute the net span the same way it does,
2428 * and then hash that.
2429 */
2430 Datum
interval_hash(PG_FUNCTION_ARGS)2431 interval_hash(PG_FUNCTION_ARGS)
2432 {
2433 Interval *interval = PG_GETARG_INTERVAL_P(0);
2434 INT128 span = interval_cmp_value(interval);
2435 int64 span64;
2436
2437 /*
2438 * Use only the least significant 64 bits for hashing. The upper 64 bits
2439 * seldom add any useful information, and besides we must do it like this
2440 * for compatibility with hashes calculated before use of INT128 was
2441 * introduced.
2442 */
2443 span64 = int128_to_int64(span);
2444
2445 return DirectFunctionCall1(hashint8, Int64GetDatumFast(span64));
2446 }
2447
2448 /* overlaps_timestamp() --- implements the SQL OVERLAPS operator.
2449 *
2450 * Algorithm is per SQL spec. This is much harder than you'd think
2451 * because the spec requires us to deliver a non-null answer in some cases
2452 * where some of the inputs are null.
2453 */
2454 Datum
overlaps_timestamp(PG_FUNCTION_ARGS)2455 overlaps_timestamp(PG_FUNCTION_ARGS)
2456 {
2457 /*
2458 * The arguments are Timestamps, but we leave them as generic Datums to
2459 * avoid unnecessary conversions between value and reference forms --- not
2460 * to mention possible dereferences of null pointers.
2461 */
2462 Datum ts1 = PG_GETARG_DATUM(0);
2463 Datum te1 = PG_GETARG_DATUM(1);
2464 Datum ts2 = PG_GETARG_DATUM(2);
2465 Datum te2 = PG_GETARG_DATUM(3);
2466 bool ts1IsNull = PG_ARGISNULL(0);
2467 bool te1IsNull = PG_ARGISNULL(1);
2468 bool ts2IsNull = PG_ARGISNULL(2);
2469 bool te2IsNull = PG_ARGISNULL(3);
2470
2471 #define TIMESTAMP_GT(t1,t2) \
2472 DatumGetBool(DirectFunctionCall2(timestamp_gt,t1,t2))
2473 #define TIMESTAMP_LT(t1,t2) \
2474 DatumGetBool(DirectFunctionCall2(timestamp_lt,t1,t2))
2475
2476 /*
2477 * If both endpoints of interval 1 are null, the result is null (unknown).
2478 * If just one endpoint is null, take ts1 as the non-null one. Otherwise,
2479 * take ts1 as the lesser endpoint.
2480 */
2481 if (ts1IsNull)
2482 {
2483 if (te1IsNull)
2484 PG_RETURN_NULL();
2485 /* swap null for non-null */
2486 ts1 = te1;
2487 te1IsNull = true;
2488 }
2489 else if (!te1IsNull)
2490 {
2491 if (TIMESTAMP_GT(ts1, te1))
2492 {
2493 Datum tt = ts1;
2494
2495 ts1 = te1;
2496 te1 = tt;
2497 }
2498 }
2499
2500 /* Likewise for interval 2. */
2501 if (ts2IsNull)
2502 {
2503 if (te2IsNull)
2504 PG_RETURN_NULL();
2505 /* swap null for non-null */
2506 ts2 = te2;
2507 te2IsNull = true;
2508 }
2509 else if (!te2IsNull)
2510 {
2511 if (TIMESTAMP_GT(ts2, te2))
2512 {
2513 Datum tt = ts2;
2514
2515 ts2 = te2;
2516 te2 = tt;
2517 }
2518 }
2519
2520 /*
2521 * At this point neither ts1 nor ts2 is null, so we can consider three
2522 * cases: ts1 > ts2, ts1 < ts2, ts1 = ts2
2523 */
2524 if (TIMESTAMP_GT(ts1, ts2))
2525 {
2526 /*
2527 * This case is ts1 < te2 OR te1 < te2, which may look redundant but
2528 * in the presence of nulls it's not quite completely so.
2529 */
2530 if (te2IsNull)
2531 PG_RETURN_NULL();
2532 if (TIMESTAMP_LT(ts1, te2))
2533 PG_RETURN_BOOL(true);
2534 if (te1IsNull)
2535 PG_RETURN_NULL();
2536
2537 /*
2538 * If te1 is not null then we had ts1 <= te1 above, and we just found
2539 * ts1 >= te2, hence te1 >= te2.
2540 */
2541 PG_RETURN_BOOL(false);
2542 }
2543 else if (TIMESTAMP_LT(ts1, ts2))
2544 {
2545 /* This case is ts2 < te1 OR te2 < te1 */
2546 if (te1IsNull)
2547 PG_RETURN_NULL();
2548 if (TIMESTAMP_LT(ts2, te1))
2549 PG_RETURN_BOOL(true);
2550 if (te2IsNull)
2551 PG_RETURN_NULL();
2552
2553 /*
2554 * If te2 is not null then we had ts2 <= te2 above, and we just found
2555 * ts2 >= te1, hence te2 >= te1.
2556 */
2557 PG_RETURN_BOOL(false);
2558 }
2559 else
2560 {
2561 /*
2562 * For ts1 = ts2 the spec says te1 <> te2 OR te1 = te2, which is a
2563 * rather silly way of saying "true if both are non-null, else null".
2564 */
2565 if (te1IsNull || te2IsNull)
2566 PG_RETURN_NULL();
2567 PG_RETURN_BOOL(true);
2568 }
2569
2570 #undef TIMESTAMP_GT
2571 #undef TIMESTAMP_LT
2572 }
2573
2574
2575 /*----------------------------------------------------------
2576 * "Arithmetic" operators on date/times.
2577 *---------------------------------------------------------*/
2578
2579 Datum
timestamp_smaller(PG_FUNCTION_ARGS)2580 timestamp_smaller(PG_FUNCTION_ARGS)
2581 {
2582 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2583 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2584 Timestamp result;
2585
2586 /* use timestamp_cmp_internal to be sure this agrees with comparisons */
2587 if (timestamp_cmp_internal(dt1, dt2) < 0)
2588 result = dt1;
2589 else
2590 result = dt2;
2591 PG_RETURN_TIMESTAMP(result);
2592 }
2593
2594 Datum
timestamp_larger(PG_FUNCTION_ARGS)2595 timestamp_larger(PG_FUNCTION_ARGS)
2596 {
2597 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2598 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2599 Timestamp result;
2600
2601 if (timestamp_cmp_internal(dt1, dt2) > 0)
2602 result = dt1;
2603 else
2604 result = dt2;
2605 PG_RETURN_TIMESTAMP(result);
2606 }
2607
2608
2609 Datum
timestamp_mi(PG_FUNCTION_ARGS)2610 timestamp_mi(PG_FUNCTION_ARGS)
2611 {
2612 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
2613 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
2614 Interval *result;
2615
2616 result = (Interval *) palloc(sizeof(Interval));
2617
2618 if (TIMESTAMP_NOT_FINITE(dt1) || TIMESTAMP_NOT_FINITE(dt2))
2619 ereport(ERROR,
2620 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2621 errmsg("cannot subtract infinite timestamps")));
2622
2623 result->time = dt1 - dt2;
2624
2625 result->month = 0;
2626 result->day = 0;
2627
2628 /*----------
2629 * This is wrong, but removing it breaks a lot of regression tests.
2630 * For example:
2631 *
2632 * test=> SET timezone = 'EST5EDT';
2633 * test=> SELECT
2634 * test-> ('2005-10-30 13:22:00-05'::timestamptz -
2635 * test(> '2005-10-29 13:22:00-04'::timestamptz);
2636 * ?column?
2637 * ----------------
2638 * 1 day 01:00:00
2639 * (1 row)
2640 *
2641 * so adding that to the first timestamp gets:
2642 *
2643 * test=> SELECT
2644 * test-> ('2005-10-29 13:22:00-04'::timestamptz +
2645 * test(> ('2005-10-30 13:22:00-05'::timestamptz -
2646 * test(> '2005-10-29 13:22:00-04'::timestamptz)) at time zone 'EST';
2647 * timezone
2648 * --------------------
2649 * 2005-10-30 14:22:00
2650 * (1 row)
2651 *----------
2652 */
2653 result = DatumGetIntervalP(DirectFunctionCall1(interval_justify_hours,
2654 IntervalPGetDatum(result)));
2655
2656 PG_RETURN_INTERVAL_P(result);
2657 }
2658
2659 /*
2660 * interval_justify_interval()
2661 *
2662 * Adjust interval so 'month', 'day', and 'time' portions are within
2663 * customary bounds. Specifically:
2664 *
2665 * 0 <= abs(time) < 24 hours
2666 * 0 <= abs(day) < 30 days
2667 *
2668 * Also, the sign bit on all three fields is made equal, so either
2669 * all three fields are negative or all are positive.
2670 */
2671 Datum
interval_justify_interval(PG_FUNCTION_ARGS)2672 interval_justify_interval(PG_FUNCTION_ARGS)
2673 {
2674 Interval *span = PG_GETARG_INTERVAL_P(0);
2675 Interval *result;
2676 TimeOffset wholeday;
2677 int32 wholemonth;
2678
2679 result = (Interval *) palloc(sizeof(Interval));
2680 result->month = span->month;
2681 result->day = span->day;
2682 result->time = span->time;
2683
2684 TMODULO(result->time, wholeday, USECS_PER_DAY);
2685 result->day += wholeday; /* could overflow... */
2686
2687 wholemonth = result->day / DAYS_PER_MONTH;
2688 result->day -= wholemonth * DAYS_PER_MONTH;
2689 result->month += wholemonth;
2690
2691 if (result->month > 0 &&
2692 (result->day < 0 || (result->day == 0 && result->time < 0)))
2693 {
2694 result->day += DAYS_PER_MONTH;
2695 result->month--;
2696 }
2697 else if (result->month < 0 &&
2698 (result->day > 0 || (result->day == 0 && result->time > 0)))
2699 {
2700 result->day -= DAYS_PER_MONTH;
2701 result->month++;
2702 }
2703
2704 if (result->day > 0 && result->time < 0)
2705 {
2706 result->time += USECS_PER_DAY;
2707 result->day--;
2708 }
2709 else if (result->day < 0 && result->time > 0)
2710 {
2711 result->time -= USECS_PER_DAY;
2712 result->day++;
2713 }
2714
2715 PG_RETURN_INTERVAL_P(result);
2716 }
2717
2718 /*
2719 * interval_justify_hours()
2720 *
2721 * Adjust interval so 'time' contains less than a whole day, adding
2722 * the excess to 'day'. This is useful for
2723 * situations (such as non-TZ) where '1 day' = '24 hours' is valid,
2724 * e.g. interval subtraction and division.
2725 */
2726 Datum
interval_justify_hours(PG_FUNCTION_ARGS)2727 interval_justify_hours(PG_FUNCTION_ARGS)
2728 {
2729 Interval *span = PG_GETARG_INTERVAL_P(0);
2730 Interval *result;
2731 TimeOffset wholeday;
2732
2733 result = (Interval *) palloc(sizeof(Interval));
2734 result->month = span->month;
2735 result->day = span->day;
2736 result->time = span->time;
2737
2738 TMODULO(result->time, wholeday, USECS_PER_DAY);
2739 result->day += wholeday; /* could overflow... */
2740
2741 if (result->day > 0 && result->time < 0)
2742 {
2743 result->time += USECS_PER_DAY;
2744 result->day--;
2745 }
2746 else if (result->day < 0 && result->time > 0)
2747 {
2748 result->time -= USECS_PER_DAY;
2749 result->day++;
2750 }
2751
2752 PG_RETURN_INTERVAL_P(result);
2753 }
2754
2755 /*
2756 * interval_justify_days()
2757 *
2758 * Adjust interval so 'day' contains less than 30 days, adding
2759 * the excess to 'month'.
2760 */
2761 Datum
interval_justify_days(PG_FUNCTION_ARGS)2762 interval_justify_days(PG_FUNCTION_ARGS)
2763 {
2764 Interval *span = PG_GETARG_INTERVAL_P(0);
2765 Interval *result;
2766 int32 wholemonth;
2767
2768 result = (Interval *) palloc(sizeof(Interval));
2769 result->month = span->month;
2770 result->day = span->day;
2771 result->time = span->time;
2772
2773 wholemonth = result->day / DAYS_PER_MONTH;
2774 result->day -= wholemonth * DAYS_PER_MONTH;
2775 result->month += wholemonth;
2776
2777 if (result->month > 0 && result->day < 0)
2778 {
2779 result->day += DAYS_PER_MONTH;
2780 result->month--;
2781 }
2782 else if (result->month < 0 && result->day > 0)
2783 {
2784 result->day -= DAYS_PER_MONTH;
2785 result->month++;
2786 }
2787
2788 PG_RETURN_INTERVAL_P(result);
2789 }
2790
2791 /* timestamp_pl_interval()
2792 * Add an interval to a timestamp data type.
2793 * Note that interval has provisions for qualitative year/month and day
2794 * units, so try to do the right thing with them.
2795 * To add a month, increment the month, and use the same day of month.
2796 * Then, if the next month has fewer days, set the day of month
2797 * to the last day of month.
2798 * To add a day, increment the mday, and use the same time of day.
2799 * Lastly, add in the "quantitative time".
2800 */
2801 Datum
timestamp_pl_interval(PG_FUNCTION_ARGS)2802 timestamp_pl_interval(PG_FUNCTION_ARGS)
2803 {
2804 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
2805 Interval *span = PG_GETARG_INTERVAL_P(1);
2806 Timestamp result;
2807
2808 if (TIMESTAMP_NOT_FINITE(timestamp))
2809 result = timestamp;
2810 else
2811 {
2812 if (span->month != 0)
2813 {
2814 struct pg_tm tt,
2815 *tm = &tt;
2816 fsec_t fsec;
2817
2818 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
2819 ereport(ERROR,
2820 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2821 errmsg("timestamp out of range")));
2822
2823 tm->tm_mon += span->month;
2824 if (tm->tm_mon > MONTHS_PER_YEAR)
2825 {
2826 tm->tm_year += (tm->tm_mon - 1) / MONTHS_PER_YEAR;
2827 tm->tm_mon = ((tm->tm_mon - 1) % MONTHS_PER_YEAR) + 1;
2828 }
2829 else if (tm->tm_mon < 1)
2830 {
2831 tm->tm_year += tm->tm_mon / MONTHS_PER_YEAR - 1;
2832 tm->tm_mon = tm->tm_mon % MONTHS_PER_YEAR + MONTHS_PER_YEAR;
2833 }
2834
2835 /* adjust for end of month boundary problems... */
2836 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2837 tm->tm_mday = (day_tab[isleap(tm->tm_year)][tm->tm_mon - 1]);
2838
2839 if (tm2timestamp(tm, fsec, NULL, ×tamp) != 0)
2840 ereport(ERROR,
2841 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2842 errmsg("timestamp out of range")));
2843 }
2844
2845 if (span->day != 0)
2846 {
2847 struct pg_tm tt,
2848 *tm = &tt;
2849 fsec_t fsec;
2850 int julian;
2851
2852 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
2853 ereport(ERROR,
2854 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2855 errmsg("timestamp out of range")));
2856
2857 /* Add days by converting to and from Julian */
2858 julian = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + span->day;
2859 j2date(julian, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2860
2861 if (tm2timestamp(tm, fsec, NULL, ×tamp) != 0)
2862 ereport(ERROR,
2863 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2864 errmsg("timestamp out of range")));
2865 }
2866
2867 timestamp += span->time;
2868
2869 if (!IS_VALID_TIMESTAMP(timestamp))
2870 ereport(ERROR,
2871 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2872 errmsg("timestamp out of range")));
2873
2874 result = timestamp;
2875 }
2876
2877 PG_RETURN_TIMESTAMP(result);
2878 }
2879
2880 Datum
timestamp_mi_interval(PG_FUNCTION_ARGS)2881 timestamp_mi_interval(PG_FUNCTION_ARGS)
2882 {
2883 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
2884 Interval *span = PG_GETARG_INTERVAL_P(1);
2885 Interval tspan;
2886
2887 tspan.month = -span->month;
2888 tspan.day = -span->day;
2889 tspan.time = -span->time;
2890
2891 return DirectFunctionCall2(timestamp_pl_interval,
2892 TimestampGetDatum(timestamp),
2893 PointerGetDatum(&tspan));
2894 }
2895
2896
2897 /* timestamptz_pl_interval()
2898 * Add an interval to a timestamp with time zone data type.
2899 * Note that interval has provisions for qualitative year/month
2900 * units, so try to do the right thing with them.
2901 * To add a month, increment the month, and use the same day of month.
2902 * Then, if the next month has fewer days, set the day of month
2903 * to the last day of month.
2904 * Lastly, add in the "quantitative time".
2905 */
2906 Datum
timestamptz_pl_interval(PG_FUNCTION_ARGS)2907 timestamptz_pl_interval(PG_FUNCTION_ARGS)
2908 {
2909 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
2910 Interval *span = PG_GETARG_INTERVAL_P(1);
2911 TimestampTz result;
2912 int tz;
2913
2914 if (TIMESTAMP_NOT_FINITE(timestamp))
2915 result = timestamp;
2916 else
2917 {
2918 if (span->month != 0)
2919 {
2920 struct pg_tm tt,
2921 *tm = &tt;
2922 fsec_t fsec;
2923
2924 if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, NULL) != 0)
2925 ereport(ERROR,
2926 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2927 errmsg("timestamp out of range")));
2928
2929 tm->tm_mon += span->month;
2930 if (tm->tm_mon > MONTHS_PER_YEAR)
2931 {
2932 tm->tm_year += (tm->tm_mon - 1) / MONTHS_PER_YEAR;
2933 tm->tm_mon = ((tm->tm_mon - 1) % MONTHS_PER_YEAR) + 1;
2934 }
2935 else if (tm->tm_mon < 1)
2936 {
2937 tm->tm_year += tm->tm_mon / MONTHS_PER_YEAR - 1;
2938 tm->tm_mon = tm->tm_mon % MONTHS_PER_YEAR + MONTHS_PER_YEAR;
2939 }
2940
2941 /* adjust for end of month boundary problems... */
2942 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2943 tm->tm_mday = (day_tab[isleap(tm->tm_year)][tm->tm_mon - 1]);
2944
2945 tz = DetermineTimeZoneOffset(tm, session_timezone);
2946
2947 if (tm2timestamp(tm, fsec, &tz, ×tamp) != 0)
2948 ereport(ERROR,
2949 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2950 errmsg("timestamp out of range")));
2951 }
2952
2953 if (span->day != 0)
2954 {
2955 struct pg_tm tt,
2956 *tm = &tt;
2957 fsec_t fsec;
2958 int julian;
2959
2960 if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, NULL) != 0)
2961 ereport(ERROR,
2962 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2963 errmsg("timestamp out of range")));
2964
2965 /* Add days by converting to and from Julian */
2966 julian = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + span->day;
2967 j2date(julian, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2968
2969 tz = DetermineTimeZoneOffset(tm, session_timezone);
2970
2971 if (tm2timestamp(tm, fsec, &tz, ×tamp) != 0)
2972 ereport(ERROR,
2973 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2974 errmsg("timestamp out of range")));
2975 }
2976
2977 timestamp += span->time;
2978
2979 if (!IS_VALID_TIMESTAMP(timestamp))
2980 ereport(ERROR,
2981 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
2982 errmsg("timestamp out of range")));
2983
2984 result = timestamp;
2985 }
2986
2987 PG_RETURN_TIMESTAMP(result);
2988 }
2989
2990 Datum
timestamptz_mi_interval(PG_FUNCTION_ARGS)2991 timestamptz_mi_interval(PG_FUNCTION_ARGS)
2992 {
2993 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
2994 Interval *span = PG_GETARG_INTERVAL_P(1);
2995 Interval tspan;
2996
2997 tspan.month = -span->month;
2998 tspan.day = -span->day;
2999 tspan.time = -span->time;
3000
3001 return DirectFunctionCall2(timestamptz_pl_interval,
3002 TimestampGetDatum(timestamp),
3003 PointerGetDatum(&tspan));
3004 }
3005
3006
3007 Datum
interval_um(PG_FUNCTION_ARGS)3008 interval_um(PG_FUNCTION_ARGS)
3009 {
3010 Interval *interval = PG_GETARG_INTERVAL_P(0);
3011 Interval *result;
3012
3013 result = (Interval *) palloc(sizeof(Interval));
3014
3015 result->time = -interval->time;
3016 /* overflow check copied from int4um */
3017 if (interval->time != 0 && SAMESIGN(result->time, interval->time))
3018 ereport(ERROR,
3019 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3020 errmsg("interval out of range")));
3021 result->day = -interval->day;
3022 if (interval->day != 0 && SAMESIGN(result->day, interval->day))
3023 ereport(ERROR,
3024 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3025 errmsg("interval out of range")));
3026 result->month = -interval->month;
3027 if (interval->month != 0 && SAMESIGN(result->month, interval->month))
3028 ereport(ERROR,
3029 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3030 errmsg("interval out of range")));
3031
3032 PG_RETURN_INTERVAL_P(result);
3033 }
3034
3035
3036 Datum
interval_smaller(PG_FUNCTION_ARGS)3037 interval_smaller(PG_FUNCTION_ARGS)
3038 {
3039 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
3040 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
3041 Interval *result;
3042
3043 /* use interval_cmp_internal to be sure this agrees with comparisons */
3044 if (interval_cmp_internal(interval1, interval2) < 0)
3045 result = interval1;
3046 else
3047 result = interval2;
3048 PG_RETURN_INTERVAL_P(result);
3049 }
3050
3051 Datum
interval_larger(PG_FUNCTION_ARGS)3052 interval_larger(PG_FUNCTION_ARGS)
3053 {
3054 Interval *interval1 = PG_GETARG_INTERVAL_P(0);
3055 Interval *interval2 = PG_GETARG_INTERVAL_P(1);
3056 Interval *result;
3057
3058 if (interval_cmp_internal(interval1, interval2) > 0)
3059 result = interval1;
3060 else
3061 result = interval2;
3062 PG_RETURN_INTERVAL_P(result);
3063 }
3064
3065 Datum
interval_pl(PG_FUNCTION_ARGS)3066 interval_pl(PG_FUNCTION_ARGS)
3067 {
3068 Interval *span1 = PG_GETARG_INTERVAL_P(0);
3069 Interval *span2 = PG_GETARG_INTERVAL_P(1);
3070 Interval *result;
3071
3072 result = (Interval *) palloc(sizeof(Interval));
3073
3074 result->month = span1->month + span2->month;
3075 /* overflow check copied from int4pl */
3076 if (SAMESIGN(span1->month, span2->month) &&
3077 !SAMESIGN(result->month, span1->month))
3078 ereport(ERROR,
3079 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3080 errmsg("interval out of range")));
3081
3082 result->day = span1->day + span2->day;
3083 if (SAMESIGN(span1->day, span2->day) &&
3084 !SAMESIGN(result->day, span1->day))
3085 ereport(ERROR,
3086 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3087 errmsg("interval out of range")));
3088
3089 result->time = span1->time + span2->time;
3090 if (SAMESIGN(span1->time, span2->time) &&
3091 !SAMESIGN(result->time, span1->time))
3092 ereport(ERROR,
3093 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3094 errmsg("interval out of range")));
3095
3096 PG_RETURN_INTERVAL_P(result);
3097 }
3098
3099 Datum
interval_mi(PG_FUNCTION_ARGS)3100 interval_mi(PG_FUNCTION_ARGS)
3101 {
3102 Interval *span1 = PG_GETARG_INTERVAL_P(0);
3103 Interval *span2 = PG_GETARG_INTERVAL_P(1);
3104 Interval *result;
3105
3106 result = (Interval *) palloc(sizeof(Interval));
3107
3108 result->month = span1->month - span2->month;
3109 /* overflow check copied from int4mi */
3110 if (!SAMESIGN(span1->month, span2->month) &&
3111 !SAMESIGN(result->month, span1->month))
3112 ereport(ERROR,
3113 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3114 errmsg("interval out of range")));
3115
3116 result->day = span1->day - span2->day;
3117 if (!SAMESIGN(span1->day, span2->day) &&
3118 !SAMESIGN(result->day, span1->day))
3119 ereport(ERROR,
3120 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3121 errmsg("interval out of range")));
3122
3123 result->time = span1->time - span2->time;
3124 if (!SAMESIGN(span1->time, span2->time) &&
3125 !SAMESIGN(result->time, span1->time))
3126 ereport(ERROR,
3127 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3128 errmsg("interval out of range")));
3129
3130 PG_RETURN_INTERVAL_P(result);
3131 }
3132
3133 /*
3134 * There is no interval_abs(): it is unclear what value to return:
3135 * http://archives.postgresql.org/pgsql-general/2009-10/msg01031.php
3136 * http://archives.postgresql.org/pgsql-general/2009-11/msg00041.php
3137 */
3138
3139 Datum
interval_mul(PG_FUNCTION_ARGS)3140 interval_mul(PG_FUNCTION_ARGS)
3141 {
3142 Interval *span = PG_GETARG_INTERVAL_P(0);
3143 float8 factor = PG_GETARG_FLOAT8(1);
3144 double month_remainder_days,
3145 sec_remainder,
3146 result_double;
3147 int32 orig_month = span->month,
3148 orig_day = span->day;
3149 Interval *result;
3150
3151 result = (Interval *) palloc(sizeof(Interval));
3152
3153 result_double = span->month * factor;
3154 if (isnan(result_double) ||
3155 result_double > INT_MAX || result_double < INT_MIN)
3156 ereport(ERROR,
3157 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3158 errmsg("interval out of range")));
3159 result->month = (int32) result_double;
3160
3161 result_double = span->day * factor;
3162 if (isnan(result_double) ||
3163 result_double > INT_MAX || result_double < INT_MIN)
3164 ereport(ERROR,
3165 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3166 errmsg("interval out of range")));
3167 result->day = (int32) result_double;
3168
3169 /*
3170 * The above correctly handles the whole-number part of the month and day
3171 * products, but we have to do something with any fractional part
3172 * resulting when the factor is non-integral. We cascade the fractions
3173 * down to lower units using the conversion factors DAYS_PER_MONTH and
3174 * SECS_PER_DAY. Note we do NOT cascade up, since we are not forced to do
3175 * so by the representation. The user can choose to cascade up later,
3176 * using justify_hours and/or justify_days.
3177 */
3178
3179 /*
3180 * Fractional months full days into days.
3181 *
3182 * Floating point calculation are inherently imprecise, so these
3183 * calculations are crafted to produce the most reliable result possible.
3184 * TSROUND() is needed to more accurately produce whole numbers where
3185 * appropriate.
3186 */
3187 month_remainder_days = (orig_month * factor - result->month) * DAYS_PER_MONTH;
3188 month_remainder_days = TSROUND(month_remainder_days);
3189 sec_remainder = (orig_day * factor - result->day +
3190 month_remainder_days - (int) month_remainder_days) * SECS_PER_DAY;
3191 sec_remainder = TSROUND(sec_remainder);
3192
3193 /*
3194 * Might have 24:00:00 hours due to rounding, or >24 hours because of time
3195 * cascade from months and days. It might still be >24 if the combination
3196 * of cascade and the seconds factor operation itself.
3197 */
3198 if (Abs(sec_remainder) >= SECS_PER_DAY)
3199 {
3200 result->day += (int) (sec_remainder / SECS_PER_DAY);
3201 sec_remainder -= (int) (sec_remainder / SECS_PER_DAY) * SECS_PER_DAY;
3202 }
3203
3204 /* cascade units down */
3205 result->day += (int32) month_remainder_days;
3206 result_double = rint(span->time * factor + sec_remainder * USECS_PER_SEC);
3207 if (isnan(result_double) || !FLOAT8_FITS_IN_INT64(result_double))
3208 ereport(ERROR,
3209 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3210 errmsg("interval out of range")));
3211 result->time = (int64) result_double;
3212
3213 PG_RETURN_INTERVAL_P(result);
3214 }
3215
3216 Datum
mul_d_interval(PG_FUNCTION_ARGS)3217 mul_d_interval(PG_FUNCTION_ARGS)
3218 {
3219 /* Args are float8 and Interval *, but leave them as generic Datum */
3220 Datum factor = PG_GETARG_DATUM(0);
3221 Datum span = PG_GETARG_DATUM(1);
3222
3223 return DirectFunctionCall2(interval_mul, span, factor);
3224 }
3225
3226 Datum
interval_div(PG_FUNCTION_ARGS)3227 interval_div(PG_FUNCTION_ARGS)
3228 {
3229 Interval *span = PG_GETARG_INTERVAL_P(0);
3230 float8 factor = PG_GETARG_FLOAT8(1);
3231 double month_remainder_days,
3232 sec_remainder;
3233 int32 orig_month = span->month,
3234 orig_day = span->day;
3235 Interval *result;
3236
3237 result = (Interval *) palloc(sizeof(Interval));
3238
3239 if (factor == 0.0)
3240 ereport(ERROR,
3241 (errcode(ERRCODE_DIVISION_BY_ZERO),
3242 errmsg("division by zero")));
3243
3244 result->month = (int32) (span->month / factor);
3245 result->day = (int32) (span->day / factor);
3246
3247 /*
3248 * Fractional months full days into days. See comment in interval_mul().
3249 */
3250 month_remainder_days = (orig_month / factor - result->month) * DAYS_PER_MONTH;
3251 month_remainder_days = TSROUND(month_remainder_days);
3252 sec_remainder = (orig_day / factor - result->day +
3253 month_remainder_days - (int) month_remainder_days) * SECS_PER_DAY;
3254 sec_remainder = TSROUND(sec_remainder);
3255 if (Abs(sec_remainder) >= SECS_PER_DAY)
3256 {
3257 result->day += (int) (sec_remainder / SECS_PER_DAY);
3258 sec_remainder -= (int) (sec_remainder / SECS_PER_DAY) * SECS_PER_DAY;
3259 }
3260
3261 /* cascade units down */
3262 result->day += (int32) month_remainder_days;
3263 result->time = rint(span->time / factor + sec_remainder * USECS_PER_SEC);
3264
3265 PG_RETURN_INTERVAL_P(result);
3266 }
3267
3268 /*
3269 * interval_accum, interval_accum_inv, and interval_avg implement the
3270 * AVG(interval) aggregate.
3271 *
3272 * The transition datatype for this aggregate is a 2-element array of
3273 * intervals, where the first is the running sum and the second contains
3274 * the number of values so far in its 'time' field. This is a bit ugly
3275 * but it beats inventing a specialized datatype for the purpose.
3276 */
3277
3278 Datum
interval_accum(PG_FUNCTION_ARGS)3279 interval_accum(PG_FUNCTION_ARGS)
3280 {
3281 ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
3282 Interval *newval = PG_GETARG_INTERVAL_P(1);
3283 Datum *transdatums;
3284 int ndatums;
3285 Interval sumX,
3286 N;
3287 Interval *newsum;
3288 ArrayType *result;
3289
3290 deconstruct_array(transarray,
3291 INTERVALOID, sizeof(Interval), false, 'd',
3292 &transdatums, NULL, &ndatums);
3293 if (ndatums != 2)
3294 elog(ERROR, "expected 2-element interval array");
3295
3296 sumX = *(DatumGetIntervalP(transdatums[0]));
3297 N = *(DatumGetIntervalP(transdatums[1]));
3298
3299 newsum = DatumGetIntervalP(DirectFunctionCall2(interval_pl,
3300 IntervalPGetDatum(&sumX),
3301 IntervalPGetDatum(newval)));
3302 N.time += 1;
3303
3304 transdatums[0] = IntervalPGetDatum(newsum);
3305 transdatums[1] = IntervalPGetDatum(&N);
3306
3307 result = construct_array(transdatums, 2,
3308 INTERVALOID, sizeof(Interval), false, 'd');
3309
3310 PG_RETURN_ARRAYTYPE_P(result);
3311 }
3312
3313 Datum
interval_combine(PG_FUNCTION_ARGS)3314 interval_combine(PG_FUNCTION_ARGS)
3315 {
3316 ArrayType *transarray1 = PG_GETARG_ARRAYTYPE_P(0);
3317 ArrayType *transarray2 = PG_GETARG_ARRAYTYPE_P(1);
3318 Datum *transdatums1;
3319 Datum *transdatums2;
3320 int ndatums1;
3321 int ndatums2;
3322 Interval sum1,
3323 N1;
3324 Interval sum2,
3325 N2;
3326
3327 Interval *newsum;
3328 ArrayType *result;
3329
3330 deconstruct_array(transarray1,
3331 INTERVALOID, sizeof(Interval), false, 'd',
3332 &transdatums1, NULL, &ndatums1);
3333 if (ndatums1 != 2)
3334 elog(ERROR, "expected 2-element interval array");
3335
3336 sum1 = *(DatumGetIntervalP(transdatums1[0]));
3337 N1 = *(DatumGetIntervalP(transdatums1[1]));
3338
3339 deconstruct_array(transarray2,
3340 INTERVALOID, sizeof(Interval), false, 'd',
3341 &transdatums2, NULL, &ndatums2);
3342 if (ndatums2 != 2)
3343 elog(ERROR, "expected 2-element interval array");
3344
3345 sum2 = *(DatumGetIntervalP(transdatums2[0]));
3346 N2 = *(DatumGetIntervalP(transdatums2[1]));
3347
3348 newsum = DatumGetIntervalP(DirectFunctionCall2(interval_pl,
3349 IntervalPGetDatum(&sum1),
3350 IntervalPGetDatum(&sum2)));
3351 N1.time += N2.time;
3352
3353 transdatums1[0] = IntervalPGetDatum(newsum);
3354 transdatums1[1] = IntervalPGetDatum(&N1);
3355
3356 result = construct_array(transdatums1, 2,
3357 INTERVALOID, sizeof(Interval), false, 'd');
3358
3359 PG_RETURN_ARRAYTYPE_P(result);
3360 }
3361
3362 Datum
interval_accum_inv(PG_FUNCTION_ARGS)3363 interval_accum_inv(PG_FUNCTION_ARGS)
3364 {
3365 ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
3366 Interval *newval = PG_GETARG_INTERVAL_P(1);
3367 Datum *transdatums;
3368 int ndatums;
3369 Interval sumX,
3370 N;
3371 Interval *newsum;
3372 ArrayType *result;
3373
3374 deconstruct_array(transarray,
3375 INTERVALOID, sizeof(Interval), false, 'd',
3376 &transdatums, NULL, &ndatums);
3377 if (ndatums != 2)
3378 elog(ERROR, "expected 2-element interval array");
3379
3380 sumX = *(DatumGetIntervalP(transdatums[0]));
3381 N = *(DatumGetIntervalP(transdatums[1]));
3382
3383 newsum = DatumGetIntervalP(DirectFunctionCall2(interval_mi,
3384 IntervalPGetDatum(&sumX),
3385 IntervalPGetDatum(newval)));
3386 N.time -= 1;
3387
3388 transdatums[0] = IntervalPGetDatum(newsum);
3389 transdatums[1] = IntervalPGetDatum(&N);
3390
3391 result = construct_array(transdatums, 2,
3392 INTERVALOID, sizeof(Interval), false, 'd');
3393
3394 PG_RETURN_ARRAYTYPE_P(result);
3395 }
3396
3397 Datum
interval_avg(PG_FUNCTION_ARGS)3398 interval_avg(PG_FUNCTION_ARGS)
3399 {
3400 ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
3401 Datum *transdatums;
3402 int ndatums;
3403 Interval sumX,
3404 N;
3405
3406 deconstruct_array(transarray,
3407 INTERVALOID, sizeof(Interval), false, 'd',
3408 &transdatums, NULL, &ndatums);
3409 if (ndatums != 2)
3410 elog(ERROR, "expected 2-element interval array");
3411
3412 sumX = *(DatumGetIntervalP(transdatums[0]));
3413 N = *(DatumGetIntervalP(transdatums[1]));
3414
3415 /* SQL defines AVG of no values to be NULL */
3416 if (N.time == 0)
3417 PG_RETURN_NULL();
3418
3419 return DirectFunctionCall2(interval_div,
3420 IntervalPGetDatum(&sumX),
3421 Float8GetDatum((double) N.time));
3422 }
3423
3424
3425 /* timestamp_age()
3426 * Calculate time difference while retaining year/month fields.
3427 * Note that this does not result in an accurate absolute time span
3428 * since year and month are out of context once the arithmetic
3429 * is done.
3430 */
3431 Datum
timestamp_age(PG_FUNCTION_ARGS)3432 timestamp_age(PG_FUNCTION_ARGS)
3433 {
3434 Timestamp dt1 = PG_GETARG_TIMESTAMP(0);
3435 Timestamp dt2 = PG_GETARG_TIMESTAMP(1);
3436 Interval *result;
3437 fsec_t fsec,
3438 fsec1,
3439 fsec2;
3440 struct pg_tm tt,
3441 *tm = &tt;
3442 struct pg_tm tt1,
3443 *tm1 = &tt1;
3444 struct pg_tm tt2,
3445 *tm2 = &tt2;
3446
3447 result = (Interval *) palloc(sizeof(Interval));
3448
3449 if (timestamp2tm(dt1, NULL, tm1, &fsec1, NULL, NULL) == 0 &&
3450 timestamp2tm(dt2, NULL, tm2, &fsec2, NULL, NULL) == 0)
3451 {
3452 /* form the symbolic difference */
3453 fsec = fsec1 - fsec2;
3454 tm->tm_sec = tm1->tm_sec - tm2->tm_sec;
3455 tm->tm_min = tm1->tm_min - tm2->tm_min;
3456 tm->tm_hour = tm1->tm_hour - tm2->tm_hour;
3457 tm->tm_mday = tm1->tm_mday - tm2->tm_mday;
3458 tm->tm_mon = tm1->tm_mon - tm2->tm_mon;
3459 tm->tm_year = tm1->tm_year - tm2->tm_year;
3460
3461 /* flip sign if necessary... */
3462 if (dt1 < dt2)
3463 {
3464 fsec = -fsec;
3465 tm->tm_sec = -tm->tm_sec;
3466 tm->tm_min = -tm->tm_min;
3467 tm->tm_hour = -tm->tm_hour;
3468 tm->tm_mday = -tm->tm_mday;
3469 tm->tm_mon = -tm->tm_mon;
3470 tm->tm_year = -tm->tm_year;
3471 }
3472
3473 /* propagate any negative fields into the next higher field */
3474 while (fsec < 0)
3475 {
3476 fsec += USECS_PER_SEC;
3477 tm->tm_sec--;
3478 }
3479
3480 while (tm->tm_sec < 0)
3481 {
3482 tm->tm_sec += SECS_PER_MINUTE;
3483 tm->tm_min--;
3484 }
3485
3486 while (tm->tm_min < 0)
3487 {
3488 tm->tm_min += MINS_PER_HOUR;
3489 tm->tm_hour--;
3490 }
3491
3492 while (tm->tm_hour < 0)
3493 {
3494 tm->tm_hour += HOURS_PER_DAY;
3495 tm->tm_mday--;
3496 }
3497
3498 while (tm->tm_mday < 0)
3499 {
3500 if (dt1 < dt2)
3501 {
3502 tm->tm_mday += day_tab[isleap(tm1->tm_year)][tm1->tm_mon - 1];
3503 tm->tm_mon--;
3504 }
3505 else
3506 {
3507 tm->tm_mday += day_tab[isleap(tm2->tm_year)][tm2->tm_mon - 1];
3508 tm->tm_mon--;
3509 }
3510 }
3511
3512 while (tm->tm_mon < 0)
3513 {
3514 tm->tm_mon += MONTHS_PER_YEAR;
3515 tm->tm_year--;
3516 }
3517
3518 /* recover sign if necessary... */
3519 if (dt1 < dt2)
3520 {
3521 fsec = -fsec;
3522 tm->tm_sec = -tm->tm_sec;
3523 tm->tm_min = -tm->tm_min;
3524 tm->tm_hour = -tm->tm_hour;
3525 tm->tm_mday = -tm->tm_mday;
3526 tm->tm_mon = -tm->tm_mon;
3527 tm->tm_year = -tm->tm_year;
3528 }
3529
3530 if (tm2interval(tm, fsec, result) != 0)
3531 ereport(ERROR,
3532 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3533 errmsg("interval out of range")));
3534 }
3535 else
3536 ereport(ERROR,
3537 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3538 errmsg("timestamp out of range")));
3539
3540 PG_RETURN_INTERVAL_P(result);
3541 }
3542
3543
3544 /* timestamptz_age()
3545 * Calculate time difference while retaining year/month fields.
3546 * Note that this does not result in an accurate absolute time span
3547 * since year and month are out of context once the arithmetic
3548 * is done.
3549 */
3550 Datum
timestamptz_age(PG_FUNCTION_ARGS)3551 timestamptz_age(PG_FUNCTION_ARGS)
3552 {
3553 TimestampTz dt1 = PG_GETARG_TIMESTAMPTZ(0);
3554 TimestampTz dt2 = PG_GETARG_TIMESTAMPTZ(1);
3555 Interval *result;
3556 fsec_t fsec,
3557 fsec1,
3558 fsec2;
3559 struct pg_tm tt,
3560 *tm = &tt;
3561 struct pg_tm tt1,
3562 *tm1 = &tt1;
3563 struct pg_tm tt2,
3564 *tm2 = &tt2;
3565 int tz1;
3566 int tz2;
3567
3568 result = (Interval *) palloc(sizeof(Interval));
3569
3570 if (timestamp2tm(dt1, &tz1, tm1, &fsec1, NULL, NULL) == 0 &&
3571 timestamp2tm(dt2, &tz2, tm2, &fsec2, NULL, NULL) == 0)
3572 {
3573 /* form the symbolic difference */
3574 fsec = fsec1 - fsec2;
3575 tm->tm_sec = tm1->tm_sec - tm2->tm_sec;
3576 tm->tm_min = tm1->tm_min - tm2->tm_min;
3577 tm->tm_hour = tm1->tm_hour - tm2->tm_hour;
3578 tm->tm_mday = tm1->tm_mday - tm2->tm_mday;
3579 tm->tm_mon = tm1->tm_mon - tm2->tm_mon;
3580 tm->tm_year = tm1->tm_year - tm2->tm_year;
3581
3582 /* flip sign if necessary... */
3583 if (dt1 < dt2)
3584 {
3585 fsec = -fsec;
3586 tm->tm_sec = -tm->tm_sec;
3587 tm->tm_min = -tm->tm_min;
3588 tm->tm_hour = -tm->tm_hour;
3589 tm->tm_mday = -tm->tm_mday;
3590 tm->tm_mon = -tm->tm_mon;
3591 tm->tm_year = -tm->tm_year;
3592 }
3593
3594 /* propagate any negative fields into the next higher field */
3595 while (fsec < 0)
3596 {
3597 fsec += USECS_PER_SEC;
3598 tm->tm_sec--;
3599 }
3600
3601 while (tm->tm_sec < 0)
3602 {
3603 tm->tm_sec += SECS_PER_MINUTE;
3604 tm->tm_min--;
3605 }
3606
3607 while (tm->tm_min < 0)
3608 {
3609 tm->tm_min += MINS_PER_HOUR;
3610 tm->tm_hour--;
3611 }
3612
3613 while (tm->tm_hour < 0)
3614 {
3615 tm->tm_hour += HOURS_PER_DAY;
3616 tm->tm_mday--;
3617 }
3618
3619 while (tm->tm_mday < 0)
3620 {
3621 if (dt1 < dt2)
3622 {
3623 tm->tm_mday += day_tab[isleap(tm1->tm_year)][tm1->tm_mon - 1];
3624 tm->tm_mon--;
3625 }
3626 else
3627 {
3628 tm->tm_mday += day_tab[isleap(tm2->tm_year)][tm2->tm_mon - 1];
3629 tm->tm_mon--;
3630 }
3631 }
3632
3633 while (tm->tm_mon < 0)
3634 {
3635 tm->tm_mon += MONTHS_PER_YEAR;
3636 tm->tm_year--;
3637 }
3638
3639 /*
3640 * Note: we deliberately ignore any difference between tz1 and tz2.
3641 */
3642
3643 /* recover sign if necessary... */
3644 if (dt1 < dt2)
3645 {
3646 fsec = -fsec;
3647 tm->tm_sec = -tm->tm_sec;
3648 tm->tm_min = -tm->tm_min;
3649 tm->tm_hour = -tm->tm_hour;
3650 tm->tm_mday = -tm->tm_mday;
3651 tm->tm_mon = -tm->tm_mon;
3652 tm->tm_year = -tm->tm_year;
3653 }
3654
3655 if (tm2interval(tm, fsec, result) != 0)
3656 ereport(ERROR,
3657 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3658 errmsg("interval out of range")));
3659 }
3660 else
3661 ereport(ERROR,
3662 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3663 errmsg("timestamp out of range")));
3664
3665 PG_RETURN_INTERVAL_P(result);
3666 }
3667
3668
3669 /*----------------------------------------------------------
3670 * Conversion operators.
3671 *---------------------------------------------------------*/
3672
3673
3674 /* timestamp_trunc()
3675 * Truncate timestamp to specified units.
3676 */
3677 Datum
timestamp_trunc(PG_FUNCTION_ARGS)3678 timestamp_trunc(PG_FUNCTION_ARGS)
3679 {
3680 text *units = PG_GETARG_TEXT_PP(0);
3681 Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
3682 Timestamp result;
3683 int type,
3684 val;
3685 char *lowunits;
3686 fsec_t fsec;
3687 struct pg_tm tt,
3688 *tm = &tt;
3689
3690 if (TIMESTAMP_NOT_FINITE(timestamp))
3691 PG_RETURN_TIMESTAMP(timestamp);
3692
3693 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
3694 VARSIZE_ANY_EXHDR(units),
3695 false);
3696
3697 type = DecodeUnits(0, lowunits, &val);
3698
3699 if (type == UNITS)
3700 {
3701 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
3702 ereport(ERROR,
3703 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3704 errmsg("timestamp out of range")));
3705
3706 switch (val)
3707 {
3708 case DTK_WEEK:
3709 {
3710 int woy;
3711
3712 woy = date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
3713
3714 /*
3715 * If it is week 52/53 and the month is January, then the
3716 * week must belong to the previous year. Also, some
3717 * December dates belong to the next year.
3718 */
3719 if (woy >= 52 && tm->tm_mon == 1)
3720 --tm->tm_year;
3721 if (woy <= 1 && tm->tm_mon == MONTHS_PER_YEAR)
3722 ++tm->tm_year;
3723 isoweek2date(woy, &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
3724 tm->tm_hour = 0;
3725 tm->tm_min = 0;
3726 tm->tm_sec = 0;
3727 fsec = 0;
3728 break;
3729 }
3730 case DTK_MILLENNIUM:
3731 /* see comments in timestamptz_trunc */
3732 if (tm->tm_year > 0)
3733 tm->tm_year = ((tm->tm_year + 999) / 1000) * 1000 - 999;
3734 else
3735 tm->tm_year = -((999 - (tm->tm_year - 1)) / 1000) * 1000 + 1;
3736 case DTK_CENTURY:
3737 /* see comments in timestamptz_trunc */
3738 if (tm->tm_year > 0)
3739 tm->tm_year = ((tm->tm_year + 99) / 100) * 100 - 99;
3740 else
3741 tm->tm_year = -((99 - (tm->tm_year - 1)) / 100) * 100 + 1;
3742 case DTK_DECADE:
3743 /* see comments in timestamptz_trunc */
3744 if (val != DTK_MILLENNIUM && val != DTK_CENTURY)
3745 {
3746 if (tm->tm_year > 0)
3747 tm->tm_year = (tm->tm_year / 10) * 10;
3748 else
3749 tm->tm_year = -((8 - (tm->tm_year - 1)) / 10) * 10;
3750 }
3751 case DTK_YEAR:
3752 tm->tm_mon = 1;
3753 case DTK_QUARTER:
3754 tm->tm_mon = (3 * ((tm->tm_mon - 1) / 3)) + 1;
3755 case DTK_MONTH:
3756 tm->tm_mday = 1;
3757 case DTK_DAY:
3758 tm->tm_hour = 0;
3759 case DTK_HOUR:
3760 tm->tm_min = 0;
3761 case DTK_MINUTE:
3762 tm->tm_sec = 0;
3763 case DTK_SECOND:
3764 fsec = 0;
3765 break;
3766
3767 case DTK_MILLISEC:
3768 fsec = (fsec / 1000) * 1000;
3769 break;
3770
3771 case DTK_MICROSEC:
3772 break;
3773
3774 default:
3775 ereport(ERROR,
3776 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3777 errmsg("timestamp units \"%s\" not supported",
3778 lowunits)));
3779 result = 0;
3780 }
3781
3782 if (tm2timestamp(tm, fsec, NULL, &result) != 0)
3783 ereport(ERROR,
3784 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3785 errmsg("timestamp out of range")));
3786 }
3787 else
3788 {
3789 ereport(ERROR,
3790 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3791 errmsg("timestamp units \"%s\" not recognized",
3792 lowunits)));
3793 result = 0;
3794 }
3795
3796 PG_RETURN_TIMESTAMP(result);
3797 }
3798
3799 /* timestamptz_trunc()
3800 * Truncate timestamp to specified units.
3801 */
3802 Datum
timestamptz_trunc(PG_FUNCTION_ARGS)3803 timestamptz_trunc(PG_FUNCTION_ARGS)
3804 {
3805 text *units = PG_GETARG_TEXT_PP(0);
3806 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
3807 TimestampTz result;
3808 int tz;
3809 int type,
3810 val;
3811 bool redotz = false;
3812 char *lowunits;
3813 fsec_t fsec;
3814 struct pg_tm tt,
3815 *tm = &tt;
3816
3817 if (TIMESTAMP_NOT_FINITE(timestamp))
3818 PG_RETURN_TIMESTAMPTZ(timestamp);
3819
3820 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
3821 VARSIZE_ANY_EXHDR(units),
3822 false);
3823
3824 type = DecodeUnits(0, lowunits, &val);
3825
3826 if (type == UNITS)
3827 {
3828 if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, NULL) != 0)
3829 ereport(ERROR,
3830 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3831 errmsg("timestamp out of range")));
3832
3833 switch (val)
3834 {
3835 case DTK_WEEK:
3836 {
3837 int woy;
3838
3839 woy = date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
3840
3841 /*
3842 * If it is week 52/53 and the month is January, then the
3843 * week must belong to the previous year. Also, some
3844 * December dates belong to the next year.
3845 */
3846 if (woy >= 52 && tm->tm_mon == 1)
3847 --tm->tm_year;
3848 if (woy <= 1 && tm->tm_mon == MONTHS_PER_YEAR)
3849 ++tm->tm_year;
3850 isoweek2date(woy, &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday));
3851 tm->tm_hour = 0;
3852 tm->tm_min = 0;
3853 tm->tm_sec = 0;
3854 fsec = 0;
3855 redotz = true;
3856 break;
3857 }
3858 /* one may consider DTK_THOUSAND and DTK_HUNDRED... */
3859 case DTK_MILLENNIUM:
3860
3861 /*
3862 * truncating to the millennium? what is this supposed to
3863 * mean? let us put the first year of the millennium... i.e.
3864 * -1000, 1, 1001, 2001...
3865 */
3866 if (tm->tm_year > 0)
3867 tm->tm_year = ((tm->tm_year + 999) / 1000) * 1000 - 999;
3868 else
3869 tm->tm_year = -((999 - (tm->tm_year - 1)) / 1000) * 1000 + 1;
3870 /* FALL THRU */
3871 case DTK_CENTURY:
3872 /* truncating to the century? as above: -100, 1, 101... */
3873 if (tm->tm_year > 0)
3874 tm->tm_year = ((tm->tm_year + 99) / 100) * 100 - 99;
3875 else
3876 tm->tm_year = -((99 - (tm->tm_year - 1)) / 100) * 100 + 1;
3877 /* FALL THRU */
3878 case DTK_DECADE:
3879
3880 /*
3881 * truncating to the decade? first year of the decade. must
3882 * not be applied if year was truncated before!
3883 */
3884 if (val != DTK_MILLENNIUM && val != DTK_CENTURY)
3885 {
3886 if (tm->tm_year > 0)
3887 tm->tm_year = (tm->tm_year / 10) * 10;
3888 else
3889 tm->tm_year = -((8 - (tm->tm_year - 1)) / 10) * 10;
3890 }
3891 /* FALL THRU */
3892 case DTK_YEAR:
3893 tm->tm_mon = 1;
3894 /* FALL THRU */
3895 case DTK_QUARTER:
3896 tm->tm_mon = (3 * ((tm->tm_mon - 1) / 3)) + 1;
3897 /* FALL THRU */
3898 case DTK_MONTH:
3899 tm->tm_mday = 1;
3900 /* FALL THRU */
3901 case DTK_DAY:
3902 tm->tm_hour = 0;
3903 redotz = true; /* for all cases >= DAY */
3904 /* FALL THRU */
3905 case DTK_HOUR:
3906 tm->tm_min = 0;
3907 /* FALL THRU */
3908 case DTK_MINUTE:
3909 tm->tm_sec = 0;
3910 /* FALL THRU */
3911 case DTK_SECOND:
3912 fsec = 0;
3913 break;
3914 case DTK_MILLISEC:
3915 fsec = (fsec / 1000) * 1000;
3916 break;
3917 case DTK_MICROSEC:
3918 break;
3919
3920 default:
3921 ereport(ERROR,
3922 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3923 errmsg("timestamp with time zone units \"%s\" not "
3924 "supported", lowunits)));
3925 result = 0;
3926 }
3927
3928 if (redotz)
3929 tz = DetermineTimeZoneOffset(tm, session_timezone);
3930
3931 if (tm2timestamp(tm, fsec, &tz, &result) != 0)
3932 ereport(ERROR,
3933 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
3934 errmsg("timestamp out of range")));
3935 }
3936 else
3937 {
3938 ereport(ERROR,
3939 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3940 errmsg("timestamp with time zone units \"%s\" not recognized",
3941 lowunits)));
3942 result = 0;
3943 }
3944
3945 PG_RETURN_TIMESTAMPTZ(result);
3946 }
3947
3948 /* interval_trunc()
3949 * Extract specified field from interval.
3950 */
3951 Datum
interval_trunc(PG_FUNCTION_ARGS)3952 interval_trunc(PG_FUNCTION_ARGS)
3953 {
3954 text *units = PG_GETARG_TEXT_PP(0);
3955 Interval *interval = PG_GETARG_INTERVAL_P(1);
3956 Interval *result;
3957 int type,
3958 val;
3959 char *lowunits;
3960 fsec_t fsec;
3961 struct pg_tm tt,
3962 *tm = &tt;
3963
3964 result = (Interval *) palloc(sizeof(Interval));
3965
3966 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
3967 VARSIZE_ANY_EXHDR(units),
3968 false);
3969
3970 type = DecodeUnits(0, lowunits, &val);
3971
3972 if (type == UNITS)
3973 {
3974 if (interval2tm(*interval, tm, &fsec) == 0)
3975 {
3976 switch (val)
3977 {
3978 /* fall through */
3979 case DTK_MILLENNIUM:
3980 /* caution: C division may have negative remainder */
3981 tm->tm_year = (tm->tm_year / 1000) * 1000;
3982 case DTK_CENTURY:
3983 /* caution: C division may have negative remainder */
3984 tm->tm_year = (tm->tm_year / 100) * 100;
3985 case DTK_DECADE:
3986 /* caution: C division may have negative remainder */
3987 tm->tm_year = (tm->tm_year / 10) * 10;
3988 case DTK_YEAR:
3989 tm->tm_mon = 0;
3990 case DTK_QUARTER:
3991 tm->tm_mon = 3 * (tm->tm_mon / 3);
3992 case DTK_MONTH:
3993 tm->tm_mday = 0;
3994 case DTK_DAY:
3995 tm->tm_hour = 0;
3996 case DTK_HOUR:
3997 tm->tm_min = 0;
3998 case DTK_MINUTE:
3999 tm->tm_sec = 0;
4000 case DTK_SECOND:
4001 fsec = 0;
4002 break;
4003 case DTK_MILLISEC:
4004 fsec = (fsec / 1000) * 1000;
4005 break;
4006 case DTK_MICROSEC:
4007 break;
4008
4009 default:
4010 if (val == DTK_WEEK)
4011 ereport(ERROR,
4012 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4013 errmsg("interval units \"%s\" not supported "
4014 "because months usually have fractional weeks",
4015 lowunits)));
4016 else
4017 ereport(ERROR,
4018 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4019 errmsg("interval units \"%s\" not supported",
4020 lowunits)));
4021 }
4022
4023 if (tm2interval(tm, fsec, result) != 0)
4024 ereport(ERROR,
4025 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4026 errmsg("interval out of range")));
4027 }
4028 else
4029 elog(ERROR, "could not convert interval to tm");
4030 }
4031 else
4032 {
4033 ereport(ERROR,
4034 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4035 errmsg("interval units \"%s\" not recognized",
4036 lowunits)));
4037 }
4038
4039 PG_RETURN_INTERVAL_P(result);
4040 }
4041
4042 /* isoweek2j()
4043 *
4044 * Return the Julian day which corresponds to the first day (Monday) of the given ISO 8601 year and week.
4045 * Julian days are used to convert between ISO week dates and Gregorian dates.
4046 */
4047 int
isoweek2j(int year,int week)4048 isoweek2j(int year, int week)
4049 {
4050 int day0,
4051 day4;
4052
4053 /* fourth day of current year */
4054 day4 = date2j(year, 1, 4);
4055
4056 /* day0 == offset to first day of week (Monday) */
4057 day0 = j2day(day4 - 1);
4058
4059 return ((week - 1) * 7) + (day4 - day0);
4060 }
4061
4062 /* isoweek2date()
4063 * Convert ISO week of year number to date.
4064 * The year field must be specified with the ISO year!
4065 * karel 2000/08/07
4066 */
4067 void
isoweek2date(int woy,int * year,int * mon,int * mday)4068 isoweek2date(int woy, int *year, int *mon, int *mday)
4069 {
4070 j2date(isoweek2j(*year, woy), year, mon, mday);
4071 }
4072
4073 /* isoweekdate2date()
4074 *
4075 * Convert an ISO 8601 week date (ISO year, ISO week) into a Gregorian date.
4076 * Gregorian day of week sent so weekday strings can be supplied.
4077 * Populates year, mon, and mday with the correct Gregorian values.
4078 * year must be passed in as the ISO year.
4079 */
4080 void
isoweekdate2date(int isoweek,int wday,int * year,int * mon,int * mday)4081 isoweekdate2date(int isoweek, int wday, int *year, int *mon, int *mday)
4082 {
4083 int jday;
4084
4085 jday = isoweek2j(*year, isoweek);
4086 /* convert Gregorian week start (Sunday=1) to ISO week start (Monday=1) */
4087 if (wday > 1)
4088 jday += wday - 2;
4089 else
4090 jday += 6;
4091 j2date(jday, year, mon, mday);
4092 }
4093
4094 /* date2isoweek()
4095 *
4096 * Returns ISO week number of year.
4097 */
4098 int
date2isoweek(int year,int mon,int mday)4099 date2isoweek(int year, int mon, int mday)
4100 {
4101 float8 result;
4102 int day0,
4103 day4,
4104 dayn;
4105
4106 /* current day */
4107 dayn = date2j(year, mon, mday);
4108
4109 /* fourth day of current year */
4110 day4 = date2j(year, 1, 4);
4111
4112 /* day0 == offset to first day of week (Monday) */
4113 day0 = j2day(day4 - 1);
4114
4115 /*
4116 * We need the first week containing a Thursday, otherwise this day falls
4117 * into the previous year for purposes of counting weeks
4118 */
4119 if (dayn < day4 - day0)
4120 {
4121 day4 = date2j(year - 1, 1, 4);
4122
4123 /* day0 == offset to first day of week (Monday) */
4124 day0 = j2day(day4 - 1);
4125 }
4126
4127 result = (dayn - (day4 - day0)) / 7 + 1;
4128
4129 /*
4130 * Sometimes the last few days in a year will fall into the first week of
4131 * the next year, so check for this.
4132 */
4133 if (result >= 52)
4134 {
4135 day4 = date2j(year + 1, 1, 4);
4136
4137 /* day0 == offset to first day of week (Monday) */
4138 day0 = j2day(day4 - 1);
4139
4140 if (dayn >= day4 - day0)
4141 result = (dayn - (day4 - day0)) / 7 + 1;
4142 }
4143
4144 return (int) result;
4145 }
4146
4147
4148 /* date2isoyear()
4149 *
4150 * Returns ISO 8601 year number.
4151 * Note: zero or negative results follow the year-zero-exists convention.
4152 */
4153 int
date2isoyear(int year,int mon,int mday)4154 date2isoyear(int year, int mon, int mday)
4155 {
4156 float8 result;
4157 int day0,
4158 day4,
4159 dayn;
4160
4161 /* current day */
4162 dayn = date2j(year, mon, mday);
4163
4164 /* fourth day of current year */
4165 day4 = date2j(year, 1, 4);
4166
4167 /* day0 == offset to first day of week (Monday) */
4168 day0 = j2day(day4 - 1);
4169
4170 /*
4171 * We need the first week containing a Thursday, otherwise this day falls
4172 * into the previous year for purposes of counting weeks
4173 */
4174 if (dayn < day4 - day0)
4175 {
4176 day4 = date2j(year - 1, 1, 4);
4177
4178 /* day0 == offset to first day of week (Monday) */
4179 day0 = j2day(day4 - 1);
4180
4181 year--;
4182 }
4183
4184 result = (dayn - (day4 - day0)) / 7 + 1;
4185
4186 /*
4187 * Sometimes the last few days in a year will fall into the first week of
4188 * the next year, so check for this.
4189 */
4190 if (result >= 52)
4191 {
4192 day4 = date2j(year + 1, 1, 4);
4193
4194 /* day0 == offset to first day of week (Monday) */
4195 day0 = j2day(day4 - 1);
4196
4197 if (dayn >= day4 - day0)
4198 year++;
4199 }
4200
4201 return year;
4202 }
4203
4204
4205 /* date2isoyearday()
4206 *
4207 * Returns the ISO 8601 day-of-year, given a Gregorian year, month and day.
4208 * Possible return values are 1 through 371 (364 in non-leap years).
4209 */
4210 int
date2isoyearday(int year,int mon,int mday)4211 date2isoyearday(int year, int mon, int mday)
4212 {
4213 return date2j(year, mon, mday) - isoweek2j(date2isoyear(year, mon, mday), 1) + 1;
4214 }
4215
4216 /*
4217 * NonFiniteTimestampTzPart
4218 *
4219 * Used by timestamp_part and timestamptz_part when extracting from infinite
4220 * timestamp[tz]. Returns +/-Infinity if that is the appropriate result,
4221 * otherwise returns zero (which should be taken as meaning to return NULL).
4222 *
4223 * Errors thrown here for invalid units should exactly match those that
4224 * would be thrown in the calling functions, else there will be unexpected
4225 * discrepancies between finite- and infinite-input cases.
4226 */
4227 static float8
NonFiniteTimestampTzPart(int type,int unit,char * lowunits,bool isNegative,bool isTz)4228 NonFiniteTimestampTzPart(int type, int unit, char *lowunits,
4229 bool isNegative, bool isTz)
4230 {
4231 if ((type != UNITS) && (type != RESERV))
4232 {
4233 if (isTz)
4234 ereport(ERROR,
4235 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4236 errmsg("timestamp with time zone units \"%s\" not recognized",
4237 lowunits)));
4238 else
4239 ereport(ERROR,
4240 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4241 errmsg("timestamp units \"%s\" not recognized",
4242 lowunits)));
4243 }
4244
4245 switch (unit)
4246 {
4247 /* Oscillating units */
4248 case DTK_MICROSEC:
4249 case DTK_MILLISEC:
4250 case DTK_SECOND:
4251 case DTK_MINUTE:
4252 case DTK_HOUR:
4253 case DTK_DAY:
4254 case DTK_MONTH:
4255 case DTK_QUARTER:
4256 case DTK_WEEK:
4257 case DTK_DOW:
4258 case DTK_ISODOW:
4259 case DTK_DOY:
4260 case DTK_TZ:
4261 case DTK_TZ_MINUTE:
4262 case DTK_TZ_HOUR:
4263 return 0.0;
4264
4265 /* Monotonically-increasing units */
4266 case DTK_YEAR:
4267 case DTK_DECADE:
4268 case DTK_CENTURY:
4269 case DTK_MILLENNIUM:
4270 case DTK_JULIAN:
4271 case DTK_ISOYEAR:
4272 case DTK_EPOCH:
4273 if (isNegative)
4274 return -get_float8_infinity();
4275 else
4276 return get_float8_infinity();
4277
4278 default:
4279 if (isTz)
4280 ereport(ERROR,
4281 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4282 errmsg("timestamp with time zone units \"%s\" not supported",
4283 lowunits)));
4284 else
4285 ereport(ERROR,
4286 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4287 errmsg("timestamp units \"%s\" not supported",
4288 lowunits)));
4289 return 0.0; /* keep compiler quiet */
4290 }
4291 }
4292
4293 /* timestamp_part()
4294 * Extract specified field from timestamp.
4295 */
4296 Datum
timestamp_part(PG_FUNCTION_ARGS)4297 timestamp_part(PG_FUNCTION_ARGS)
4298 {
4299 text *units = PG_GETARG_TEXT_PP(0);
4300 Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
4301 float8 result;
4302 Timestamp epoch;
4303 int type,
4304 val;
4305 char *lowunits;
4306 fsec_t fsec;
4307 struct pg_tm tt,
4308 *tm = &tt;
4309
4310 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
4311 VARSIZE_ANY_EXHDR(units),
4312 false);
4313
4314 type = DecodeUnits(0, lowunits, &val);
4315 if (type == UNKNOWN_FIELD)
4316 type = DecodeSpecial(0, lowunits, &val);
4317
4318 if (TIMESTAMP_NOT_FINITE(timestamp))
4319 {
4320 result = NonFiniteTimestampTzPart(type, val, lowunits,
4321 TIMESTAMP_IS_NOBEGIN(timestamp),
4322 false);
4323 if (result)
4324 PG_RETURN_FLOAT8(result);
4325 else
4326 PG_RETURN_NULL();
4327 }
4328
4329 if (type == UNITS)
4330 {
4331 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
4332 ereport(ERROR,
4333 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4334 errmsg("timestamp out of range")));
4335
4336 switch (val)
4337 {
4338 case DTK_MICROSEC:
4339 result = tm->tm_sec * 1000000.0 + fsec;
4340 break;
4341
4342 case DTK_MILLISEC:
4343 result = tm->tm_sec * 1000.0 + fsec / 1000.0;
4344 break;
4345
4346 case DTK_SECOND:
4347 result = tm->tm_sec + fsec / 1000000.0;
4348 break;
4349
4350 case DTK_MINUTE:
4351 result = tm->tm_min;
4352 break;
4353
4354 case DTK_HOUR:
4355 result = tm->tm_hour;
4356 break;
4357
4358 case DTK_DAY:
4359 result = tm->tm_mday;
4360 break;
4361
4362 case DTK_MONTH:
4363 result = tm->tm_mon;
4364 break;
4365
4366 case DTK_QUARTER:
4367 result = (tm->tm_mon - 1) / 3 + 1;
4368 break;
4369
4370 case DTK_WEEK:
4371 result = (float8) date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
4372 break;
4373
4374 case DTK_YEAR:
4375 if (tm->tm_year > 0)
4376 result = tm->tm_year;
4377 else
4378 /* there is no year 0, just 1 BC and 1 AD */
4379 result = tm->tm_year - 1;
4380 break;
4381
4382 case DTK_DECADE:
4383
4384 /*
4385 * what is a decade wrt dates? let us assume that decade 199
4386 * is 1990 thru 1999... decade 0 starts on year 1 BC, and -1
4387 * is 11 BC thru 2 BC...
4388 */
4389 if (tm->tm_year >= 0)
4390 result = tm->tm_year / 10;
4391 else
4392 result = -((8 - (tm->tm_year - 1)) / 10);
4393 break;
4394
4395 case DTK_CENTURY:
4396
4397 /* ----
4398 * centuries AD, c>0: year in [ (c-1)* 100 + 1 : c*100 ]
4399 * centuries BC, c<0: year in [ c*100 : (c+1) * 100 - 1]
4400 * there is no number 0 century.
4401 * ----
4402 */
4403 if (tm->tm_year > 0)
4404 result = (tm->tm_year + 99) / 100;
4405 else
4406 /* caution: C division may have negative remainder */
4407 result = -((99 - (tm->tm_year - 1)) / 100);
4408 break;
4409
4410 case DTK_MILLENNIUM:
4411 /* see comments above. */
4412 if (tm->tm_year > 0)
4413 result = (tm->tm_year + 999) / 1000;
4414 else
4415 result = -((999 - (tm->tm_year - 1)) / 1000);
4416 break;
4417
4418 case DTK_JULIAN:
4419 result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
4420 result += ((((tm->tm_hour * MINS_PER_HOUR) + tm->tm_min) * SECS_PER_MINUTE) +
4421 tm->tm_sec + (fsec / 1000000.0)) / (double) SECS_PER_DAY;
4422 break;
4423
4424 case DTK_ISOYEAR:
4425 result = date2isoyear(tm->tm_year, tm->tm_mon, tm->tm_mday);
4426 /* Adjust BC years */
4427 if (result <= 0)
4428 result -= 1;
4429 break;
4430
4431 case DTK_DOW:
4432 case DTK_ISODOW:
4433 result = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
4434 if (val == DTK_ISODOW && result == 0)
4435 result = 7;
4436 break;
4437
4438 case DTK_DOY:
4439 result = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
4440 - date2j(tm->tm_year, 1, 1) + 1);
4441 break;
4442
4443 case DTK_TZ:
4444 case DTK_TZ_MINUTE:
4445 case DTK_TZ_HOUR:
4446 default:
4447 ereport(ERROR,
4448 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4449 errmsg("timestamp units \"%s\" not supported",
4450 lowunits)));
4451 result = 0;
4452 }
4453 }
4454 else if (type == RESERV)
4455 {
4456 switch (val)
4457 {
4458 case DTK_EPOCH:
4459 epoch = SetEpochTimestamp();
4460 /* try to avoid precision loss in subtraction */
4461 if (timestamp < (PG_INT64_MAX + epoch))
4462 result = (timestamp - epoch) / 1000000.0;
4463 else
4464 result = ((float8) timestamp - epoch) / 1000000.0;
4465 break;
4466
4467 default:
4468 ereport(ERROR,
4469 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4470 errmsg("timestamp units \"%s\" not supported",
4471 lowunits)));
4472 result = 0;
4473 }
4474
4475 }
4476 else
4477 {
4478 ereport(ERROR,
4479 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4480 errmsg("timestamp units \"%s\" not recognized", lowunits)));
4481 result = 0;
4482 }
4483
4484 PG_RETURN_FLOAT8(result);
4485 }
4486
4487 /* timestamptz_part()
4488 * Extract specified field from timestamp with time zone.
4489 */
4490 Datum
timestamptz_part(PG_FUNCTION_ARGS)4491 timestamptz_part(PG_FUNCTION_ARGS)
4492 {
4493 text *units = PG_GETARG_TEXT_PP(0);
4494 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
4495 float8 result;
4496 Timestamp epoch;
4497 int tz;
4498 int type,
4499 val;
4500 char *lowunits;
4501 double dummy;
4502 fsec_t fsec;
4503 struct pg_tm tt,
4504 *tm = &tt;
4505
4506 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
4507 VARSIZE_ANY_EXHDR(units),
4508 false);
4509
4510 type = DecodeUnits(0, lowunits, &val);
4511 if (type == UNKNOWN_FIELD)
4512 type = DecodeSpecial(0, lowunits, &val);
4513
4514 if (TIMESTAMP_NOT_FINITE(timestamp))
4515 {
4516 result = NonFiniteTimestampTzPart(type, val, lowunits,
4517 TIMESTAMP_IS_NOBEGIN(timestamp),
4518 true);
4519 if (result)
4520 PG_RETURN_FLOAT8(result);
4521 else
4522 PG_RETURN_NULL();
4523 }
4524
4525 if (type == UNITS)
4526 {
4527 if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, NULL) != 0)
4528 ereport(ERROR,
4529 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4530 errmsg("timestamp out of range")));
4531
4532 switch (val)
4533 {
4534 case DTK_TZ:
4535 result = -tz;
4536 break;
4537
4538 case DTK_TZ_MINUTE:
4539 result = -tz;
4540 result /= MINS_PER_HOUR;
4541 FMODULO(result, dummy, (double) MINS_PER_HOUR);
4542 break;
4543
4544 case DTK_TZ_HOUR:
4545 dummy = -tz;
4546 FMODULO(dummy, result, (double) SECS_PER_HOUR);
4547 break;
4548
4549 case DTK_MICROSEC:
4550 result = tm->tm_sec * 1000000.0 + fsec;
4551 break;
4552
4553 case DTK_MILLISEC:
4554 result = tm->tm_sec * 1000.0 + fsec / 1000.0;
4555 break;
4556
4557 case DTK_SECOND:
4558 result = tm->tm_sec + fsec / 1000000.0;
4559 break;
4560
4561 case DTK_MINUTE:
4562 result = tm->tm_min;
4563 break;
4564
4565 case DTK_HOUR:
4566 result = tm->tm_hour;
4567 break;
4568
4569 case DTK_DAY:
4570 result = tm->tm_mday;
4571 break;
4572
4573 case DTK_MONTH:
4574 result = tm->tm_mon;
4575 break;
4576
4577 case DTK_QUARTER:
4578 result = (tm->tm_mon - 1) / 3 + 1;
4579 break;
4580
4581 case DTK_WEEK:
4582 result = (float8) date2isoweek(tm->tm_year, tm->tm_mon, tm->tm_mday);
4583 break;
4584
4585 case DTK_YEAR:
4586 if (tm->tm_year > 0)
4587 result = tm->tm_year;
4588 else
4589 /* there is no year 0, just 1 BC and 1 AD */
4590 result = tm->tm_year - 1;
4591 break;
4592
4593 case DTK_DECADE:
4594 /* see comments in timestamp_part */
4595 if (tm->tm_year > 0)
4596 result = tm->tm_year / 10;
4597 else
4598 result = -((8 - (tm->tm_year - 1)) / 10);
4599 break;
4600
4601 case DTK_CENTURY:
4602 /* see comments in timestamp_part */
4603 if (tm->tm_year > 0)
4604 result = (tm->tm_year + 99) / 100;
4605 else
4606 result = -((99 - (tm->tm_year - 1)) / 100);
4607 break;
4608
4609 case DTK_MILLENNIUM:
4610 /* see comments in timestamp_part */
4611 if (tm->tm_year > 0)
4612 result = (tm->tm_year + 999) / 1000;
4613 else
4614 result = -((999 - (tm->tm_year - 1)) / 1000);
4615 break;
4616
4617 case DTK_JULIAN:
4618 result = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
4619 result += ((((tm->tm_hour * MINS_PER_HOUR) + tm->tm_min) * SECS_PER_MINUTE) +
4620 tm->tm_sec + (fsec / 1000000.0)) / (double) SECS_PER_DAY;
4621 break;
4622
4623 case DTK_ISOYEAR:
4624 result = date2isoyear(tm->tm_year, tm->tm_mon, tm->tm_mday);
4625 /* Adjust BC years */
4626 if (result <= 0)
4627 result -= 1;
4628 break;
4629
4630 case DTK_DOW:
4631 case DTK_ISODOW:
4632 result = j2day(date2j(tm->tm_year, tm->tm_mon, tm->tm_mday));
4633 if (val == DTK_ISODOW && result == 0)
4634 result = 7;
4635 break;
4636
4637 case DTK_DOY:
4638 result = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday)
4639 - date2j(tm->tm_year, 1, 1) + 1);
4640 break;
4641
4642 default:
4643 ereport(ERROR,
4644 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4645 errmsg("timestamp with time zone units \"%s\" not supported",
4646 lowunits)));
4647 result = 0;
4648 }
4649
4650 }
4651 else if (type == RESERV)
4652 {
4653 switch (val)
4654 {
4655 case DTK_EPOCH:
4656 epoch = SetEpochTimestamp();
4657 /* try to avoid precision loss in subtraction */
4658 if (timestamp < (PG_INT64_MAX + epoch))
4659 result = (timestamp - epoch) / 1000000.0;
4660 else
4661 result = ((float8) timestamp - epoch) / 1000000.0;
4662 break;
4663
4664 default:
4665 ereport(ERROR,
4666 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4667 errmsg("timestamp with time zone units \"%s\" not supported",
4668 lowunits)));
4669 result = 0;
4670 }
4671 }
4672 else
4673 {
4674 ereport(ERROR,
4675 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4676 errmsg("timestamp with time zone units \"%s\" not recognized",
4677 lowunits)));
4678
4679 result = 0;
4680 }
4681
4682 PG_RETURN_FLOAT8(result);
4683 }
4684
4685
4686 /* interval_part()
4687 * Extract specified field from interval.
4688 */
4689 Datum
interval_part(PG_FUNCTION_ARGS)4690 interval_part(PG_FUNCTION_ARGS)
4691 {
4692 text *units = PG_GETARG_TEXT_PP(0);
4693 Interval *interval = PG_GETARG_INTERVAL_P(1);
4694 float8 result;
4695 int type,
4696 val;
4697 char *lowunits;
4698 fsec_t fsec;
4699 struct pg_tm tt,
4700 *tm = &tt;
4701
4702 lowunits = downcase_truncate_identifier(VARDATA_ANY(units),
4703 VARSIZE_ANY_EXHDR(units),
4704 false);
4705
4706 type = DecodeUnits(0, lowunits, &val);
4707 if (type == UNKNOWN_FIELD)
4708 type = DecodeSpecial(0, lowunits, &val);
4709
4710 if (type == UNITS)
4711 {
4712 if (interval2tm(*interval, tm, &fsec) == 0)
4713 {
4714 switch (val)
4715 {
4716 case DTK_MICROSEC:
4717 result = tm->tm_sec * 1000000.0 + fsec;
4718 break;
4719
4720 case DTK_MILLISEC:
4721 result = tm->tm_sec * 1000.0 + fsec / 1000.0;
4722 break;
4723
4724 case DTK_SECOND:
4725 result = tm->tm_sec + fsec / 1000000.0;
4726 break;
4727
4728 case DTK_MINUTE:
4729 result = tm->tm_min;
4730 break;
4731
4732 case DTK_HOUR:
4733 result = tm->tm_hour;
4734 break;
4735
4736 case DTK_DAY:
4737 result = tm->tm_mday;
4738 break;
4739
4740 case DTK_MONTH:
4741 result = tm->tm_mon;
4742 break;
4743
4744 case DTK_QUARTER:
4745 result = (tm->tm_mon / 3) + 1;
4746 break;
4747
4748 case DTK_YEAR:
4749 result = tm->tm_year;
4750 break;
4751
4752 case DTK_DECADE:
4753 /* caution: C division may have negative remainder */
4754 result = tm->tm_year / 10;
4755 break;
4756
4757 case DTK_CENTURY:
4758 /* caution: C division may have negative remainder */
4759 result = tm->tm_year / 100;
4760 break;
4761
4762 case DTK_MILLENNIUM:
4763 /* caution: C division may have negative remainder */
4764 result = tm->tm_year / 1000;
4765 break;
4766
4767 default:
4768 ereport(ERROR,
4769 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4770 errmsg("interval units \"%s\" not supported",
4771 lowunits)));
4772 result = 0;
4773 }
4774
4775 }
4776 else
4777 {
4778 elog(ERROR, "could not convert interval to tm");
4779 result = 0;
4780 }
4781 }
4782 else if (type == RESERV && val == DTK_EPOCH)
4783 {
4784 result = interval->time / 1000000.0;
4785 result += ((double) DAYS_PER_YEAR * SECS_PER_DAY) * (interval->month / MONTHS_PER_YEAR);
4786 result += ((double) DAYS_PER_MONTH * SECS_PER_DAY) * (interval->month % MONTHS_PER_YEAR);
4787 result += ((double) SECS_PER_DAY) * interval->day;
4788 }
4789 else
4790 {
4791 ereport(ERROR,
4792 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4793 errmsg("interval units \"%s\" not recognized",
4794 lowunits)));
4795 result = 0;
4796 }
4797
4798 PG_RETURN_FLOAT8(result);
4799 }
4800
4801
4802 /* timestamp_zone_transform()
4803 * The original optimization here caused problems by relabeling Vars that
4804 * could be matched to index entries. It might be possible to resurrect it
4805 * at some point by teaching the planner to be less cavalier with RelabelType
4806 * nodes, but that will take careful analysis.
4807 */
4808 Datum
timestamp_zone_transform(PG_FUNCTION_ARGS)4809 timestamp_zone_transform(PG_FUNCTION_ARGS)
4810 {
4811 PG_RETURN_POINTER(NULL);
4812 }
4813
4814 /* timestamp_zone()
4815 * Encode timestamp type with specified time zone.
4816 * This function is just timestamp2timestamptz() except instead of
4817 * shifting to the global timezone, we shift to the specified timezone.
4818 * This is different from the other AT TIME ZONE cases because instead
4819 * of shifting _to_ a new time zone, it sets the time to _be_ the
4820 * specified timezone.
4821 */
4822 Datum
timestamp_zone(PG_FUNCTION_ARGS)4823 timestamp_zone(PG_FUNCTION_ARGS)
4824 {
4825 text *zone = PG_GETARG_TEXT_PP(0);
4826 Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
4827 TimestampTz result;
4828 int tz;
4829 char tzname[TZ_STRLEN_MAX + 1];
4830 char *lowzone;
4831 int type,
4832 val;
4833 pg_tz *tzp;
4834 struct pg_tm tm;
4835 fsec_t fsec;
4836
4837 if (TIMESTAMP_NOT_FINITE(timestamp))
4838 PG_RETURN_TIMESTAMPTZ(timestamp);
4839
4840 /*
4841 * Look up the requested timezone. First we look in the timezone
4842 * abbreviation table (to handle cases like "EST"), and if that fails, we
4843 * look in the timezone database (to handle cases like
4844 * "America/New_York"). (This matches the order in which timestamp input
4845 * checks the cases; it's important because the timezone database unwisely
4846 * uses a few zone names that are identical to offset abbreviations.)
4847 */
4848 text_to_cstring_buffer(zone, tzname, sizeof(tzname));
4849
4850 /* DecodeTimezoneAbbrev requires lowercase input */
4851 lowzone = downcase_truncate_identifier(tzname,
4852 strlen(tzname),
4853 false);
4854
4855 type = DecodeTimezoneAbbrev(0, lowzone, &val, &tzp);
4856
4857 if (type == TZ || type == DTZ)
4858 {
4859 /* fixed-offset abbreviation */
4860 tz = val;
4861 result = dt2local(timestamp, tz);
4862 }
4863 else if (type == DYNTZ)
4864 {
4865 /* dynamic-offset abbreviation, resolve using specified time */
4866 if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, tzp) != 0)
4867 ereport(ERROR,
4868 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4869 errmsg("timestamp out of range")));
4870 tz = -DetermineTimeZoneAbbrevOffset(&tm, tzname, tzp);
4871 result = dt2local(timestamp, tz);
4872 }
4873 else
4874 {
4875 /* try it as a full zone name */
4876 tzp = pg_tzset(tzname);
4877 if (tzp)
4878 {
4879 /* Apply the timezone change */
4880 if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, tzp) != 0)
4881 ereport(ERROR,
4882 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4883 errmsg("timestamp out of range")));
4884 tz = DetermineTimeZoneOffset(&tm, tzp);
4885 if (tm2timestamp(&tm, fsec, &tz, &result) != 0)
4886 ereport(ERROR,
4887 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4888 errmsg("timestamp out of range")));
4889 }
4890 else
4891 {
4892 ereport(ERROR,
4893 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4894 errmsg("time zone \"%s\" not recognized", tzname)));
4895 result = 0; /* keep compiler quiet */
4896 }
4897 }
4898
4899 if (!IS_VALID_TIMESTAMP(result))
4900 ereport(ERROR,
4901 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4902 errmsg("timestamp out of range")));
4903
4904 PG_RETURN_TIMESTAMPTZ(result);
4905 }
4906
4907 /* timestamp_izone_transform()
4908 * The original optimization here caused problems by relabeling Vars that
4909 * could be matched to index entries. It might be possible to resurrect it
4910 * at some point by teaching the planner to be less cavalier with RelabelType
4911 * nodes, but that will take careful analysis.
4912 */
4913 Datum
timestamp_izone_transform(PG_FUNCTION_ARGS)4914 timestamp_izone_transform(PG_FUNCTION_ARGS)
4915 {
4916 PG_RETURN_POINTER(NULL);
4917 }
4918
4919 /* timestamp_izone()
4920 * Encode timestamp type with specified time interval as time zone.
4921 */
4922 Datum
timestamp_izone(PG_FUNCTION_ARGS)4923 timestamp_izone(PG_FUNCTION_ARGS)
4924 {
4925 Interval *zone = PG_GETARG_INTERVAL_P(0);
4926 Timestamp timestamp = PG_GETARG_TIMESTAMP(1);
4927 TimestampTz result;
4928 int tz;
4929
4930 if (TIMESTAMP_NOT_FINITE(timestamp))
4931 PG_RETURN_TIMESTAMPTZ(timestamp);
4932
4933 if (zone->month != 0 || zone->day != 0)
4934 ereport(ERROR,
4935 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4936 errmsg("interval time zone \"%s\" must not include months or days",
4937 DatumGetCString(DirectFunctionCall1(interval_out,
4938 PointerGetDatum(zone))))));
4939
4940 tz = zone->time / USECS_PER_SEC;
4941
4942 result = dt2local(timestamp, tz);
4943
4944 if (!IS_VALID_TIMESTAMP(result))
4945 ereport(ERROR,
4946 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4947 errmsg("timestamp out of range")));
4948
4949 PG_RETURN_TIMESTAMPTZ(result);
4950 } /* timestamp_izone() */
4951
4952 /* timestamp_timestamptz()
4953 * Convert local timestamp to timestamp at GMT
4954 */
4955 Datum
timestamp_timestamptz(PG_FUNCTION_ARGS)4956 timestamp_timestamptz(PG_FUNCTION_ARGS)
4957 {
4958 Timestamp timestamp = PG_GETARG_TIMESTAMP(0);
4959
4960 PG_RETURN_TIMESTAMPTZ(timestamp2timestamptz(timestamp));
4961 }
4962
4963 static TimestampTz
timestamp2timestamptz(Timestamp timestamp)4964 timestamp2timestamptz(Timestamp timestamp)
4965 {
4966 TimestampTz result;
4967 struct pg_tm tt,
4968 *tm = &tt;
4969 fsec_t fsec;
4970 int tz;
4971
4972 if (TIMESTAMP_NOT_FINITE(timestamp))
4973 result = timestamp;
4974 else
4975 {
4976 if (timestamp2tm(timestamp, NULL, tm, &fsec, NULL, NULL) != 0)
4977 ereport(ERROR,
4978 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4979 errmsg("timestamp out of range")));
4980
4981 tz = DetermineTimeZoneOffset(tm, session_timezone);
4982
4983 if (tm2timestamp(tm, fsec, &tz, &result) != 0)
4984 ereport(ERROR,
4985 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
4986 errmsg("timestamp out of range")));
4987 }
4988
4989 return result;
4990 }
4991
4992 /* timestamptz_timestamp()
4993 * Convert timestamp at GMT to local timestamp
4994 */
4995 Datum
timestamptz_timestamp(PG_FUNCTION_ARGS)4996 timestamptz_timestamp(PG_FUNCTION_ARGS)
4997 {
4998 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(0);
4999
5000 PG_RETURN_TIMESTAMP(timestamptz2timestamp(timestamp));
5001 }
5002
5003 static Timestamp
timestamptz2timestamp(TimestampTz timestamp)5004 timestamptz2timestamp(TimestampTz timestamp)
5005 {
5006 Timestamp result;
5007 struct pg_tm tt,
5008 *tm = &tt;
5009 fsec_t fsec;
5010 int tz;
5011
5012 if (TIMESTAMP_NOT_FINITE(timestamp))
5013 result = timestamp;
5014 else
5015 {
5016 if (timestamp2tm(timestamp, &tz, tm, &fsec, NULL, NULL) != 0)
5017 ereport(ERROR,
5018 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
5019 errmsg("timestamp out of range")));
5020 if (tm2timestamp(tm, fsec, NULL, &result) != 0)
5021 ereport(ERROR,
5022 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
5023 errmsg("timestamp out of range")));
5024 }
5025 return result;
5026 }
5027
5028 /* timestamptz_zone()
5029 * Evaluate timestamp with time zone type at the specified time zone.
5030 * Returns a timestamp without time zone.
5031 */
5032 Datum
timestamptz_zone(PG_FUNCTION_ARGS)5033 timestamptz_zone(PG_FUNCTION_ARGS)
5034 {
5035 text *zone = PG_GETARG_TEXT_PP(0);
5036 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
5037 Timestamp result;
5038 int tz;
5039 char tzname[TZ_STRLEN_MAX + 1];
5040 char *lowzone;
5041 int type,
5042 val;
5043 pg_tz *tzp;
5044
5045 if (TIMESTAMP_NOT_FINITE(timestamp))
5046 PG_RETURN_TIMESTAMP(timestamp);
5047
5048 /*
5049 * Look up the requested timezone. First we look in the timezone
5050 * abbreviation table (to handle cases like "EST"), and if that fails, we
5051 * look in the timezone database (to handle cases like
5052 * "America/New_York"). (This matches the order in which timestamp input
5053 * checks the cases; it's important because the timezone database unwisely
5054 * uses a few zone names that are identical to offset abbreviations.)
5055 */
5056 text_to_cstring_buffer(zone, tzname, sizeof(tzname));
5057
5058 /* DecodeTimezoneAbbrev requires lowercase input */
5059 lowzone = downcase_truncate_identifier(tzname,
5060 strlen(tzname),
5061 false);
5062
5063 type = DecodeTimezoneAbbrev(0, lowzone, &val, &tzp);
5064
5065 if (type == TZ || type == DTZ)
5066 {
5067 /* fixed-offset abbreviation */
5068 tz = -val;
5069 result = dt2local(timestamp, tz);
5070 }
5071 else if (type == DYNTZ)
5072 {
5073 /* dynamic-offset abbreviation, resolve using specified time */
5074 int isdst;
5075
5076 tz = DetermineTimeZoneAbbrevOffsetTS(timestamp, tzname, tzp, &isdst);
5077 result = dt2local(timestamp, tz);
5078 }
5079 else
5080 {
5081 /* try it as a full zone name */
5082 tzp = pg_tzset(tzname);
5083 if (tzp)
5084 {
5085 /* Apply the timezone change */
5086 struct pg_tm tm;
5087 fsec_t fsec;
5088
5089 if (timestamp2tm(timestamp, &tz, &tm, &fsec, NULL, tzp) != 0)
5090 ereport(ERROR,
5091 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
5092 errmsg("timestamp out of range")));
5093 if (tm2timestamp(&tm, fsec, NULL, &result) != 0)
5094 ereport(ERROR,
5095 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
5096 errmsg("timestamp out of range")));
5097 }
5098 else
5099 {
5100 ereport(ERROR,
5101 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5102 errmsg("time zone \"%s\" not recognized", tzname)));
5103 result = 0; /* keep compiler quiet */
5104 }
5105 }
5106
5107 if (!IS_VALID_TIMESTAMP(result))
5108 ereport(ERROR,
5109 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
5110 errmsg("timestamp out of range")));
5111
5112 PG_RETURN_TIMESTAMP(result);
5113 }
5114
5115 /* timestamptz_izone()
5116 * Encode timestamp with time zone type with specified time interval as time zone.
5117 * Returns a timestamp without time zone.
5118 */
5119 Datum
timestamptz_izone(PG_FUNCTION_ARGS)5120 timestamptz_izone(PG_FUNCTION_ARGS)
5121 {
5122 Interval *zone = PG_GETARG_INTERVAL_P(0);
5123 TimestampTz timestamp = PG_GETARG_TIMESTAMPTZ(1);
5124 Timestamp result;
5125 int tz;
5126
5127 if (TIMESTAMP_NOT_FINITE(timestamp))
5128 PG_RETURN_TIMESTAMP(timestamp);
5129
5130 if (zone->month != 0 || zone->day != 0)
5131 ereport(ERROR,
5132 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5133 errmsg("interval time zone \"%s\" must not include months or days",
5134 DatumGetCString(DirectFunctionCall1(interval_out,
5135 PointerGetDatum(zone))))));
5136
5137 tz = -(zone->time / USECS_PER_SEC);
5138
5139 result = dt2local(timestamp, tz);
5140
5141 if (!IS_VALID_TIMESTAMP(result))
5142 ereport(ERROR,
5143 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
5144 errmsg("timestamp out of range")));
5145
5146 PG_RETURN_TIMESTAMP(result);
5147 }
5148
5149 /* generate_series_timestamp()
5150 * Generate the set of timestamps from start to finish by step
5151 */
5152 Datum
generate_series_timestamp(PG_FUNCTION_ARGS)5153 generate_series_timestamp(PG_FUNCTION_ARGS)
5154 {
5155 FuncCallContext *funcctx;
5156 generate_series_timestamp_fctx *fctx;
5157 Timestamp result;
5158
5159 /* stuff done only on the first call of the function */
5160 if (SRF_IS_FIRSTCALL())
5161 {
5162 Timestamp start = PG_GETARG_TIMESTAMP(0);
5163 Timestamp finish = PG_GETARG_TIMESTAMP(1);
5164 Interval *step = PG_GETARG_INTERVAL_P(2);
5165 MemoryContext oldcontext;
5166 Interval interval_zero;
5167
5168 /* create a function context for cross-call persistence */
5169 funcctx = SRF_FIRSTCALL_INIT();
5170
5171 /*
5172 * switch to memory context appropriate for multiple function calls
5173 */
5174 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
5175
5176 /* allocate memory for user context */
5177 fctx = (generate_series_timestamp_fctx *)
5178 palloc(sizeof(generate_series_timestamp_fctx));
5179
5180 /*
5181 * Use fctx to keep state from call to call. Seed current with the
5182 * original start value
5183 */
5184 fctx->current = start;
5185 fctx->finish = finish;
5186 fctx->step = *step;
5187
5188 /* Determine sign of the interval */
5189 MemSet(&interval_zero, 0, sizeof(Interval));
5190 fctx->step_sign = interval_cmp_internal(&fctx->step, &interval_zero);
5191
5192 if (fctx->step_sign == 0)
5193 ereport(ERROR,
5194 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5195 errmsg("step size cannot equal zero")));
5196
5197 funcctx->user_fctx = fctx;
5198 MemoryContextSwitchTo(oldcontext);
5199 }
5200
5201 /* stuff done on every call of the function */
5202 funcctx = SRF_PERCALL_SETUP();
5203
5204 /*
5205 * get the saved state and use current as the result for this iteration
5206 */
5207 fctx = funcctx->user_fctx;
5208 result = fctx->current;
5209
5210 if (fctx->step_sign > 0 ?
5211 timestamp_cmp_internal(result, fctx->finish) <= 0 :
5212 timestamp_cmp_internal(result, fctx->finish) >= 0)
5213 {
5214 /* increment current in preparation for next iteration */
5215 fctx->current = DatumGetTimestamp(
5216 DirectFunctionCall2(timestamp_pl_interval,
5217 TimestampGetDatum(fctx->current),
5218 PointerGetDatum(&fctx->step)));
5219
5220 /* do when there is more left to send */
5221 SRF_RETURN_NEXT(funcctx, TimestampGetDatum(result));
5222 }
5223 else
5224 {
5225 /* do when there is no more left */
5226 SRF_RETURN_DONE(funcctx);
5227 }
5228 }
5229
5230 /* generate_series_timestamptz()
5231 * Generate the set of timestamps from start to finish by step
5232 */
5233 Datum
generate_series_timestamptz(PG_FUNCTION_ARGS)5234 generate_series_timestamptz(PG_FUNCTION_ARGS)
5235 {
5236 FuncCallContext *funcctx;
5237 generate_series_timestamptz_fctx *fctx;
5238 TimestampTz result;
5239
5240 /* stuff done only on the first call of the function */
5241 if (SRF_IS_FIRSTCALL())
5242 {
5243 TimestampTz start = PG_GETARG_TIMESTAMPTZ(0);
5244 TimestampTz finish = PG_GETARG_TIMESTAMPTZ(1);
5245 Interval *step = PG_GETARG_INTERVAL_P(2);
5246 MemoryContext oldcontext;
5247 Interval interval_zero;
5248
5249 /* create a function context for cross-call persistence */
5250 funcctx = SRF_FIRSTCALL_INIT();
5251
5252 /*
5253 * switch to memory context appropriate for multiple function calls
5254 */
5255 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
5256
5257 /* allocate memory for user context */
5258 fctx = (generate_series_timestamptz_fctx *)
5259 palloc(sizeof(generate_series_timestamptz_fctx));
5260
5261 /*
5262 * Use fctx to keep state from call to call. Seed current with the
5263 * original start value
5264 */
5265 fctx->current = start;
5266 fctx->finish = finish;
5267 fctx->step = *step;
5268
5269 /* Determine sign of the interval */
5270 MemSet(&interval_zero, 0, sizeof(Interval));
5271 fctx->step_sign = interval_cmp_internal(&fctx->step, &interval_zero);
5272
5273 if (fctx->step_sign == 0)
5274 ereport(ERROR,
5275 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5276 errmsg("step size cannot equal zero")));
5277
5278 funcctx->user_fctx = fctx;
5279 MemoryContextSwitchTo(oldcontext);
5280 }
5281
5282 /* stuff done on every call of the function */
5283 funcctx = SRF_PERCALL_SETUP();
5284
5285 /*
5286 * get the saved state and use current as the result for this iteration
5287 */
5288 fctx = funcctx->user_fctx;
5289 result = fctx->current;
5290
5291 if (fctx->step_sign > 0 ?
5292 timestamp_cmp_internal(result, fctx->finish) <= 0 :
5293 timestamp_cmp_internal(result, fctx->finish) >= 0)
5294 {
5295 /* increment current in preparation for next iteration */
5296 fctx->current = DatumGetTimestampTz(
5297 DirectFunctionCall2(timestamptz_pl_interval,
5298 TimestampTzGetDatum(fctx->current),
5299 PointerGetDatum(&fctx->step)));
5300
5301 /* do when there is more left to send */
5302 SRF_RETURN_NEXT(funcctx, TimestampTzGetDatum(result));
5303 }
5304 else
5305 {
5306 /* do when there is no more left */
5307 SRF_RETURN_DONE(funcctx);
5308 }
5309 }
5310