From abfc5844a64c3e6403ab3cd558f5a568ee52ae49 Mon Sep 17 00:00:00 2001 From: Andrea Canciani Date: Tue, 4 Jun 2024 02:12:27 +0200 Subject: [PATCH] Minor improvement of `SqlServerParameterBasedSqlProcessor.Optimize` (#33758) * Collapse `Take 0` before optimizing the expression This opens up some additional query optimization opportunities. --- .../SqlServerParameterBasedSqlProcessor.cs | 6 +++--- .../NorthwindMiscellaneousQuerySqlServerTest.cs | 16 ++-------------- 2 files changed, 5 insertions(+), 17 deletions(-) diff --git a/src/EFCore.SqlServer/Query/Internal/SqlServerParameterBasedSqlProcessor.cs b/src/EFCore.SqlServer/Query/Internal/SqlServerParameterBasedSqlProcessor.cs index bae646eed78..17b97fdb119 100644 --- a/src/EFCore.SqlServer/Query/Internal/SqlServerParameterBasedSqlProcessor.cs +++ b/src/EFCore.SqlServer/Query/Internal/SqlServerParameterBasedSqlProcessor.cs @@ -35,10 +35,10 @@ public override Expression Optimize( IReadOnlyDictionary parametersValues, out bool canCache) { - var optimizedQueryExpression = base.Optimize(queryExpression, parametersValues, out canCache); + var optimizedQueryExpression = new SkipTakeCollapsingExpressionVisitor(Dependencies.SqlExpressionFactory) + .Process(queryExpression, parametersValues, out var canCache2); - optimizedQueryExpression = new SkipTakeCollapsingExpressionVisitor(Dependencies.SqlExpressionFactory) - .Process(optimizedQueryExpression, parametersValues, out var canCache2); + optimizedQueryExpression = base.Optimize(optimizedQueryExpression, parametersValues, out canCache); canCache &= canCache2; diff --git a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindMiscellaneousQuerySqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindMiscellaneousQuerySqlServerTest.cs index 4b321787455..58361815d19 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindMiscellaneousQuerySqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Query/NorthwindMiscellaneousQuerySqlServerTest.cs @@ -5925,13 +5925,7 @@ public override async Task Skip_0_Take_0_works_when_constant(bool async) AssertSql( """ -SELECT CASE - WHEN EXISTS ( - SELECT 1 - FROM [Orders] AS [o] - WHERE 0 = 1) THEN CAST(1 AS bit) - ELSE CAST(0 AS bit) -END +SELECT CAST(0 AS bit) FROM [Customers] AS [c] WHERE [c].[CustomerID] LIKE N'F%' ORDER BY [c].[CustomerID] @@ -5944,13 +5938,7 @@ public override async Task Skip_1_Take_0_works_when_constant(bool async) AssertSql( """ -SELECT CASE - WHEN EXISTS ( - SELECT 1 - FROM [Orders] AS [o] - WHERE 0 = 1) THEN CAST(1 AS bit) - ELSE CAST(0 AS bit) -END +SELECT CAST(0 AS bit) FROM [Customers] AS [c] WHERE [c].[CustomerID] LIKE N'F%' ORDER BY [c].[CustomerID]