Skip to content

Translate TimeSpan members and operators on SQLite - #39739

Open
Aykuttonpc wants to merge 2 commits into
dotnet:mainfrom
Aykuttonpc:sqlite-timespan-translations
Open

Aykuttonpc wants to merge 2 commits into
dotnet:mainfrom
Aykuttonpc:sqlite-timespan-translations

Conversation

@Aykuttonpc

@Aykuttonpc Aykuttonpc commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #18844

SQLite stores TimeSpan as 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 ticks
  • ef_timespan(ticks): ticks back to the canonical text format
  • ef_round(value): Math.Round, since SQLite's round() rounds half away from zero

Now translated:

  • Members: Ticks, Days, Hours, Minutes, Seconds, Milliseconds, Microseconds, Nanoseconds, and all Total*
  • Operators: +, -, unary -, <, <=, >, >=, TimeSpan / TimeSpan, TimeSpan * double, TimeSpan / double
  • Methods: Duration(), Negate()
  • Min/Max, OrderBy/ThenBy (these threw NotSupportedException before)

Example: WHERE (ef_ticks("b"."TimeSpan") / 36000000000) % 24 = 3

Design notes:

  • Ticks, not days. Implement SQLite TimeSpan translation #37804 (closed for inactivity) round-tripped through double days, 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).
  • Constants are folded. ef_ticks('01:00:00') becomes 36000000000, and ef_ticks(ef_timespan(x)) becomes x, so (a + b).Hours doesn't go through text.
  • Scaling by a double is translated before the base visitor. Otherwise the TimeSpan type mapping gets inferred onto the double operand (/ 2.0 was rendered as '2', i.e. 2 days). The result is rounded to the nearest tick, half to even, as in .NET.
  • TimeSpan expressions in the final projection are now translated as well, so GearsOfWarQuerySqliteTest.Non_string_concat_uses_appropriate_type_mapping gets 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, since Duration.Ticks is now translated; the SQLite overrides assert the aggregates and their SQL instead.
  • TimeSpans stored through a value converter (e.g. HasConversion<long>()) aren't translated, since ef_ticks would read the number as days.
  • Equality is left as text comparison, since ef_timespan produces the same canonical format the provider writes.

Not included, can follow up:

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-specific TotalHours_in_projection. I'm happy to move them to the spec base if you prefer.

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 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",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 5e81128469, thanks.

Type returnType,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
if (member.DeclaringType != typeof(TimeSpan) || instance is null)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SQLite: Translate TimeSpan members

2 participants