Skip to content

Commit 8f93bd8

Browse files
committed
Fix roundoff problems in float8_timestamptz() and make_interval().
When converting a float value to integer microseconds, we should be careful to round the value to the nearest integer, typically with rint(); simply assigning to an int64 variable will truncate, causing apparently off-by-one values in cases that should work. Most places in the datetime code got this right, but not these two. float8_timestamptz() is new as of commit e511d87 (9.6). Previous versions effectively depended on interval_mul() to do roundoff correctly, which it does, so this fixes an accuracy regression in 9.6. The problem in make_interval() dates to its introduction in 9.4. Aside from being careful to round not truncate, let's incorporate the hours and minutes inputs into the result with exact integer arithmetic, rather than risk introducing roundoff error where there need not have been any. float8_timestamptz() problem reported by Erik Nordström, though this is not his proposed patch. make_interval() problem found by me. Discussion: https://postgr.es/m/CAHuQZDS76jTYk3LydPbKpNfw9KbACmD=49dC4BrzHcfPv6yA1A@mail.gmail.com
1 parent a507b86 commit 8f93bd8

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

src/backend/utils/adt/timestamp.c

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,7 @@ float8_timestamptz(PG_FUNCTION_ARGS)
788788
seconds -= ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY);
789789

790790
#ifdef HAVE_INT64_TIMESTAMP
791-
result = seconds * USECS_PER_SEC;
791+
result = rint(seconds * USECS_PER_SEC);
792792
#else
793793
result = seconds;
794794
#endif
@@ -1623,12 +1623,14 @@ make_interval(PG_FUNCTION_ARGS)
16231623
result->month = years * MONTHS_PER_YEAR + months;
16241624
result->day = weeks * 7 + days;
16251625

1626-
secs += hours * (double) SECS_PER_HOUR + mins * (double) SECS_PER_MINUTE;
1627-
16281626
#ifdef HAVE_INT64_TIMESTAMP
1629-
result->time = (int64) (secs * USECS_PER_SEC);
1627+
result->time = hours * ((int64) SECS_PER_HOUR * USECS_PER_SEC) +
1628+
mins * ((int64) SECS_PER_MINUTE * USECS_PER_SEC) +
1629+
(int64) rint(secs * USECS_PER_SEC);
16301630
#else
1631-
result->time = secs;
1631+
result->time = hours * (double) SECS_PER_HOUR +
1632+
mins * (double) SECS_PER_MINUTE +
1633+
secs;
16321634
#endif
16331635

16341636
PG_RETURN_INTERVAL_P(result);

0 commit comments

Comments
 (0)