← News & analysis

GUIDE · GO SQLITE MIGRATIONS · 30 MIN READ

Changing a SQLite schema from Go: ALTER TABLE limits, the 12-step rebuild and tested migrations

What SQLite's ALTER TABLE changes in place, how to run the 12-step table rebuild from Go on one connection, and how to test migrations.

Edition: · Practical guide. Added to the archive on the publication date above. Sources and worked examples below.

An original turquoise rodent engineer watches sealed crates move on a conveyor from an old glass case into a new copper-framed one.
Conceptual illustration for Changing a SQLite schema from Go: ALTER TABLE limits, the 12-step rebuild and tested migrations AI-generated conceptual illustration.

What this edition tested

Most schema changes in a Go service backed by SQLite are routine: a new table, a new column, a new index. The one that is not routine arrives later, when a table that already holds real rows needs a foreign key, a different column type or STRICT typing. SQLite's ALTER TABLE cannot express those changes. The documented way around it, a table rebuild, has steps whose order matters and settings that belong to a single connection. Get them wrong through database/sql and the failure is quiet: child rows deleted by a cascade, an AUTOINCREMENT counter that hands out a deleted id again, or a pooled connection that stops enforcing foreign keys for whoever borrows it next.

This is the 25 November 2026 edition, researched and first published on 3 December 2026. Every code block and every quoted error message comes from an original lab built with Go 1.27.3 on darwin/arm64 against modernc.org/sqlite v1.64.0, the latest version on the Go module proxy as of 3 December 2026 (published 1 December 2026). Its sqlite_version() reports SQLite 3.54.1. Go 1.27.4, released on 10 November 2026 with security fixes, is the current patch release; the lab was tested with 1.27.3, and production binaries should be built with the newer patch. The lab passed gofmt, go vet ./... and go test -race -count=3 ./...: 22 tests and 8 subtests.

The tests pin what ALTER TABLE accepts and refuses in place, then run a small migration history: an ADD COLUMN step, and a rebuild that adds a foreign key and changes a column type while keeping the rows, an index, a trigger and the AUTOINCREMENT counter. They roll back a failing rebuild and compare the schema dump byte for byte, catch orphan rows with PRAGMA foreign_key_check, and show that rerunning the history against PRAGMA user_version applies nothing.

Driver choice, WAL, busy timeouts, BEGIN IMMEDIATE and a first user_version runner are covered in SQLite in Go in 2026. This guide assumes them and extends that runner so it can rebuild tables.

What ALTER TABLE changes in place

SQLite keeps its schema as the original text of each CREATE statement in the sqlite_schema table. The ALTER TABLE documentation describes the command as a way of editing that text: SQLite rewrites the stored SQL, reparses the whole schema, and succeeds only if the result is still valid. That design explains both what is cheap and what is impossible.

Four forms have long been supported. RENAME TO renames a table, and since 3.25.0 and 3.26.0 it also rewrites references in triggers, views and the foreign key clauses of other tables. RENAME COLUMN changes the name in the table and in every index, trigger and view that uses it; in the lab, one rename rewrote four references across an index, a view, and a trigger's UPDATE OF and WHEN clauses. ADD COLUMN appends a column, and DROP COLUMN removes one under conditions covered in the next section. SQLite 3.53.0, released on 9 April 2026, added ALTER COLUMN ... SET NOT NULL and DROP NOT NULL, and its release notes describe adding and removing CHECK constraints as well. In the lab, SET NOT NULL on a column that still held a NULL failed with constraint failed (19) and succeeded once that row was fixed, so existing data is checked.

ADD COLUMN is where most day-to-day migrations live, and its restrictions are precise. The new column may not be PRIMARY KEY or UNIQUE. Its default may not be CURRENT_TIME, CURRENT_DATE, CURRENT_TIMESTAMP or an expression in parentheses. A NOT NULL column needs a default other than NULL. With foreign keys enforced, a column with a REFERENCES clause must default to NULL. A generated column must be VIRTUAL, not STORED. The lab pins each rule against the error modernc returns:

