diff --git a/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs b/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs index f85f9b8cd05..15dd7082db3 100644 --- a/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs +++ b/src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs @@ -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; @@ -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()) @@ -889,6 +895,89 @@ protected virtual ModelBuilder VisitForeignKeys( return newForeignKey; } + private const string NullGuardTerm = + """(?:\[(?(?:[^\]]|\]\])+)\]|"(?(?:[^"]|"")+)"|`(?(?:[^`]|``)+)`|(?[\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 foreignKeyColumns, + IEnumerable 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; + } + } + /// /// 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 diff --git a/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteDatabaseModelFactory.cs b/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteDatabaseModelFactory.cs index 21bf488a227..3c212b7380a 100644 --- a/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteDatabaseModelFactory.cs +++ b/src/EFCore.Sqlite.Core/Scaffolding/Internal/SqliteDatabaseModelFactory.cs @@ -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" @@ -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; @@ -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 tables) { using var command1 = connection.CreateCommand(); diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs index 6ce896b7d51..13a130cae87 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/CSharpDbContextGeneratorTest.cs @@ -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("Id"); + x.Property("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 options) + : base(options) + { + } + + public virtual DbSet 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(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( diff --git a/test/EFCore.Design.Tests/Scaffolding/Internal/RelationalScaffoldingModelFactoryTest.cs b/test/EFCore.Design.Tests/Scaffolding/Internal/RelationalScaffoldingModelFactoryTest.cs index 9f7c3c6cede..8f63bce6a76 100644 --- a/test/EFCore.Design.Tests/Scaffolding/Internal/RelationalScaffoldingModelFactoryTest.cs +++ b/test/EFCore.Design.Tests/Scaffolding/Internal/RelationalScaffoldingModelFactoryTest.cs @@ -1249,6 +1249,247 @@ public void Unique_nullable_index_unused_by_foreign_key() Assert.Equal(model.FindPrimaryKey(), fk.PrincipalKey); } + [Theory] + [InlineData(null, true)] + [InlineData("([BuddyId] IS NOT NULL)", true)] + [InlineData("[BuddyId] IS NOT NULL", true)] + [InlineData("(([BuddyId] IS NOT NULL))", true)] + [InlineData("([buddyid] is not null)", true)] + [InlineData("\"BuddyId\" IS NOT NULL", true)] + [InlineData("`BuddyId` IS NOT NULL", true)] + [InlineData("BuddyId IS NOT NULL", true)] + [InlineData("buddyid IS NOT NULL AND \"BuddyId\" IS NOT NULL", true)] + [InlineData("IsActive IS NOT NULL", false)] + [InlineData("BuddyId IS NOT NULL AND IsActive IS NOT NULL", false)] + [InlineData("BuddyId IS NOT NULL OR IsActive", false)] + [InlineData("([BuddyId] IS NOT NULL AND [BuddyId] IS NOT NULL)", true)] + [InlineData("([IsActive]=(1))", false)] + [InlineData("([OtherId] IS NOT NULL)", false)] + [InlineData("([BuddyId] IS NOT NULL AND [OtherId] IS NOT NULL)", false)] + [InlineData("([BuddyId] IS NOT NULL AND [IsActive]=(1))", false)] + [InlineData("([BuddyId] IS NOT NULL OR [IsActive]=(1))", false)] + [InlineData("([BuddyId]>(10))", false)] + [InlineData("([BuddyId] IS NULL)", false)] + [InlineData("Filter SQL", false)] + public void Unique_index_with_filter_makes_foreign_key_unique_only_for_null_guard(string? filter, bool expectedUnique) + { + var table = new DatabaseTable + { + Database = Database, + Name = "Friends", + Columns = + { + IdColumn, + new DatabaseColumn + { + Table = Table, + Name = "BuddyId", + StoreType = "int", + IsNullable = true + }, + new DatabaseColumn + { + Table = Table, + Name = "IsActive", + StoreType = "bit" + } + }, + PrimaryKey = IdPrimaryKey + }; + table.Indexes.Add( + new DatabaseIndex + { + Table = Table, + Name = "IX_Foo", + IsUnique = true, + Filter = filter, + Columns = { table.Columns.ElementAt(1) } + }); + table.ForeignKeys.Add( + new DatabaseForeignKey + { + Table = table, + Name = "FK_Foo", + Columns = { table.Columns.ElementAt(1) }, + PrincipalTable = table, + PrincipalColumns = { table.Columns.ElementAt(0) } + }); + + var model = _factory.Create( + new DatabaseModel { Tables = { table } }, + new ModelReverseEngineerOptions { NoPluralize = true }).FindEntityType("Friends")!; + + var fk = Assert.Single(model.GetForeignKeys()); + Assert.Equal(expectedUnique, fk.IsUnique); + + // The index itself is still scaffolded as unique, with its filter. + var index = Assert.Single(model.GetIndexes()); + Assert.True(index.IsUnique); + } + + [Theory] + [InlineData("[A] IS NOT NULL AND [B] IS NOT NULL", true)] + [InlineData("([A] IS NOT NULL AND [B] IS NOT NULL)", true)] + [InlineData("[A] IS NOT NULL", true)] + [InlineData("[B] IS NOT NULL", true)] + [InlineData("[A] IS NOT NULL AND [C] IS NOT NULL", false)] + [InlineData("[A] IS NOT NULL AND [B]=1", false)] + [InlineData("[A]=1", false)] + public void Composite_foreign_key_with_filtered_unique_index(string filter, bool expectedUnique) + => Assert.Equal(expectedUnique, ScaffoldedForeignKeyIsUnique(["A", "B"], (["A", "B"], true, filter))); + + [Theory] + [InlineData("buddy_id", "([buddy_id] IS NOT NULL)", true)] + [InlineData("buddy_id", "([BuddyId] IS NOT NULL)", false)] + [InlineData("we]ird", "([we]]ird] IS NOT NULL)", true)] + [InlineData("we]ird", "([we]ird] IS NOT NULL)", false)] + [InlineData("a\"b", "\"a\"\"b\" IS NOT NULL", true)] + [InlineData("a\"b", "\"a\" IS NOT NULL", false)] + [InlineData("c`d", "`c``d` IS NOT NULL", true)] + [InlineData("c`d", "`c` IS NOT NULL", false)] + public void Filter_is_matched_against_database_column_names(string columnName, string filter, bool expectedUnique) + => Assert.Equal(expectedUnique, ScaffoldedForeignKeyIsUnique([columnName], ([columnName], true, filter))); + + [Theory] + [InlineData("PersonId", "personid", "[PersonId] IS NOT NULL", true)] + [InlineData("PersonId", "personid", "[personid] IS NOT NULL", false)] + [InlineData("PersonId", "personid", "[PERSONID] IS NOT NULL", false)] + [InlineData("PersonId", "personid", "[PersonId] IS NOT NULL AND [personid] IS NOT NULL", false)] + [InlineData("personid", "PersonId", "[personid] IS NOT NULL", true)] + [InlineData("personid", "PersonId", "[PersonId] IS NOT NULL", false)] + [InlineData("\u00e4", "\u00c4", "\"\u00e4\" IS NOT NULL", true)] + [InlineData("\u00e4", "\u00c4", "\"\u00c4\" IS NOT NULL", false)] + public void Filter_column_is_resolved_exactly_when_columns_differ_only_by_case( + string foreignKeyColumn, + string otherColumn, + string filter, + bool expectedUnique) + => Assert.Equal( + expectedUnique, + ScaffoldedForeignKeyIsUnique([foreignKeyColumn], [otherColumn], ([foreignKeyColumn], true, filter))); + + [Theory] + [InlineData("NULL", "NULL IS NOT NULL", false)] + [InlineData("NULL", "null IS NOT NULL", false)] + [InlineData("NULL", "(NULL IS NOT NULL)", false)] + [InlineData("NULL", "NULL IS NOT NULL AND NULL IS NOT NULL", false)] + [InlineData("NULL", "\"NULL\" IS NOT NULL", true)] + [InlineData("NULL", "[NULL] IS NOT NULL", true)] + [InlineData("NULL", "`NULL` IS NOT NULL", true)] + [InlineData("Nullable", "Nullable IS NOT NULL", true)] + public void Bare_NULL_in_filter_is_not_a_column_name(string columnName, string filter, bool expectedUnique) + => Assert.Equal(expectedUnique, ScaffoldedForeignKeyIsUnique([columnName], ([columnName], true, filter))); + + [Fact] + public void Foreign_key_is_unique_if_any_matching_unique_index_is_not_restricted() + { + Assert.True(ScaffoldedForeignKeyIsUnique(["A"], (["A"], true, "[B]=1"), (["A"], true, null))); + Assert.True(ScaffoldedForeignKeyIsUnique(["A"], (["A"], true, null), (["A"], true, "[B]=1"))); + Assert.True(ScaffoldedForeignKeyIsUnique(["A"], (["A"], true, "[B]=1"), (["A"], true, "[A] IS NOT NULL"))); + Assert.False(ScaffoldedForeignKeyIsUnique(["A"], (["A"], true, "[B]=1"), (["A"], false, null))); + } + + [Fact] + public void Adversarial_index_filters_are_handled_quickly() + { + // Long or pathological filters must neither hang nor throw; unrecognized ones are treated as restricting. + foreach (var (filter, expectedUnique) in new[] + { + (new string(' ', 100_000) + "x", false), + (new string('(', 100_000) + "[A] IS NOT NULL" + new string(')', 100_000), true), + ("[A] IS NOT NULL" + new string(')', 100_000) + "x", false), + ("[A] IS NOT NULL" + string.Concat(Enumerable.Repeat(" AND [A] IS NOT NULL", 5_000)), true), + ("[A] IS NOT NULL" + string.Concat(Enumerable.Repeat(" AND [A] IS NOT NULL", 5_000)) + " AND x", false), + ("[" + new string(']', 100_000), false) + }) + { + Assert.Equal(expectedUnique, ScaffoldedForeignKeyIsUnique(["A"], (["A"], true, filter))); + } + } + + private static bool ScaffoldedForeignKeyIsUnique( + string[] foreignKeyColumns, + params (string[] Columns, bool IsUnique, string? Filter)[] indexes) + => ScaffoldedForeignKeyIsUnique(foreignKeyColumns, [], indexes); + + private static bool ScaffoldedForeignKeyIsUnique( + string[] foreignKeyColumns, + string[] otherColumns, + params (string[] Columns, bool IsUnique, string? Filter)[] indexes) + { + var principal = new DatabaseTable { Database = Database, Name = "Principal" }; + var principalColumns = foreignKeyColumns + .Select((_, i) => new DatabaseColumn { Table = principal, Name = "P" + i, StoreType = "int" }) + .ToList(); + foreach (var column in principalColumns) + { + principal.Columns.Add(column); + } + + var principalKey = new DatabasePrimaryKey { Table = principal, Name = "PK_Principal" }; + foreach (var column in principalColumns) + { + principalKey.Columns.Add(column); + } + + principal.PrimaryKey = principalKey; + + var dependent = new DatabaseTable { Database = Database, Name = "Dependent" }; + var id = new DatabaseColumn { Table = dependent, Name = "Id", StoreType = "int" }; + dependent.Columns.Add(id); + dependent.PrimaryKey = new DatabasePrimaryKey { Table = dependent, Name = "PK_Dependent", Columns = { id } }; + + var columns = foreignKeyColumns + .Select(name => new DatabaseColumn { Table = dependent, Name = name, StoreType = "int", IsNullable = true }) + .ToList(); + foreach (var column in columns) + { + dependent.Columns.Add(column); + } + + foreach (var name in otherColumns) + { + dependent.Columns.Add(new DatabaseColumn { Table = dependent, Name = name, StoreType = "int", IsNullable = true }); + } + + var i = 0; + foreach (var (indexColumns, isUnique, filter) in indexes) + { + var index = new DatabaseIndex + { + Table = dependent, + Name = "IX_" + i++, + IsUnique = isUnique, + Filter = filter + }; + foreach (var name in indexColumns) + { + index.Columns.Add(columns.Single(c => c.Name == name)); + } + + dependent.Indexes.Add(index); + } + + var foreignKey = new DatabaseForeignKey { Table = dependent, Name = "FK_Dependent", PrincipalTable = principal }; + foreach (var column in columns) + { + foreignKey.Columns.Add(column); + } + + foreach (var column in principalColumns) + { + foreignKey.PrincipalColumns.Add(column); + } + + dependent.ForeignKeys.Add(foreignKey); + + var model = new RelationalScaffoldingModelFactoryTest()._factory.Create( + new DatabaseModel { Tables = { principal, dependent } }, + new ModelReverseEngineerOptions { NoPluralize = true }); + + return Assert.Single(model.FindEntityType("Dependent")!.GetForeignKeys()).IsUnique; + } + [Fact] public void Unique_nullable_index_used_by_foreign_key() { diff --git a/test/EFCore.SqlServer.FunctionalTests/Scaffolding/SqlServerDatabaseModelFactoryTest.cs b/test/EFCore.SqlServer.FunctionalTests/Scaffolding/SqlServerDatabaseModelFactoryTest.cs index d922b4daf5f..947a297c718 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Scaffolding/SqlServerDatabaseModelFactoryTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Scaffolding/SqlServerDatabaseModelFactoryTest.cs @@ -5549,6 +5549,106 @@ CREATE TABLE FilteredIndexTable ( }, "DROP TABLE FilteredIndexTable;"); + [Fact] + public void Foreign_key_with_filtered_unique_index_is_not_one_to_one() + => Test( + @" +CREATE TABLE FilteredPerson ( + PersonId varchar(10) NOT NULL PRIMARY KEY +); + +CREATE TABLE FilteredPersonRole ( + PersonRoleId int IDENTITY(1,1) NOT NULL PRIMARY KEY, + PersonId varchar(10) NOT NULL REFERENCES FilteredPerson (PersonId), + IsActive bit NOT NULL +); + +CREATE UNIQUE INDEX IX_FilteredPersonRole_PersonId ON FilteredPersonRole ( PersonId ) WHERE IsActive = 1;", + [], + [], + (dbModel, scaffoldingFactory) => + { + var model = scaffoldingFactory.Create(dbModel, new ModelReverseEngineerOptions()); + + var role = model.GetEntityTypes().Single(e => e.Name == "FilteredPersonRole"); + var index = Assert.Single(role.GetIndexes()); + Assert.True(index.IsUnique); + Assert.Equal("([IsActive]=(1))", index.GetFilter()); + + var fk = Assert.Single(role.GetForeignKeys()); + Assert.False(fk.IsUnique); + Assert.True(fk.PrincipalToDependent!.IsCollection); + }, + "DROP TABLE FilteredPersonRole; DROP TABLE FilteredPerson;"); + + [Fact] + public void Foreign_key_with_unique_index_filtering_only_nulls_is_one_to_one() + => Test( + @" +CREATE TABLE NullableFilteredPerson ( + PersonId varchar(10) NOT NULL PRIMARY KEY +); + +CREATE TABLE NullableFilteredPersonRole ( + PersonRoleId int IDENTITY(1,1) NOT NULL PRIMARY KEY, + PersonId varchar(10) NULL REFERENCES NullableFilteredPerson (PersonId) +); + +CREATE UNIQUE INDEX IX_NullableFilteredPersonRole_PersonId ON NullableFilteredPersonRole ( PersonId ) WHERE PersonId IS NOT NULL;", + [], + [], + (dbModel, scaffoldingFactory) => + { + var model = scaffoldingFactory.Create(dbModel, new ModelReverseEngineerOptions()); + + var role = model.GetEntityTypes().Single(e => e.Name == "NullableFilteredPersonRole"); + var index = Assert.Single(role.GetIndexes()); + Assert.Equal("([PersonId] IS NOT NULL)", index.GetFilter()); + + var fk = Assert.Single(role.GetForeignKeys()); + Assert.True(fk.IsUnique); + Assert.False(fk.PrincipalToDependent!.IsCollection); + }, + "DROP TABLE NullableFilteredPersonRole; DROP TABLE NullableFilteredPerson;"); + + [Theory] + [InlineData("A IS NOT NULL AND B IS NOT NULL", true)] + [InlineData("A IS NOT NULL", true)] + [InlineData("A IS NOT NULL AND B > 0", false)] + [InlineData("A > 0", false)] + public void Composite_foreign_key_on_filtered_unique_index_is_one_to_one_only_if_filter_just_excludes_nulls( + string filter, + bool expectedUnique) + => Test( + $@" +CREATE TABLE CompositePrincipal ( + A int NOT NULL, + B int NOT NULL, + PRIMARY KEY (A, B) +); + +CREATE TABLE CompositeDependent ( + Id int NOT NULL PRIMARY KEY, + A int NULL, + B int NULL, + FOREIGN KEY (A, B) REFERENCES CompositePrincipal (A, B) +); + +CREATE UNIQUE INDEX IX_CompositeDependent ON CompositeDependent (A, B) WHERE {filter};", + [], + [], + (dbModel, scaffoldingFactory) => + { + var model = scaffoldingFactory.Create(dbModel, new ModelReverseEngineerOptions()); + + var dependent = model.GetEntityTypes().Single(e => e.Name == "CompositeDependent"); + var fk = Assert.Single(dependent.GetForeignKeys()); + + Assert.Equal(expectedUnique, fk.IsUnique); + Assert.Equal(!expectedUnique, fk.PrincipalToDependent!.IsCollection); + }, + "DROP TABLE CompositeDependent; DROP TABLE CompositePrincipal;"); + [Fact] public void Ignore_hypothetical_index() => Test( diff --git a/test/EFCore.Sqlite.FunctionalTests/Migrations/MigrationsSqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Migrations/MigrationsSqliteTest.cs index 291dd17bd8a..149a293faeb 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Migrations/MigrationsSqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Migrations/MigrationsSqliteTest.cs @@ -2309,10 +2309,6 @@ protected override bool AssertComputedColumns protected override bool AssertCollations => false; - // Reverse engineering of index filters isn't supported in SQLite - protected override bool AssertIndexFilters - => false; - // Reverse engineering of constraint names isn't supported in SQLite protected override bool AssertConstraintNames => false; diff --git a/test/EFCore.Sqlite.FunctionalTests/Scaffolding/SqliteDatabaseModelFactoryTest.cs b/test/EFCore.Sqlite.FunctionalTests/Scaffolding/SqliteDatabaseModelFactoryTest.cs index 80ca60bf868..4e28341d847 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Scaffolding/SqliteDatabaseModelFactoryTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Scaffolding/SqliteDatabaseModelFactoryTest.cs @@ -68,6 +68,34 @@ private void Test( } } + private void Test( + string createSql, + IEnumerable tables, + IEnumerable schemas, + Action asserter, + string cleanupSql) + { + Fixture.TestStore.ExecuteNonQuery(createSql); + + try + { + var serviceProvider = SqliteTestHelpers.Instance.CreateDesignServiceProvider().CreateScope().ServiceProvider; + + var databaseModel = serviceProvider.GetRequiredService().Create( + Fixture.TestStore.ConnectionString, + new DatabaseModelFactoryOptions(tables, schemas)); + Assert.NotNull(databaseModel); + asserter(databaseModel, serviceProvider.GetRequiredService()); + } + finally + { + if (!string.IsNullOrEmpty(cleanupSql)) + { + Fixture.TestStore.ExecuteNonQuery(cleanupSql); + } + } + } + #region FilteringSchemaTable [Fact] @@ -1364,6 +1392,140 @@ Id2 text }, "DROP TABLE UniqueIndex;"); + [Fact] + public void Set_filter_to_null_for_index_without_filter() + => Test( + @" +CREATE TABLE UnfilteredIndex ( + Id1 int, + Id2 text +); + +CREATE UNIQUE INDEX IX_UNFILTERED on UnfilteredIndex (Id2);", + [], + [], + dbModel => Assert.Null(Assert.Single(dbModel.Tables.Single().Indexes).Filter), + "DROP TABLE UnfilteredIndex;"); + + [Theory] + [InlineData("WHERE Id1 = 1", "Id1 = 1")] + [InlineData("where \"Id2\" IS NOT NULL AND \"Id2\" <> ''", "\"Id2\" IS NOT NULL AND \"Id2\" <> ''")] + [InlineData("WHERE Id2 = ' where (x'", "Id2 = ' where (x'")] + [InlineData("/* where */ -- where\n WHERE Id1 IS NOT NULL", "Id1 IS NOT NULL")] + [InlineData("WHERE -- where\n Id1 IS NOT NULL", "Id1 IS NOT NULL")] + [InlineData("WHERE Id1 IS NOT NULL -- trailing", "Id1 IS NOT NULL")] + [InlineData("WHERE Id1 IS NOT NULL /* trailing */", "Id1 IS NOT NULL")] + [InlineData("WHERE Id2 = '-- not a comment' /* c */", "Id2 = '-- not a comment'")] + [InlineData("WHERE Id2 = 'it''s'", "Id2 = 'it''s'")] + [InlineData("WHERE (Id1 > 1) ", "(Id1 > 1)")] + public void Set_filter_for_partial_index(string whereClause, string expectedFilter) + => Test( + $@" +CREATE TABLE ""Filtered where"" ( + Id1 int, + Id2 text +); + +CREATE UNIQUE INDEX ""IX where"" on ""Filtered where"" (Id2) {whereClause};", + [], + [], + dbModel => + { + var index = Assert.Single(dbModel.Tables.Single().Indexes); + + Assert.Equal("IX where", index.Name); + Assert.True(index.IsUnique); + Assert.Equal(expectedFilter, index.Filter); + }, + "DROP TABLE \"Filtered where\";"); + + [Theory] + [InlineData("CREATE UNIQUE INDEX IF NOT EXISTS IX ON T (A) WHERE A = 'it''s' -- tail", "A = 'it''s'")] + [InlineData("CREATE INDEX main.IX ON T (A) WHERE A > 1", "A > 1")] + [InlineData("CREATE INDEX \"main\".\"IX\" ON [T] (A) WHERE A > 1", "A > 1")] + [InlineData("CREATE\n\tINDEX IX ON T (A)\n\tWHERE\tA > 1\n", "A > 1")] + [InlineData("CREATE INDEX IX ON T (A) WHERE (A > 1) AND (A < 5)", "(A > 1) AND (A < 5)")] + public void Set_filter_for_partial_index_with_different_statement_forms(string createIndexSql, string expectedFilter) + => Test( + $@" +CREATE TABLE T ( + A int +); + +{createIndexSql};", + [], + [], + dbModel => + { + var index = Assert.Single(dbModel.Tables.Single().Indexes); + + Assert.Equal("IX", index.Name); + Assert.Equal(expectedFilter, index.Filter); + }, + "DROP TABLE T;"); + + [Theory] + [InlineData("where\u2603")] + [InlineData("\u2603where")] + [InlineData("where\u00e9")] + [InlineData("where\U0001F600")] + public void Set_filter_for_partial_index_with_unquoted_identifier_containing_where(string indexName) + => Test( + $@" +CREATE TABLE T ( + A int +); + +CREATE UNIQUE INDEX {indexName} ON T (A) WHERE A IS NOT NULL;", + [], + [], + dbModel => + { + var index = Assert.Single(dbModel.Tables.Single().Indexes); + + Assert.Equal(indexName, index.Name); + Assert.Equal("A IS NOT NULL", index.Filter); + }, + "DROP TABLE T;"); + + [Theory] + [InlineData("WHERE IsActive = 1", false)] + [InlineData("WHERE IsActive = 1 AND PersonId IS NOT NULL", false)] + [InlineData("WHERE PersonId IS NOT NULL", true)] + [InlineData("WHERE \"PersonId\" IS NOT NULL -- no nulls", true)] + [InlineData("", true)] + public void Foreign_key_on_filtered_unique_index_is_one_to_one_only_if_filter_just_excludes_nulls( + string whereClause, + bool expectedUnique) + => Test( + $@" +CREATE TABLE FilteredPerson ( + PersonId text PRIMARY KEY +); + +CREATE TABLE FilteredPersonRole ( + PersonRoleId integer PRIMARY KEY, + PersonId text NULL REFERENCES FilteredPerson (PersonId), + IsActive int NOT NULL +); + +CREATE UNIQUE INDEX IX_FilteredPersonRole_PersonId ON FilteredPersonRole (PersonId) {whereClause};", + [], + [], + (dbModel, scaffoldingFactory) => + { + var model = scaffoldingFactory.Create(dbModel, new ModelReverseEngineerOptions()); + + var role = model.GetEntityTypes().Single(e => e.Name == "FilteredPersonRole"); + var index = Assert.Single(role.GetIndexes()); + Assert.True(index.IsUnique); + + var fk = Assert.Single(role.GetForeignKeys()); + Assert.Equal(expectedUnique, fk.IsUnique); + Assert.Equal(!expectedUnique, fk.PrincipalToDependent!.IsCollection); + }, + "DROP TABLE FilteredPersonRole; DROP TABLE FilteredPerson;"); + [Fact] public void Skip_index_on_expression_with_warning() => Test(