Skip to content

Commit 142b129

Browse files
committed
Keep the NULL marker of a distinct count typed
Null semantics can find the counted expression non-nullable after translation (a parameter, a null-checked predicate) and drop the marker's only WHEN, leaving COUNT(DISTINCT (NULL)), which SQL Server rejects. Give the CASE a typed NULL ELSE so it collapses to CAST(NULL AS int) instead, and treat COALESCE with a non-nullable argument and CASE with non-nullable results as non-nullable so those get no marker at all.
1 parent dd75595 commit 142b129

4 files changed

Lines changed: 81 additions & 10 deletions

File tree

‎src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1905,20 +1905,24 @@ private bool TryTranslateAsEnumerableExpression(
19051905
{
19061906
// COUNT(DISTINCT x) skips NULL, but LINQ's Distinct().Count() counts null as one more distinct value. Add one when
19071907
// the rows being counted contain a NULL. That is itself a distinct count, so it is 0 or 1 and never NULL.
1908+
// Null semantics may still find x non-nullable (a parameter, a predicate) and drop the WHEN, so the ELSE is a typed
1909+
// NULL: some databases (SQL Server) reject COUNT over an untyped NULL.
19081910
var isNull = _sqlExpressionFactory.IsNull(distinctSelector);
1911+
var intTypeMapping = Dependencies.TypeMappingSource.FindMapping(typeof(int), Dependencies.Model);
1912+
var nullMarker = _sqlExpressionFactory.Case(
1913+
[
1914+
new CaseWhenClause(
1915+
enumerableExpression.Predicate is null
1916+
? isNull
1917+
: _sqlExpressionFactory.AndAlso(enumerableExpression.Predicate, isNull),
1918+
_sqlExpressionFactory.Constant(1, intTypeMapping))
1919+
],
1920+
elseResult: _sqlExpressionFactory.Convert(
1921+
_sqlExpressionFactory.Constant(null, typeof(int?), intTypeMapping), typeof(int), intTypeMapping));
19091922
var nullCount = Dependencies.AggregateMethodCallTranslatorProvider.Translate(
19101923
_model,
19111924
method,
1912-
new EnumerableExpression(
1913-
_sqlExpressionFactory.Case(
1914-
[
1915-
new CaseWhenClause(
1916-
enumerableExpression.Predicate is null
1917-
? isNull
1918-
: _sqlExpressionFactory.AndAlso(enumerableExpression.Predicate, isNull),
1919-
_sqlExpressionFactory.Constant(1))
1920-
],
1921-
elseResult: null)) { GroupingOwner = enumerableExpression.GroupingOwner }.SetDistinct(true),
1925+
new EnumerableExpression(nullMarker) { GroupingOwner = enumerableExpression.GroupingOwner }.SetDistinct(true),
19221926
scalarArguments,
19231927
_queryCompilationContext.Logger);
19241928

@@ -1975,6 +1979,12 @@ static bool MayBeNull(SqlExpression expression)
19751979
{
19761980
ColumnExpression column => column.IsNullable,
19771981
SqlConstantExpression constant => constant.Value is null,
1982+
SqlFunctionExpression { IsBuiltIn: true, Name: "COALESCE", Arguments: { } coalesceArguments }
1983+
=> coalesceArguments.All(MayBeNull),
1984+
CaseExpression caseExpression
1985+
=> caseExpression.ElseResult is null
1986+
|| MayBeNull(caseExpression.ElseResult)
1987+
|| caseExpression.WhenClauses.Any(c => MayBeNull(c.Result)),
19781988
SqlFunctionExpression function
19791989
=> function.IsNullable
19801990
|| (function is { Arguments: { } arguments, ArgumentsPropagateNullability: { } propagate }

‎test/EFCore.Specification.Tests/Query/NorthwindGroupByQueryTestBase.cs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2397,6 +2397,21 @@ public virtual Task GroupBy_Property_Select_Distinct_Count_over_nullable_column_
23972397
}),
23982398
elementSorter: e => e.Key);
23992399

2400+
[Theory, MemberData(nameof(IsAsyncData))]
2401+
public virtual Task GroupBy_Property_Select_Distinct_Count_over_non_nullable_expression(bool async)
2402+
=> AssertQuery(
2403+
async,
2404+
ss => ss.Set<Customer>()
2405+
.GroupBy(c => c.Country)
2406+
.Select(g => new
2407+
{
2408+
g.Key,
2409+
Coalesced = g.Select(c => c.Region ?? "unknown").Distinct().Count(),
2410+
Conditional = g.Select(c => c.Region == null ? "none" : "some").Distinct().LongCount(),
2411+
NotNullFiltered = g.Where(c => c.Region != null && c.City != "London").Select(c => c.Region).Distinct().Count()
2412+
}),
2413+
elementSorter: e => e.Key);
2414+
24002415
[Theory, MemberData(nameof(IsAsyncData))]
24012416
public virtual Task GroupBy_Property_Select_Count_with_not_null_and_other_predicate(bool async)
24022417
=> AssertQuery(

‎test/EFCore.SqlServer.FunctionalTests/Query/NorthwindGroupByQuerySqlServerTest.cs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2570,6 +2570,7 @@ public override async Task GroupBy_Select_Distinct_Any_with_nullable_element(boo
25702570
"""
25712571
SELECT [o].[CustomerID] AS [Key], COUNT(DISTINCT ([o].[EmployeeID])) + COUNT(DISTINCT (CASE
25722572
WHEN [o].[EmployeeID] IS NULL THEN 1
2573+
ELSE CAST(NULL AS int)
25732574
END)) AS [Employees], CASE
25742575
WHEN EXISTS (
25752576
SELECT 1
@@ -2839,6 +2840,7 @@ public override async Task GroupBy_aggregate_through_navigation_with_distinct_co
28392840
WHEN [c].[City] = N'London' THEN 1
28402841
END) AS [Londons], COUNT(DISTINCT ([o].[CustomerID])) + COUNT(DISTINCT (CASE
28412842
WHEN [o].[CustomerID] IS NULL THEN 1
2843+
ELSE CAST(NULL AS int)
28422844
END)) AS [Customers]
28432845
FROM [Orders] AS [o]
28442846
LEFT JOIN [Customers] AS [c] ON [o].[CustomerID] = [c].[CustomerID]
@@ -3469,8 +3471,10 @@ public override async Task GroupBy_Select_Distinct_aggregate(bool async)
34693471
"""
34703472
SELECT [o].[CustomerID] AS [Key], AVG(DISTINCT (CAST([o].[OrderID] AS float))) AS [Average], COUNT(DISTINCT ([o].[EmployeeID])) + COUNT(DISTINCT (CASE
34713473
WHEN [o].[EmployeeID] IS NULL THEN 1
3474+
ELSE CAST(NULL AS int)
34723475
END)) AS [Count], COUNT_BIG(DISTINCT ([o].[EmployeeID])) + COUNT_BIG(DISTINCT (CASE
34733476
WHEN [o].[EmployeeID] IS NULL THEN 1
3477+
ELSE CAST(NULL AS int)
34743478
END)) AS [LongCount], MAX([o].[OrderDate]) AS [Max], MIN([o].[OrderDate]) AS [Min], ISNULL(SUM(DISTINCT ([o].[OrderID])), 0) AS [Sum]
34753479
FROM [Orders] AS [o]
34763480
GROUP BY [o].[CustomerID]
@@ -4027,8 +4031,10 @@ public override async Task GroupBy_Property_Select_Distinct_Count_over_nullable_
40274031
"""
40284032
SELECT [c].[Country] AS [Key], COUNT(DISTINCT ([c].[Region])) + COUNT(DISTINCT (CASE
40294033
WHEN [c].[Region] IS NULL THEN 1
4034+
ELSE CAST(NULL AS int)
40304035
END)) AS [Count], COUNT_BIG(DISTINCT ([c].[Region])) + COUNT_BIG(DISTINCT (CASE
40314036
WHEN [c].[Region] IS NULL THEN 1
4037+
ELSE CAST(NULL AS int)
40324038
END)) AS [LongCount]
40334039
FROM [Customers] AS [c]
40344040
GROUP BY [c].[Country]
@@ -4043,16 +4049,35 @@ public override async Task GroupBy_Property_Select_Distinct_Count_over_nullable_
40434049
"""
40444050
SELECT [c].[Country] AS [Key], COUNT(DISTINCT (NULLIF([c].[Region], N'WA'))) + COUNT(DISTINCT (CASE
40454051
WHEN ([c].[Region] <> N'WA' OR [c].[Region] IS NULL) AND [c].[Region] IS NULL THEN 1
4052+
ELSE CAST(NULL AS int)
40464053
END)) AS [Count], COUNT_BIG(DISTINCT (CASE
40474054
WHEN [c].[City] <> N'London' OR [c].[City] IS NULL THEN [c].[Region]
40484055
END)) + COUNT_BIG(DISTINCT (CASE
40494056
WHEN ([c].[City] <> N'London' OR [c].[City] IS NULL) AND [c].[Region] IS NULL THEN 1
4057+
ELSE CAST(NULL AS int)
40504058
END)) AS [LongCount]
40514059
FROM [Customers] AS [c]
40524060
GROUP BY [c].[Country]
40534061
""");
40544062
}
40554063

4064+
public override async Task GroupBy_Property_Select_Distinct_Count_over_non_nullable_expression(bool async)
4065+
{
4066+
await base.GroupBy_Property_Select_Distinct_Count_over_non_nullable_expression(async);
4067+
4068+
AssertSql(
4069+
"""
4070+
SELECT [c].[Country] AS [Key], COUNT(DISTINCT (COALESCE([c].[Region], N'unknown'))) AS [Coalesced], COUNT_BIG(DISTINCT (CASE
4071+
WHEN [c].[Region] IS NULL THEN N'none'
4072+
ELSE N'some'
4073+
END)) AS [Conditional], COUNT(DISTINCT (CASE
4074+
WHEN [c].[City] <> N'London' OR [c].[City] IS NULL THEN [c].[Region]
4075+
END)) + COUNT(DISTINCT (CAST(NULL AS int))) AS [NotNullFiltered]
4076+
FROM [Customers] AS [c]
4077+
GROUP BY [c].[Country]
4078+
""");
4079+
}
4080+
40564081
public override async Task GroupBy_Property_Select_Count_with_not_null_and_other_predicate(bool async)
40574082
{
40584083
await base.GroupBy_Property_Select_Count_with_not_null_and_other_predicate(async);

‎test/EFCore.Sqlite.FunctionalTests/Query/NorthwindGroupByQuerySqliteTest.cs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,8 +310,10 @@ public override async Task GroupBy_Property_Select_Distinct_Count_over_nullable_
310310
"""
311311
SELECT "c"."Country" AS "Key", COUNT(DISTINCT ("c"."Region")) + COUNT(DISTINCT (CASE
312312
WHEN "c"."Region" IS NULL THEN 1
313+
ELSE CAST(NULL AS INTEGER)
313314
END)) AS "Count", COUNT(DISTINCT ("c"."Region")) + COUNT(DISTINCT (CASE
314315
WHEN "c"."Region" IS NULL THEN 1
316+
ELSE CAST(NULL AS INTEGER)
315317
END)) AS "LongCount"
316318
FROM "Customers" AS "c"
317319
GROUP BY "c"."Country"
@@ -326,16 +328,35 @@ public override async Task GroupBy_Property_Select_Distinct_Count_over_nullable_
326328
"""
327329
SELECT "c"."Country" AS "Key", COUNT(DISTINCT (NULLIF("c"."Region", 'WA'))) + COUNT(DISTINCT (CASE
328330
WHEN ("c"."Region" <> 'WA' OR "c"."Region" IS NULL) AND "c"."Region" IS NULL THEN 1
331+
ELSE CAST(NULL AS INTEGER)
329332
END)) AS "Count", COUNT(DISTINCT (CASE
330333
WHEN "c"."City" <> 'London' OR "c"."City" IS NULL THEN "c"."Region"
331334
END)) + COUNT(DISTINCT (CASE
332335
WHEN ("c"."City" <> 'London' OR "c"."City" IS NULL) AND "c"."Region" IS NULL THEN 1
336+
ELSE CAST(NULL AS INTEGER)
333337
END)) AS "LongCount"
334338
FROM "Customers" AS "c"
335339
GROUP BY "c"."Country"
336340
""");
337341
}
338342

343+
public override async Task GroupBy_Property_Select_Distinct_Count_over_non_nullable_expression(bool async)
344+
{
345+
await base.GroupBy_Property_Select_Distinct_Count_over_non_nullable_expression(async);
346+
347+
AssertSql(
348+
"""
349+
SELECT "c"."Country" AS "Key", COUNT(DISTINCT (COALESCE("c"."Region", 'unknown'))) AS "Coalesced", COUNT(DISTINCT (CASE
350+
WHEN "c"."Region" IS NULL THEN 'none'
351+
ELSE 'some'
352+
END)) AS "Conditional", COUNT(DISTINCT (CASE
353+
WHEN "c"."City" <> 'London' OR "c"."City" IS NULL THEN "c"."Region"
354+
END)) + COUNT(DISTINCT (CAST(NULL AS INTEGER))) AS "NotNullFiltered"
355+
FROM "Customers" AS "c"
356+
GROUP BY "c"."Country"
357+
""");
358+
}
359+
339360
private void AssertSql(params string[] expected)
340361
=> Fixture.TestSqlLoggerFactory.AssertBaseline(expected);
341362

0 commit comments

Comments
 (0)