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

Cosmos: Add translator for Regex.IsMatch method #28121

Merged
merged 4 commits into from
May 30, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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 @@ -33,7 +33,8 @@ public CosmosMethodCallTranslatorProvider(
new CosmosStringMethodTranslator(sqlExpressionFactory),
Marusyk marked this conversation as resolved.
Show resolved Hide resolved
new ContainsTranslator(sqlExpressionFactory),
new RandomTranslator(sqlExpressionFactory),
new MathTranslator(sqlExpressionFactory)
new MathTranslator(sqlExpressionFactory),
new RegexMethodTranslator(sqlExpressionFactory)
//new LikeTranslator(sqlExpressionFactory),
//new EnumHasFlagTranslator(sqlExpressionFactory),
//new GetValueOrDefaultTranslator(sqlExpressionFactory),
Expand Down
94 changes: 94 additions & 0 deletions src/EFCore.Cosmos/Query/Internal/RegexMethodTranslator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Text.RegularExpressions;

namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal;

/// <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 class RegexMethodTranslator : IMethodCallTranslator
{
private static readonly MethodInfo IsMatch =
typeof(Regex).GetRuntimeMethod(nameof(Regex.IsMatch), new[] { typeof(string), typeof(string) })!;

private static readonly MethodInfo IsMatchWithRegexOptions =
typeof(Regex).GetRuntimeMethod(nameof(Regex.IsMatch), new[] { typeof(string), typeof(string), typeof(RegexOptions) })!;

private static readonly ISet<RegexOptions> AllowedOptions = new HashSet<RegexOptions>
Marusyk marked this conversation as resolved.
Show resolved Hide resolved
{
RegexOptions.None,
RegexOptions.IgnoreCase,
RegexOptions.Multiline,
RegexOptions.Singleline,
RegexOptions.IgnorePatternWhitespace
};

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 RegexMethodTranslator(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
/// 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 virtual SqlExpression? Translate(
SqlExpression? instance,
MethodInfo method,
IReadOnlyList<SqlExpression> arguments,
IDiagnosticsLogger<DbLoggerCategory.Query> logger)
{
if (method != IsMatch && method != IsMatchWithRegexOptions)
{
return null;
}

RegexOptions options;
if (method == IsMatch)
{
options = RegexOptions.None;
}
else if (arguments[2] is SqlConstantExpression { Value: RegexOptions regexOptions }
&& AllowedOptions.Contains(regexOptions))
{
options = regexOptions;
}
else
{
return null;
}

string modifier = options switch
Marusyk marked this conversation as resolved.
Show resolved Hide resolved
{
RegexOptions.Multiline => "m",
RegexOptions.Singleline => "s",
RegexOptions.IgnoreCase => "i",
RegexOptions.IgnorePatternWhitespace => "x",
_ => ""
};

var (input, pattern) = (arguments[0], arguments[1]);
var stringTypeMapping = ExpressionExtensions.InferTypeMapping(input, pattern);
Marusyk marked this conversation as resolved.
Show resolved Hide resolved

return _sqlExpressionFactory.Function(
"RegexMatch",
new[] { input, pattern, _sqlExpressionFactory.Constant(modifier) },
Marusyk marked this conversation as resolved.
Show resolved Hide resolved
method.ReturnType,
stringTypeMapping);
}
}
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 System.Text.RegularExpressions;
using Microsoft.Azure.Cosmos;
using Microsoft.EntityFrameworkCore.TestModels.Northwind;

Expand Down Expand Up @@ -1204,20 +1205,104 @@ public override async Task Int_Compare_to_simple_zero(bool async)

public override async Task Regex_IsMatch_MethodCall(bool async)
{
// Cosmos client evaluation. Issue #17246.
await AssertTranslationFailed(() => base.Regex_IsMatch_MethodCall(async));
await base.Regex_IsMatch_MethodCall(async);

AssertSql();
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND RegexMatch(c[""CustomerID""], ""^T"", """"))");
}

public override async Task Regex_IsMatch_MethodCall_constant_input(bool async)
{
// Cosmos client evaluation. Issue #17246.
await AssertTranslationFailed(() => base.Regex_IsMatch_MethodCall_constant_input(async));
await base.Regex_IsMatch_MethodCall_constant_input(async);

AssertSql();
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND RegexMatch(""ALFKI"", c[""CustomerID""], """"))");
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Regex_IsMatch_MethodCall_With_Option_None(bool async)
{
await AssertQuery(
async,
ss => ss.Set<Customer>().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.None)),
entryCount: 6);

AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND RegexMatch(c[""CustomerID""], ""^T"", """"))");
Copy link
Contributor

Choose a reason for hiding this comment

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

do we need to print last argument if options are none?

Copy link
Member Author

@Marusyk Marusyk Jun 1, 2022

Choose a reason for hiding this comment

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

IMO, yes. If Cosmos allows it and a user specifically indicated None, then why not. Clear behavior.
Of course I can change it if you want

Copy link
Member

Choose a reason for hiding this comment

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

I'd go with Smit's suggestion, always better to emit clearer, more concise SQL. Added to #28139.

Copy link
Member Author

@Marusyk Marusyk Jun 2, 2022

Choose a reason for hiding this comment

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

ok, please assign 28139 to me

}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Regex_IsMatch_MethodCall_With_Option_IgnoreCase(bool async)
{
await AssertQuery(
async,
ss => ss.Set<Customer>().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.IgnoreCase)),
entryCount: 6);

AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND RegexMatch(c[""CustomerID""], ""^T"", ""i""))");
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Regex_IsMatch_MethodCall_With_Option_Multiline(bool async)
{
await AssertQuery(
async,
ss => ss.Set<Customer>().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.Multiline)),
entryCount: 6);

AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND RegexMatch(c[""CustomerID""], ""^T"", ""m""))");
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Regex_IsMatch_MethodCall_With_Option_Singleline(bool async)
{
await AssertQuery(
async,
ss => ss.Set<Customer>().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.Singleline)),
entryCount: 6);

AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND RegexMatch(c[""CustomerID""], ""^T"", ""s""))");
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Regex_IsMatch_MethodCall_With_Option_IgnorePatternWhitespace(bool async)
{
await AssertQuery(
async,
ss => ss.Set<Customer>().Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.IgnorePatternWhitespace)),
entryCount: 6);

AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND RegexMatch(c[""CustomerID""], ""^T"", ""x""))");
}

[Fact]
Copy link
Contributor

Choose a reason for hiding this comment

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

ConditionalTheory
sync/async both version
Use AssertQuery syntax

cc: @roji

Copy link
Member

Choose a reason for hiding this comment

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

Yep, doing as part of #28139

public void Regex_IsMatchOptionsUnsupported()
=> Assert.Throws<InvalidOperationException>(() =>
Fixture.CreateContext().Customers.Where(o => Regex.IsMatch(o.CustomerID, "^T", RegexOptions.RightToLeft)).ToList());

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Case_insensitive_string_comparison_instance(bool async)
Expand Down