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