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