SQLite from Go: connections, drivers and types · 4 MIN READ

Choose a SQLite driver and configure every connection through the DSN

Compare modernc.org/sqlite, mattn/go-sqlite3 and ncruces/go-sqlite3, and use DSN parameters so that every pooled connection gets the same pragmas and transaction mode.

Three mature SQLite drivers exist for Go and they differ in how the C library reaches your binary: translated to Go, linked through cgo, or compiled to WebAssembly. Whichever you pick, most SQLite settings belong to a connection rather than to the file, and database/sql opens connections whenever it likes. A setting that is not in the data source name is a setting some of your connections do not have.

sqlite · A MAP OF THE IDEA

  1. Pick a driver
  2. Build one DSN
  3. Pragmas per connection
  4. Ping at startup

Useful when

  • Every connection is configured identically, including replacements.
  • Pure-Go drivers keep cross-compilation and static binaries simple.

Watch out

  • DSN parameter names differ between drivers.
  • mattn and ncruces both register sqlite3 and cannot share a binary.

Implementation & operation cost: One constructor that owns the DSN, plus a driver choice made consciously for your build and deployment targets.

01

Three drivers, three ways to ship the C library

modernc.org/sqlite is the SQLite C source mechanically translated to Go. It needs no C toolchain, cross-compiles like any Go package with CGO_ENABLED=0, registers the driver name "sqlite", and ships with FTS5 and JSON enabled; the price is a larger binary, slower builds and somewhat lower raw speed than C on heavy workloads, on the platforms its generated code supports. github.com/mattn/go-sqlite3 wraps the real C amalgamation through cgo, registers "sqlite3", needs CGO_ENABLED=1 and a C compiler for every target, and enables some features such as FTS5 only through build tags. github.com/ncruces/go-sqlite3 starts from a WebAssembly build of SQLite and, since v0.33.0, translates it into Go source with wasm2go, so no Wasm runtime such as wazero is involved: no cgo, its database/sql driver lives in the driver subpackage, and the embed subpackage is deprecated because the SQLite build is already compiled in; importing it now only prints a message that the import is unnecessary. mattn and ncruces both register "sqlite3", so one binary cannot import both.

02

A PRAGMA through the pool reaches one connection

The program first runs PRAGMA foreign_keys = ON with db.ExecContext on a plain path, then holds three connections at once and reads four settings on each. Only the connection that happened to execute the pragma has it. Then it opens a second database whose DSN carries _pragma parameters and _txlock=immediate: modernc.org/sqlite executes each _pragma (busy_timeout first, the rest in a fixed order) every time the pool opens a connection, so all three agree.

go
package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"
	"path/filepath"

	_ "modernc.org/sqlite"
)

// settings reads the pragmas that matter on one specific connection.
func settings(ctx context.Context, conn *sql.Conn) string {
	var fk, busy, sync int
	var journal string
	for _, q := range []struct {
		sql  string
		dest any
	}{
		{"PRAGMA foreign_keys", &fk},
		{"PRAGMA busy_timeout", &busy},
		{"PRAGMA journal_mode", &journal},
		{"PRAGMA synchronous", &sync},
	} {
		if err := conn.QueryRowContext(ctx, q.sql).Scan(q.dest); err != nil {
			log.Fatal(err)
		}
	}
	return fmt.Sprintf("foreign_keys=%d busy_timeout=%d journal_mode=%s synchronous=%d", fk, busy, journal, sync)
}

// report holds three connections at once, so the pool must open three.
func report(ctx context.Context, label string, db *sql.DB) {
	var conns []*sql.Conn
	for i := 0; i < 3; i++ {
		conn, err := db.Conn(ctx)
		if err != nil {
			log.Fatal(err)
		}
		conns = append(conns, conn)
		fmt.Printf("%s conn %d: %s\n", label, i+1, settings(ctx, conn))
	}
	for _, c := range conns {
		c.Close()
	}
}

