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

Generated by: LCOV version 1.14