GUIDE · GO SQLITE · 28 MIN READ
SQLite in Go in 2026: drivers, WAL, busy timeouts and STRICT tables
Run SQLite from Go: modernc, mattn and ncruces compared, per-connection pragmas, WAL with BEGIN IMMEDIATE, STRICT tables, migrations and backups.
Edition: · Practical guide. Added to the archive on the publication date above. Sources and worked examples below.

What this edition tested
SQLite is easy to start with and easy to misjudge. A Go service opens a file, runs happily in development, then meets its first concurrent writes and starts returning database is locked. Another team discovers months later that rows point at parents that never existed, because the schema declared foreign keys that no connection was enforcing. Neither is a bug in SQLite. Both come from documented defaults that live on each connection and are easy to leave unset when the database is reached through database/sql.
This is the 29 November 2026 edition, researched and first published on 30 November 2026. Every behaviour described here was checked in an original lab built with Go 1.27.3 on darwin/arm64 against modernc.org/sqlite v1.63.0, the latest version on the Go module proxy that day (published 22 November 2026). Its sqlite_version() reports SQLite 3.54.1. The lab passed go vet ./..., gofmt and go test -race -count=3 ./.... Its tests show that foreign keys are enforced only when the pragma is set on the connection, that a STRICT table rejects a value of the wrong type, that two writers using a busy timeout and BEGIN IMMEDIATE both succeed, that a deferred transaction upgraded under contention fails with SQLITE_BUSY, and that migrations keyed on PRAGMA user_version are idempotent. Separate build probes compared binary size and cross-compilation for the three common drivers.
Pool behaviour that applies to any database, such as connection budgets, Rows ownership and deadline design, is covered in Go database/sql under load. This guide does not repeat it. It concentrates on what changes when the database is a file opened inside your own process.
Three drivers, three build stories
All three widely used drivers implement database/sql and run SQLite's own query planner. The difference that matters most in production is how SQLite gets into your binary, because that decides whether you need a C toolchain, how you cross-compile and what you can target.
- modernc.org/sqlite is a cgo-free port. SQLite's C amalgamation is transpiled to Go, and the package registers the driver name
sqlite. Its documentation lists the supported GOOS and GOARCH pairs, covering Linux, macOS, Windows, FreeBSD, NetBSD, OpenBSD and illumos on the architectures it names, and asks you to use exactly themodernc.org/libcversion its own go.mod requires. For v1.63.0 that is v1.80.1, which the lab's go.mod resolved to. The documentation also says the transpiled core runs slower than natively compiled C in CPU-bound work, and publishes its own measured ratios. - github.com/mattn/go-sqlite3 compiles the SQLite C amalgamation through cgo and registers
sqlite3. Its README states the requirement plainly:CGO_ENABLED=1and agcccompiler on the path. The latest release on the proxy is v1.14.53. The README says the stable line is v1.14 and not v2, and the module's go.mod retracts the accidental v2 tags. - github.com/ncruces/go-sqlite3 is also cgo-free and registers
sqlite3from itsdriverpackage. It is often described as SQLite compiled to Wasm and run on the wazero runtime. That was accurate up to v0.32.0. Since v0.33.0, released in March 2026, the README says it wraps a Wasm build of SQLite and uses wasm2go to translate it to Go, and the go.mod of the current v0.38.1 no longer requires wazero. The README warns that memory usage will be higher than alternatives, because each connection executes within a Wasm sandboxed environment.
The drivers also disagree on defaults. In the lab, a modernc connection opened without parameters reported busy_timeout 0, foreign_keys 0 and journal_mode delete. The mattn source sets a 5000 ms busy timeout unless the DSN overrides it and begins transactions as DEFERRED. The ncruces driver documentation sets a one-minute busy timeout and makes immediate the default _txlock. Code that may move between drivers should state these values in its DSN instead of inheriting them.
GopherForge users meet a fourth registration. GopherForge 1.3.5, currently in App Store review, adds a SQLite app template and a SQLite course. On iPhone and iPad, programs reach SQLite through the app's bundled gopherforge.app/sqlite driver, registered as sqlite and accepting modernc-compatible _pragma parameters, because modernc does not build for the WASI sandbox. Programs there can open databases only under /sandbox, and ATTACH and VACUUM INTO are refused.
What the build probes showed
The lab contains three small programs behind a sizeprobe build tag, so ordinary go test and go vet never compile them. Each opens :memory: through one driver and prints sqlite_version(); all three printed 3.54.1. Built with Go 1.27.3 on darwin/arm64, the executables measured:
- modernc.org/sqlite: 9,971,042 bytes with a plain
go build, and 6,453,730 bytes with-trimpath -ldflags="-s -w". - mattn/go-sqlite3: 7,082,002 bytes plain, 3,771,954 bytes stripped.
- ncruces/go-sqlite3: 13,922,978 bytes plain, 7,813,106 bytes stripped.
These are single measurements of a minimal program on one platform and toolchain, not a benchmark. If size matters to your deployment, measure your own binary with your own dependencies.
Cross-compilation separated the drivers more sharply. With CGO_ENABLED=0, the modernc and ncruces probes built from the Mac for linux/amd64, linux/arm64 and windows/amd64, and the Linux results were statically linked executables. The ncruces probe also compiled for wasip1/wasm and js/wasm; it was not executed there. The modernc probe failed for both Wasm targets with build constraints exclude all Go files inside modernc.org/libc, which is the build failure behind GopherForge's own driver.
The mattn probe is the instructive one. With CGO_ENABLED=0 it compiles without complaint, because the package ships a stub for builds without cgo, and then fails when it opens a database: Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub. A pipeline that builds with cgo disabled therefore produces a binary that passes compilation and fails on first use, so test the artifact you ship. With CGO_ENABLED=1 GOOS=linux GOARCH=amd64, the host C compiler could not even assemble runtime/cgo for the target. The README's answer is a cross toolchain, such as musl-cross or xgo. If one machine builds releases for several platforms, that requirement is the real cost of the cgo driver.

