purego-sqlite
Use SQLite from Go without cgo. The library loads the system libsqlite3.so
at runtime through purego, so builds work
with CGO_ENABLED=0.
Early stage (v0.x). Linux only. The public API may change.
Install
go get bnema.dev/purego-sqlite
Requirements:
- Go 1.27+
libsqlite3.so or libsqlite3.so.0 installed on the system
- Optional:
SQLITE_LIB_PATH=/custom/path/libsqlite3.so loads only that file
Quick start
The package offers two ways to use SQLite:
| Package |
Use it when |
driver |
You want the standard database/sql API |
sqlite |
You need SQLite features such as Go SQL functions, hooks, blobs or backups |
With database/sql
import (
"database/sql"
_ "bnema.dev/purego-sqlite/driver"
)
db, err := sql.Open("sqlite3", "./app.db")
The Context methods (QueryContext, ExecContext, PrepareContext,
BeginTx) support cancellation. Cancelling a context interrupts only the
running operation, so the connection stays usable.
The driver registers as sqlite3, the same name as mattn/go-sqlite3. Do not
import both in one binary.
With the direct API
import "bnema.dev/purego-sqlite/sqlite"
conn, err := sqlite.Open("./app.db")
if err != nil {
return err
}
defer conn.Close()
if _, err := conn.Exec("CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, name TEXT)"); err != nil {
return err
}
rows, err := conn.Query("SELECT name FROM users WHERE id = ?", 42)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return err
}
}
return rows.Err()
Features
| Area |
Supported |
| Connections |
Open (paths and file: URIs), OpenFlags (flags and VFS), Close, Interrupt, limits, status counters |
| Statements |
Prepare, bind, step, scan, reset, column metadata, expanded and normalized SQL |
| Errors |
Typed errors with errors.Is / errors.As, primary and extended codes |
| Transactions |
Through SQL, autocommit and transaction state |
| Blobs |
Incremental read, write and reopen |
| Backup |
Online backup, all at once or in steps |
| WAL |
WALCheckpoint, WALAutoCheckpoint |
| Extensions |
EnableLoadExtensionAPI, LoadExtension |
| Go callbacks |
Scalar functions, aggregates, collations, ExecFunc, busy handler, commit / rollback / update hooks, progress handler, authorizer |
database/sql |
Driver with context cancellation and time.Time decoding |
| Testing |
Mockable interfaces and generated mocks |
Main features not supported yet (cmd/sqlitegen/coverage_gen.tsv lists the
status of every C function):
- Window functions written in Go (SQL window functions work)
- Virtual tables and R*Tree callbacks
trace_v2, wal_hook, preupdate_hook, unlock_notify
- Session and changeset extension
serialize / deserialize, snapshots
- UTF-16 APIs (Go strings are UTF-8)
Direct API guide
Open a database
sqlite.Open(dsn) opens read-write and creates the file if needed. It accepts
file: URIs, for example file:app.db?mode=ro for read-only access.
sqlite.OpenFlags(dsn, flags, vfs) takes explicit SQLITE_OPEN_* flags and a
VFS name ("" for the default).
Run statements
conn.Exec returns a *sqlite.Result (LastInsertId, RowsAffected),
conn.Query returns *sqlite.Rows, and conn.Prepare returns *sqlite.Stmt.
conn.Exec(sql) without arguments can run several statements at once
(a script).
conn.Exec(sql, args...) and conn.Query(sql, args...) prepare a single
statement. The number of arguments must equal the statement’s
NumInput() (usually one per ?).
To reuse a statement, prepare it once and bind values yourself. Bind indices
start at 1, column indices at 0.
stmt, err := conn.Prepare("SELECT ?")
if err != nil {
return err
}
defer stmt.Close()
if err := stmt.BindText(1, "hello"); err != nil {
return err
}
row, err := stmt.Step() // true: a row is ready, false: done
if err != nil {
return err
}
if row {
var value string
if err := stmt.Scan(&value); err != nil {
return err
}
}
Reset lets you run the statement again with the same bindings.
ClearBindings sets every parameter back to NULL.
Handle errors
_, err := conn.Exec("INSERT INTO users(id, name) VALUES (1, 'a')")
switch {
case errors.Is(err, sqlite.ErrConstraintPrimaryKey):
// duplicate primary key
case errors.Is(err, sqlite.ErrBusy):
// database locked by another connection, retry later
}
var sqlErr *sqlite.Error
if errors.As(err, &sqlErr) {
// sqlErr has the SQLite message and codes
}
sqlite.ErrConstraint matches every constraint error. Specific sentinels
such as ErrConstraintPrimaryKey, ErrConstraintUnique or
ErrConstraintNotNull match only their extended code.
If the installed SQLite lacks a function, the call returns an error matching
sqlite.ErrNotAvailable. Functions and methods that cannot return an error
panic in that case, and also when libsqlite3.so fails to load.
Read and write blobs
Open a blob in place and read or write bytes without loading the whole value.
Reads and writes cannot change the blob size: create it first with
zeroblob(n).
// files(id INTEGER PRIMARY KEY, data BLOB), row 1 holds zeroblob(4)
blob, err := conn.BlobOpen("main", "files", "data", 1, true)
if err != nil {
return err
}
writeErr := blob.Write([]byte("data"), 0)
return errors.Join(writeErr, blob.Close())
Back up a database
Copy src into dst while src stays in use. Step(-1) copies everything;
a positive number copies that many pages per step.
backup, err := dst.Backup("main", src, "main")
if err != nil {
return err
}
for {
done, err := backup.Step(-1)
if errors.Is(err, sqlite.ErrBusy) || errors.Is(err, sqlite.ErrLocked) {
time.Sleep(10 * time.Millisecond) // add a deadline in production
continue
}
if err != nil || done {
return errors.Join(err, backup.Close())
}
}
Do not use dst for anything else until the backup is closed.
Go callbacks
These let SQLite call your Go code. They are available on *sqlite.Conn.
SQL functions
// SELECT double(21) returns 42
err := conn.CreateFunction("double", 1, sqlite.SQLITE_DETERMINISTIC,
func(ctx *sqlite.Context, args []*sqlite.Value) {
ctx.ResultInt64(args[0].Int64() * 2)
})
The arity is the number of arguments (-1 accepts any number). Passing nil
instead of a function removes it.
Aggregates
An aggregate receives one Step per row and one Final at the end.
CreateAggregate takes a factory, because SQLite needs a fresh instance per
query and per group.
type sum struct{ total int64 }
func (s *sum) Step(_ *sqlite.Context, args []*sqlite.Value) { s.total += args[0].Int64() }
func (s *sum) Final(ctx *sqlite.Context) { ctx.ResultInt64(s.total) }
// SELECT mysum(price) FROM items
err := conn.CreateAggregate("mysum", 1, 0, func() sqlite.Aggregate { return &sum{} })
Collations
// ORDER BY name COLLATE nocase_go
err := conn.CreateCollation("nocase_go", func(a, b string) int {
return strings.Compare(strings.ToLower(a), strings.ToLower(b))
})
Hooks
conn.BusyTimeout(5000) // wait up to 5 s when the database is locked
conn.UpdateHook(func(op int, db, table string, rowid int64) {
log.Printf("row %d changed in %s", rowid, table)
})
conn.SetAuthorizer(func(action int, a1, a2, a3, a4 string) sqlite.AuthResult {
return sqlite.AuthOK // or AuthDeny, AuthIgnore
})
Each of these returns an error. Also available: BusyHandler, CommitHook
(return true to cancel the commit), RollbackHook and ProgressHandler
(return true to interrupt). Passing nil removes a hook. BusyTimeout
replaces any BusyHandler.
Visit rows from a script
ExecFunc runs one or more statements and calls your function for each row.
Values are copied text, nil means SQL NULL, and returning true stops
execution with sqlite.ErrAbort. Text and blobs stop at their first NUL byte:
use Query to read them in full.
err := conn.ExecFunc("SELECT id, name FROM users", func(columns []string, values []*string) bool {
fmt.Println(columns, *values[0])
return false // keep going
})
Callback rules
Context and Value are valid only during the callback. Text() and
Blob() return copies you can keep.
- Do not use the connection from inside a hook, and never close it there.
- Collations can run on several SQLite threads at once: make them safe for
concurrent use. Their strings borrow SQLite memory: copy them
(
strings.Clone) if you keep them.
- A panic in a callback is recovered and returned as a
*sqlite.CallbackPanicError by the call that triggered it (Step, Exec,
Close, …). It does not roll back the transaction.
- A collation must not panic: SQLite cannot fail a comparison, so an index
may end up inconsistent. Run
REINDEX after fixing the comparator.
- Aggregates cannot be used as window functions.
Rules for connections and handles
- Do not use one connection from several goroutines at the same time.
Conn.Interrupt is the exception.
- Close rows, statements, blobs and backups before their connection.
- Methods on a closed handle return
sqlite.ErrMisuse, or do nothing when
they have no error result.
Testing with mocks
Depend on sqliteiface.DB instead of *sqlite.Conn. In production, pass
sqliteiface.Wrap(conn). In tests, pass a mock from sqlite/mocks. Tests
that use mocks do not need libsqlite3.so.
type UserRepo struct{ db sqliteiface.DB }
func (r *UserRepo) Count() (n int64, err error) {
rows, err := r.db.Query("SELECT count(*) FROM users")
if err != nil {
return 0, err
}
defer func() { err = errors.Join(err, rows.Close()) }()
if !rows.Next() {
return 0, rows.Err()
}
err = rows.Scan(&n)
return n, err
}
func TestCount(t *testing.T) {
db := mocks.NewMockDB(t)
rows := mocks.NewMockRows(t)
db.EXPECT().Query("SELECT count(*) FROM users").Return(rows, nil)
rows.EXPECT().Next().Return(true)
rows.EXPECT().Scan(mock.Anything).RunAndReturn(func(dest ...any) error {
*(dest[0].(*int64)) = 3
return nil
})
rows.EXPECT().Close().Return(nil)
n, err := (&UserRepo{db: db}).Count()
require.NoError(t, err)
require.Equal(t, int64(3), n)
}
Available mocks: MockDB, MockStmt, MockRows, MockResult.
database/sql value decoding
The driver returns time.Time only for columns declared as DATE,
DATETIME or TIMESTAMP. Dates stored in TEXT columns, and expressions
without a declared type, keep their SQLite type.
Contributing
How it works
cmd/sqlitegen reads the vendored sqlite3.h and generates:
internal/capi: low-level purego bindings for each C function (internal)
sqlite/*_gen.go: the safe Go methods, error handling and callback glue
cmd/sqlitegen/spec.go controls how each C function is exposed, and
coverage_gen.tsv lists the status of every function.
Build and test
CGO_ENABLED=0 go build ./...
CGO_ENABLED=0 go test ./...
go test -tags integration ./... # needs libsqlite3.so
Regenerate
go generate ./...
This uses the vendored header and Mockery v3.9.2. To use another header:
go run ./cmd/sqlitegen --header /path/sqlite3.h
Layout
sqlite/ public Go API
sqliteiface/ mockable interfaces
mocks/ generated mocks
driver/ database/sql driver
internal/
capi/ generated purego bindings
bindgen/ reusable generator core
loader/ shared library loader
cmd/sqlitegen/ generator, SQLite spec and vendored header
integration/ database/sql integration tests
License
MIT
评论