Throw when reading an interval with negative months as TimeSpan by alaricd · Pull Request #6682 · npgsql/npgsql · GitHub
Skip to content

Throw when reading an interval with negative months as TimeSpan - #6682

Open
alaricd wants to merge 1 commit into
npgsql:mainfrom
pengdows:fix/interval-negative-months
Open

alaricd wants to merge 1 commit into
npgsql:mainfrom
pengdows:fix/interval-negative-months

Conversation

@alaricd

@alaricd alaricd commented Oct 20, 2026

Copy link
Copy Markdown

Reading an interval that has months as a TimeSpan throws InvalidCastException, because a month has no fixed length (#4599). The check in TimeSpanIntervalConverter.Read is months > 0, though, so a negative month count gets past it and the months are dropped:

// SELECT INTERVAL '1 month'   -> InvalidCastException, as intended
// SELECT INTERVAL '-1 month'  -> TimeSpan.Zero, no exception
var value = reader.GetFieldValue<TimeSpan>(0);

This changes the check to months != 0, which is what DurationConverter in Npgsql.NodaTime already does for the same case.

Interval_with_negative_months_cannot_read_as_TimeSpan sits next to the existing Interval_with_months_cannot_read_as_TimeSpan and fails without the fix. The DateTimeTests and NodaTime tests pass against PostgreSQL 17 (155).

Found with the pengdows ADO.NET conformance suite, whose type-fidelity tests round-trip each type's values through every driver. Npgsql 4 and 5 read -1 month as -30 days; 6 through current main read it as zero.

🤖 Generated with Claude Code

Reading an interval with months as TimeSpan throws, since a month has no
fixed length, but the check was months > 0, so '-1 month' read silently
as TimeSpan.Zero. Check months != 0, as DurationConverter in the NodaTime
plugin already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@alaricd
alaricd requested review from roji and vonzshik as code owners October 20, 2026 14:23

This branch has not been deployed

No deployments
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