Put per-connection settings in the DSN
database/sql opens connections whenever its pool needs one, so any setting SQLite keeps on a connection must be applied every time a connection opens. A db.Exec("PRAGMA ...") at startup reaches one connection and silently misses the others. modernc's mechanism is the _pragma DSN parameter: each value is run with PRAGMA prepended as the driver opens a connection, and the parameter may repeat. The driver also accepts mattn-style shorthand keys such as _busy_timeout, _foreign_keys and _journal_mode, validates their values, and applies _busy_timeout before the _pragma list.
Two details in modernc's Driver.Open documentation deserve attention. First, a _pragma value is executed as SQL text rather than as one validated PRAGMA, so anything after a semicolon runs too. If a DSN can come from configuration instead of a constant, call sqlite.StrictPragmas(true) so that multi-statement values are rejected. Second, the form of the name matters. For a plain file name the driver removes the query before SQLite sees it, so SQLite's own URI parameters, mode=ro included, are ignored without an error. Only a name starting with file: passes them through. The lab checks both halves: app.db?mode=ro created a writable database, while file:app.db?mode=ro refused an INSERT with SQLITE_READONLY.
Building the URI with net/url avoids a second trap. A path containing a space, ? or # would otherwise end the file name early. The lab's helper escapes the path, and a test opens a database inside a directory named odd name #1?:
// FileDSN returns a "file:" URI for the database at path with the given
// query parameters. net/url escapes spaces, '?' and '#' in the path, which
// would otherwise end the file name early; SQLite decodes them again.
func FileDSN(path string, params url.Values) (string, error) {
abs, err := filepath.Abs(path)
if err != nil {
return "", err
}
u := url.URL{Scheme: "file", Path: filepath.ToSlash(abs), RawQuery: params.Encode()}
return u.String(), nil
}url.Values also escapes the parentheses in busy_timeout(5000); the driver decodes them. Rather than trust the string, the lab queries PRAGMA busy_timeout, journal_mode, synchronous and foreign_keys on a writer connection and asserts 5000, wal, 1 and 1.
Foreign keys are off until each connection asks
SQLite parses REFERENCES clauses whether or not it enforces them. Its documentation says foreign key constraints are disabled by default, for backwards compatibility, and must be enabled separately for each database connection. The lab shows what that means from Go. On a connection opened without the pragma, inserting a child whose parent does not exist succeeds, and a later query finds the orphan. With ?_pragma=foreign_keys(1) the same insert fails with extended code 787, SQLITE_CONSTRAINT_FOREIGNKEY, and the message FOREIGN KEY constraint failed.
The per-connection rule is easiest to see with two sql.Conn values borrowed from the same pool:
if _, err := first.ExecContext(ctx, "PRAGMA foreign_keys = ON"); err != nil {
t.Fatal(err)
}
var on int
if err := second.QueryRowContext(ctx, "PRAGMA foreign_keys").Scan(&on); err != nil {
t.Fatal(err)
}
if on != 0 {
t.Fatalf("second connection foreign_keys = %d, want 0", on)
}
if _, err := second.ExecContext(ctx, orphan); err != nil {
t.Fatalf("second connection rejected the orphan: %v", err)
}
if _, err := first.ExecContext(ctx, orphan); err == nil {
t.Fatal("first connection accepted an orphan after PRAGMA foreign_keys = ON")
}The first connection rejects the orphan and the second accepts it. In a service this appears as intermittent enforcement: requests that happen to borrow the connection where someone ran the PRAGMA behave correctly, and the others accept orphans. modernc's documentation makes the general point: a connection returned to the pool keeps PRAGMAs set with Exec, so state every connection needs belongs in the DSN or a connection hook.
A fourth subtest covers a detail that shapes migrations. The PRAGMA documentation says foreign_keys is a no-op inside a transaction, and the lab confirms that PRAGMA foreign_keys = ON after BEGIN leaves the value at 0. The same applies in reverse. SQLite's procedure for table changes that ALTER TABLE cannot express starts by turning foreign keys off and only then begins a transaction. A runner that wraps every step in a transaction, like the one later in this guide, cannot perform that first step from inside a migration, so such a rebuild needs its own code path on a dedicated connection.
WAL lets readers run beside one writer
Write-ahead logging is the setting that makes SQLite comfortable behind a Go service. The WAL documentation lists, among its advantages over the default rollback journal, that readers do not block writers and a writer does not block readers. It is equally clear about the limit: there can only be one writer at a time, because there is only one WAL file. WAL is also persistent: once set, it stays in effect for later connections and after the database is closed and reopened. That is why the lab's Open pings the writer pool, whose DSN sets journal_mode(WAL), before it opens the read-only pool. modernc's documentation notes that a mode=ro connection whose DSN asks to switch a database that is not yet in WAL mode fails to open with SQLITE_READONLY.
WAL comes with conditions. All processes using the database must be on the same host computer; WAL does not work over a network filesystem. A reader sees the snapshot that existed when its read transaction began, and a checkpoint cannot reset the WAL file while a reader still needs older pages. With overlapping readers and always at least one active, checkpoints may never complete and the WAL can grow without bound, which the documentation calls checkpoint starvation. In Go terms, close Rows promptly, avoid long read transactions, and do not stream a large export through one open query while the service keeps writing.
The lab also sets synchronous=NORMAL. The PRAGMA documentation describes that trade precisely: in WAL mode, NORMAL is always consistent and safe from corruption, but a transaction committed under it might roll back after a power loss or system crash. If losing the most recent commits to a power failure is unacceptable, keep FULL and accept the extra syncs.
A busy timeout helps only before a transaction reads
When another connection holds the write lock, SQLite returns SQLITE_BUSY, which modernc reports as database is locked (5). PRAGMA busy_timeout installs a handler that sleeps and retries until the given number of milliseconds has accumulated. It is the first thing to set, and modernc does not set it for you. It is not enough on its own, because SQLite does not always call the handler.
The transaction documentation explains why. A plain BEGIN is DEFERRED: the first SELECT starts a read transaction and the first write tries to upgrade it. If another connection has already modified the database, or is in the process of modifying it, the upgrade is not possible and the statement fails with SQLITE_BUSY. The busy-handler documentation adds that SQLite returns SQLITE_BUSY instead of invoking the handler when waiting could deadlock, which is exactly a reader that wants to become a writer while someone else writes.
The lab reproduces this deterministically with two pools on one WAL file, each with a 5000 ms busy timeout and default DEFERRED transactions:
// Two pools with the default DEFERRED transactions and a 5 s busy timeout.
deferred := "file:" + path + "?_pragma=busy_timeout(5000)"
a, b := openDSN(t, deferred), openDSN(t, deferred)
txA, err := a.BeginTx(ctx, nil)
if err != nil {
t.Fatal(err)
}
defer txA.Rollback()
readA := scalar[int](t, txA, "SELECT hits FROM counters WHERE name = 'jobs'") // A now holds a read snapshot
txB, err := b.BeginTx(ctx, nil)
if err != nil {
t.Fatal(err)
}
mustExec(t, txB, "UPDATE counters SET hits = hits + 10 WHERE name = 'jobs'") // B holds the write lock
began := time.Now()
_, err = txA.ExecContext(ctx, "UPDATE counters SET hits = ? WHERE name = 'jobs'", readA+1)
elapsed := time.Since(began)
if !sqliteflow.IsBusy(err) {
t.Fatalf("upgrade while B writes: %v (code %d), want SQLITE_BUSY", err, sqliteflow.Code(err))
}
if elapsed > 2*time.Second {
t.Fatalf("upgrade failed after %v; the busy timeout should not have been waited out", elapsed)
}A's UPDATE failed with code 5 almost at once; the logged elapsed time rounded to 0 ms, so the five-second budget was never used. After B committed, A's next attempt failed with extended code 517, SQLITE_BUSY_SNAPSHOT: its snapshot was stale and no amount of waiting could make it current. Rolling back and running the whole transaction again succeeded and included B's change.
BEGIN IMMEDIATE takes the write lock before anything is read, so the busy timeout applies to it. modernc exposes it as _txlock=immediate, which makes every BeginTx on that pool issue BEGIN IMMEDIATE. The lab runs this read-modify-write function from two independent handles, twenty times each and concurrently; all forty transactions commit and the counter ends at 40:
// increment is a read-modify-write transaction: the shape that breaks when
// two connections start it as DEFERRED.
func increment(ctx context.Context, db *sql.DB) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
var hits int64
if err := tx.QueryRowContext(ctx, "SELECT hits FROM counters WHERE name = 'jobs'").Scan(&hits); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "UPDATE counters SET hits = ? WHERE name = 'jobs'", hits+1); err != nil {
return err
}
return tx.Commit()
}A second test holds the write lock in one transaction for 300 ms; the other writer's BeginTx waited 340 to 350 ms in the busy handler across verbose runs and then committed. As a negative control, a copy of the lab with _txlock=deferred failed both tests: the concurrent writers reported codes 5 and 517, and the second writer no longer waited for the lock.
Branch on the code, not on the message text:
// Code returns the SQLite result code carried by err, or 0 when err did not
// come from SQLite. modernc.org/sqlite reports extended codes, such as 517
// for SQLITE_BUSY_SNAPSHOT; the low byte is the primary code.
func Code(err error) int {
var e *sqlite.Error
if errors.As(err, &e) {
return e.Code()
}
return 0
}
// IsBusy reports whether err is SQLITE_BUSY or one of its extended codes.
func IsBusy(err error) bool {
return Code(err)&0xff == sqlite3.SQLITE_BUSY
}A SQLITE_BUSY_SNAPSHOT, or a BUSY from an upgrade, means the transaction must start again from BeginTx, never that the failed statement should be repeated. A BUSY from BEGIN IMMEDIATE after the timeout expired means the lock stayed taken for the whole budget, which is a capacity signal rather than an invitation to retry in a loop. Bounded, whole-operation retries are discussed in retries and idempotency keys.

