Repository navigation
Not planned
Not planned
Copy link
Description
| Environment | |
|---|---|
| PostgreSQL | 18.6 (postgres:18), session TimeZone Etc/UTC |
| .NET 10 | runtime 10.0.15, Npgsql.EntityFrameworkCore.PostgreSQL 10.0.4, EF Core 10.0.15, Npgsql 10.0.4 |
| .NET 11 | runtime 11.0.0, Npgsql.EntityFrameworkCore.PostgreSQL 11.0.0, EF Core 11.0.0, Npgsql 11.0.0 |
| Also | macOS arm64 |
Both lines print the same output. main at 9a76cd8 has the same code.
Split from #4094 at your request.
Without options, the pattern gets the p flag so that . doesn't match a newline, as in .NET. But p also stops a negated bracket from matching a newline, and .NET's [^x] does match \n.
| LINQ | Input | .NET | PostgreSQL | SQL |
|---|---|---|---|---|
Regex.IsMatch(r.Text, "a.b") |
a\nb |
no match | no match | r."Text" ~ '(?p)a.b' |
Regex.IsMatch(r.Text, "a[^x]b") |
a\nb |
match | no match | r."Text" ~ '(?p)a[^x]b' |
Repro
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;
await using var context = new TestContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();
context.Rows.Add(new Row { Text = "a\nb" });
await context.SaveChangesAsync();
var rows = await context.Rows.AsNoTracking().ToListAsync();
// Without RegexOptions.Singleline, . doesn't match \n but a negated bracket does
Console.WriteLine($"IsMatch(\"a\\nb\", \"a.b\"): .NET {rows.Count(r => Regex.IsMatch(r.Text, "a.b"))}, database {await context.Rows.CountAsync(r => Regex.IsMatch(r.Text, "a.b"))}");
Console.WriteLine($"IsMatch(\"a\\nb\", \"a[^x]b\"): .NET {rows.Count(r => Regex.IsMatch(r.Text, "a[^x]b"))}, database {await context.Rows.CountAsync(r => Regex.IsMatch(r.Text, "a[^x]b"))}");
public class TestContext : DbContext
{
public DbSet<Row> Rows => Set<Row>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseNpgsql(Environment.GetEnvironmentVariable("Test__Npgsql__DefaultConnection"))
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging();
}
public class Row
{
public int Id { get; set; }
public string Text { get; set; } = "";
}Output, the same on both lines:
IsMatch("a\nb", "a.b"): .NET 0, database 0
IsMatch("a\nb", "a[^x]b"): .NET 1, database 0
The flag is chosen at NpgsqlQuerySqlGenerator.cs#L1058-L1062. PostgreSQL has no flag where . excludes newlines but [^…] includes them (p and n restrict both, s and w neither), so matching .NET exactly would mean rewriting a constant pattern (. → [^\n] with no flag). If that's not wanted, a docs note on the regex translation would make the difference visible.
Metadata
Metadata
Assignees
Labels
No labels
Activity
roji commentedon Nov 25, 2026
AI Triage
The below is an AI-generated analysis and may contain inaccuracies.
Confirmed semantic mismatch in supported released Npgsql providers and current main. My recommendation is to document the dialect limitation rather than introduce automatic pattern rewriting for this issue. This is distinct from the simple combined-options mapping defect in #4155, now fixed by #4164.
Reproduction and regression status
An independent standalone console program, outside the provider checkout, reproduced the report against an isolated PostgreSQL 18.4 instance on macOS arm64, with connection timezone UTC:
a.bdatabase counta[^x]bdatabase count287351de397dc2889eb45ac0e0fc6e7250671c14For the same input
"a\nb", .NET returns false fora.b, but true fora[^x]b. Capturinga[^x]bin a variable instead of using a literal also returned database count 0 on all four versions.Thus this is not newly introduced in 10.0 or 11.0: it already reproduces on 8.0.8. No tested version worked; the original introduction and a last-known-good version were not established. PostgreSQL 18.6 and the reporter's .NET 10 runtime patch were not available, so those exact patches were not retested.
The released 10.0.4, 11.0.0 and main executions generated:
With a captured pattern:
Cause and other-provider comparison
Current SQL generation uses
pto keep dot from matching newline. PostgreSQL documents that this option also excludes newline from complemented bracket expressions. .NET instead defines dot and negative character groups separately.Direct PostgreSQL execution confirmed:
a.bmatches"a\nb"a[^x]bmatches"a\nb"pnswThere is no equivalent flag for .NET's default dot/bracket combination.
MultilinewithoutSinglelinehas the same bracket mismatch undern; fixing the combinedSingleline | Multilinecase does not fix this case.SQLite/EF Core 11.0 executed the exact two-argument queries and returned counts 0 for dot and 1 for the negative bracket, including a parameterized pattern. Its regex function calls .NET's implementation. This is therefore a PostgreSQL-provider semantic mismatch, not a demonstrated upstream EF query-pipeline defect.
No matching existing provider/upstream duplicate or fix was found in targeted searches. #4094 now concerns replacement syntax; #4155/#4164 concern combined options. #2585 changed SQL construction, not this semantic distinction. dotnet/efcore#22497 introduced SQLite translation, not a fix for this issue.
Fix feasibility
There are possible partial improvements, but no general flag-only correction:
pwould fix this example without a parser. However, an equivalent captured parameter would still behave differently, and mixed dot/bracket patterns remain wrong. Whether a literal-only improvement is worthwhile is an explicit compatibility/scope decision, not a complete solution.[^\n]and usings(wwith multiline anchors) can handle ordinary patterns. A lexical scanner is needed, notstring.Replace: direct probes showed that naive replacement changes workinga\.banda[.]binto nonmatching patterns. Escaped-backslash parity, bracket boundaries, POSIX bracket constructs, and comments/expanded syntax must be distinguished. .NET inline option scopes also change which dots need rewriting; PostgreSQL only supports embedded options at the start, not .NET's scoped/mid-pattern forms. These are existing dialect restrictions, not features a narrow improvement necessarily needs to implement, but rewriting must not silently reinterpret them.pand rewriting a negative bracket into a grouped newline alternative can work. It must preserve quantifiers and avoid introducing capturing groups. It must not add newline when the original class excludes it through\n,\s,\u000A, or a range: direct probes confirmed these classes should remain nonmatching. A lookahead-based reformulation can avoid computing class membership, but still needs correct class boundaries and produces more complex regexes.swould instead change existing wildcard-dot matches, while switching anchor modes would change line behavior.This would be a best-effort dialect adapter, not exact .NET parity. Even after a dot rewrite, other differences remain: for example, the direct probe
Regex.IsMatch("a\n", "^a$")is true in .NET but false under PostgreSQLpors, because of trailing-newline anchor treatment.Given the existing dynamic-pattern support and the narrow scope of this issue, documenting is preferable to a transparent constant-only rewrite or new runtime machinery.
Practical workarounds and suggested documentation
For the reported pattern, this preserves default dot/anchor settings and worked on all four provider executions:
This is an application-owned adjustment for a class known to allow newline, not an instruction to add newline to every negative class.
For application-owned patterns, another approach is
RegexOptions.Singlelinewith actual wildcard dots explicitly written as[^\n]. The probes confirmed botha[^x]bmatching newline anda[^\n]bexcluding it under that option. Singleline alone is not a general workaround, because it also changes ordinary dots. For exact .NET semantics, explicitly evaluate Regex on the client after suitable server-side narrowing, accepting the additional data transfer.Suggested note beside the regex entries/on the introduction of the translations page, whose source is npgsql/doc's
conceptual/EFCore.PG/mapping/translations.md:This is a longstanding limitation, so the conceptual translation documentation is the appropriate location, not a new-version fix note. No implementation, documentation edit, or closure is proposed as already performed.
minimal repro
Use
Npgsql.EntityFrameworkCore.PostgreSQL11.0.0 in anet11.0console project. SetTest__Npgsql__DefaultConnectionto a disposable PostgreSQL database: this program deletes and recreates it. The following compact program was also independently compiled and executed.Output:
roji commentedon Nov 25, 2026
Closing as not planned. This is a longstanding difference between PostgreSQL and .NET regular-expression semantics, which we will document rather than add automatic pattern rewriting.
PostgreSQL uses the
p/nmodes to prevent.from matching LF, but those modes also prevent negated character classes such as[^x]from matching LF. In .NET, a default-mode dot excludes LF while[^x]includes it. No PostgreSQL flag provides that combination; changing flags globally would fix this example but change existing wildcard-dot behavior.A pattern rewrite could improve some cases, but would require parsing escapes, character classes and options correctly, and handling constant, parameterized and database-derived patterns consistently. That would introduce substantial complexity and additional processing for only partial .NET compatibility, since other dialect differences would remain. A constant-only rewrite would also make equivalent literal and parameterized patterns behave differently. We do not consider those tradeoffs worthwhile for this issue.
The limitation and the supported options/overloads are documented in npgsql/doc#485, currently open. For this particular application-owned pattern,
a(?:[^x]|\n)bexplicitly allows LF without changing dot behavior; this is not a general rewrite for arbitrary negated classes. Use explicit client-side evaluation when exact .NET regex semantics are required.