go
for _, tc := range []struct{ column, want string }{
	{"code TEXT UNIQUE", "Cannot add a UNIQUE column"},
	{"k INTEGER PRIMARY KEY", "Cannot add a PRIMARY KEY column"},
	{"added TEXT DEFAULT CURRENT_TIMESTAMP", "Cannot add a column with non-constant default"},
	{"two INTEGER DEFAULT (1 + 1)", "Cannot add a column with non-constant default"},
	{"note TEXT NOT NULL", "Cannot add a NOT NULL column with default value NULL"},
	{"customer_id INTEGER REFERENCES customers (id) DEFAULT 1", "Cannot add a REFERENCES column with non-NULL default value"},
	{"twice INTEGER GENERATED ALWAYS AS (id * 2) STORED", "cannot add a STORED column"},
	{"seen TIMESTAMP", `unknown datatype for items.seen: "TIMESTAMP"`},
	{"rank INTEGER NOT NULL DEFAULT 0 CHECK (rank > 0)", "CHECK constraint failed"},
} {

Two rows deserve a second look. In a STRICT table the new column's type must be one of the STRICT type names, so TIMESTAMP is refused. And a CHECK constraint on a new column is tested against every existing row, behaviour the documentation dates to 3.37.0, so DEFAULT 0 CHECK (rank > 0) fails on a table that already has rows. The cost model follows from the design. A rename, or an ADD COLUMN without constraints, only edits text, and the documentation says it runs as quickly on a table of ten million rows as on one row. Adding a column with a CHECK constraint, adding a generated column with NOT NULL, or dropping a column has to read or rewrite the table, so it takes time proportional to its size.

When DROP COLUMN refuses

DROP COLUMN rewrites the table's content to purge the column's data, and it only works when nothing else in the schema still needs that column. The documentation lists the reasons it fails: the column is part of the PRIMARY KEY, has a UNIQUE constraint, is indexed, appears in the WHERE clause of a partial index, is named in a CHECK constraint that is not associated with the column itself, is used in a foreign key constraint, feeds the expression of a generated column, or appears in a trigger or view. The lab's test table has one column for each case it checks, and the messages name the object in the way:

  • cannot drop PRIMARY KEY column: "id" and cannot drop UNIQUE column: "code".
  • error in index t_indexed after drop column: no such column: indexed, and the same form for the partial index.
  • error in table t after drop column: no such column: checked for a table-level CHECK constraint.
  • unknown column "parent_id" in foreign key definition for a table-level FOREIGN KEY clause.
  • error in view t_view after drop column and error in trigger t_trigger after drop column.

Constraints written on the column itself travel with it. A column carrying its own CHECK (own_check > 0) and another carrying its own REFERENCES parents (id) both dropped cleanly. That follows from how the command works: SQLite deletes the column definition from the CREATE TABLE text, which removes any constraint written inside it, and fails only if traces of the column elsewhere would stop the schema from parsing.

In practice, a migration that drops a column first drops the index, view or trigger that uses it, then drops the column, then recreates the view or trigger without it, all in one transaction. When the column belongs to the primary key, carries a UNIQUE constraint or is part of a table-level foreign key, there is no in-place route at all, and the table has to be rebuilt.

A four-panel diagram headed keys off, copy, swap and check shows a table rebuild from disabling foreign keys to verifying links.
AI-generated conceptual illustration.

Changes that need a new table

Anything beyond those forms needs what the documentation calls the generalized ALTER TABLE procedure: create a new table in the desired shape and move the data into it. The page names the cases directly: dropping a column, changing the order of columns, adding or removing a UNIQUE constraint or PRIMARY KEY, adding CHECK, FOREIGN KEY or NOT NULL constraints, and changing the datatype of a column. Making an existing table STRICT belongs here too, because STRICT is a table option written after the closing parenthesis of CREATE TABLE. On SQLite 3.53.0 and later, NOT NULL and CHECK have in-place forms; foreign keys, types, keys and STRICT still do not.

The documented steps, for a table X:

  • Step 1: if foreign key constraints are enabled, disable them with PRAGMA foreign_keys=OFF.
  • Step 2: start a transaction.
  • Step 3: remember the indexes, triggers and views associated with X.
  • Steps 4 and 5: create new_X in the revised format and copy the rows with INSERT INTO new_X SELECT ... FROM X.
  • Steps 6 and 7: DROP TABLE X, then ALTER TABLE new_X RENAME TO X.
  • Steps 8 and 9: recreate the indexes, triggers and views, dropping and recreating any view the change affects.
  • Step 10: if foreign keys were enabled, run PRAGMA foreign_key_check.
  • Steps 11 and 12: commit the transaction, then enable foreign keys again.

In the lab this is the third migration. The first release stored orders.quantity as TEXT and declared no foreign key on customer_id. The rebuild makes the table STRICT, stores the quantity as an INTEGER guarded by a CHECK constraint, and references customers:

go
RebuildTable("orders: STRICT, integer quantity, foreign key to customers", Rebuild{
	Table: "orders",
	Create: `CREATE TABLE new_orders (
		id          INTEGER PRIMARY KEY AUTOINCREMENT,
		customer_id INTEGER NOT NULL REFERENCES customers (id),
		quantity    INTEGER NOT NULL CHECK (quantity > 0),
		note        TEXT NOT NULL DEFAULT ''
	) STRICT`,
	Copy: `INSERT INTO new_orders (id, customer_id, quantity, note)
		SELECT id, customer_id, quantity, note FROM orders`,
	Recreate: []string{
		`CREATE INDEX orders_customer ON orders (customer_id)`,
		`CREATE TRIGGER orders_created AFTER INSERT ON orders BEGIN
			INSERT INTO order_log (order_id, event) VALUES (new.id, 'created');
		END`,
	},
}),

The same documentation page describes a shortcut for changes that leave stored content alone, such as removing a CHECK, FOREIGN KEY or NOT NULL constraint or changing a default: edit the SQL text in sqlite_schema directly under PRAGMA writable_schema=ON and increment schema_version. It also warns, twice, that a mistake in that edit can render the database corrupt and unreadable. Keep it out of application migrations. modernc offers an opt-in _defensive=1 DSN parameter under which PRAGMA writable_schema=ON becomes a silent no-op, a reasonable setting for application connections that should never edit the schema table.

Turn foreign keys off before BEGIN

Step 1 looks like a convenience. It is a guard against data loss. The foreign key documentation says that when enforcement is on, DROP TABLE performs an implicit DELETE of every row before dropping the table; that DELETE does not fire triggers, but it does run foreign key actions and checks. Dropping the old table halfway through a rebuild therefore looks, to every child table, like deleting every parent row.

The lab runs the swap of a customers table on a connection whose DSN sets foreign_keys(1). With a child table declared ON DELETE CASCADE, the transaction committed without an error, and every row of carts was gone. With a child that uses the default action, DROP TABLE failed with FOREIGN KEY constraint failed (787), which at least stops the migration. With PRAGMA foreign_keys = OFF issued before BEGIN, the same swap kept all three child rows.

Two properties of the pragma decide where it goes. First, it is a no-op inside a transaction: enforcement can only change when there is no pending BEGIN or SAVEPOINT, so a runner that sets it after starting its transaction has changed nothing. In the lab the statement succeeds inside a transaction and PRAGMA foreign_keys still reads 1 afterwards. Second, it is a setting of the connection, not of the database file. Through database/sql, the pragma, the BEGIN, the copy and the pragma that restores enforcement must therefore all run on the same connection, which is what db.Conn provides and what a later section builds on.

Turning enforcement off has a cost the documentation spells out as well: while it is off, nothing stops a statement from violating foreign key constraints. Step 10 exists to catch exactly that before the commit, and the lab's runner treats it as mandatory for every rebuild on a database that enforces foreign keys.

Never rename the old table out of the way

The order of steps 4 to 7 looks arbitrary, and the documentation marks the tempting alternative as incorrect: rename X to a temporary name, create the new X, copy the rows, drop the renamed original. Since 3.26.0, renaming a table rewrites the FOREIGN KEY clauses that refer to it whether or not enforcement is on, unless legacy_alter_table is set. Renaming the old table first therefore drags every child's REFERENCES clause along with it.

The lab runs that order with foreign keys off:

go
mustExec(t, db, `BEGIN;
	ALTER TABLE customers RENAME TO old_customers;
	CREATE TABLE customers (id INTEGER PRIMARY KEY, email TEXT NOT NULL);
	INSERT INTO customers SELECT id, email FROM old_customers;
	DROP TABLE old_customers;
	COMMIT;`)

Every statement succeeds. Afterwards carts is declared with REFERENCES "old_customers" (id), a table that no longer exists, and once enforcement is back on, the next insert into carts fails with no such table: main.old_customers. The documented order creates the new table under a new name and renames it into place last, so the only table SQLite renames is one that nothing else refers to yet.

That final rename leaves a mark worth knowing about for schema tests. SQLite rewrites the stored statement with the new name in quotes, so after the lab's rebuild the stored SQL for the table begins CREATE TABLE "orders", while tables created directly keep their original spelling. A golden schema file generated from a migrated database records that correctly; one written by hand usually does not.

Views and triggers that name the table

DROP TABLE removes the table's own indexes and triggers. Views, and triggers attached to other tables, stay in the schema while the table they name is briefly missing, and that is where the default rename behaviour gets in the way. With legacy_alter_table off, ALTER TABLE RENAME checks the whole schema, and a view or trigger that names a table which does not exist at that moment stops it. In the lab, step 7 failed with error in view order_ids: no such table: main.orders for a view that only selects id, and with error in trigger returns_reorder: no such table: main.orders for a trigger on another table that inserts into orders. The rebuild did not affect either object.

There are two ways through. The documentation's step 9 drops and recreates the views a change affects; with the default rename behaviour, that has to include every view and every trigger on another table that names X, dropped before step 6 and recreated after step 7. The other way is PRAGMA legacy_alter_table=ON, under which RENAME rewrites only the initial occurrence of the name in the table's own CREATE statement and its indexes and triggers, and leaves references in view definitions and trigger bodies alone. The pragma documentation says new applications should leave it off, so the lab turns it on only for a rebuild, only on the migration's connection, and turns it off again in the same place that restores foreign keys.

Legacy mode removes a check along with the obstacle. A view that uses a column the rebuild renamed or dropped passes the swap and fails later, when someone queries it. The lab's Rebuild helper therefore ends by preparing SELECT * FROM view LIMIT 0 for every view in the schema, inside the transaction. A migration that renames customer_id to buyer_id without recreating order_counts fails with view order_counts: SQL logic error: no such column: customer_id, and nothing is committed. Triggers on other tables are not covered by that check; a test that fires them is.

Step 3's suggested query, SELECT type, sql FROM sqlite_schema WHERE tbl_name='X', finds the table's indexes and triggers but not the views that read from it, because the schema table stores a view under its own name in tbl_name. The helper records the names of the indexes and triggers the drop will take with it, then runs steps 4 to 8:

go
func (r Rebuild) run(ctx context.Context, tx *sql.Tx) error {
	// Step 3: remember what DROP TABLE takes with it.
	kept, err := namesOn(ctx, tx, r.Table)
	if err != nil {
		return err
	}
	seq, counted, err := sequence(ctx, tx, r.Table)
	if err != nil {
		return err
	}
	// Steps 4 to 8: create under a new name, copy, drop, rename, recreate.
	steps := append([]string{
		r.Create,
		r.Copy,
		"DROP TABLE " + quote(r.Table),
		"ALTER TABLE " + quote("new_"+r.Table) + " RENAME TO " + quote(r.Table),
	}, r.Recreate...)
	for _, q := range steps {
		if _, err := tx.ExecContext(ctx, q); err != nil {
			return err
		}
	}

After the counter repair described next, it compares those names with what exists and fails with rebuild of orders did not recreate orders_customer if the migration forgot one. A missing index never causes an error on its own, so this check is the only thing that notices before production does.

The engineer reattaches tagged fixtures to a new glass case on a turntable while an ivory tally drum keeps its raised setting.
A rebuild drops the table's own indexes and triggers with it; the migration has to put each one back and keep the AUTOINCREMENT counter where it was. AI-generated conceptual illustration.

Keep the AUTOINCREMENT counter

AUTOINCREMENT changes how SQLite picks a rowid: the new id is larger than any id the table has ever held, so the id of a deleted row is never handed out again. SQLite keeps that high-water mark in its internal sqlite_sequence table. A rebuild breaks the promise unless the migration repairs it. DROP TABLE removes the old table's counter, and the copy gives the new table a counter equal to the largest id it copied. If the newest rows had been deleted before the migration, the next insert reuses their ids.

The lab shows it with a rebuild run by hand:

go
mustExec(t, db, `CREATE TABLE jobs (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);
	INSERT INTO jobs (name) VALUES ('a'), ('b'), ('c');
	DELETE FROM jobs WHERE id = 3;
	PRAGMA foreign_keys = OFF;
	BEGIN;
	CREATE TABLE new_jobs (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL);
	INSERT INTO new_jobs (id, name) SELECT id, name FROM jobs;
	DROP TABLE jobs;
	ALTER TABLE new_jobs RENAME TO jobs;
	COMMIT;
	PRAGMA foreign_keys = ON;
	INSERT INTO jobs (name) VALUES ('d');`)

The row inserted afterwards received id 3, the id of the row deleted before the migration. In a negative control where the table was empty before the rebuild, the counter fell to 0 and the next order received id 1. The documentation allows ordinary UPDATE, INSERT and DELETE statements on sqlite_sequence and warns that changing it perturbs the algorithm, so the repair is narrow: read the old value at step 3, and after the rename raise the new value to it, never lower it.

go
// The copy left the AUTOINCREMENT counter at the largest id copied.
// Ids of deleted rows must stay used, so put the old value back.
if counted {
	err := tx.QueryRowContext(ctx, `UPDATE sqlite_sequence SET seq = max(seq, ?)
		WHERE name = ? RETURNING seq`, seq, r.Table).Scan(&seq)
	if errors.Is(err, sql.ErrNoRows) {
		return fmt.Errorf("rebuild of %s lost its AUTOINCREMENT counter", r.Table)
	}
	if err != nil {
		return err
	}
}

RETURNING, available since SQLite 3.35.0, reports the value written. No row at all means the new table has no counter, which is what happens when its definition lost AUTOINCREMENT. The helper treats that as a mistake in the migration rather than a choice, and the lab's test for that case fails with rebuild of orders lost its AUTOINCREMENT counter. In the real migration the counter stood at 3 before the rebuild and at 3 afterwards, and the next order received id 4.

The autoincrement documentation also says the keyword costs extra CPU, memory, disk space and disk I/O and is usually not needed. If your tables use a plain INTEGER PRIMARY KEY, there is no counter to carry, and a deleted largest id may be reused whether or not you rebuild.

Foreign key mismatch and foreign_key_check

Adding a foreign key introduces a class of error that CREATE TABLE does not catch. The foreign key documentation separates DDL errors, which SQLite can see in the child table alone, from DML errors, which need both tables and are reported only when content changes. A parent key must be the parent's primary key or be covered by a UNIQUE constraint that uses the collation from its CREATE TABLE; otherwise the error is "foreign key mismatch". In the lab, a notes table declaring email TEXT REFERENCES customers (email) was created without complaint, and the first INSERT into it failed with foreign key mismatch - "notes" referencing "customers". PRAGMA foreign_key_check failed with the same error instead of returning rows, so a runner that checks before COMMIT rolls back a rebuild that would otherwise have committed an unusable table.

A UNIQUE index on customers.email fixed it. The documentation points out the weakness of that particular fix: when a parent key is unique only because of a separate CREATE UNIQUE INDEX, dropping that index later, and then the parent table, reports no error and can leave orphans behind. Declare UNIQUE inside the parent table's definition when you can.

With enforcement off during the copy, rows that point at missing parents move into the new table silently. PRAGMA foreign_key_check returns one row per violation: the child table, the rowid of the offending row (NULL for a WITHOUT ROWID table), the parent table, and the index of the failing constraint as PRAGMA foreign_key_list numbers them. PRAGMA integrity_check does not report foreign key errors. Starting from an order whose customer_id is 7, with no such customer, the lab's migration fails with foreign_key_check found 1 orphan rows: orders rowid 2 -> customers (foreign key 0). The schema dump is unchanged and the version stays at 2. A copy of the lab that left enforcement on during the rebuild failed the same test differently: the copy itself stopped with FOREIGN KEY constraint failed (787), which says that something is wrong but not which row.

Orphans found this way need a decision, not a retry. Repair or delete them in an earlier migration, or make the column nullable and set them to NULL, and keep that cleanup in the history so that every database receives the same treatment.

STRICT tables turn bad data into a rollback

A rebuild is the only way to make an existing table STRICT, and STRICT changes the copy from forgiving to exact. In a STRICT table, a column of type INTEGER accepts integers, NULL where allowed, and values SQLite can convert losslessly; anything else raises SQLITE_CONSTRAINT_DATATYPE. The old orders.quantity was TEXT, so the copy into quantity INTEGER turns '3' into the integer 3, and after the lab's successful rebuild every quantity reports typeof integer. A single row holding 'n/a' stops the copy with cannot store TEXT value in INTEGER column new_orders.quantity (3091).

The lab asserts what the rollback leaves behind: the schema dump identical byte for byte, the same PRAGMA schema_version, the same rows and the same AUTOINCREMENT counter, user_version still 2, and the pool's connection back to foreign_keys 1 and legacy_alter_table 0. The CREATE, the DROP TABLE and the rename are all part of the transaction and disappear with it.

The tempting fix is wrong. SQLite's CAST never fails: casting text with no numeric prefix to INTEGER yields 0, and the lab confirms CAST('n/a' AS INTEGER) is 0. Wrapping the column in CAST would turn bad data into plausible data, and in this schema only the CHECK (quantity > 0) would notice. Decide what the bad rows mean, and clean them in an explicit migration step before the rebuild.

STRICT keeps applying after the rebuild. Later ADD COLUMN migrations on the table must use one of INT, INTEGER, REAL, TEXT, BLOB or ANY, and PRAGMA integrity_check verifies the types of the stored values. The compatibility floor, SQLite 3.37.0 for any tool that opens the same file, is covered in the earlier guide.

A migration runner on one connection

The lab's Migrate takes one connection from the pool with db.Conn and runs everything on it: reading the version, the backup, the pragmas and every transaction. The database/sql documentation says that queries run on the same Conn run in the same database session. The modernc package documentation states the other half: state set on a pooled connection, PRAGMAs included, is inherited by the next caller to borrow it, and state that only one caller should see belongs on a held sql.Conn that is undone or closed before it is released.

Each step runs in apply:

go
func apply(ctx context.Context, conn *sql.Conn, m Migration, version int) (ran bool, err error) {
	enforced := false // foreign keys were on before relax turned them off
	if m.Rebuild {
		var restore func() error
		// Plain assignment: with := the deferred Join below would write to
		// a new err scoped to this block, and a failed restore would be lost.
		if enforced, restore, err = relax(ctx, conn); err != nil {
			return false, err
		}
		// Deferred first, so it runs after the transaction has ended:
		// PRAGMA foreign_keys is a no-op inside a transaction.
		defer func() { err = errors.Join(err, restore()) }()
	}

	tx, err := conn.BeginTx(ctx, nil) // BEGIN IMMEDIATE, from _txlock in the DSN
	if err != nil {
		return false, err
	}
	defer tx.Rollback()

	// Read the version again under the write lock: another process may have
	// applied this step while this one waited for the lock.
	var current int
	if err := tx.QueryRowContext(ctx, "PRAGMA user_version").Scan(&current); err != nil {
		return false, err
	}
	if current != version {
		return false, nil
	}
	if err := m.Up(ctx, tx); err != nil {
		return false, fmt.Errorf("migration %d (%s): %w", version+1, m.Name, err)
	}
	if enforced {
		if err := foreignKeyCheck(ctx, tx); err != nil {
			return false, fmt.Errorf("migration %d (%s): %w", version+1, m.Name, err)
		}
	}
	// PRAGMA takes no bound parameters; version is an int.
	if _, err := tx.ExecContext(ctx, fmt.Sprintf("PRAGMA user_version = %d", version+1)); err != nil {
		return false, err
	}
	return true, tx.Commit()
}

The pool's DSN sets _txlock=immediate, so BeginTx issues BEGIN IMMEDIATE, which the transaction documentation describes as starting a write at once instead of waiting for the first write statement. Reading user_version again under that lock is what makes two processes starting together safe: the second waits, sees the new version and skips the step. The lab runs two independent pools on one file concurrently and asserts that the three steps were applied exactly once in total. Setting user_version inside the same transaction means a failed step leaves the old version in place.

The order of the two defers matters. Deferred calls run last in, first out, so tx.Rollback runs before the restore, and the restore's PRAGMA foreign_keys lands outside the transaction, where it has an effect. The comment about := records a mistake the lab made along the way. With enforced, restore, err := relax(...) inside the if, the deferred errors.Join assigns to a new err declared in that block, and a failed restore vanishes. A negative control with a restore that could not run returned only the migration's error under :=, and both errors with plain assignment.

Restoring the settings is the part that protects every later request:

go
func relax(ctx context.Context, conn *sql.Conn) (enforced bool, restore func() error, err error) {
	if err := conn.QueryRowContext(ctx, "PRAGMA foreign_keys").Scan(&enforced); err != nil {
		return false, nil, err
	}
	if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys = OFF; PRAGMA legacy_alter_table = ON"); err != nil {
		return false, nil, err
	}
	restore = func() error {
		ctx := context.WithoutCancel(ctx) // must run even if ctx was canceled
		_, err := conn.ExecContext(ctx, fmt.Sprintf(
			"PRAGMA legacy_alter_table = OFF; PRAGMA foreign_keys = %t", enforced))
		var now bool
		if err == nil {
			err = conn.QueryRowContext(ctx, "PRAGMA foreign_keys").Scan(&now)
		}
		if err == nil && now != enforced {
			err = errors.New("foreign_keys did not change; is a transaction still open?")
		}
		if err != nil {
			// driver.ErrBadConn from Raw makes database/sql close the
			// connection instead of returning it to the pool.
			conn.Raw(func(any) error { return driver.ErrBadConn })
			return fmt.Errorf("restoring connection settings: %w", err)
		}
		return nil
	}
	return enforced, restore, nil
}

context.WithoutCancel keeps a canceled migration from also canceling its cleanup. If the restore still fails, or reads back the wrong value, returning driver.ErrBadConn from Conn.Raw makes database/sql treat the connection as unusable and close it rather than return it to the pool. The next connection the pool opens gets foreign_keys(1) from the DSN. The lab cancels a context halfway through a rebuild and then asserts that the pool hands out a connection with foreign keys on and legacy mode off. A copy of the lab whose restore did nothing failed seven tests, each reporting foreign_keys = 0 after Migrate, and in one of them the pool then accepted an order for a customer that does not exist.

One caution about pools limited to one connection: a caller that already holds that connection and then calls Migrate waits in db.Conn until its context is canceled. Run migrations at startup, before the service takes traffic, and give that call a deadline.

Idempotent, ordered and backed up

Idempotency comes from the version, not from the SQL. SQLite's ADD COLUMN has no IF NOT EXISTS form, so running migration 2 a second time fails, and the runner never does:

go
// The version is what makes a step safe to run twice. ADD COLUMN has
// no IF NOT EXISTS, so running the step's SQL again fails.
_, err := db.ExecContext(t.Context(), `ALTER TABLE orders ADD COLUMN note TEXT NOT NULL DEFAULT ''`)
if err == nil || !strings.Contains(err.Error(), "duplicate column name: note") {
	t.Errorf("repeating ADD COLUMN: %v, want duplicate column name", err)
}

// An older binary refuses a schema it does not know.
_, err = sqliteschema.Migrate(t.Context(), db, sqliteschema.History[:2], sqliteschema.Options{})
if err == nil || !strings.Contains(err.Error(), "schema version 3 is newer than this program (2)") {
	t.Errorf("older history: %v", err)
}

A second Migrate against an up-to-date file applies zero steps and leaves the schema dump unchanged. A binary whose history is shorter than the file's version refuses to touch it, which matters when a deploy is rolled back to a release that does not know the new schema. Resist the urge to sprinkle IF NOT EXISTS over CREATE statements to make reruns pass: it hides a database that has drifted from the history instead of failing on it.

The history is append-only, and that includes whitespace. SQLite stores each CREATE statement exactly as it was executed, indentation included, so reformatting a shipped migration gives new installations different sqlite_schema text from upgraded ones. The golden test in the next section catches that.

Take a backup before the first pending step. The runner writes a VACUUM INTO copy named after the current version, app-v2.db in the lab, and only when there is something to apply, so restarts do not pile up identical copies. The copy has to be made before BEGIN: inside a transaction, the lab's attempt fails with cannot VACUUM from within a transaction. The copy passed PRAGMA integrity_check, reported user_version 2 and still held the TEXT quantities, which is the state you want back if the new release has to be withdrawn. The VACUUM documentation describes the trade-off against the online backup API: VACUUM INTO produces a minimal file, while the backup API uses fewer CPU cycles and can run incrementally. Both are covered, together with the reason a plain file copy of a live WAL database is not a backup, in the earlier SQLite guide.

A rolled-back transaction protects you from a migration that fails. The backup protects you from one that succeeds and turns out to be wrong.

Test migrations like code

Four kinds of tests catch nearly everything in this guide, and all of them run against temporary files in milliseconds.

The first is a golden schema. Dump writes user_version and every row of sqlite_schema except page numbers, in a stable order, and a test compares a freshly migrated database with testdata/schema.golden. go test -update rewrites the file once a reviewer has read the diff. The same comparison runs on a database that held data at version 2 before migrating, and the two must match. That test notices a reformatted migration, an upgrade path that forgets an index, and the quoted table name a rebuild leaves behind.

The second checks that data survived in the shape the new schema promises:

go
// Index: recreated and chosen by the planner.
plan := rowsText(t, db, "EXPLAIN QUERY PLAN SELECT id FROM orders WHERE customer_id = 1")
if !strings.Contains(plan, "INDEX orders_customer") {
	t.Errorf("plan does not use orders_customer:\n%s", plan)
}
// Counter: the deleted id 3 is not handed out again.
mustExec(t, db, `INSERT INTO orders (customer_id, quantity) VALUES (1, 4)`)
if id := scalar[int64](t, db, "SELECT max(id) FROM orders"); id != 4 {
	t.Errorf("next id = %d, want 4", id)
}
// Trigger: recreated and firing.
if got := rowsText(t, db, "SELECT order_id, event FROM order_log ORDER BY rowid DESC LIMIT 1"); got != "4 | created\n" {
	t.Errorf("order_log after insert = %q", got)
}
// View: still answers.
if n := scalar[int](t, db, "SELECT orders FROM order_counts WHERE customer_id = 1"); n != 2 {
	t.Errorf("order_counts for customer 1 = %d, want 2", n)
}
// Foreign key: enforced on the pool's connection.
_, err = db.ExecContext(t.Context(), `INSERT INTO orders (customer_id, quantity) VALUES (99, 1)`)
if got := sqliteschema.Code(err); got != sqlite3.SQLITE_CONSTRAINT_FOREIGNKEY {
	t.Errorf("order for a missing customer: %v (code %d), want SQLITE_CONSTRAINT_FOREIGNKEY", err, got)
}

The query plan reads SEARCH orders USING COVERING INDEX orders_customer (customer_id=?), so the index is not only present but chosen. The third kind is failure: a rebuild that must fail, followed by a comparison of the dump, schema_version, rows and counter with their earlier values. The lab has one for bad data, one for orphans, and one each for a stale view, a forgotten index and a dropped AUTOINCREMENT. The fourth checks the connection afterwards, because a migration that succeeds but leaves foreign_keys off is a defect no schema dump can show.

Run negative controls at least once. Copies of the lab outside the repository, each with one safeguard removed, failed as they should: without the counter repair, next id = 3, want 4; without legacy mode, eight tests stopped on error in view order_counts: no such table: main.orders; without the view check, the migration with the stale view committed; without the restore, seven tests found foreign keys off. Tests that cannot fail prove little.

GopherForge 1.3.8, now in App Review, performs this same rebuild when its SQLite table designer changes a table or its diagram edits a relationship. To practise on something small, the SQLite with Go course covers the basics, and the SQLite app template already tracks its migrations in user_version, which makes it a good place to add a first rebuild step.

A checklist for the next schema change

Before writing the migration:

  • Check for an in-place form first: RENAME TO, RENAME COLUMN, ADD COLUMN within its restrictions, DROP COLUMN when nothing else uses the column, and on SQLite 3.53.0 or later SET or DROP NOT NULL and CHECK constraints.
  • Treat everything else as a rebuild: create new_X, copy, drop X, rename new_X to X. Never rename X out of the way first.
  • Find bad data and orphans before the rebuild, and clean them in an explicit step. Do not hide them with CAST.

When running it:

  • Use one sql.Conn. Turn foreign keys off and legacy_alter_table on before BEGIN; restore both after the transaction ends, with a context that cannot be canceled, and close the connection if the restore fails.
  • Begin with BEGIN IMMEDIATE, read user_version again under the lock, and set the new version in the same transaction.
  • Record the table's indexes and triggers before the drop, confirm they exist afterwards, recreate the views the change affects, and prepare every view before COMMIT.
  • Carry the AUTOINCREMENT counter across with max(seq, old), and fail if the counter disappeared.
  • Run PRAGMA foreign_key_check before COMMIT, and treat any row, or a foreign key mismatch, as a failure.
  • Take a VACUUM INTO copy named after the current version before the first pending step.

After it:

  • Keep the history append-only, byte for byte, and pin it with a golden sqlite_schema dump, a data-preservation test, a failure test and a connection-state test.

The code is in the sqliteschema folder of this edition's lab archive. Run go test -race ./... there, then delete the counter repair or the legacy_alter_table pragma and watch which tests fail. Connection pool sizing and transaction deadlines for the rest of the service are covered in Go database/sql under load.

Primary sources & editorial method

We checked these primary references on 3 December 2026. Release facts are attributed; recommended workflows and examples are GopherForge analysis. Illustrations are conceptual, not vendor screenshots or benchmarks.