Skip to content

Commit

Permalink
Optimize string.IndexOf(string, int) translation when startIndex
Browse files Browse the repository at this point in the history
…is a constant (#1652)
  • Loading branch information
LeaFrock authored May 21, 2022
1 parent 43896e5 commit bd970d6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -622,9 +622,12 @@ private SqlExpression CharLength(SqlExpression value)

private SqlExpression Locate(SqlExpression sub, SqlExpression str, SqlExpression startIndex = null)
{
var args = startIndex is null
? new SqlExpression[] { sub, str }
: new SqlExpression[] { sub, str, _sqlExpressionFactory.Add(startIndex, _sqlExpressionFactory.Constant(1)) };
var args = startIndex switch
{
null => new SqlExpression[] { sub, str },
SqlConstantExpression { Value:int idx } => new SqlExpression[] { sub, str, _sqlExpressionFactory.Constant(idx + 1) },
_ => new SqlExpression[] { sub, str, _sqlExpressionFactory.Add(startIndex, _sqlExpressionFactory.Constant(1)) }
};
return _sqlExpressionFactory.NullableFunction("LOCATE", args, typeof(int));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -705,12 +705,27 @@ ELSE LOCATE(CONVERT(LCASE('nt') USING utf8mb4) COLLATE utf8mb4_bin, LCASE(`c`.`C
END = 1");
}

[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public async Task StringIndexOf_with_constant_start_index(bool async)
{
await AssertQuery(
async,
ss => ss.Set<Customer>().Where(c => c.CustomerID.IndexOf("nt", 0, StringComparison.OrdinalIgnoreCase) == 1),
entryCount: 1);

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 (LOCATE(CONVERT(LCASE('nt') USING utf8mb4) COLLATE utf8mb4_bin, LCASE(`c`.`CustomerID`), 1) - 1) = 1");
}

[ConditionalTheory]
[InlineData(0, 1, false)]
[InlineData(2, 0, false)]
[InlineData(0, 1, true)]
[InlineData(2, 0, true)]
public async Task StringIndexOf_with_start_index(int startIndex, int expected, bool async)
public async Task StringIndexOf_with_parameter_start_index(int startIndex, int expected, bool async)
{
await AssertQuery(
async,
Expand Down

0 comments on commit bd970d6

Please sign in to comment.