timescale / timescaledb

An open-source time-series SQL database optimized for fast ingest and complex queries. Packaged as a PostgreSQL extension.
https://www.timescale.com/
Other
16.83k stars 852 forks source link

[Bug]: days_in_month() calculates incorrectly #6985

Open JimRowan opened 1 month ago

JimRowan commented 1 month ago

What type of bug is this?

Incorrect result

What subsystems and features are affected?

Other

What happened?

When provided an argument towards the end of the month, days_in_month() gives incorrect results when the following month has a different number of days!

TimescaleDB version affected

2.14.2

PostgreSQL version used

16

What operating system did you use?

RHEL 8.7 x64

What installation method did you use?

RPM

What platform did you run on?

On prem/Self-hosted

Relevant log output and stack trace

No response

How can we reproduce the bug?

# select days_in_month('1/31/2023 00:00:00'::timestamptz);
 days_in_month 
───────────────
            28
(1 row)

Correct value is 31.

# \sf+ days_in_month
        CREATE OR REPLACE FUNCTION public.days_in_month(date timestamp with time zone)
         RETURNS integer
         LANGUAGE sql
         IMMUTABLE PARALLEL SAFE STRICT
         SET search_path TO 'pg_catalog', 'pg_temp'
1       AS $function$
2       SELECT CAST(EXTRACT('day' FROM ($1 + interval '1 month' - $1)) as INTEGER)
3       $function$

Line 2 should be:
SELECT CAST(EXTRACT('day' FROM (date_trunc('month', $1) + interval '1 month' - date_trunc('month', $1))) AS INTEGER)