One writer pool beside a read-only pool
Inside one process, the simplest way to avoid writer contention is to have one writing connection. The lab's Open creates two *sql.DB values on the same file: a writer limited to a single connection with _txlock=immediate, and a reader pool opened with mode=ro.
// Open opens the database at path, creating it if needed. Pragmas are
// per-connection settings, so they travel in the DSN and every connection
// the pools open gets them.
func Open(ctx context.Context, path string, readers int) (*DB, error) {
writeDSN, err := FileDSN(path, url.Values{
"_txlock": {"immediate"},
"_pragma": {"busy_timeout(5000)", "journal_mode(WAL)", "synchronous(NORMAL)", "foreign_keys(1)"},
})
if err != nil {
return nil, err
}
readDSN, err := FileDSN(path, url.Values{
"mode": {"ro"},
"_pragma": {"busy_timeout(5000)"},
})
if err != nil {
return nil, err
}
w, err := sql.Open("sqlite", writeDSN)
if err != nil {
return nil, err
}
w.SetMaxOpenConns(1)
// Opening the writer first creates the file and switches it to WAL,
// which persists in the file, before a read-only connection sees it.
if err := w.PingContext(ctx); err != nil {
w.Close()
return nil, err
}
r, err := sql.Open("sqlite", readDSN)
if err != nil {
w.Close()
return nil, err
}
r.SetMaxOpenConns(readers)
if err := r.PingContext(ctx); err != nil {
r.Close()
w.Close()
return nil, err
}
return &DB{Write: w, Read: r}, nil
}With SetMaxOpenConns(1), concurrent writes queue inside database/sql instead of colliding inside SQLite. In the lab, eight goroutines each perform ten upserts through the writer while four goroutines query through the reader pool; no call fails and the counter ends at 80. The writer pool's Stats recorded between 76 and 79 waits across three verbose runs, which is the queue doing its job; reading WaitCount and WaitDuration is covered in the database/sql guide linked above. A write sent to the read pool fails with SQLITE_READONLY, so a misrouted INSERT is caught by the first test that makes it.
A single connection has one sharp edge. A goroutine holding a transaction from the writer pool owns its only connection, so any call on that pool from inside the transaction can only wait. The lab demonstrates it: inside an open transaction, an upsert on app.Write with a 200 ms deadline returns context.DeadlineExceeded. Without a deadline it would wait forever. Pass the *sql.Tx to everything that runs inside the transaction.
The pattern does not remove the need for a busy timeout. Other processes on the same host, such as a second copy of the binary during a deploy, a migration job or an operator's shell, still contend at the SQLite level, which is why the writer DSN keeps busy_timeout(5000). modernc's documentation gives a reason to bound the reader pool too: each connection carries its own page cache, and database/sql opens connections without limit by default.
STRICT tables end silent type conversion
An ordinary SQLite table uses type affinity: the declared type is a preference, not a constraint. The datatype documentation applies its rules in order. A declared type containing INT gets INTEGER affinity; one containing CHAR, CLOB or TEXT gets TEXT; BLOB or no type at all gets BLOB; REAL, FLOA or DOUB gets REAL; anything else becomes NUMERIC. The lab pins two consequences. Inserting 'abc' into an ordinary INTEGER column stores text, and typeof reports text. A column declared STRING, which is not a SQLite type name, gets NUMERIC affinity, so the code '007' comes back as the integer 7.
Adding STRICT after the closing parenthesis of CREATE TABLE changes the rules for that table. Since SQLite 3.37.0, every column of a STRICT table must use INT, INTEGER, REAL, TEXT, BLOB or ANY, and a value that cannot be converted losslessly raises SQLITE_CONSTRAINT_DATATYPE. Lossless conversion still happens, as it does in other engines:
mustExec(t, db, `CREATE TABLE strict_items (qty INTEGER NOT NULL) STRICT;
CREATE TABLE loose_items (qty INTEGER NOT NULL, code STRING)`)
_, err := db.Exec("INSERT INTO strict_items VALUES (?)", "abc")
if got := sqliteflow.Code(err); got != sqlite3.SQLITE_CONSTRAINT_DATATYPE {
t.Fatalf("STRICT insert of 'abc': %v (code %d), want SQLITE_CONSTRAINT_DATATYPE", err, got)
}
t.Logf("STRICT: %v", err)
// Text that converts losslessly is still coerced, as in other engines.
mustExec(t, db, "INSERT INTO strict_items VALUES (?)", "42")
if got := scalar[string](t, db, "SELECT typeof(qty) FROM strict_items"); got != "integer" {
t.Fatalf("STRICT '42' stored as %s, want integer", got)
}The rejected insert reports cannot store TEXT value in INTEGER column strict_items.qty (3091), and the text '42' is stored as an integer. A column declared ANY in a STRICT table keeps values exactly as received. CHECK, NOT NULL, UNIQUE and foreign key constraints work as in ordinary tables, and the on-disk format is the same. The documented cost is compatibility: a database containing STRICT tables can only be read and written by SQLite 3.37.0 or later. All three drivers discussed here bundle 3.54.1, so the practical risk is an old external tool, such as an outdated command-line shell on a server, opening the same file. The lab's schema declares every table STRICT, and new schemas should start that way.
UPSERT with RETURNING in one statement
Counters, last-seen timestamps and idempotency records are often written as a SELECT followed by an INSERT or UPDATE. Even inside BEGIN IMMEDIATE, that is two statements and more code than needed. UPSERT, added in SQLite 3.24.0, and RETURNING, added in 3.35.0, turn it into one statement whose result comes back through QueryRowContext:
// Hit counts one visit to name and returns the new total. UPSERT with
// RETURNING makes it a single statement, so there is no gap between reading
// the old value and writing the new one.
func Hit(ctx context.Context, db *sql.DB, name string) (int64, error) {
var hits int64
err := db.QueryRowContext(ctx, `
INSERT INTO counters (name, hits) VALUES (?, 1)
ON CONFLICT (name) DO UPDATE SET hits = hits + 1
RETURNING hits`, name).Scan(&hits)
return hits, err
}Three calls return 1, 2 and 3 in the lab. In DO UPDATE SET hits = hits + 1, the bare column name refers to the existing row; the excluded. qualifier would refer to the value that the INSERT tried to write. The RETURNING documentation says an UPSERT reports both inserted and updated rows. With DO NOTHING no row changes, so nothing is returned, and Scan reports sql.ErrNoRows. The lab asserts exactly that, which matters wherever code treats ErrNoRows as "not found".
Three more caveats from the documentation are worth knowing before relying on RETURNING. Rows come back in arbitrary order, not necessarily the order in which they were changed. Returned values are computed before any AFTER trigger modifies the row. And an INSERT that takes its rows from a SELECT needs a WHERE clause, even WHERE true, before ON CONFLICT, to resolve a parsing ambiguity. Because the statement is a write, run it on the writer pool, which also gives it the busy timeout and the queue described above.
Migrations with PRAGMA user_version
SQLite reserves an integer at offset 60 of the database header for applications. PRAGMA user_version reads and writes it, and SQLite makes no use of it itself, which makes it a natural schema version that travels inside the file. The lab's runner keeps an append-only slice of SQL steps, applies the step at index user_version, and raises the version in the same transaction:
func migrateOne(ctx context.Context, db *sql.DB, steps []string) (done bool, err error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return false, err
}
defer tx.Rollback()
var version int
if err := tx.QueryRowContext(ctx, "PRAGMA user_version").Scan(&version); err != nil {
return false, err
}
switch {
case version > len(steps):
return false, fmt.Errorf("schema version %d is newer than this binary (%d)", version, len(steps))
case version == len(steps):
return true, nil
}
if _, err := tx.ExecContext(ctx, steps[version]); err != nil {
return false, fmt.Errorf("migration %d: %w", version+1, err)
}
// PRAGMA does not take 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 false, tx.Commit()
}Schema changes roll back with the transaction, so a failing step leaves nothing half-applied. In the lab, a step that creates table b and then inserts into a missing table returns migration 2: SQL logic error: no such table: missing (1); afterwards user_version is still 1 and b does not exist. A second run against an up-to-date file applies zero steps and leaves sqlite_schema unchanged, which is the idempotence a startup migration needs. A binary whose list is shorter than the file's version refuses to continue, so an older release cannot write to a schema it does not understand after a rollback.
The version is read inside the transaction for a reason. Two processes that start together and read it outside both see 0 and both try step one. On the writer pool, _txlock=immediate makes the second process wait in BEGIN IMMEDIATE until the first commits, and it then reads the new version. The lab opens two independent handles on one file, runs both migrations concurrently and asserts that exactly three steps were applied in total. The deferred negative control failed this test with database is locked (5).
PRAGMA statements do not accept bound parameters, so the runner formats the next version itself. That is safe only because the value is an int; never format anything else into SQL this way.
Back up a live database
A plain file copy of a live database is not a backup. In WAL mode, changes are appended to the -wal file and reach the main file only when a checkpoint transfers them, and SQLite's guide to avoiding corruption warns that a copy taken in the middle of a transaction might contain some old and some new content. That guide lists VACUUM INTO, the backup API and the sqlite3_rsync utility as safe ways to copy a live database. The lab tests the first two through modernc.
VACUUM INTO builds a new, compacted database from a read transaction on the source, leaving the original unchanged. The target must not exist or must be empty. Its argument is an expression, so a ? placeholder carries the path safely, and the documentation says SQLite syncs the output when the source's synchronous setting is NORMAL or FULL. The lab's helper writes to a temporary name and renames it into place:
// BackupTo writes a consistent copy of the database to dest with VACUUM
// INTO. SQLite refuses to write into an existing non-empty file, so the copy
// goes to a temporary name first and is renamed into place.
func BackupTo(ctx context.Context, db *sql.DB, dest string) error {
tmp := dest + ".partial"
if err := os.Remove(tmp); err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
if _, err := db.ExecContext(ctx, "VACUUM INTO ?", tmp); err != nil {
return err
}
return os.Rename(tmp, dest)
}VACUUM INTO worked from the read-only pool, so backups need not queue behind the single writer. A second VACUUM INTO the same name failed with output file already exists, which is why the helper removes a leftover temporary file first. The copy passed PRAGMA integrity_check, contained all 200 rows and the source's user_version, and used journal_mode delete.
The online backup API copies pages incrementally. modernc exposes it on its driver connection, which sql.Conn.Raw reaches; the driver connection must not be used after the function returns:
// OnlineBackup copies the database to dest with SQLite's online backup API,
// pagesPerStep pages at a time, through modernc.org/sqlite's driver
// connection. A write from another connection between steps makes SQLite
// restart the copy, so keep steps large on a busy database.
func OnlineBackup(ctx context.Context, db *sql.DB, dest string, pagesPerStep int32) error {
conn, err := db.Conn(ctx)
if err != nil {
return err
}
defer conn.Close()
return conn.Raw(func(driverConn any) error {
src, ok := driverConn.(interface {
NewBackup(dest string) (*sqlite.Backup, error)
})
if !ok {
return errors.New("driver connection has no backup API")
}
b, err := src.NewBackup(dest)
if err != nil {
return err
}
for more := true; more; {
more, err = b.Step(pagesPerStep)
if err == nil {
err = ctx.Err()
}
if err != nil {
b.Finish() // releases both ends; err already says why
return err
}
}
return b.Finish()
})
}That copy also passed the checks, but unlike the VACUUM INTO copy it reported journal_mode WAL when opened. The SQLite documentation describes the trade-off. VACUUM INTO produces a minimal file with deleted content purged; the backup API uses fewer CPU cycles and can run incrementally, but if another connection writes to the source between steps, the backup restarts, and if that happens often enough it may never finish. On a busy database, copy in large steps or use VACUUM INTO. Either way, open the copy, run integrity_check and count something before trusting it.
Test against temporary files, not :memory:
Each :memory: name opens a distinct database. The SQLite documentation says two connections opened with :memory: create two independent in-memory databases. Through a pool, that means a table created on one connection is missing on the next, and the lab's test gets no such table from a second sql.Conn. Shared-cache URIs can join them, but SQLite describes shared-cache mode as obsolete and discourages its use, and mattn's README warns that the in-memory database disappears when the pool closes its last connection.
A temporary file avoids all of that and exercises the same WAL, locking and pragma behaviour as production. The lab's helper gives each test its own directory and closes the pools before the directory is removed:
// openApp gives each test its own database file in a temporary directory,
// migrated to the current schema. Cleanup functions run last added, first
// called, so the pools close before t.TempDir removes the file, its -wal
// and its -shm.
func openApp(t *testing.T) *sqliteflow.DB {
t.Helper()
db, err := sqliteflow.Open(t.Context(), filepath.Join(t.TempDir(), "app.db"), 4)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := db.Close(); err != nil {
t.Error(err)
}
})
if _, err := sqliteflow.Migrate(t.Context(), db.Write, sqliteflow.Schema); err != nil {
t.Fatal(err)
}
return db
}t.Context is canceled just before cleanup functions run, and cleanups run last added, first called, so db.Close happens before t.TempDir deletes app.db, its -wal and its -shm. Every test starts from the real migration list, so the schema under test is the schema that ships, STRICT tables and foreign keys included. Real files also make the concurrency tests meaningful: two sqliteflow.Open calls on one path give two independent sets of connections that contend for SQLite's locks, which is how the lab stands in for two processes.
Keep a few tests that pin driver defaults, as the lab's TestDriverDefaults does. They are cheap, and they are the tests that fail first when someone swaps drivers, upgrades one, or removes a DSN parameter that looked redundant.
When SQLite is the wrong choice
SQLite's documentation is direct about where a client/server engine works better. If many client programs send SQL to the same database over a network, use a client/server database: network filesystems add latency, and buggy file locking in many of them can let two clients corrupt the same file. A website that is write-intensive, or busy enough to need multiple servers, should consider a client/server engine. SQLite supports an unlimited number of simultaneous readers but only one writer at any instant; for many applications writers simply queue, and some applications need more write concurrency than that. A database is limited to 281 terabytes, and many filesystems limit a single file to less.
For a Go service the practical question is deployment shape. One process, or a few on one host, writing in short transactions to data that lives on that host: SQLite with WAL, a busy timeout, BEGIN IMMEDIATE, one writer pool and STRICT tables is a sound default, and the operational surface is a file you can back up with one statement. Several replicas behind a load balancer that must all write the same data cannot share that file safely, and the data belongs on a database server. A later move is easier when queries stay behind a repository layer and migrations are explicit.
The lab is part of this edition's downloadable archive, in the sqliteflow folder. Run go test -race ./... there; the size probes need -tags sizeprobe, and the mattn probe also needs cgo and a C compiler.
Primary sources & editorial method
We checked these primary references on 30 November 2026. Release facts are attributed; recommended workflows and examples are GopherForge analysis. Illustrations are conceptual, not vendor screenshots or benchmarks.
- modernc.org/sqlite package documentation
- mattn/go-sqlite3 README
- ncruces/go-sqlite3 README
- ncruces/go-sqlite3 database/sql driver
- database/sql package
- testing package
- SQLite foreign key support
- SQLite PRAGMA statements
- SQLite write-ahead logging
- SQLite transactions
- SQLite busy timeout
- SQLite busy handler
- SQLite result codes
- SQLite STRICT tables
- Datatypes in SQLite
- SQLite UPSERT
- SQLite RETURNING clause
- SQLite ALTER TABLE
- SQLite VACUUM and VACUUM INTO
- SQLite online backup API
- How to corrupt an SQLite database file
- SQLite in-memory databases
- SQLite shared-cache mode
- Appropriate uses for SQLite