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