Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using System.Text.RegularExpressions;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Scaffolding.Metadata;
Expand Down Expand Up @@ -874,7 +875,12 @@ protected virtual ModelBuilder VisitForeignKeys(
var dependentIndexes = dependentEntityType.GetIndexes()
.Where(i => i.Properties.SequenceEqual(dependentProperties));
newForeignKey.IsUnique = dependentKey != null
|| dependentIndexes.Any(i => i.IsUnique);
|| dependentIndexes.Any(
i => i.IsUnique
&& !HasRowRestrictingFilter(
i.GetFilter(),
foreignKey.Columns.Select(c => c.Name),
foreignKey.Table.Columns.Select(c => c.Name)));

if (!string.IsNullOrEmpty(foreignKey.Name)
&& foreignKey.Name != newForeignKey.GetDefaultName())
Expand All @@ -889,6 +895,89 @@ protected virtual ModelBuilder VisitForeignKeys(
return newForeignKey;
}

private const string NullGuardTerm =
"""(?:\[(?<bracket>(?:[^\]]|\]\])+)\]|"(?<quote>(?:[^"]|"")+)"|`(?<backtick>(?:[^`]|``)+)`|(?<bare>[\p{L}_][\p{L}\p{N}_$]*))\s+IS\s+NOT\s+NULL""";

private static readonly Regex NullGuardTermRegex = new(
NullGuardTerm,
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant,
TimeSpan.FromMilliseconds(1000.0));

private static readonly Regex NullGuardFilterRegex = new(
$@"^[\s(]*{NullGuardTerm}(?:[\s)]*\sAND\s[\s(]*{NullGuardTerm})*[\s)]*$",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant,
TimeSpan.FromMilliseconds(1000.0));

// A unique index with a filter only guarantees uniqueness for the rows that satisfy the filter, so it does not make the
// foreign key one-to-one. The exception is a filter that only excludes rows where the foreign key columns are null:
// those rows don't take part in the relationship, and this is the filter that providers generate by convention
// for unique indexes over nullable columns. Parsing arbitrary SQL is out of scope, so only this exact shape is
// recognized; anything else is assumed to restrict the rows. Wrongly assuming a restriction results in a collection
// navigation, which works for any data, while wrongly assuming uniqueness results in a reference navigation that
// throws when multiple dependents exist.
// The names in the filter are resolved against all the columns of the table, not just the foreign key columns, because
// case-sensitive databases can have columns that differ only by case, and the filter could refer to a different one.
private static bool HasRowRestrictingFilter(
string? filter,
IEnumerable<string> foreignKeyColumns,
IEnumerable<string> tableColumns)
{
if (string.IsNullOrWhiteSpace(filter))
{
return false;
}

try
{
if (!NullGuardFilterRegex.IsMatch(filter))
{
return true;
}

var foreignKeyColumnSet = foreignKeyColumns.ToHashSet(StringComparer.Ordinal);
var tableColumnList = tableColumns.ToList();
foreach (Match match in NullGuardTermRegex.Matches(filter))
{
var name = match.Groups["bracket"].Success
? match.Groups["bracket"].Value.Replace("]]", "]")
: match.Groups["quote"].Success
? match.Groups["quote"].Value.Replace("\"\"", "\"")
: match.Groups["backtick"].Success
? match.Groups["backtick"].Value.Replace("``", "`")
: match.Groups["bare"].Value;

// A bare NULL is the keyword, which makes the predicate always false, not a column.
if (match.Groups["bare"].Success
&& name.Equals("NULL", StringComparison.OrdinalIgnoreCase))
{
return true;
}

// Prefer the exact name. Only fall back to ignoring case if that identifies a single column, since databases
// that are not case-sensitive resolve names this way and an ambiguous name can't be attributed to a column.
var column = tableColumnList.Contains(name, StringComparer.Ordinal)
? name
: tableColumnList.Where(c => string.Equals(c, name, StringComparison.OrdinalIgnoreCase)).ToList()
is [var single]
? single
: null;

if (column == null
|| !foreignKeyColumnSet.Contains(column))
{
return true;
}
}

return false;
}
catch (RegexMatchTimeoutException)
{
// Not something we can recognize, so assume that it restricts the rows.
return true;
}
}

/// <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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1039,7 +1039,7 @@ private void GetIndexes(DbConnection connection, DatabaseTable table)
using var command1 = connection.CreateCommand();
command1.CommandText =
"""
SELECT "name", "unique"
SELECT "name", "unique", "partial"
FROM pragma_index_list(@table)
WHERE "origin" = 'c' AND instr("name", 'sqlite_') <> 1
ORDER BY "seq"
Expand All @@ -1060,6 +1060,29 @@ ORDER BY "seq"
IsUnique = reader1.GetBoolean(1)
};

if (reader1.GetBoolean(2))
{
using var command3 = connection.CreateCommand();
command3.CommandText =
"""
SELECT "sql"
FROM "sqlite_master"
WHERE "type" = 'index' AND "name" = @index AND "tbl_name" = @table
""";

var parameter3 = command3.CreateParameter();
parameter3.ParameterName = "@index";
parameter3.Value = index.Name;
command3.Parameters.Add(parameter3);

var parameter4 = command3.CreateParameter();
parameter4.ParameterName = "@table";
parameter4.Value = table.Name;
command3.Parameters.Add(parameter4);

index.Filter = GetIndexFilter(command3.ExecuteScalar() as string);
}

_logger.IndexFound(index.Name, table.Name, index.IsUnique);

var isExpressionIndex = false;
Expand Down Expand Up @@ -1108,6 +1131,109 @@ ORDER BY "seqno"
}
}

// SQLite stores the CREATE INDEX statement as written, so the filter is the text following the first WHERE keyword that is
// outside of quotes, comments and parentheses. Nothing before the filter can be an unquoted WHERE (it is a reserved word),
// and parentheses only occur in the column list, so this doesn't need to understand the rest of the statement.
// Comments are dropped from the filter, since they are not part of the expression and a line comment could otherwise
// swallow whatever is appended to the filter later. Callers should only call this for indexes that SQLite reports as partial.
private static string? GetIndexFilter(string? sql)
{
if (sql == null)
{
return null;
}

StringBuilder? filter = null;
var depth = 0;
for (var i = 0; i < sql.Length; i++)
{
var c = sql[i];
switch (c)
{
case '\'' or '"' or '`' or '[':
{
var end = c == '[' ? sql.IndexOf(']', i + 1) : SkipQuoted(sql, i);
if (end < 0)
{
return null;
}

filter?.Append(sql, i, end - i + 1);
i = end;
break;
}
case '-' when i + 1 < sql.Length && sql[i + 1] == '-':
{
// The line break (if any) is left for the next iteration
var end = sql.IndexOf('\n', i + 2);
filter?.Append(' ');
i = end < 0 ? sql.Length : end - 1;
break;
}
case '/' when i + 1 < sql.Length && sql[i + 1] == '*':
{
// An unterminated block comment runs to the end of the statement
var end = sql.IndexOf("*/", i + 2, StringComparison.Ordinal);
filter?.Append(' ');
i = end < 0 ? sql.Length : end + 1;
break;
}
case 'W' or 'w' when filter == null
&& depth == 0
&& (i == 0 || !IsIdentifierChar(sql[i - 1]))
&& string.Compare(sql, i, "WHERE", 0, 5, StringComparison.OrdinalIgnoreCase) == 0
&& (i + 5 == sql.Length || !IsIdentifierChar(sql[i + 5])):
filter = new StringBuilder();
i += 4;
break;
default:
if (filter != null)
{
filter.Append(c);
}
else if (c == '(')
{
depth++;
}
else if (c == ')')
{
depth--;
}

break;
}
}

return filter?.ToString().Trim() is { Length: > 0 } result ? result : null;

// SQLite allows every non-ASCII character in an unquoted identifier, not just letters and digits.
static bool IsIdentifierChar(char c)
=> c >= '\u0080' || char.IsLetterOrDigit(c) || c is '_' or '$';

// Returns the index of the closing quote, or -1 if there isn't one. A doubled quote is an escaped quote.
static int SkipQuoted(string sql, int start)
{
var quote = sql[start];
for (var i = start + 1; i < sql.Length; i++)
{
if (sql[i] != quote)
{
continue;
}

if (i + 1 < sql.Length && sql[i + 1] == quote)
{
i++;
continue;
}

return i;
}

return -1;
}
}

private void GetForeignKeys(DbConnection connection, DatabaseTable table, IList<DatabaseTable> tables)
{
using var command1 = connection.CreateCommand();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,68 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
model =>
Assert.Equal(2, model.FindEntityType("TestNamespace.EntityWithIndexes")!.GetIndexes().Count()));

[Fact]
public Task Index_filter_with_quotes_line_breaks_and_braces_is_escaped()
=> TestAsync(
modelBuilder => modelBuilder
.Entity(
"EntityWithFilteredIndex",
x =>
{
x.Property<int>("Id");
x.Property<string>("A");
x.HasKey("Id");
x.HasIndex(["A"], "IndexOnA")
.IsUnique()
.HasFilter("\"A\" = 'a\"b' -- {c}\r\n AND A <> '{'");
}),
new ModelCodeGenerationOptions { UseDataAnnotations = false },
code => AssertFileContents(
$$"""
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

namespace TestNamespace;

public partial class TestDbContext : DbContext
{
public TestDbContext()
{
}

public TestDbContext(DbContextOptions<TestDbContext> options)
: base(options)
{
}

public virtual DbSet<EntityWithFilteredIndex> EntityWithFilteredIndex { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
#warning {{DesignStrings.SensitiveInformationWarning}}
=> optionsBuilder.UseSqlServer("Initial Catalog=TestDatabase");

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EntityWithFilteredIndex>(entity =>
{
entity.HasIndex(e => e.A, "IndexOnA")
.IsUnique()
.HasFilter("\"A\" = 'a\"b' -- {c}\r\n AND A <> '{'");
});

OnModelCreatingPartial(modelBuilder);
}

partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
""",
code.ContextFile),
model =>
Assert.Equal(
"\"A\" = 'a\"b' -- {c}\r\n AND A <> '{'",
model.FindEntityType("TestNamespace.EntityWithFilteredIndex")!.GetIndexes().Single().GetFilter()));

[Fact]
public Task Entity_with_indexes_and_use_data_annotations_true_generates_fluent_API_only_for_indexes_with_annotations()
=> TestAsync(
Expand Down
Loading
Loading