Fix for edge case in date_bin() function - Mailing list pgsql-hackers

From Moaaz Assali
Subject Fix for edge case in date_bin() function
Date
Msg-id CALkF+nvtuas-2kydG-WfofbRSJpyODAJWun==W-yO5j2R4meqA@mail.gmail.com
Whole thread Raw
Responses Re: Fix for edge case in date_bin() function
Re: Fix for edge case in date_bin() function
List pgsql-hackers
Hello,

The date_bin() function has a bug where it returns an incorrect binned date when both of the following are true:
1) the origin timestamp is before the source timestamp
2) the origin timestamp is exactly equivalent to some valid binned date in the set of binned dates that date_bin() can return given a specific stride and source timestamp.

For example, consider the following function call:
date_bin('30 minutes'::interval, '2024-01-01 15:00:00'::timestamp, '2024-01-01 17:00:00'::timestamp);

This function call will return '2024-01-01 14:30:00' instead of '2024-01-01 15:00:00' despite '2024-01-01 15:00:00' being the valid binned date for the timestamp '2024-01-01 15:00:00'. This commit fixes that by editing the timestamp_bin() function in timestamp.c file.

The reason this happens is that the code in timestamp_bin() that allows for correct date binning when source timestamp < origin timestamp subtracts one stride in all cases.
However, that is not valid for this case when the source timestamp is exactly equivalent to a valid binned date as in the example mentioned above.

To account for this edge, we simply add another condition in the if statement to not perform the subtraction by one stride interval if the time difference is divisible by the stride.

Best regards,
Moaaz Assali
Attachment

pgsql-hackers by date:

Previous
From: "Hayato Kuroda (Fujitsu)"
Date:
Subject: RE: Have pg_basebackup write "dbname" in "primary_conninfo"?
Next
From: Daniel Gustafsson
Date:
Subject: Re: Fix for edge case in date_bin() function