Skip to content
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

TrimStart and TrimEnd with optional char array implementation for SQL Server #33715

Merged
merged 14 commits into from
Jun 20, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
8 changes: 8 additions & 0 deletions src/EFCore.SqlServer/Properties/SqlServerStrings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/EFCore.SqlServer/Properties/SqlServerStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -362,4 +362,7 @@
<data name="TransientExceptionDetected" xml:space="preserve">
<value>An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure' to the 'UseSqlServer' call.</value>
</data>
<data name="TrimStartTrimEndWithArgsCompatibilityLevelTooLow" xml:space="preserve">
<value>EF Core's SQL Server compatibility level is set to {compatibilityLevel}; compatibility level 160 (SQL Server 2022) is the minimum for functions LTRIM and RTRIM with the optional characters positional argument.</value>
</data>
</root>
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal;
abdielcs marked this conversation as resolved.
Show resolved Hide resolved
using Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.Translators;

namespace Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;
Expand All @@ -19,7 +20,7 @@ public class SqlServerMethodCallTranslatorProvider : RelationalMethodCallTransla
/// 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 SqlServerMethodCallTranslatorProvider(RelationalMethodCallTranslatorProviderDependencies dependencies)
public SqlServerMethodCallTranslatorProvider(RelationalMethodCallTranslatorProviderDependencies dependencies, ISqlServerSingletonOptions sqlServerSingletonOptions)
: base(dependencies)
{
var sqlExpressionFactory = dependencies.SqlExpressionFactory;
Expand All @@ -39,7 +40,7 @@ public SqlServerMethodCallTranslatorProvider(RelationalMethodCallTranslatorProvi
new SqlServerMathTranslator(sqlExpressionFactory),
new SqlServerNewGuidTranslator(sqlExpressionFactory),
new SqlServerObjectToStringTranslator(sqlExpressionFactory, typeMappingSource),
new SqlServerStringMethodTranslator(sqlExpressionFactory),
new SqlServerStringMethodTranslator(sqlExpressionFactory, sqlServerSingletonOptions),
new SqlServerTimeOnlyMethodTranslator(sqlExpressionFactory)
]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal;
using Microsoft.EntityFrameworkCore.SqlServer.Internal;
using ExpressionExtensions = Microsoft.EntityFrameworkCore.Query.ExpressionExtensions;

namespace Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.Translators;
Expand Down Expand Up @@ -61,6 +63,12 @@ private static readonly MethodInfo TrimEndMethodInfoWithCharArrayArg
private static readonly MethodInfo TrimMethodInfoWithCharArrayArg
= typeof(string).GetRuntimeMethod(nameof(string.Trim), [typeof(char[])])!;

private static readonly MethodInfo TrimStartMethodInfoWithCharArg
= typeof(string).GetRuntimeMethod(nameof(string.TrimStart), [typeof(char)])!;

private static readonly MethodInfo TrimEndMethodInfoWithCharArg
= typeof(string).GetRuntimeMethod(nameof(string.TrimEnd), [typeof(char)])!;

private static readonly MethodInfo FirstOrDefaultMethodInfoWithoutArgs
= typeof(Enumerable).GetRuntimeMethods().Single(
m => m.Name == nameof(Enumerable.FirstOrDefault)
Expand All @@ -73,15 +81,19 @@ private static readonly MethodInfo LastOrDefaultMethodInfoWithoutArgs

private readonly ISqlExpressionFactory _sqlExpressionFactory;

private readonly ISqlServerSingletonOptions _sqlServerSingletonOptions;

/// <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 SqlServerStringMethodTranslator(ISqlExpressionFactory sqlExpressionFactory)
public SqlServerStringMethodTranslator(ISqlExpressionFactory sqlExpressionFactory, ISqlServerSingletonOptions sqlServerSingletonOptions)
{
_sqlExpressionFactory = sqlExpressionFactory;

_sqlServerSingletonOptions = sqlServerSingletonOptions;
}

/// <summary>
Expand Down Expand Up @@ -182,7 +194,6 @@ public SqlServerStringMethodTranslator(ISqlExpressionFactory sqlExpressionFactor

if (TrimStartMethodInfoWithoutArgs.Equals(method)
|| (TrimStartMethodInfoWithCharArrayArg.Equals(method)
// SqlServer LTRIM does not take arguments
&& ((arguments[0] as SqlConstantExpression)?.Value as Array)?.Length == 0))
{
return _sqlExpressionFactory.Function(
Expand All @@ -194,9 +205,35 @@ public SqlServerStringMethodTranslator(ISqlExpressionFactory sqlExpressionFactor
instance.TypeMapping);
}

if (TrimStartMethodInfoWithCharArg.Equals(method)
&& CheckTrimStartTrimEndWithArgsCompatibilityLevel())
{
return _sqlExpressionFactory.Function(
"LTRIM",
new[] { instance, arguments[0] },
nullable: true,
argumentsPropagateNullability: new[] { true, true },
instance.Type,
instance.TypeMapping);
}

if (TrimStartMethodInfoWithCharArrayArg.Equals(method)
&& CheckTrimStartTrimEndWithArgsCompatibilityLevel())
{
var firstArgumentValue = (arguments[0] as SqlConstantExpression)?.Value as char[];
abdielcs marked this conversation as resolved.
Show resolved Hide resolved
var firstArgument = _sqlExpressionFactory.Constant(new string(firstArgumentValue), instance.TypeMapping);

return _sqlExpressionFactory.Function(
"LTRIM",
new[] { instance, firstArgument },
nullable: true,
argumentsPropagateNullability: new[] { true, true },
instance.Type,
instance.TypeMapping);
}

if (TrimEndMethodInfoWithoutArgs.Equals(method)
|| (TrimEndMethodInfoWithCharArrayArg.Equals(method)
// SqlServer RTRIM does not take arguments
&& ((arguments[0] as SqlConstantExpression)?.Value as Array)?.Length == 0))
{
return _sqlExpressionFactory.Function(
Expand All @@ -208,6 +245,34 @@ public SqlServerStringMethodTranslator(ISqlExpressionFactory sqlExpressionFactor
instance.TypeMapping);
}


if (TrimEndMethodInfoWithCharArg.Equals(method)
&& CheckTrimStartTrimEndWithArgsCompatibilityLevel())
{
return _sqlExpressionFactory.Function(
"RTRIM",
new[] { instance, arguments[0] },
nullable: true,
argumentsPropagateNullability: new[] { true, true },
instance.Type,
instance.TypeMapping);
}

if (TrimEndMethodInfoWithCharArrayArg.Equals(method)
&& CheckTrimStartTrimEndWithArgsCompatibilityLevel())
{
var firstArgumentValue = (arguments[0] as SqlConstantExpression)?.Value as char[];
var firstArgument = _sqlExpressionFactory.Constant(new string(firstArgumentValue), instance.TypeMapping);

return _sqlExpressionFactory.Function(
"RTRIM",
new[] { instance, firstArgument },
nullable: true,
argumentsPropagateNullability: new[] { true, true },
instance.Type,
instance.TypeMapping);
}

if (TrimMethodInfoWithoutArgs.Equals(method)
|| (TrimMethodInfoWithCharArrayArg.Equals(method)
// SqlServer LTRIM/RTRIM does not take arguments
Expand Down Expand Up @@ -357,4 +422,16 @@ private SqlExpression TranslateIndexOf(
},
charIndexExpression);
}

private bool CheckTrimStartTrimEndWithArgsCompatibilityLevel()
=> CheckCompatibilityLevel(160, SqlServerStrings.TrimStartTrimEndWithArgsCompatibilityLevelTooLow);

private bool CheckCompatibilityLevel(int compatibilityLevel, Func<object?, string> compatibilityTooLowFunction)
{
if (_sqlServerSingletonOptions.CompatibilityLevel < compatibilityLevel)
{
throw new InvalidOperationException(compatibilityTooLowFunction(compatibilityLevel));
abdielcs marked this conversation as resolved.
Show resolved Hide resolved
}
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2540,20 +2540,30 @@ WHERE LTRIM([c].[ContactTitle]) = N'Owner'
""");
}

[SqlServerCondition(SqlServerCondition.SupportsFunctions2022)]
public override async Task TrimStart_with_char_argument_in_predicate(bool async)
{
// String.Trim with parameters. Issue #22927.
await AssertTranslationFailed(() => base.TrimStart_with_char_argument_in_predicate(async));
await base.TrimStart_with_char_argument_in_predicate(async);

AssertSql();
AssertSql(
"""
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE LTRIM([c].[ContactTitle], N'O') = N'wner'
""");
}

[SqlServerCondition(SqlServerCondition.SupportsFunctions2022)]
public override async Task TrimStart_with_char_array_argument_in_predicate(bool async)
{
// String.Trim with parameters. Issue #22927.
await AssertTranslationFailed(() => base.TrimStart_with_char_array_argument_in_predicate(async));
await base.TrimStart_with_char_array_argument_in_predicate(async);

AssertSql();
AssertSql(
"""
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE LTRIM([c].[ContactTitle], N'Ow') = N'ner'
""");
}

public override async Task TrimEnd_without_arguments_in_predicate(bool async)
Expand All @@ -2568,20 +2578,30 @@ WHERE RTRIM([c].[ContactTitle]) = N'Owner'
""");
}

[SqlServerCondition(SqlServerCondition.SupportsFunctions2022)]
public override async Task TrimEnd_with_char_argument_in_predicate(bool async)
{
// String.Trim with parameters. Issue #22927.
await AssertTranslationFailed(() => base.TrimEnd_with_char_argument_in_predicate(async));
await base.TrimEnd_with_char_argument_in_predicate(async);

AssertSql();
AssertSql(
"""
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE RTRIM([c].[ContactTitle], N'r') = N'Owne'
""");
}

[SqlServerCondition(SqlServerCondition.SupportsFunctions2022)]
public override async Task TrimEnd_with_char_array_argument_in_predicate(bool async)
{
// String.Trim with parameters. Issue #22927.
await AssertTranslationFailed(() => base.TrimEnd_with_char_array_argument_in_predicate(async));
await base.TrimEnd_with_char_array_argument_in_predicate(async);

AssertSql();
AssertSql(
"""
SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE RTRIM([c].[ContactTitle], N'er') = N'Own'
""");
}

public override async Task Trim_without_argument_in_predicate(bool async)
Expand Down
Loading