---
title: "Apply versioned SQLite schema changes in C#"
url: https://recursiveai.org/onelite/cookbook/apply-versioned-sqlite-schema-updates/
description: "Apply versioned SQLite schema changes in C# with OneLite. Run pending SQL scripts in one transaction and keep the old schema if a script fails."
version: "1.0.0"
---

# Apply versioned SQLite schema changes in C#

**OneLite** is a free, open-source SQLite-compatible database for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneLite) · [GitHub](https://github.com/recursive-ai-oss/onelite-csharp) · [Docs](https://recursiveai.org/onelite/docs/) · [Download example (.zip)](https://recursiveai.org/onelite/cookbook/apply-versioned-sqlite-schema-updates/apply-versioned-sqlite-schema-updates.zip)

`MigrateAsync` runs pending schema scripts and tracks the version in `PRAGMA user_version`.

```shell
dotnet add package RecursiveAI.OneLite
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
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](https://recursiveai.org/onelite/cookbook/apply-versioned-sqlite-schema-updates/apply-versioned-sqlite-schema-updates.zip), then `dotnet run`.

The two scripts create a table and an index. The number printed is the new version:

```text
2
```

## The 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.

```csharp
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'
    """);
```

```text
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:

```csharp
await reopened.MigrateAsync(createNotes, addIndex,
    "ALTER TABLE notes ADD COLUMN title TEXT;");
Console.WriteLine(await Version(reopened));
```

```text
3
```

## Related recipes

- [Run SQLite transactions in C#](https://recursiveai.org/onelite/cookbook/sqlite-transactions-csharp/)
- [List SQLite table columns in C#](https://recursiveai.org/onelite/cookbook/list-sqlite-table-columns/)
- [Roll back part of a SQLite transaction with a savepoint](https://recursiveai.org/onelite/cookbook/roll-back-part-of-sqlite-transaction-with-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](https://recursiveai.org/onelite/docs/happy-path/#migrations) 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`](https://www.sqlite.org/pragma.html#pragma_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`](https://www.sqlite.org/pragma.html#pragma_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.
