Skip to content
Open
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 @@ -1895,6 +1895,45 @@ private bool TryTranslateAsEnumerableExpression(
var translation = Dependencies.AggregateMethodCallTranslatorProvider.Translate(
_model, method, enumerableExpression, scalarArguments, _queryCompilationContext.Logger);

if (translation != null
&& method.DeclaringType == typeof(Queryable)
&& method.Name is nameof(Queryable.Count) or nameof(Queryable.LongCount)
&& enumerableExpression is { IsDistinct: true, Selector: SqlExpression distinctSelector }
&& MayBeNull(distinctSelector)
&& !(TryGetNullCheckedColumn(enumerableExpression.Predicate) is ColumnExpression checkedColumn
&& checkedColumn.Equals(distinctSelector)))
{
// COUNT(DISTINCT x) skips NULL, but LINQ's Distinct().Count() counts null as one more distinct value. Add one when
// the rows being counted contain a NULL. That is itself a distinct count, so it is 0 or 1 and never NULL.
// Null semantics may still find x non-nullable (a parameter, a predicate) and drop the WHEN, so the ELSE is a typed
// NULL: some databases (SQL Server) reject COUNT over an untyped NULL.
var isNull = _sqlExpressionFactory.IsNull(distinctSelector);
Comment thread
seragAhmed marked this conversation as resolved.
Resolved
var intTypeMapping = Dependencies.TypeMappingSource.FindMapping(typeof(int), Dependencies.Model);
var nullMarker = _sqlExpressionFactory.Case(
[
new CaseWhenClause(
enumerableExpression.Predicate is null
? isNull
: _sqlExpressionFactory.AndAlso(enumerableExpression.Predicate, isNull),
_sqlExpressionFactory.Constant(1, intTypeMapping))
],
elseResult: _sqlExpressionFactory.Convert(
_sqlExpressionFactory.Constant(null, typeof(int?), intTypeMapping), typeof(int), intTypeMapping));
var nullCount = Dependencies.AggregateMethodCallTranslatorProvider.Translate(
_model,
method,
new EnumerableExpression(nullMarker) { GroupingOwner = enumerableExpression.GroupingOwner }.SetDistinct(true),
scalarArguments,
_queryCompilationContext.Logger);

if (nullCount is null)
{
return null;
}

translation = _sqlExpressionFactory.Add(translation, nullCount);
}

// #27130: SQL evaluates an aggregate in the innermost query whose columns its argument references - or, when it references
// none (COUNT(*)), in the query it is written in. A grouping from an enclosing query stays in scope inside subqueries, so an
// aggregate over it isn't necessarily written in the query owning that grouping, and even one that is can name only columns
Expand Down Expand Up @@ -1933,6 +1972,33 @@ private bool TryTranslateAsEnumerableExpression(
} => column,
_ => null
};

// Whether a distinct count's operand can be NULL. Anything not known to be non-nullable is assumed nullable.
static bool MayBeNull(SqlExpression expression)
=> expression switch
{
ColumnExpression column => column.IsNullable,
SqlConstantExpression constant => constant.Value is null,
SqlFunctionExpression { IsBuiltIn: true, Name: "COALESCE", Arguments: { } coalesceArguments }
=> coalesceArguments.All(MayBeNull),
CaseExpression caseExpression
=> caseExpression.ElseResult is null
|| MayBeNull(caseExpression.ElseResult)
|| caseExpression.WhenClauses.Any(c => MayBeNull(c.Result)),
SqlFunctionExpression function
=> function.IsNullable
|| (function is { Arguments: { } arguments, ArgumentsPropagateNullability: { } propagate }
&& arguments.Where((argument, i) => propagate[i] && MayBeNull(argument)).Any()),
SqlUnaryExpression { OperatorType: ExpressionType.Convert or ExpressionType.Negate } unary => MayBeNull(unary.Operand),
SqlUnaryExpression { OperatorType: ExpressionType.Equal or ExpressionType.NotEqual } => false,
SqlBinaryExpression
{
OperatorType: ExpressionType.Add or ExpressionType.Subtract or ExpressionType.Multiply
or ExpressionType.Divide or ExpressionType.Modulo
} binary
=> MayBeNull(binary.Left) || MayBeNull(binary.Right),
_ => true
};
}

// An aggregate TranslateAggregateMethod refused to fold, with the GROUP BY of the query owning its grouping. The caller that owns
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2369,6 +2369,49 @@ public virtual Task GroupBy_Property_Select_Select_Distinct_Count_with_not_null_
.Select(g => new { g.Key, Count = g.Select(c => c.Region).Distinct().Count(r => r != null) }),
elementSorter: e => e.Key);

