Repository navigation
SQLite: re-create complex indexes after a table rebuild (#95) - #138
Merged
Merged
Conversation
UseComplexIndexes() on SQLite wraps the provider's migrations SQL generator. The differ asks the context for the generator in effect; only when it is the wrapper does a migration that rebuilds a table carrying a complex index scaffold drops plus marked creates, instead of #86's refusal. The creates sit before the base operations with __requires_UseComplexIndexes__() ANDed onto their filter: the wrapper moves them behind the rebuild, any other generator fails on them before anything is dropped. The marker is in the filter because SQLite with double-quoted string literals on accepts an unknown quoted column as a string. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #95
Problem
On SQLite, an
ALTER COLUMN, aDROP COLUMN, a key or constraint change, a table comment, a new column with a comment, or a table rename (EF renames the primary key with it) rebuilds the table. EF Core re-creates only its own indexes. #86 mademigrations addrefuse such a migration when the table carries a complex index, and pointed to a three-migration split. This PR letsUseComplexIndexes()turn that refusal into a migration that works, without opening a silent path.Measurements (EF Core 10.0.11, Microsoft.Data.Sqlite with SQLite 3.53.3, real in-memory databases)
Which operations rebuild, and in what order. From
SqliteMigrationsSqlGenerator.RewriteOperations(v10.0.11), confirmed by rendering each kind:AlterColumn,DropColumn,Add/DropPrimaryKey,Add/DropUniqueConstraint,Add/DropCheckConstraint,DropForeignKey,AddForeignKey(unless the table is created in the same migration, matched by name),AlterTable, andAddColumnwith a comment.DropPrimaryKey/AddPrimaryKey, so it does. The rebuild runs under the new name.Sql()and data operations included. Then comeCREATE TABLE "ef_temp_…"andINSERT … SELECTfor each rebuilt table, thenPRAGMA foreign_keys = 0(outside the transaction), thenDROPandRENAMEper table, thenPRAGMA foreign_keys = 1(outside the transaction). EF's own indexes are re-created after all of that.CreateIndexover a column the rebuild adds back, or a column renamed into a dropped column's name, is pulled out. It is re-created only if EF's model has the index, so a complex create placed after the base operations can disappear.Decorating the generator, and a second replacement. EF applies options extensions in the order they were first added, then
ReplacedServices. The core package does not reference SQLite.UseComplexIndexes()now adds an options extension whoseApplyServiceswraps the lastIMigrationsSqlGeneratorregistration, when that registration is SQLite's generator or derives from it. A registration another package made earlier is kept, not replaced.ReplaceServicekeyed on SQLite's type no longer matches the wrapped registration. The wrapper builds that replacement as its inner generator, so both packages' work runs.ReplaceService<IMigrationsSqlGenerator, X>()without a key replaces the wrapper, in either call order. So does an extension added after ours. EF keeps one registration without a word.ICurrentDbContext, through a new constructor) and lifts the refusal only when that generator is the wrapper. Otherwise it refuses as SQLite: a migration that rebuilds a table silently drops every complex index on it #86 does, and the message says why:UseComplexIndexes()missing, called beforeUseSqlite(), or "the one in effect is X … EF Core keeps only one".migrations add(refusal) and at apply (marker) instead.The design-time and runtime split.
AddDbContextDesignTimeServiceshands the design-time services the context'sICurrentDbContext, somigrations addsees the context's real generator.no such function: __requires_UseComplexIndexes__, the index and the dropped column are still there, the data is intact.Columns. With SQLite's double-quoted string literals on (SQLITE_DBCONFIG_DQS_DDL, the default in a stock SQLite build such as a systemlibsqlite3or another SQLitePCLRaw bundle),CREATE INDEX … ("Email_Value", "__requires_…__")is accepted: the quoted name is read as a string literal, and the index would then be lost in the rebuild. An unknown function call fails with DQS on or off. Measured both ways.Idempotent scripts,
EnsureCreated, andGenerateCreateScript.SqliteHistoryRepository.GetBeginIfNotExistsScriptthrowsNotSupportedException(EF source v10.0.11).dotnet ef migrations scriptgoes through the context'sIMigrator, so the context's generator, the wrapper, renders the creates after the rebuild.EnsureCreated/GenerateCreateScript: they diff fromnull, so nothing rebuilds and the wrapper passes everything through. Tested.Without runtime wiring: the refusal from #86 stays, and the message now names
UseComplexIndexes()afterUseSqlite()as the other way out. Applications onUseInternalServiceProviderget the wrapper fromAddComplexIndexes()called afterAddEntityFrameworkSqlite().TPC: the rebuilt-table scan uses the #93 descriptors, so a derived table's copy of a base declaration is dropped and re-created like any other. Tested.
Change
CustomMigrationsModelDiffer:ICurrentDbContext; dependency injection picks it.SqliteRebuiltTablesreplacesThrowIfSqliteRebuildDropsIndexes. It returns each rebuilt table with its name before the renames, and refuses unlessRefusesSqliteRebuild()finds the wrapper in effect.CustomIndex:AfterTableRebuildand the filter marker, and placed after the drops and before the base operations.BuildCreateIndexOperationwas extracted from the create loop.SqliteRebuildMigrationsSqlGenerator(internal): takes the marked creates out, followsRenameTableoperations, generates the rest with the inner generator, then appends the creates with their filter restored. It refuses a marker edited by hand.Decoratewraps the registration.ComplexIndexOptionsExtension(internal): added byUseComplexIndexes();AddComplexIndexes()callsDecoratedirectly.ComplexIndexAnnotations.AfterTableRebuild: new public constant.docs/upgrading.md(SQLite: a migration that rebuilds a table silently drops every complex index on it #86's entry updated, a new "SQLite re-creates complex indexes after a table rebuild"), and a CLAUDE.md paragraph on the SQLite generator seam.DocumentationApiTestsallowsUseSqliteandReplaceServiceas EF Core API.Tests
SqliteTableRebuildTestsscaffolds through design-time services built as EF'sDesignTimeServicesBuilderbuilds them, and applies through EF'sIMigrationCommandExecutor, on real in-memory SQLite. There are 29 tests:AlterColumn,DropColumn, add/drop unique, add/drop check, add/drop FK, PK change,AlterTable, a column with a comment, and a table rename. After each step both complex indexes exist on the right table with their filter, and the unique one refuses a duplicate.EnsureCreated, and the scaffolded C# carrying the marker and the annotation.ReplaceServicebefore or after (refused, naming the generator), a keyedReplaceService(wrapped, both run), another package's extension before ours (wrapped) or after (refused),UseComplexIndexes()beforeUseSqlite()(refused, saying so), an internal service provider (wrapped), and an edited marker (refused).dotnet efagainst the packed packages. It scaffolds a rebuild with the marker, failsdatabase updatewithout the registration and keeps the index, applies with it and re-creates the index, shows no churn, and is refused atmigrations addwithout the registration.Each part reverted, each guard red
AddComplexIndexes()withoutDecorateThe unit suite passes (558,
TestCategory!=Integration&TestCategory!=SqlServer), and so doestest/consumer-smoke-test.sh. Not run locally: the PostgreSQL and SQL Server integration lanes (this PR touches no satellite code).Finding filed
#134: on SQLite, a NULLS-ordered complex index carries the Npgsql column sentinel. With DQS on it applies with a constant column and without its ordering. It is outside #95's scope.
🤖 Generated with Claude Code