func main() {
	ctx := context.Background()
	dir, err := os.MkdirTemp("", "dsn")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)

	// 1. Plain path, then a PRAGMA through the pool: it lands on one connection.
	plain, err := sql.Open("sqlite", filepath.Join(dir, "plain.db"))
	if err != nil {
		log.Fatal(err)
	}
	if _, err := plain.ExecContext(ctx, "PRAGMA foreign_keys = ON"); err != nil {
		log.Fatal(err)
	}
	report(ctx, "db.Exec pragma", plain)
	plain.Close()

	// 2. The same settings in the DSN: the driver runs them on every new connection.
	const params = "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)" +
		"&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)&_txlock=immediate"
	dsn := "file:" + filepath.ToSlash(filepath.Join(dir, "app.db")) + "?" + params
	fmt.Println("DSN parameters:", params)

	db, err := sql.Open("sqlite", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	report(ctx, "DSN pragmas   ", db)
	// Closing a *sql.Conn returns it to the pool; at most two stay idle by default.
	fmt.Println("connections kept idle:", db.Stats().Idle)
}
Read the code

The first three lines show foreign_keys=1 on connection 1 and 0 on connections 2 and 3, all in rollback-journal mode (journal_mode=delete, synchronous=2 is FULL). With the DSN, every connection reports foreign_keys=1, busy_timeout=5000, journal_mode=wal and synchronous=1 (NORMAL). The last line shows that after the three *sql.Conn values are closed, the pool keeps two of them idle, its default MaxIdleConns.

03

Which settings live where

journal_mode=WAL is persistent: once one connection switches the file, the mode is stored in the database and later connections inherit it. foreign_keys, busy_timeout, synchronous, cache_size, temp_store and query_only are per connection and reset to their defaults on every new connection. user_version and application_id are stored in the file header. That is why the DSN is the right home for the per-connection group: a pool may close an idle connection after ConnMaxIdleTime and open a new one in the middle of a request, and that new connection must be configured before your first statement runs.

04

DSN syntax per driver

modernc.org/sqlite accepts a plain path or a file: URI, repeated _pragma=name(value) parameters, _txlock=deferred|immediate|exclusive for BeginTx, and _time_format=sqlite for how time.Time values are written; recent versions also accept mattn-style shorthands. mattn/go-sqlite3 uses keys such as _foreign_keys=1, _busy_timeout=5000, _journal_mode=WAL and _txlock=immediate. ncruces/go-sqlite3 uses file: URIs with _pragma and _txlock. Standard SQLite URI parameters such as mode=ro, mode=memory, cache=shared and immutable=1 are interpreted by SQLite itself. Keep the DSN in one constructor function so the parameters cannot drift between call sites.

go
func OpenDB(path string) (*sql.DB, error) {
	dsn := "file:" + filepath.ToSlash(path) +
		"?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)" +
		"&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)&_txlock=immediate"
	db, err := sql.Open("sqlite", dsn)
	if err != nil {
		return nil, err
	}
	if err := db.Ping(); err != nil {
		db.Close()
		return nil, err
	}
	return db, nil
}
Read the code

One function owns the data source name, so tests, commands and the server all open the database with identical settings. The Ping turns a malformed parameter or an unwritable directory into a startup error instead of a failure on the first request.

05

Choosing in practice

Prefer modernc.org/sqlite or ncruces when you want plain go build, easy cross-compilation, static binaries and scratch containers; prefer mattn when you already have cgo in the build, need the C library's full speed or a C extension. Benchmark your own queries before deciding on speed alone, because for many services the time is spent in I/O and fsync, not in the SQL engine. The GopherForge app's coming gopherforge.app/sqlite driver also registers the name sqlite and follows modernc's _pragma parameters, so a database/sql program written against modernc reads the same. Other DSN parameters, such as _txlock, are driver-specific: check them against the driver you ship, and remember that pragmas issued as statements behave the same with every driver.

TAKE THIS WITH YOU

Pick the driver by how you build and ship: modernc for pure Go, mattn for cgo and C speed, ncruces for Wasm without cgo. Put every per-connection pragma and the transaction mode in the DSN, because the pool opens new connections on its own schedule.

Check your understanding

You run db.Exec("PRAGMA foreign_keys = ON") once after sql.Open. Why do some later inserts still accept orphan rows?

Go to the source

Progress stays in this browser. No account needed.