[Theory, MemberData(nameof(IsAsyncData))]
public virtual Task GroupBy_Property_Select_Distinct_Count_over_nullable_column(bool async)
=> AssertQuery(
async,
ss => ss.Set<Customer>()
.GroupBy(c => c.Country)
.Select(g => new
{
g.Key,
Count = g.Select(c => c.Region).Distinct().Count(),
LongCount = g.Select(c => c.Region).Distinct().LongCount()
}),
elementSorter: e => e.Key);

[Theory, MemberData(nameof(IsAsyncData))]
public virtual Task GroupBy_Property_Select_Distinct_Count_over_nullable_column_with_predicate(bool async)
=> AssertQuery(
async,
ss => ss.Set<Customer>()
.GroupBy(c => c.Country)
.Select(g => new
{
g.Key,
Count = g.Select(c => c.Region).Distinct().Count(r => r != "WA"),
LongCount = g.Where(c => c.City != "London").Select(c => c.Region).Distinct().LongCount()
}),
elementSorter: e => e.Key);

[Theory, MemberData(nameof(IsAsyncData))]
public virtual Task GroupBy_Property_Select_Distinct_Count_over_non_nullable_expression(bool async)
=> AssertQuery(
async,
ss => ss.Set<Customer>()
.GroupBy(c => c.Country)
.Select(g => new
{
g.Key,
Coalesced = g.Select(c => c.Region ?? "unknown").Distinct().Count(),
Conditional = g.Select(c => c.Region == null ? "none" : "some").Distinct().LongCount(),
NotNullFiltered = g.Where(c => c.Region != null && c.City != "London").Select(c => c.Region).Distinct().Count()
}),
elementSorter: e => e.Key);

