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

Generated by: LCOV version 1.14