From d316b35b6cf33279f23a0cb87edff2ca5e549a52 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Thu, 26 Sep 2024 22:00:51 +0200 Subject: [PATCH] Properly escape constant regex patterns (#3299) Fixes #3292 --- .../Query/Internal/NpgsqlQuerySqlGenerator.cs | 2 +- .../Query/NorthwindFunctionsQueryNpgsqlTest.cs | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/EFCore.PG/Query/Internal/NpgsqlQuerySqlGenerator.cs b/src/EFCore.PG/Query/Internal/NpgsqlQuerySqlGenerator.cs index 3418d5045..5c1ed24f1 100644 --- a/src/EFCore.PG/Query/Internal/NpgsqlQuerySqlGenerator.cs +++ b/src/EFCore.PG/Query/Internal/NpgsqlQuerySqlGenerator.cs @@ -987,7 +987,7 @@ protected virtual Expression VisitRegexMatch(PgRegexMatchExpression expression, } else { - Sql.Append(constantPattern); + Sql.Append(constantPattern.Replace("'", "''")); Sql.Append("'"); } diff --git a/test/EFCore.PG.FunctionalTests/Query/NorthwindFunctionsQueryNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/Query/NorthwindFunctionsQueryNpgsqlTest.cs index f522b5ac4..43c78f8c2 100644 --- a/test/EFCore.PG.FunctionalTests/Query/NorthwindFunctionsQueryNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/NorthwindFunctionsQueryNpgsqlTest.cs @@ -111,6 +111,23 @@ await AssertQuery( """); } + [Theory] + [MemberData(nameof(IsAsyncData))] + public async Task Regex_IsMatch_with_constant_pattern_properly_escaped(bool async) + { + await AssertQuery( + async, + cs => cs.Set().Where(c => Regex.IsMatch(c.CompanyName, "^A';foo")), + assertEmpty: true); + + 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 c."CompanyName" ~ '(?p)^A'';foo' +"""); + } + [Theory] [MemberData(nameof(IsAsyncData))] public async Task Regex_IsMatch_with_parameter_pattern(bool async)