[Theory, MemberData(nameof(IsAsyncData))]
public virtual Task GroupBy_Property_Select_Count_with_not_null_and_other_predicate(bool async)
=> AssertQuery(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2568,7 +2568,10 @@ public override async Task GroupBy_Select_Distinct_Any_with_nullable_element(boo

AssertSql(
"""
SELECT [o].[CustomerID] AS [Key], COUNT(DISTINCT ([o].[EmployeeID])) AS [Employees], CASE
SELECT [o].[CustomerID] AS [Key], COUNT(DISTINCT ([o].[EmployeeID])) + COUNT(DISTINCT (CASE
WHEN [o].[EmployeeID] IS NULL THEN 1
ELSE CAST(NULL AS int)
END)) AS [Employees], CASE
WHEN EXISTS (
SELECT 1
FROM [Orders] AS [o0]
Expand Down Expand Up @@ -2835,7 +2838,10 @@ public override async Task GroupBy_aggregate_through_navigation_with_distinct_co
"""
SELECT [o].[EmployeeID] AS [Key], MAX([c].[Region]) AS [Region], COUNT(CASE
WHEN [c].[City] = N'London' THEN 1
END) AS [Londons], COUNT(DISTINCT ([o].[CustomerID])) AS [Customers]
END) AS [Londons], COUNT(DISTINCT ([o].[CustomerID])) + COUNT(DISTINCT (CASE
WHEN [o].[CustomerID] IS NULL THEN 1
ELSE CAST(NULL AS int)
END)) AS [Customers]
FROM [Orders] AS [o]
LEFT JOIN [Customers] AS [c] ON [o].[CustomerID] = [c].[CustomerID]
GROUP BY [o].[EmployeeID]
Expand Down Expand Up @@ -3463,7 +3469,13 @@ public override async Task GroupBy_Select_Distinct_aggregate(bool async)

AssertSql(
"""
SELECT [o].[CustomerID] AS [Key], AVG(DISTINCT (CAST([o].[OrderID] AS float))) AS [Average], COUNT(DISTINCT ([o].[EmployeeID])) AS [Count], COUNT_BIG(DISTINCT ([o].[EmployeeID])) AS [LongCount], MAX([o].[OrderDate]) AS [Max], MIN([o].[OrderDate]) AS [Min], ISNULL(SUM(DISTINCT ([o].[OrderID])), 0) AS [Sum]
SELECT [o].[CustomerID] AS [Key], AVG(DISTINCT (CAST([o].[OrderID] AS float))) AS [Average], COUNT(DISTINCT ([o].[EmployeeID])) + COUNT(DISTINCT (CASE
WHEN [o].[EmployeeID] IS NULL THEN 1
ELSE CAST(NULL AS int)
END)) AS [Count], COUNT_BIG(DISTINCT ([o].[EmployeeID])) + COUNT_BIG(DISTINCT (CASE
WHEN [o].[EmployeeID] IS NULL THEN 1
ELSE CAST(NULL AS int)
END)) AS [LongCount], MAX([o].[OrderDate]) AS [Max], MIN([o].[OrderDate]) AS [Min], ISNULL(SUM(DISTINCT ([o].[OrderID])), 0) AS [Sum]
FROM [Orders] AS [o]
GROUP BY [o].[CustomerID]
""");
Expand Down Expand Up @@ -4011,6 +4023,61 @@ GROUP BY [c].[Country]
""");
}

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

AssertSql(
"""
SELECT [c].[Country] AS [Key], COUNT(DISTINCT ([c].[Region])) + COUNT(DISTINCT (CASE
WHEN [c].[Region] IS NULL THEN 1
ELSE CAST(NULL AS int)
END)) AS [Count], COUNT_BIG(DISTINCT ([c].[Region])) + COUNT_BIG(DISTINCT (CASE
WHEN [c].[Region] IS NULL THEN 1
ELSE CAST(NULL AS int)
END)) AS [LongCount]
FROM [Customers] AS [c]
GROUP BY [c].[Country]
""");
}

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

AssertSql(
"""
SELECT [c].[Country] AS [Key], COUNT(DISTINCT (NULLIF([c].[Region], N'WA'))) + COUNT(DISTINCT (CASE
WHEN ([c].[Region] <> N'WA' OR [c].[Region] IS NULL) AND [c].[Region] IS NULL THEN 1
ELSE CAST(NULL AS int)
END)) AS [Count], COUNT_BIG(DISTINCT (CASE
WHEN [c].[City] <> N'London' OR [c].[City] IS NULL THEN [c].[Region]
END)) + COUNT_BIG(DISTINCT (CASE
WHEN ([c].[City] <> N'London' OR [c].[City] IS NULL) AND [c].[Region] IS NULL THEN 1
ELSE CAST(NULL AS int)
END)) AS [LongCount]
FROM [Customers] AS [c]
GROUP BY [c].[Country]
""");
}

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

AssertSql(
"""
SELECT [c].[Country] AS [Key], COUNT(DISTINCT (COALESCE([c].[Region], N'unknown'))) AS [Coalesced], COUNT_BIG(DISTINCT (CASE
WHEN [c].[Region] IS NULL THEN N'none'
ELSE N'some'
END)) AS [Conditional], COUNT(DISTINCT (CASE
WHEN [c].[City] <> N'London' OR [c].[City] IS NULL THEN [c].[Region]
END)) + COUNT(DISTINCT (CAST(NULL AS int))) AS [NotNullFiltered]
FROM [Customers] AS [c]
GROUP BY [c].[Country]
""");
}

public override async Task GroupBy_Property_Select_Count_with_not_null_and_other_predicate(bool async)
{
await base.GroupBy_Property_Select_Count_with_not_null_and_other_predicate(async);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,61 @@ public override async Task GroupBy_selecting_grouping_element_list_with_captured
AssertSql();
}

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

AssertSql(
"""
SELECT "c"."Country" AS "Key", COUNT(DISTINCT ("c"."Region")) + COUNT(DISTINCT (CASE
WHEN "c"."Region" IS NULL THEN 1
ELSE CAST(NULL AS INTEGER)
END)) AS "Count", COUNT(DISTINCT ("c"."Region")) + COUNT(DISTINCT (CASE
WHEN "c"."Region" IS NULL THEN 1
ELSE CAST(NULL AS INTEGER)
END)) AS "LongCount"
FROM "Customers" AS "c"
GROUP BY "c"."Country"
""");
}

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

AssertSql(
"""
SELECT "c"."Country" AS "Key", COUNT(DISTINCT (NULLIF("c"."Region", 'WA'))) + COUNT(DISTINCT (CASE
WHEN ("c"."Region" <> 'WA' OR "c"."Region" IS NULL) AND "c"."Region" IS NULL THEN 1
ELSE CAST(NULL AS INTEGER)
END)) AS "Count", COUNT(DISTINCT (CASE
WHEN "c"."City" <> 'London' OR "c"."City" IS NULL THEN "c"."Region"
END)) + COUNT(DISTINCT (CASE
WHEN ("c"."City" <> 'London' OR "c"."City" IS NULL) AND "c"."Region" IS NULL THEN 1
ELSE CAST(NULL AS INTEGER)
END)) AS "LongCount"
FROM "Customers" AS "c"
GROUP BY "c"."Country"
""");
}

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

AssertSql(
"""
SELECT "c"."Country" AS "Key", COUNT(DISTINCT (COALESCE("c"."Region", 'unknown'))) AS "Coalesced", COUNT(DISTINCT (CASE
WHEN "c"."Region" IS NULL THEN 'none'
ELSE 'some'
END)) AS "Conditional", COUNT(DISTINCT (CASE
WHEN "c"."City" <> 'London' OR "c"."City" IS NULL THEN "c"."Region"
END)) + COUNT(DISTINCT (CAST(NULL AS INTEGER))) AS "NotNullFiltered"
FROM "Customers" AS "c"
GROUP BY "c"."Country"
""");
}

private void AssertSql(params string[] expected)
=> Fixture.TestSqlLoggerFactory.AssertBaseline(expected);

Expand Down
Loading