Skip to content

Fix TimeOnly.IsBetween for midnight-spanning ranges - #4127

Merged
roji merged 1 commit into
npgsql:mainfrom
emremenekse:fix/timeonly-isbetween-midnight
Nov 17, 2026
Merged

roji merged 1 commit into
npgsql:mainfrom
emremenekse:fix/timeonly-isbetween-midnight

Conversation

@emremenekse

@emremenekse emremenekse commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

TimeOnly.IsBetween currently uses time >= start AND time < end for every range. A query for 22:00–02:00 consequently misses matching values such as 23:00 and 00:30. Use OR when constant bounds span midnight, retain AND for normal/equal-bound ranges, and express both alternatives for parameter or column bounds. The start remains inclusive and the end exclusive; equal bounds remain empty.

Fixes #4129. Split from #4090; this addresses only TimeOnly.IsBetween.

The change infers a consistent type mapping for the receiver and bounds. It does not change parameter-based SQL processing or command caching.

Validation

Local Windows validation with the pinned SDK 11.0.100 and isolated PostgreSQL 18.6 testcontainers:

  • The midnight regression failed before the fix: expected five rows, received zero. Four further sync/async and constant/parameter cases over ten explicit clock values also failed with the original translator: expected six values, received none. After the fix, all 43 TimeOnly cases passed without skips.
  • All temporal translation suites: 179 passed, including those 43 cases.
  • Unit tests: 769 passed; six existing skips reference Allow value comparers for supertypes of the mapping's type dotnet/efcore#30939.
  • Full solution Release build: zero warnings/errors; git diff --check passed.

Tests check results and exact SQL for normal/midnight ranges, boundaries (including exclusion of 21:00 and 02:00), equal bounds, microsecond precision, nulls, negation, column/calculated bounds, and one compiled query executed with changing range parameters.

Local performance check

Compared warm EF Count calls with hand-written correct range predicates over 100,000 synthetic rows: six shapes, indexed/unindexed, automatic preparation disabled/enabled (24 comparisons). Each pair used ten warmups and seven alternating batches, with 100 calls per indexed batch and 20 per unindexed batch. All counts and twelve explicit boundary rows matched C# results. Captured EXPLAIN plans used the same scan types as the reference: index-only scans for normal/narrow/equal ranges and two bitmap index scans for midnight ranges.

Indexed local medians with automatic preparation enabled:

Parameterized range Hand-written predicate IsBetween
14:00–16:00 893.60 us 912.42 us
22:00–02:00 1775.91 us 1799.20 us
14:00–14:05 556.47 us 590.28 us
22:00–22:00 535.17 us 560.48 us

The largest relative overhead in the measured cases was about 6.1% (34 us). These are local medians, not confidence intervals or an application-wide speedup claim. The incorrect pre-fix predicate is not a working performance reference.

The measured parameterized prepared Count statement used custom plans. Forced generic plans, cold compilation, allocations, concurrent load, and performance of complex per-row bounds were not measured. The full functional suite, other PostgreSQL versions and GitHub CI have not been run for this local change.

Use OR for constant ranges spanning midnight and preserve AND for normal
and equal-bound ranges. Handle both directions for parameter/column bounds.

Add result and SQL regressions for boundaries, nulls, precision, negation
and compiled queries with changing parameters.

Part of npgsql#4090

@roji roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recommendation: Proceed with this fix. I found no blocking correctness or scope issues at bab7a23.

Problem

The premise is correct. The existing translator always emits time >= start AND time < end. That cannot match an overnight range, although .NET treats it as wrapping around midnight. For example:

context.Set<ClockRow>()
    .Where(r => r.Time.IsBetween(new TimeOnly(22, 0), new TimeOnly(2, 0)));

Rows at 23:00 and 00:30 should match, but neither does before this fix. This addresses the IsBetween portion of #4090; its other temporal issues should remain separate.

Expected approach

Keep the change in the method translator: use AND for ordinary/equal constant bounds and OR for overnight constants. For parameters and column expressions, emit both alternatives guarded by the ordering of the bounds. Preserve inclusive start, exclusive end, and an empty equal-bound range. Focused result/SQL tests should cover boundaries, dynamic bounds, nulls, negation, and parameter reuse. No public API, persisted-format, migration, or conceptual-documentation change is needed.

PR alignment and before/after SQL

The implementation follows that approach with a small localized change. Its type-mapping and predicate construction also follow EF's SQL Server implementation. It introduces no command-cache or parameter-processing plumbing.

Captured SQL for the constant overnight query, omitting only the identical ORDER BY:

-- Before: incorrectly returns no rows
SELECT c."Time"
FROM "ClockRows" AS c
WHERE c."Time" >= TIME '22:00:00' AND c."Time" < TIME '02:00:00'

-- After
SELECT c."Time"
FROM "ClockRows" AS c
WHERE c."Time" >= TIME '22:00:00' OR c."Time" < TIME '02:00:00'

For captured TimeOnly start, end parameters, the predicate changes as follows (line-wrapped for readability):

-- Before
WHERE c."Time" >= @start AND c."Time" < @end

-- After: the same SQL handles ordinary, overnight, and equal bounds
WHERE (@start <= @end AND c."Time" >= @start AND c."Time" < @end)
   OR (@start > @end AND (c."Time" >= @start OR c."Time" < @end))

Ordinary constant ranges retain their existing AND SQL; equal constant bounds remain empty.

Gaps

No required changes identified. The regression coverage covers the relevant cases, including a compiled query executed with changing parameters. The larger dynamic predicate is justified by runtime/per-row bounds, rather than unnecessary abstraction.

Manual validation

I wrote and ran a separate .NET 11 consumer program against both the base revision and PR head, using isolated PostgreSQL 18.6 containers and a mapped temporary table containing 13 explicit clock values. Nine scenarios covered ordinary/overnight/equal constants and parameters, negation, column bounds, and calculated bounds. Five scenarios disagreed with the .NET API before the fix; all nine matched afterward. The overnight query changed from zero rows to the six expected values, including 22:00 and excluding 02:00.

Separately, all 43 TimeOnly translation tests passed without skips using the repository's automatic isolated PostGIS testcontainer. This assessment is based on executed consumer queries as well as code and tests, not on the PR's reported validation or benchmarks.

Posted by copilot

@roji roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, LGTM!

@roji

roji commented Nov 17, 2026

Copy link
Copy Markdown
Member

@emremenekse if you post on #4129 I'll assign you to it for creddit.

@roji
roji enabled auto-merge (squash) November 17, 2026 10:29
@roji
roji merged commit 3cba3fa into npgsql:main Nov 17, 2026
10 checks passed
roji added a commit that referenced this pull request Nov 17, 2026
Backport #4127 to hotfix/10.0.4, retaining cached MethodInfo matching and adapting raw SQL test baselines to the existing TimeOnly casts.

Fixes #4129.

(cherry picked from commit bab7a23)

Co-authored-by: Emre Menekşe <[email protected]>
Co-authored-by: Copilot App <[email protected]>
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.

TimeOnly.IsBetween returns incorrect results for ranges spanning midnight

2 participants