LCOV - code coverage report
Current view: top level - src/backend/utils/adt - timestamp.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 1410 2118 66.6 %
Date: 2020-05-29 00:07:09 Functions: 125 155 80.6 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13