MigrateAsync runs pending schema scripts and tracks the version in PRAGMA user_version.
dotnet add package RecursiveAI.OneLiteRequires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.
using RecursiveAI.OneLite; await using var db = await Database.OpenAsync(":memory:"); await db.MigrateAsync( "CREATE TABLE notes(body TEXT);", "CREATE INDEX ix ON notes(body);"); Console.WriteLine(await db.ScalarAsync<long>( $"PRAGMA user_version"));
Unzip the example, then dotnet run.
The two scripts create a table and an index. The number printed is the new version:
2The full program
This example creates a temporary notes.db at version 1. It tries to apply two pending scripts together: one adds an index, and the next tries to index a column that doesn’t exist. It reopens the file to check the version and see whether the first index survived.
using RecursiveAI.OneLite; const string createNotes = "CREATE TABLE notes(body TEXT);"; const string addIndex = "CREATE INDEX notes_body ON notes(body);"; const string badStep = "CREATE INDEX bad ON notes(missing_column);"; var scratch = Directory.CreateTempSubdirectory("onelite-migrate-"); var path = Path.Combine(scratch.FullName, "notes.db"); try { await using (var db = await Database.OpenAsync(path)) { await db.MigrateAsync(createNotes); Console.WriteLine($"Start: version {await Version(db)}"); try { await db.MigrateAsync(createNotes, addIndex, badStep); throw new InvalidOperationException("Expected the third script to fail."); } catch (OneLiteException e) { Console.WriteLine($"Migration failed: {e.Message}"); } } await using var reopened = await Database.OpenAsync(path); Console.WriteLine($"After reopening: version {await Version(reopened)}"); Console.WriteLine($"notes_body indexes: {await IndexCount(reopened)}"); await reopened.MigrateAsync(createNotes, addIndex); Console.WriteLine($"After applying step 2: version {await Version(reopened)}"); Console.WriteLine($"notes_body indexes: {await IndexCount(reopened)}"); } finally { scratch.Delete(recursive: true); } static ValueTask<long> Version(Database db) => db.ScalarAsync<long>($"PRAGMA user_version"); static ValueTask<long> IndexCount(Database db) => db.ScalarAsync<long>($""" SELECT count(*) FROM sqlite_schema WHERE type = 'index' AND name = 'notes_body' """);
Start: version 1 Migration failed: no such column: missing_column After reopening: version 1 notes_body indexes: 0 After applying step 2: version 2 notes_body indexes: 1
A SQL error throws OneLiteException; neither pending script commits. The program then applies just the valid step and cleans up the temporary database on exit.
Variations
Add a column in the next release. Insert this after the last Console.WriteLine inside the outer try. Keep the first two scripts in the list so older databases can still upgrade:
await reopened.MigrateAsync(createNotes, addIndex, "ALTER TABLE notes ADD COLUMN title TEXT;"); Console.WriteLine(await Version(reopened));
3Related recipes
- Run SQLite transactions in C#
- List SQLite table columns in C#
- Roll back part of a SQLite transaction with a savepoint
The short answer
Call db.MigrateAsync with the complete list of SQL scripts, oldest first. OneLite reads the database’s PRAGMA user_version, skips the scripts it has already applied, and commits the remaining scripts and the new version together. Append new scripts rather than editing or renumbering old ones. If any pending script fails, the database keeps the schema and version it had before that call.
How do you run a SQLite schema migration on an existing database?
Use the path to your database with Database.OpenAsync in place of ":memory:". Run the migration before serving requests that need the new schema. Supply the same ordered list whether the database is new or several versions behind. If it’s at version 1 and the list has three entries, OneLite skips the first and runs the second and third in that order. If there are three entries and the file is already at version 3, there’s nothing to apply.
Each entry is a version, not necessarily one statement. For example, you can put a table and the index it needs in the same script if they belong to the same change. The migration API wraps the pending scripts in a transaction and writes the version for you. Leave BEGIN, COMMIT and PRAGMA user_version = … out of the scripts so OneLite controls that transaction and counter.
What is PRAGMA user_version in SQLite?
user_version is an integer stored in the database header for applications to use. SQLite doesn’t interpret it. OneLite uses it as the number of applied migration scripts, so the version travels with the database file. It isn’t the same as schema_version, which SQLite changes internally when the schema changes.
A version of 0 doesn’t tell you the database is empty. An existing file may already have tables but no migration history. Check its schema before bringing it under the script list; otherwise the first script could try to create a table that already exists. If the version is higher than the length of your list, MigrateAsync throws InvalidOperationException rather than attempting a downgrade.
Can you roll back a failed SQLite schema migration?
OneLite rolls back the whole pending batch when a script fails, not just the last statement that ran. In the example, step 2 made an index, then step 3 failed. Since both were pending in one call, the reopened file is still at version 1 and the index is absent. Step 1 had already committed in an earlier call, so the notes table is still there and step 2 can run again.
That’s different from undoing a migration that already committed. A later release can append a new script that reverses a schema change, but removing an entry from the list doesn’t undo it or recover data that an earlier script deleted.