Skip to content

SQLite: re-create complex indexes after a table rebuild (#95) - #138

Merged
CaffeinatedCoder merged 1 commit into
mainfrom
feat/95-sqlite-rebuild-recreate
Oct 20, 2026
Merged

CaffeinatedCoder merged 1 commit into
mainfrom
feat/95-sqlite-rebuild-recreate

Conversation

@CaffeinatedCoder

Copy link
Copy Markdown
Owner

Closes #95

Problem

On SQLite, an ALTER COLUMN, a DROP 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 made migrations add refuse such a migration when the table carries a complex index, and pointed to a three-migration split. This PR lets UseComplexIndexes() 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:

  • What triggers a rebuild: AlterColumn, DropColumn, Add/DropPrimaryKey, Add/DropUniqueConstraint, Add/DropCheckConstraint, DropForeignKey, AddForeignKey (unless the table is created in the same migration, matched by name), AlterTable, and AddColumn with a comment.
  • No rebuild when the table is missing from the target model. The rebuild is also skipped when there is no model at all.
  • Renames: a rename on its own does not rebuild. A table rename comes with DropPrimaryKey/AddPrimaryKey, so it does. The rebuild runs under the new name.
  • Ordering: every non-rebuild operation stays in place, Sql() and data operations included. Then come CREATE TABLE "ef_temp_…" and INSERT … SELECT for each rebuilt table, then PRAGMA foreign_keys = 0 (outside the transaction), then DROP and RENAME per table, then PRAGMA foreign_keys = 1 (outside the transaction). EF's own indexes are re-created after all of that.
  • A trap: a CreateIndex over 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.

  • Wrapping the registration: UseComplexIndexes() now adds an options extension whose ApplyServices wraps the last IMigrationsSqlGenerator registration, when that registration is SQLite's generator or derives from it. A registration another package made earlier is kept, not replaced.
  • Keyed replacements: a ReplaceService keyed on SQLite's type no longer matches the wrapped registration. The wrapper builds that replacement as its inner generator, so both packages' work runs.
  • Plain replacements: a 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.
  • Detection: the differ does not trust the registration calls. It asks the context for the generator in effect (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 before UseSqlite(), or "the one in effect is X … EF Core keeps only one".
  • Why not fail at startup: an app that combines two generator packages and never rebuilds a table would break on upgrade. The failure lands at migrations add (refusal) and at apply (marker) instead.

The design-time and runtime split. AddDbContextDesignTimeServices hands the design-time services the context's ICurrentDbContext, so migrations add sees the context's real generator.

  • A migration scaffolded with the wrapper but applied without it (other context configuration, another app) fails on the first marked create. That create sits before the base operations, inside the transaction, before the rebuild. Measured: no such function: __requires_UseComplexIndexes__, the index and the dropped column are still there, the data is intact.
  • The marker is in the filter, not in Columns. With SQLite's double-quoted string literals on (SQLITE_DBCONFIG_DQS_DDL, the default in a stock SQLite build such as a system libsqlite3 or 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.
  • The marked creates go before the base operations. Any later position falls into the deferral trap above. Measured: reverting the position makes a create silently disappear.

Idempotent scripts, EnsureCreated, and GenerateCreateScript.

  • Idempotent scripts: SQLite has none to design for. SqliteHistoryRepository.GetBeginIfNotExistsScript throws NotSupportedException (EF source v10.0.11).
  • Plain scripts: dotnet ef migrations script goes through the context's IMigrator, so the context's generator, the wrapper, renders the creates after the rebuild.
  • EnsureCreated / GenerateCreateScript: they diff from null, so nothing rebuilds and the wrapper passes everything through. Tested.

Without runtime wiring: the refusal from #86 stays, and the message now names UseComplexIndexes() after UseSqlite() as the other way out. Applications on UseInternalServiceProvider get the wrapper from AddComplexIndexes() called after AddEntityFrameworkSqlite().

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:
    • A second public constructor taking ICurrentDbContext; dependency injection picks it.
    • SqliteRebuiltTables replaces ThrowIfSqliteRebuildDropsIndexes. It returns each rebuilt table with its name before the renames, and refuses unless RefusesSqliteRebuild() finds the wrapper in effect.
    • For each rebuilt table, every complex index on it gets a drop (unchanged ones too, so a missing wrapper fails on the marker rather than on "already exists") and a create. That create is marked with CustomIndex:AfterTableRebuild and the filter marker, and placed after the drops and before the base operations.
    • BuildCreateIndexOperation was extracted from the create loop.
  • SqliteRebuildMigrationsSqlGenerator (internal): takes the marked creates out, follows RenameTable operations, generates the rest with the inner generator, then appends the creates with their filter restored. It refuses a marker edited by hand. Decorate wraps the registration.
  • ComplexIndexOptionsExtension (internal): added by UseComplexIndexes(); AddComplexIndexes() calls Decorate directly.
  • ComplexIndexAnnotations.AfterTableRebuild: new public constant.
  • Docs: the README's SQLite paragraph and runtime-wiring table, the core README, the changelogs (root and core: SQLite: a migration that rebuilds a table silently drops every complex index on it #86's row updated, a SQLite: re-create complex indexes after a table rebuild instead of refusing the migration #95 row under Changed answers, the constructor and constant under Added), 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.
  • Other: DocumentationApiTests allows UseSqlite and ReplaceService as EF Core API.

Tests

SqliteTableRebuildTests scaffolds through design-time services built as EF's DesignTimeServicesBuilder builds them, and applies through EF's IMigrationCommandExecutor, on real in-memory SQLite. There are 29 tests:

  • Every rebuild kind, up and down: 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.
  • Indexes added or changed in the rebuilding migration, a TPC derived table, EnsureCreated, and the scaffolded C# carrying the marker and the annotation.
  • Misconfigurations: no wiring (refused), a differ without a context (refused), the wrapper missing at apply with DQS off and on (fails on the marker, index and column intact), the deferral edge without the wrapper (fails), ReplaceService before or after (refused, naming the generator), a keyed ReplaceService (wrapped, both run), another package's extension before ours (wrapped) or after (refused), UseComplexIndexes() before UseSqlite() (refused, saying so), an internal service provider (wrapped), and an edited marker (refused).
  • Consumer smoke test: a new SQLite consumer runs the real dotnet ef against the packed packages. It scaffolds a rebuild with the marker, fails database update without the registration and keeps the index, applies with it and re-creates the index, shows no churn, and is refused at migrations add without the registration.

Each part reverted, each guard red

Reverted Tests that fail
The wrapper passes everything through 14: every wired apply
The differ always lifts the refusal 6: every refusal test
The differ checks only that the extension is registered 4: replaced (×2), extension after ours, wiring before the provider
Marked creates placed after the base operations the deferral edge ("no exception was thrown", a silent loss) and the table-rename kind
No drop of the unchanged indexes 3: the marker is missing from the error ("index … already exists" instead)
Marker as a column instead of in the filter 17, including DQS on: no exception, the migration applied
No rename tracking in the wrapper the table-rename kind
A keyed replacement not used as the inner generator the keyed-replacement test
AddComplexIndexes() without Decorate the internal-service-provider test

The unit suite passes (558, TestCategory!=Integration&TestCategory!=SqlServer), and so does test/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

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]>
@CaffeinatedCoder CaffeinatedCoder added this to the 5.5.0 milestone Oct 20, 2026
@CaffeinatedCoder CaffeinatedCoder added enhancement New feature or request package/core Affects EFCore.ComplexIndexes area/indexes Complex-property, composite, unique and filtered indexes area/migrations The differs, snapshot format, EnsureCreated and design-time wiring labels Oct 20, 2026
@CaffeinatedCoder
CaffeinatedCoder merged commit d496376 into main Oct 20, 2026
@CaffeinatedCoder
CaffeinatedCoder deleted the feat/95-sqlite-rebuild-recreate branch October 20, 2026 09:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/indexes Complex-property, composite, unique and filtered indexes area/migrations The differs, snapshot format, EnsureCreated and design-time wiring enhancement New feature or request package/core Affects EFCore.ComplexIndexes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SQLite: re-create complex indexes after a table rebuild instead of refusing the migration

1 participant