Skip to content

Implement DateOnly.DayNumber translations for SqlServer/Sqlite #36189

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,8 @@ namespace Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class SqlServerDateOnlyMemberTranslator : IMemberTranslator
public class SqlServerDateOnlyMemberTranslator(ISqlExpressionFactory sqlExpressionFactory) : IMemberTranslator
{
private static readonly Dictionary<string, string> DatePartMapping
= new()
{
{ nameof(DateOnly.Year), "year" },
{ nameof(DateOnly.Month), "month" },
{ nameof(DateOnly.DayOfYear), "dayofyear" },
{ nameof(DateOnly.Day), "day" }
};

private readonly ISqlExpressionFactory _sqlExpressionFactory;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public SqlServerDateOnlyMemberTranslator(ISqlExpressionFactory sqlExpressionFactory)
=> _sqlExpressionFactory = sqlExpressionFactory;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
Expand All @@ -45,12 +25,39 @@ public SqlServerDateOnlyMemberTranslator(ISqlExpressionFactory sqlExpressionFact
MemberInfo member,
Type returnType,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
=> member.DeclaringType == typeof(DateOnly) && DatePartMapping.TryGetValue(member.Name, out var datePart)
? _sqlExpressionFactory.Function(
{
if (member.DeclaringType != typeof(DateOnly) || instance is null)
{
return null;
}

return member.Name switch
{
nameof(DateOnly.Year) => DatePart("year"),
nameof(DateOnly.Month) => DatePart("month"),
nameof(DateOnly.DayOfYear) => DatePart("dayofyear"),
nameof(DateOnly.Day) => DatePart("day"),

nameof(DateOnly.DayNumber) => sqlExpressionFactory.Function(
"DATEDIFF",
[
sqlExpressionFactory.Fragment("day"),
sqlExpressionFactory.Constant(new DateOnly(1, 1, 1)),
instance
],
nullable: true,
argumentsPropagateNullability: [false, true, true],
Copy link
Contributor

Choose a reason for hiding this comment

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

Shouldn't this be [false, false, true]?

Copy link
Member Author

Choose a reason for hiding this comment

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

It could be - it doesn't matter either way, as the second argument is a non-null constant (and so the logic handling null semantics will do the right thing anyway). Up to now I've been generally specifying the function behavior in argumentsPropagateNullability, without taking the actual arguments into account - but let me know if you think we should do something else.

Copy link
Contributor

Choose a reason for hiding this comment

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

Up to you.

returnType),

_ => null
};

SqlExpression DatePart(string datePart)
=> sqlExpressionFactory.Function(
"DATEPART",
new[] { _sqlExpressionFactory.Fragment(datePart), instance! },
[sqlExpressionFactory.Fragment(datePart), instance],
nullable: true,
argumentsPropagateNullability: Statics.FalseTrue,
returnType)
: null;
returnType);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,29 +12,8 @@ namespace Microsoft.EntityFrameworkCore.Sqlite.Query.Internal;
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class SqliteDateOnlyMemberTranslator : IMemberTranslator
public class SqliteDateOnlyMemberTranslator(SqliteSqlExpressionFactory sqlExpressionFactory) : IMemberTranslator
{
private static readonly Dictionary<string, string> DatePartMapping
= new()
{
{ nameof(DateOnly.Year), "%Y" },
{ nameof(DateOnly.Month), "%m" },
{ nameof(DateOnly.DayOfYear), "%j" },
{ nameof(DateOnly.Day), "%d" },
{ nameof(DateOnly.DayOfWeek), "%w" }
};

private readonly SqliteSqlExpressionFactory _sqlExpressionFactory;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public SqliteDateOnlyMemberTranslator(SqliteSqlExpressionFactory sqlExpressionFactory)
=> _sqlExpressionFactory = sqlExpressionFactory;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
Expand All @@ -46,12 +25,44 @@ public SqliteDateOnlyMemberTranslator(SqliteSqlExpressionFactory sqlExpressionFa
MemberInfo member,
Type returnType,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
=> member.DeclaringType == typeof(DateOnly) && DatePartMapping.TryGetValue(member.Name, out var datePart)
? _sqlExpressionFactory.Convert(
_sqlExpressionFactory.Strftime(
{
if (member.DeclaringType != typeof(DateOnly) || instance is null)
{
return null;
}

return member.Name switch
{
nameof(DateOnly.Year) => DatePart("%Y"),
nameof(DateOnly.Month) => DatePart("%m"),
nameof(DateOnly.DayOfYear) => DatePart("%j"),
nameof(DateOnly.Day) => DatePart("%d"),
nameof(DateOnly.DayOfWeek) => DatePart("%w"),

nameof(DateOnly.DayNumber)
=> sqlExpressionFactory.Convert(
sqlExpressionFactory.Subtract(
JulianDay(instance),
JulianDay(sqlExpressionFactory.Constant(new DateOnly(1, 1, 1)))),
typeof(int)),

_ => null
};

SqlExpression DatePart(string datePart)
=> sqlExpressionFactory.Convert(
sqlExpressionFactory.Strftime(
typeof(string),
datePart,
instance!),
returnType)
: null;
instance),
returnType);

SqlExpression JulianDay(SqlExpression argument)
=> sqlExpressionFactory.Function(
"julianday",
[argument],
nullable: true,
argumentsPropagateNullability: Statics.TrueArrays[1],
returnType: typeof(double));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ public override Task DayOfYear(bool async)
public override Task DayOfWeek(bool async)
=> AssertTranslationFailed(() => base.DayOfWeek(async));

// Cosmos does not support DateTimeDiff with years under 1601
public override Task DayNumber(bool async)
=> AssertTranslationFailed(() => base.DayNumber(async));

public override Task AddYears(bool async)
=> AssertTranslationFailed(() => base.AddYears(async));

Expand All @@ -35,6 +39,10 @@ public override Task AddMonths(bool async)
public override Task AddDays(bool async)
=> AssertTranslationFailed(() => base.AddDays(async));

// Cosmos does not support DateTimeDiff with years under 1601
public override Task DayNumber_subtraction(bool async)
=> AssertTranslationFailed(() => base.DayNumber_subtraction(async));

public override Task FromDateTime(bool async)
=> AssertTranslationFailed(() => base.FromDateTime(async));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ public virtual Task DayOfWeek(bool async)
async,
ss => ss.Set<BasicTypesEntity>().Where(b => b.DateOnly.DayOfWeek == System.DayOfWeek.Saturday));

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task DayNumber(bool async)
=> AssertQuery(
async,
ss => ss.Set<BasicTypesEntity>().Where(b => b.DateOnly.DayNumber == 726780));

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task AddYears(bool async)
Expand All @@ -64,6 +71,13 @@ public virtual Task AddDays(bool async)
async,
ss => ss.Set<BasicTypesEntity>().Where(b => b.DateOnly.AddDays(3) == new DateOnly(1990, 11, 13)));

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task DayNumber_subtraction(bool async)
=> AssertQuery(
async,
ss => ss.Set<BasicTypesEntity>().Where(b => b.DateOnly.DayNumber - new DateOnly(1990, 11, 5).DayNumber == 5));

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual Task FromDateTime(bool async)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,18 @@ public override async Task DayOfWeek(bool async)
AssertSql();
}

public override async Task DayNumber(bool async)
{
await base.DayNumber(async);

AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE DATEDIFF(day, '0001-01-01', [b].[DateOnly]) = 726780
""");
}

public override async Task AddYears(bool async)
{
await base.AddYears(async);
Expand Down Expand Up @@ -103,6 +115,20 @@ WHERE DATEADD(day, CAST(3 AS int), [b].[DateOnly]) = '1990-11-13'
""");
}

public override async Task DayNumber_subtraction(bool async)
{
await base.DayNumber_subtraction(async);

AssertSql(
"""
@DayNumber='726775'

SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE DATEDIFF(day, '0001-01-01', [b].[DateOnly]) - @DayNumber = 5
""");
}

public override async Task FromDateTime(bool async)
{
await base.FromDateTime(async);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,18 @@ WHERE CAST(strftime('%w', "b"."DateOnly") AS INTEGER) = 6
""");
}

public override async Task DayNumber(bool async)
{
await base.DayNumber(async);

AssertSql(
"""
SELECT "b"."Id", "b"."Bool", "b"."Byte", "b"."ByteArray", "b"."DateOnly", "b"."DateTime", "b"."DateTimeOffset", "b"."Decimal", "b"."Double", "b"."Enum", "b"."FlagsEnum", "b"."Float", "b"."Guid", "b"."Int", "b"."Long", "b"."Short", "b"."String", "b"."TimeOnly", "b"."TimeSpan"
FROM "BasicTypesEntities" AS "b"
WHERE CAST(julianday("b"."DateOnly") - julianday('0001-01-01') AS INTEGER) = 726780
""");
}

public override async Task AddYears(bool async)
{
await base.AddYears(async);
Expand Down Expand Up @@ -110,6 +122,20 @@ WHERE date("b"."DateOnly", CAST(3 AS TEXT) || ' days') = '1990-11-13'
""");
}

public override async Task DayNumber_subtraction(bool async)
{
await base.DayNumber_subtraction(async);

AssertSql(
"""
@DayNumber='726775'

SELECT "b"."Id", "b"."Bool", "b"."Byte", "b"."ByteArray", "b"."DateOnly", "b"."DateTime", "b"."DateTimeOffset", "b"."Decimal", "b"."Double", "b"."Enum", "b"."FlagsEnum", "b"."Float", "b"."Guid", "b"."Int", "b"."Long", "b"."Short", "b"."String", "b"."TimeOnly", "b"."TimeSpan"
FROM "BasicTypesEntities" AS "b"
WHERE CAST(julianday("b"."DateOnly") - julianday('0001-01-01') AS INTEGER) - @DayNumber = 5
""");
}

public override async Task FromDateTime(bool async)
{
await base.FromDateTime(async);
Expand Down