SQLite project: a tested notes repository · 4 MIN READ
Migrate a schema with PRAGMA user_version: ordered steps, one transaction each
Apply append-only migrations that record their version in PRAGMA user_version inside the same transaction, skip applied steps, roll back a failing step and refuse a newer schema.
A SQLite file outlives the binary that created it: users keep it, copy it and open it with the next release. A migration runner must know which schema the file has and move it forward exactly once per step. SQLite gives every database a 32-bit integer in its header, PRAGMA user_version, that the library never touches. Store the schema version there and change it in the same transaction as the schema itself, because SQLite DDL is transactional.
sqlite · A MAP OF THE IDEA
- Read user_version
- Refuse newer schemas
- Step + bump in one tx
- Repeat until current
Useful when
- The version travels inside every copy of the file.
- A failed step leaves schema and version consistent.
Watch out
- ALTER TABLE is limited; many changes need a rebuild.
- foreign_keys cannot be toggled inside a transaction.
Implementation & operation cost: A slice of SQL strings, one transaction per step and the discipline of never editing a shipped migration.
The version lives in the file header
PRAGMA user_version reads and writes four bytes at offset 60 of the database header. A new file reports 0. Nothing else uses the value, so it is yours to define: here it means how many migrations from an append-only slice have been applied. Because CREATE TABLE, ALTER TABLE and the user_version write are all part of the transaction, a crash or an error halfway through a step leaves the old schema and the old number together, never a new table with an old version. Unlike a schema_migrations table, the header value travels with every copy and every backup and costs no extra schema object.
An idempotent runner
migrate reads the version, refuses a file whose version is higher than the number of migrations it knows, and then applies each pending step in its own transaction together with PRAGMA user_version = v+1. PRAGMA arguments cannot be bound as ? parameters, so the statement is built with fmt.Sprintf from an int the program computed, never from input. The program simulates an older release that knows two migrations, a newer release that knows three, a second run, a broken fourth migration, a DROP COLUMN, and the old release opening the upgraded file.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"path/filepath"
"strings"
_ "modernc.org/sqlite"
)
// Migrations are append-only: index i moves the schema from version i to i+1.
// Never edit or reorder a migration that has shipped.
var migrations = []string{
// 1: the first schema.
`CREATE TABLE notes (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
body TEXT NOT NULL DEFAULT ''
)`,
// 2: a nullable column with a constant default is a cheap ALTER.
`ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0`,
// 3: an index is just another schema object.
`CREATE INDEX notes_pinned ON notes (pinned, id)`,
}
func userVersion(ctx context.Context, q interface {
QueryRowContext(context.Context, string, ...any) *sql.Row
}) (int, error) {
var v int
err := q.QueryRowContext(ctx, "PRAGMA user_version").Scan(&v)
return v, err
}
// migrate applies every pending migration, each in its own transaction that
// also records the new version, so a crash leaves a consistent schema.
func migrate(ctx context.Context, db *sql.DB, steps []string) (applied int, err error) {
current, err := userVersion(ctx, db)
if err != nil {
return 0, err
}
if current > len(steps) {
return 0, fmt.Errorf("database schema version %d is newer than this program (%d)", current, len(steps))
}
for v := current; v < len(steps); v++ {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return applied, err
}
if _, err := tx.ExecContext(ctx, steps[v]); err != nil {
tx.Rollback()
return applied, fmt.Errorf("migration %d: %w", v+1, err)
}
// PRAGMA arguments cannot be bound; v+1 is an int we computed, not input.
if _, err := tx.ExecContext(ctx, fmt.Sprintf("PRAGMA user_version = %d", v+1)); err != nil {
tx.Rollback()
return applied, err
}
if err := tx.Commit(); err != nil {
return applied, err
}
applied++
}
return applied, nil
}
func columns(ctx context.Context, db *sql.DB) string {
rows, err := db.QueryContext(ctx, "SELECT name FROM pragma_table_info('notes') ORDER BY cid")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var names []string
for rows.Next() {
var n string
if err := rows.Scan(&n); err != nil {
log.Fatal(err)
}
names = append(names, n)
}
return strings.Join(names, ", ")
}
func main() {
ctx := context.Background()
dir, err := os.MkdirTemp("", "migrations")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
db, err := sql.Open("sqlite", filepath.Join(dir, "app.db"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
v, _ := userVersion(ctx, db)
fmt.Println("new file, user_version:", v)
// An older release knew only the first two migrations.
n, err := migrate(ctx, db, migrations[:2])
fmt.Println("old release applied:", n, "err:", err)
if _, err := db.ExecContext(ctx, "INSERT INTO notes (title) VALUES ('kept across upgrades')"); err != nil {
log.Fatal(err)
}
n, err = migrate(ctx, db, migrations)
v, _ = userVersion(ctx, db)
fmt.Println("new release applied:", n, "err:", err, "version:", v)
n, err = migrate(ctx, db, migrations)
fmt.Println("second run applied:", n, "err:", err)
fmt.Println("columns:", columns(ctx, db))
// A broken migration rolls back together with its version bump.
broken := append(append([]string{}, migrations...), "ALTER TABLE notes ADD COLUMN created TEXT DEFAULT CURRENT_TIMESTAMP")
n, err = migrate(ctx, db, broken)
v, _ = userVersion(ctx, db)
fmt.Println("broken migration applied:", n, "version still:", v)
fmt.Println("error:", err)
// DROP COLUMN exists since SQLite 3.35 for columns nothing else depends on.
dropped := append(append([]string{}, migrations...), "ALTER TABLE notes DROP COLUMN body")
n, err = migrate(ctx, db, dropped)
fmt.Println("drop column applied:", n, "err:", err)
fmt.Println("columns:", columns(ctx, db))
// An older binary must refuse a schema it does not know.
_, err = migrate(ctx, db, migrations[:2])
fmt.Println("old release now:", err)
var title string
db.QueryRowContext(ctx, "SELECT title FROM notes").Scan(&title)
fmt.Println("data survived:", title)
}The old release applies two steps and the row it inserts survives every later upgrade. The new release applies only the third step and reports version 3; a second run applies nothing. The broken step fails with "Cannot add a column with non-constant default" and the version stays 3 because the bump rolled back with it. DROP COLUMN body succeeds and the columns become id, title, pinned. The old release then refuses version 4 instead of writing to a schema it does not understand.
What ALTER TABLE can and cannot do
SQLite supports a small ALTER TABLE: RENAME TO, RENAME COLUMN, ADD COLUMN and, since 3.35, DROP COLUMN. ADD COLUMN cannot add a PRIMARY KEY or UNIQUE column, cannot use a non-constant default such as CURRENT_TIMESTAMP, and needs a default when it is NOT NULL. DROP COLUMN fails when the column is part of an index, a primary key, a unique or foreign key constraint, or is used by a view, trigger, generated column or CHECK. Adding an index, a view or a trigger is an ordinary CREATE statement and needs no special care.
Every other change is a table rebuild
Changing a column type, adding a CHECK or a foreign key, or making a table STRICT means creating a new table, copying the rows, dropping the old one and renaming the new one, the procedure the SQLite documentation lists step by step. Turn foreign keys off first, because dropping a referenced parent with enforcement on would delete or reject child rows, and run PRAGMA foreign_key_check before committing. PRAGMA foreign_keys is a no-op inside a transaction, so such a migration needs a runner hook that sets it on the same connection before BEGIN.
-- Outside any transaction, on the one connection that runs the migration:
PRAGMA foreign_keys = OFF;
BEGIN IMMEDIATE;
CREATE TABLE notes_new (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL CHECK (length(title) BETWEEN 1 AND 200),
pinned INTEGER NOT NULL DEFAULT 0
) STRICT;
INSERT INTO notes_new (id, title, pinned) SELECT id, title, pinned FROM notes;
DROP TABLE notes;
ALTER TABLE notes_new RENAME TO notes;
CREATE INDEX notes_pinned ON notes (pinned, id); -- indexes, triggers and views again
PRAGMA foreign_key_check; -- must return no rows
PRAGMA user_version = 5;
COMMIT;
PRAGMA foreign_keys = ON;The new table carries the new constraint, the copy keeps ids, and the rename puts it in place. Indexes and triggers on the old table are dropped with it and must be created again. foreign_key_check returns one row per violation; an empty result is the condition for COMMIT. The version bump is part of the same transaction.
Rules that keep migrations safe
Never edit, reorder or delete a migration that has shipped: some file somewhere is at that version. Keep each step small and data-preserving, test the runner against a copy of a real old database, and take a VACUUM INTO backup before a rebuild. Run migrations once at startup through the same pool the program uses, before serving traffic. This runner reads the version before it begins each step, which is fine for one process; if two processes can start at the same moment, re-read user_version inside a BEGIN IMMEDIATE transaction (for example with _txlock=immediate) so the second waits on busy_timeout, sees the new version and applies nothing. Refusing a newer schema is what makes a rollback of the binary safe.
TAKE THIS WITH YOU
Keep migrations as an append-only list, store the applied count in PRAGMA user_version, and bump it inside the same transaction as the step. Use ALTER TABLE where it is allowed, rebuild the table for everything else, and refuse schemas newer than the code.
Check your understanding
A migration step fails halfway. Why does PRAGMA user_version still show the previous version afterwards?
Go to the source
Progress stays in this browser. No account needed.