Repository navigation
Translate TimeSpan members and operators on SQLite - #39739
Open
Aykuttonpc wants to merge 2 commits into
Open
Aykuttonpc wants to merge 2 commits into
Aykuttonpc wants to merge 2 commits into
Conversation
SQLite stores TimeSpan as text, so operations are translated over integer ticks via two new UDFs, ef_ticks and ef_timespan. This covers the TimeSpan members, +, -, unary -, comparisons, division by TimeSpan, scaling by a double, Duration(), Negate(), Min/Max and OrderBy/ThenBy. Fixes dotnet#18844
Contributor
There was a problem hiding this comment.
🟡 Changes recommended
SQLite TimeSpan translations use incorrect midpoint rounding and interpret long-converted ticks as days, causing incorrect query results and possible overflows.
2 open issues
What changed in this PR
Adds tick-based TimeSpan query translation to EF Core’s SQLite provider, addressing #18844 without the precision loss of converting through floating-point days. TimeSpan.FromX and DateTime arithmetic remain out of scope.
Changes:
- Registers tick conversion functions and translates TimeSpan members, arithmetic, comparisons, and instance methods.
- Enables numeric TimeSpan ordering and Min/Max aggregation.
- Adds functional coverage and updates SQL baselines for newly translated queries.
| File | Description |
|---|---|
test/EFCore.Sqlite.FunctionalTests/Query/Translations/Temporal/TimeSpanTranslationsSqliteTest.cs |
Adds member, operator, projection, aggregate, and nullable coverage. |
test/EFCore.Sqlite.FunctionalTests/Query/Inheritance/TPTGearsOfWarQuerySqliteTest.cs |
Verifies translated tick aggregates for TPT queries. |
test/EFCore.Sqlite.FunctionalTests/Query/Inheritance/TPCGearsOfWarQuerySqliteTest.cs |
Verifies translated tick aggregates for TPC queries. |
test/EFCore.Sqlite.FunctionalTests/Query/GearsOfWarQuerySqliteTest.cs |
Updates arithmetic projection and tick aggregate baselines. |
test/EFCore.Sqlite.FunctionalTests/BuiltInDataTypesSqliteTest.cs |
Replaces TimeSpan ordering and aggregate rejection checks with result assertions. |
src/EFCore.Sqlite.Core/Storage/Internal/SqliteRelationalConnection.cs |
Registers ef_ticks and ef_timespan. |
src/EFCore.Sqlite.Core/Query/Internal/Translators/SqliteTimeSpanMethodTranslator.cs |
Translates Duration() and Negate(). |
src/EFCore.Sqlite.Core/Query/Internal/Translators/SqliteTimeSpanMemberTranslator.cs |
Translates tick, component, and total-value properties. |
src/EFCore.Sqlite.Core/Query/Internal/Translators/SqliteQueryableAggregateMethodTranslator.cs |
Computes TimeSpan Min/Max using ticks. |
src/EFCore.Sqlite.Core/Query/Internal/SqliteSqlTranslatingExpressionVisitor.cs |
Translates arithmetic, scaling, negation, and comparisons. |
src/EFCore.Sqlite.Core/Query/Internal/SqliteSqlExpressionFactory.cs |
Adds conversion helpers with constant folding and round-trip elimination. |
src/EFCore.Sqlite.Core/Query/Internal/SqliteQueryableMethodTranslatingExpressionVisitor.cs |
Orders TimeSpan values by ticks. |
src/EFCore.Sqlite.Core/Query/Internal/SqliteMethodCallTranslatorProvider.cs |
Registers the TimeSpan method translator. |
src/EFCore.Sqlite.Core/Query/Internal/SqliteMemberTranslatorProvider.cs |
Registers the TimeSpan member translator. |
Review effort: Balanced
| return SqliteFactory.EfTimeSpan( | ||
| _sqlExpressionFactory.Convert( | ||
| _sqlExpressionFactory.Function( | ||
| "round", |
Contributor
Author
There was a problem hiding this comment.
Fixed in 5e81128469, thanks.
| Type returnType, | ||
| IDiagnosticsLogger<DbLoggerCategory.Query> logger) | ||
| { | ||
| if (member.DeclaringType != typeof(TimeSpan) || instance is null) |
Contributor
Author
There was a problem hiding this comment.
Fixed in 5e81128469, thanks.
…QLite - TimeSpan * double and / double now round with Math.Round through a new ef_round function, since SQLite's round() rounds half away from zero. - TimeSpan member and method translations are skipped when the value is not stored as a TimeSpan (e.g. HasConversion<long>()), where ef_ticks() would read the number as days.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Fixes #18844
SQLite stores
TimeSpanas text ([-][d.]hh:mm:ss[.fffffff]), so most operations on it were blocked. This translates them by working on the integer ticks, through new UDFs registered alongside the existing decimal ones:ef_ticks(timespan): TEXT (or REAL days) to ticksef_timespan(ticks): ticks back to the canonical text formatef_round(value):Math.Round, since SQLite'sround()rounds half away from zeroNow translated:
Ticks,Days,Hours,Minutes,Seconds,Milliseconds,Microseconds,Nanoseconds, and allTotal*+,-, unary-,<,<=,>,>=,TimeSpan / TimeSpan,TimeSpan * double,TimeSpan / doubleDuration(),Negate()Min/Max,OrderBy/ThenBy(these threwNotSupportedExceptionbefore)Example:
WHERE (ef_ticks("b"."TimeSpan") / 36000000000) % 24 = 3Design notes:
doubledays, which loses precision. That's the problem @bricelam hit in his branch. With integer ticks, components, comparisons, addition and subtraction are exact, and integer/and%in SQLite truncate toward zero like the .NET definitions. That makes negative values work too ((-ts).Hours == -3).ef_ticks('01:00:00')becomes36000000000, andef_ticks(ef_timespan(x))becomesx, so(a + b).Hoursdoesn't go through text./ 2.0was rendered as'2', i.e. 2 days). The result is rounded to the nearest tick, half to even, as in .NET.GearsOfWarQuerySqliteTest.Non_string_concat_uses_appropriate_type_mappinggets a new baseline (ef_timespan(ef_ticks("m"."Duration") + ef_ticks(@interval))instead of client evaluation).Client_eval_followed_by_aggregate_operation(GearsOfWar, TPC, TPT) no longer throws on SQLite, sinceDuration.Ticksis now translated; the SQLite overrides assert the aggregates and their SQL instead.HasConversion<long>()) aren't translated, sinceef_tickswould read the number as days.ef_timespanproduces the same canonical format the provider writes.Not included, can follow up:
TimeSpan.FromXDateTime ± TimeSpanandDateTime - DateTime. These need DateTime-to-ticks; SQLite: DateTime.Ticks translation loses sub-millisecond precision and is off by floating-point error #39531 touches the same area.Known differences from .NET: arithmetic overflow and division by zero yield SQLite's result (REAL or NULL) instead of throwing.
The operator tests are in
TimeSpanTranslationsSqliteTest, following the SQL Server-specificTotalHours_in_projection. I'm happy to move them to the spec base if you prefer.