SQLite project: a tested notes repository · 4 MIN READ
Back up and maintain a live database: VACUUM INTO, checkpoints, VACUUM and ANALYZE
Take a consistent backup of a WAL database with VACUUM INTO, verify the copy, reclaim free pages, truncate the WAL with a checkpoint and keep planner statistics current.
A SQLite database is a file, which makes it tempting to back it up with cp. In WAL mode the committed state is split between app.db and app.db-wal, and a writer can change either while you copy. SQLite provides safe ways to produce a consistent snapshot while the program keeps running, and a few maintenance commands that keep the file compact and the query planner well informed.
sqlite · A MAP OF THE IDEA
- VACUUM INTO temp path
- integrity_check the copy
- Rename into place
- optimize on close
Useful when
- Consistent online backups with one SQL statement.
- The copy is compacted and self-contained.
Watch out
- File copies of an open database can be torn.
- VACUUM needs free space and holds the write lock.
Implementation & operation cost: Disk space for one extra copy, a scheduled backup job and an occasional maintenance window for VACUUM.
Why copying the file is unsafe
In WAL mode new commits are appended to the -wal file and only moved into the main file by a checkpoint. Copying app.db alone can lose every commit since the last checkpoint; copying app.db and app.db-wal one after another can capture them from different moments, and a write between the two reads can tear a page. Even in rollback-journal mode a copy taken during a write can be corrupt. File-level copies are safe only when no connection has the database open. Inside the program, use VACUUM INTO or the online backup API, both of which read through a transaction and produce a single, self-contained file.
Snapshot, verify, compact, checkpoint
The program writes 2000 rows to a WAL database, backs it up with VACUUM INTO and a bound path, opens the copy read-only and checks it. It then deletes two thirds of the rows and compares page_count and freelist_count before and after VACUUM, truncates the WAL with a checkpoint, and finishes with ANALYZE and PRAGMA optimize.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"path/filepath"
"strings"
_ "modernc.org/sqlite"
)
func one[T any](ctx context.Context, db *sql.DB, query string, args ...any) T {
var v T
if err := db.QueryRowContext(ctx, query, args...).Scan(&v); err != nil {
log.Fatalf("%s: %v", query, err)
}
return v
}
func pages(ctx context.Context, db *sql.DB) string {
return fmt.Sprintf("page_count=%d freelist_count=%d",
one[int](ctx, db, "PRAGMA page_count"), one[int](ctx, db, "PRAGMA freelist_count"))
}
func main() {
ctx := context.Background()
dir, err := os.MkdirTemp("", "backup")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
live := filepath.Join(dir, "live.db")
db, err := sql.Open("sqlite", "file:"+live+"?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)")
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(1) // keep the walkthrough on one connection
if _, err := db.ExecContext(ctx, `CREATE TABLE events (id INTEGER PRIMARY KEY, kind TEXT NOT NULL, payload TEXT NOT NULL);
CREATE INDEX events_kind ON events (kind)`); err != nil {
log.Fatal(err)
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
log.Fatal(err)
}
for i := range 2000 {
kind := []string{"click", "view", "buy"}[i%3]
if _, err := tx.ExecContext(ctx, "INSERT INTO events (kind, payload) VALUES (?, ?)", kind, strings.Repeat("x", 200)); err != nil {
log.Fatal(err)
}
}
if err := tx.Commit(); err != nil {
log.Fatal(err)
}
fmt.Println("journal_mode:", one[string](ctx, db, "PRAGMA journal_mode"))
info, _ := os.Stat(live + "-wal")
fmt.Println("WAL file holds committed pages:", info.Size() > 0)
// VACUUM INTO writes a consistent, compacted copy from a read transaction.
// The target is an ordinary bound value and must not exist yet.
backup := filepath.Join(dir, "backup.db")
if _, err := db.ExecContext(ctx, "VACUUM INTO ?", backup); err != nil {
log.Fatal(err)
}
_, err = db.ExecContext(ctx, "VACUUM INTO ?", backup)
fmt.Println("second VACUUM INTO same file:", err)
copyDB, err := sql.Open("sqlite", "file:"+backup+"?mode=ro")
if err != nil {
log.Fatal(err)
}
fmt.Println("backup integrity_check:", one[string](ctx, copyDB, "PRAGMA integrity_check"))
fmt.Println("backup rows:", one[int](ctx, copyDB, "SELECT count(*) FROM events"))
fmt.Println("backup journal_mode:", one[string](ctx, copyDB, "PRAGMA journal_mode"))
copyDB.Close()
// Deleting rows frees pages but does not shrink the file.
fmt.Println("before delete:", pages(ctx, db))
if _, err := db.ExecContext(ctx, "DELETE FROM events WHERE kind <> 'buy'"); err != nil {
log.Fatal(err)
}
fmt.Println("after delete: ", pages(ctx, db))
if _, err := db.ExecContext(ctx, "VACUUM"); err != nil {
log.Fatal(err)
}
fmt.Println("after VACUUM: ", pages(ctx, db))
// Move WAL content into the main file and truncate the log to zero bytes.
var busy, logFrames, checkpointed int
if err := db.QueryRowContext(ctx, "PRAGMA wal_checkpoint(TRUNCATE)").Scan(&busy, &logFrames, &checkpointed); err != nil {
log.Fatal(err)
}
info, _ = os.Stat(live + "-wal")
fmt.Println("checkpoint busy:", busy, "WAL size after TRUNCATE:", info.Size())
// Statistics for the planner, then the routine maintenance call for close.
if _, err := db.ExecContext(ctx, "ANALYZE"); err != nil {
log.Fatal(err)
}
fmt.Println("sqlite_stat1 rows:", one[int](ctx, db, "SELECT count(*) FROM sqlite_stat1"))
if _, err := db.ExecContext(ctx, "PRAGMA optimize"); err != nil {
log.Fatal(err)
}
fmt.Println("PRAGMA optimize: done")
}The WAL file is non-empty after the inserts, so the latest commits are not in live.db yet; VACUUM INTO still captures them. A second VACUUM INTO the same name fails with "output file already exists". The copy passes integrity_check, has all 2000 rows and uses journal_mode delete. Deleting rows leaves page_count at 116 with 68 free pages; VACUUM shrinks it to 41 pages. The TRUNCATE checkpoint reports busy 0 and a zero-byte WAL, and ANALYZE writes one sqlite_stat1 row for the events_kind index.
VACUUM INTO as a backup
VACUUM INTO 'file' builds a new, defragmented database from a read transaction on the source, so writers on other connections continue and the copy reflects exactly one committed moment. The argument is an expression, so a ? placeholder carries the path safely. The target must not exist; write to a temporary name and rename it into place so a crash never leaves a half-written file under the final name. The copy is in rollback-journal mode, contains no WAL, and can be opened, verified or shipped on its own. For very large databases, the online backup API copies incrementally and can yield between steps. In the coming GopherForge SQLite template, the app's driver keeps programs inside /sandbox and refuses VACUUM INTO and ATTACH; copy a project database with the database browser's export through Files instead.
// backupTo writes a consistent snapshot next to the live file, then renames it
// into place, so a crash never leaves a half-written backup under the final name.
func backupTo(ctx context.Context, db *sql.DB, dest string) error {
tmp := dest + ".partial"
os.Remove(tmp) // VACUUM INTO refuses an existing file
if _, err := db.ExecContext(ctx, "VACUUM INTO ?", tmp); err != nil {
return err
}
return os.Rename(tmp, dest)
}The helper removes a stale partial file, writes the snapshot under a temporary name and renames it. A rename within one directory replaces the old backup atomically on the same file system, so readers of dest see either the previous backup or the complete new one.
Free pages, VACUUM and auto_vacuum
DELETE marks pages as free and keeps them for later inserts; the file does not shrink. PRAGMA freelist_count shows how many are free. VACUUM rewrites the whole database into a new file, which needs up to twice the space, holds the write lock for the duration and can renumber rowids of tables without an INTEGER PRIMARY KEY. Run it in a maintenance window when free pages are a large share of the file, not on every start. auto_vacuum=INCREMENTAL, set before the first table is created, lets PRAGMA incremental_vacuum return free pages in small batches instead.
Checkpoints and planner statistics
SQLite checkpoints automatically when the WAL reaches about 1000 pages, but a long-lived reader can prevent the log from being reset and it keeps growing. PRAGMA wal_checkpoint(TRUNCATE) copies everything into the main file and truncates the log to zero bytes when no reader blocks it; its first result column is 1 when it could not finish. ANALYZE stores index statistics in sqlite_stat1 so the planner can choose between indexes. PRAGMA optimize runs ANALYZE only where it looks useful and is cheap; the SQLite documentation recommends calling it before closing short-lived connections and periodically in long-running ones.
TAKE THIS WITH YOU
Never copy a live database file. Back up with VACUUM INTO a new path or the online backup API, verify the copy with integrity_check, VACUUM only when free pages matter, truncate the WAL with a checkpoint and let PRAGMA optimize maintain statistics.
Check your understanding
A service runs in WAL mode and a nightly job copies app.db with cp. What can the backup be missing?
Go to the source
Progress stays in this browser. No account needed.