Skip to content

Fix interval overflow when scanning into time.Duration - #2723

Open
flip-sa wants to merge 1 commit into
jackc:masterfrom
flip-sa:fix-interval-duration-overflow
Open

flip-sa wants to merge 1 commit into
jackc:masterfrom
flip-sa:fix-interval-duration-overflow

Conversation

@flip-sa

@flip-sa flip-sa commented Nov 20, 2026

Copy link
Copy Markdown

Scanning an interval that does not fit in time.Duration (about 292 years) silently overflowed. The result was wrong, often with the opposite sign, and no error was returned:

m := pgtype.NewMap()                                                                                                                                         
var d time.Duration                                                                                                                                                                               
err := m.Scan(pgtype.IntervalOID, pgtype.TextFormatCode, []byte("300 years"), &d)                                                    
// before: d = -2532095h34m33.709551616s, err = nil                                                                                                     
// after:  err = interval of 3600 months, 0 days and 0 microseconds is out of range for time.Duration

A realistic case is a "lifetime" plan stored as interval '999 years': it was read as a negative duration, so time.Now().Add(d) was in the past.

durationWrapper.ScanInterval now returns an error when the interval does not fit. Two places can overflow, and both are checked before the arithmetic:

  • the sum of months, days and microseconds in microseconds (Months alone can exceed int64 when converted);

  • the conversion from microseconds to nanoseconds.

This also fixes the NULL error message, which referred to *time.Interval.

Tests:

  • TestIntervalCodec: the largest interval that fits still round trips.
  • TestIntervalScanDurationOverflowReturnsError: one microsecond over the limit, ±300 years, and math.MaxInt32 months return an error in text and binary formats. This test fails before the fix and passes afterward.

go test -race ./pgtype passes.

Scanning an interval that does not fit in time.Duration (about 292 years)
silently overflowed and produced a wrong value, often with the opposite
sign. It now returns an error. Both the microsecond sum and the conversion
to nanoseconds are checked.

Also fix the NULL error message, which referred to *time.Interval.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant