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

Generated by: LCOV version 1.14