Fix mis-rounding and overflow hazards in date_bin().
authorTom Lane <tgl@sss.pgh.pa.us>
Wed, 28 Feb 2024 19:00:30 +0000 (14:00 -0500)
committerTom Lane <tgl@sss.pgh.pa.us>
Wed, 28 Feb 2024 19:00:30 +0000 (14:00 -0500)
commitdb8855b66f5cfd9761b1763fdc6b8d93179607df
tree07eddd2984821780beae0eb7bed2584e5f305a48
parent172d7f7e666ee0612b7d56d7b73a7ebc98476a66
Fix mis-rounding and overflow hazards in date_bin().

In the case where the target timestamp is before the origin timestamp
and their difference is already an exact multiple of the stride, the
code incorrectly subtracted the stride anyway.

Also detect several integer-overflow cases that previously produced
bogus results.  (The submitted patch tried to avoid overflow, but
I'm not convinced it's right, and problematic cases are so far out of
the plausibly-useful range that they don't seem worth sweating over.
Let's just use overflow-detecting arithmetic and throw errors.)

timestamp_bin() and timestamptz_bin() are basically identical and
so had identical bugs.  Fix both.

Report and patch by Moaaz Assali, adjusted some by me.  Back-patch
to v14 where date_bin() was introduced.

Discussion: https://postgr.es/m/CALkF+nvtuas-2kydG-WfofbRSJpyODAJWun==W-yO5j2R4meqA@mail.gmail.com
src/backend/utils/adt/timestamp.c
src/test/regress/expected/timestamp.out
src/test/regress/expected/timestamptz.out
src/test/regress/sql/timestamp.sql
src/test/regress/sql/timestamptz.sql