SQLite from Go: connections, drivers and types · 3 MIN READ
Foreign keys are off until each connection turns them on
Show that REFERENCES clauses are not enforced by default, enable enforcement for every connection through the DSN, use ON DELETE CASCADE and find existing violations with foreign_key_check.
SQLite parses and stores every REFERENCES clause, and then, for backward compatibility, ignores it unless the connection has run PRAGMA foreign_keys = ON. The setting is not stored in the file and must be enabled on every connection, so a database written by a tool or a forgotten code path can already contain orphans.
sqlite · A MAP OF THE IDEA
- Declare REFERENCES
- Index the child column
- foreign_keys(1) in DSN
- foreign_key_check data
Useful when
- The database, not every code path, guards references.
- CASCADE and SET NULL keep related rows consistent.
Watch out
- Any connection without the pragma writes orphans.
- The pragma is silently ignored inside a transaction.
Implementation & operation cost: One DSN parameter, an index per foreign key and a one-time foreign_key_check on existing data.
Off by default, per connection
Foreign key enforcement was added to SQLite long after many applications depended on it being absent, so the default stayed OFF and remains so unless SQLite is compiled with a different default. PRAGMA foreign_keys = ON affects only the connection that runs it, lasts until that connection closes, and is a no-op inside an open transaction. With database/sql the dependable place is the DSN, so the driver turns it on for each connection the pool opens.
Same file, two kinds of connection
The program creates authors and books with ON DELETE CASCADE, then inserts a book for a missing author through a default connection and through one opened with _pragma=foreign_keys(1). It uses pragma_foreign_key_check to find the orphan, errors.As to read the extended result code, and finally tries to turn enforcement off inside a transaction.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"modernc.org/sqlite"
sqlite3 "modernc.org/sqlite/lib"
)
var ctx = context.Background()
const schema = `
CREATE TABLE authors (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE books (
id INTEGER PRIMARY KEY,
author_id INTEGER NOT NULL REFERENCES authors (id) ON DELETE CASCADE,
title TEXT NOT NULL
);
CREATE INDEX books_author ON books (author_id); -- the child side needs its own index
INSERT INTO authors (id, name) VALUES (1, 'Kernighan');
INSERT INTO books (author_id, title) VALUES (1, 'The Go Programming Language');`
func open(path, params string) *sql.DB {
db, err := sql.Open("sqlite", "file:"+filepath.ToSlash(path)+params)
if err != nil {
log.Fatal(err)
}
return db
}
func count(db *sql.DB, query string) int {
var n int
if err := db.QueryRowContext(ctx, query).Scan(&n); err != nil {
log.Fatal(err)
}
return n
}
func describe(err error) string {
var se *sqlite.Error
if errors.As(err, &se) {
return fmt.Sprintf("rejected, code %d (SQLITE_CONSTRAINT_FOREIGNKEY=%d)", se.Code(), sqlite3.SQLITE_CONSTRAINT_FOREIGNKEY)
}
if err != nil {
return err.Error()
}
return "accepted"
}
func main() {
dir, err := os.MkdirTemp("", "fk")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "library.db")
// Default connection: the REFERENCES clause is parsed and stored, but not enforced.
loose := open(path, "")
if _, err := loose.ExecContext(ctx, schema); err != nil {
log.Fatal(err)
}
fmt.Println("default PRAGMA foreign_keys =", count(loose, "PRAGMA foreign_keys"))
_, err = loose.ExecContext(ctx, "INSERT INTO books (author_id, title) VALUES (99, 'Orphan')")
fmt.Println("default: book for missing author 99:", describe(err))
fmt.Println("default: orphans found by foreign_key_check:", count(loose, "SELECT count(*) FROM pragma_foreign_key_check('books')"))
if _, err := loose.ExecContext(ctx, "DELETE FROM books WHERE author_id = 99"); err != nil {
log.Fatal(err)
}
loose.Close()
// Enforcing connection: the driver runs PRAGMA foreign_keys = ON on every new connection.
db := open(path, "?_pragma=foreign_keys(1)")
defer db.Close()
fmt.Println("DSN PRAGMA foreign_keys =", count(db, "PRAGMA foreign_keys"))
_, err = db.ExecContext(ctx, "INSERT INTO books (author_id, title) VALUES (99, 'Orphan')")
fmt.Println("enforced: book for missing author 99:", describe(err))
_, err = db.ExecContext(ctx, "UPDATE authors SET id = 2 WHERE id = 1")
fmt.Println("enforced: change a referenced key:", describe(err))
if _, err := db.ExecContext(ctx, "DELETE FROM authors WHERE id = 1"); err != nil {
log.Fatal(err)
}
fmt.Println("enforced: books left after deleting author 1 (ON DELETE CASCADE):", count(db, "SELECT count(*) FROM books"))
// Inside a transaction the pragma is a silent no-op.
tx, err := db.BeginTx(ctx, nil)
if err != nil {
log.Fatal(err)
}
if _, err := tx.ExecContext(ctx, "PRAGMA foreign_keys = OFF"); err != nil {
log.Fatal(err)
}
var inTx int
if err := tx.QueryRowContext(ctx, "PRAGMA foreign_keys").Scan(&inTx); err != nil {
log.Fatal(err)
}
fmt.Println("PRAGMA foreign_keys = OFF inside a transaction leaves it at", inTx)
if err := tx.Rollback(); err != nil {
log.Fatal(err)
}
}The default connection reports foreign_keys 0, accepts the orphan and foreign_key_check finds one violation. After deleting it, the DSN connection reports 1, rejects the orphan and an update of a referenced key with extended code 787, SQLITE_CONSTRAINT_FOREIGNKEY, and deleting author 1 cascades to the book. The last line shows the pragma left at 1 because it ran inside a transaction.
Actions and indexes
ON DELETE and ON UPDATE accept NO ACTION (the default), RESTRICT, SET NULL, SET DEFAULT and CASCADE. NO ACTION is checked at the end of the statement, RESTRICT immediately; DEFERRABLE INITIALLY DEFERRED moves the check to COMMIT, which helps when inserting rows that reference each other. SQLite does not create an index on the child column for you. Without books(author_id) indexed, every delete of an author scans the whole books table to find children, so add the index in the same migration as the constraint.
Turning it on for an existing database
Before enabling enforcement on data that was written without it, run PRAGMA foreign_key_check: it lists every row whose reference has no parent, with the table, rowid and constraint, and changes nothing. Fix or delete those rows in a migration, then enable the pragma in the DSN. Table rebuilds during migrations are the one time you deliberately switch enforcement off, outside the transaction, followed by foreign_key_check before committing, as the documented ALTER TABLE procedure describes.
SELECT "table", rowid, parent, fkid FROM pragma_foreign_key_check;
-- books | 7 | authors | 0 means books row 7 references a missing authorThe table-valued form of the pragma can be filtered and joined like a table. An empty result means every reference has a parent and enforcement can be enabled without breaking existing writes.
TAKE THIS WITH YOU
Foreign keys in SQLite are enforced only on connections that ran PRAGMA foreign_keys = ON, outside a transaction. Put it in the DSN, index every child column, choose ON DELETE actions deliberately and run foreign_key_check before relying on existing data.
Check your understanding
Your schema declares REFERENCES authors(id), yet an insert with a missing author succeeds. What is the most likely cause?
Go to the source
Progress stays in this browser. No account needed.