SQLite project: a tested notes repository · 5 MIN READ
Project: a tested notes repository with migrations, transactions and full-text search
Build a small notes store on SQLite that migrates itself, writes in IMMEDIATE transactions with RETURNING and optimistic versions, cascades tags, and searches with FTS5, with a check for every behaviour.
This project puts the course together in one package-sized program: a repository type that owns its *sql.DB, configures every connection through the DSN, migrates with PRAGMA user_version, keeps writes in short transactions, detects lost updates with a version column, and offers ranked search that is safe for any input. The same shape fits a command-line tool, a small web service or the coming GopherForge SQLite project template, where a program writes its database under /sandbox in the next app update.
sqlite · A MAP OF THE IDEA
- Open: DSN + migrate
- Write in IMMEDIATE tx
- Version-checked UPDATE
- Search quoted FTS5
Useful when
- One file holds data, schema version and search index.
- Constraints and triggers keep related rows consistent.
Watch out
- One writer at a time: keep transactions short.
- Triggers and FTS add work to every write.
Implementation & operation cost: About two hundred lines of Go and two migrations; the ongoing cost is keeping tests for every migration and behaviour.
Schema and configuration
Two migrations define the schema. The first creates a STRICT notes table with a CHECK on the title and a version column, and a STRICT WITHOUT ROWID note_tags table whose foreign key cascades deletes; the second adds an external-content FTS5 index with triggers and rebuilds it so existing notes become searchable. Open builds one DSN that turns on foreign keys and a busy timeout for every pooled connection, selects WAL with synchronous=NORMAL, and sets _txlock=immediate so every BeginTx issues BEGIN IMMEDIATE and takes the write lock before reading.
The repository and its checks
Create inserts with RETURNING id, version and writes tags in the same transaction. Update changes a row only WHERE id = ? AND version = ?, and tells a conflict from a missing note with a second query inside the same transaction. Delete uses RETURNING to detect a missing note. Search quotes every word before MATCH and can filter by tag. main exercises each behaviour and prints one PASS or FAIL line per check, then closes and reopens the store.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
_ "modernc.org/sqlite"
)
// ---- schema ---------------------------------------------------------------
var migrations = []string{
`CREATE TABLE notes (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL CHECK (title <> ''),
body TEXT NOT NULL DEFAULT '',
version INTEGER NOT NULL DEFAULT 1
) STRICT;
CREATE TABLE note_tags (
note_id INTEGER NOT NULL REFERENCES notes (id) ON DELETE CASCADE,
tag TEXT NOT NULL,
PRIMARY KEY (note_id, tag)
) STRICT, WITHOUT ROWID;
CREATE INDEX note_tags_tag ON note_tags (tag, note_id);`,
`CREATE VIRTUAL TABLE notes_fts USING fts5 (title, body, content='notes', content_rowid='id');
CREATE TRIGGER notes_ai AFTER INSERT ON notes BEGIN
INSERT INTO notes_fts (rowid, title, body) VALUES (new.id, new.title, new.body);
END;
CREATE TRIGGER notes_ad AFTER DELETE ON notes BEGIN
INSERT INTO notes_fts (notes_fts, rowid, title, body) VALUES ('delete', old.id, old.title, old.body);
END;
CREATE TRIGGER notes_au AFTER UPDATE OF title, body ON notes BEGIN
INSERT INTO notes_fts (notes_fts, rowid, title, body) VALUES ('delete', old.id, old.title, old.body);
INSERT INTO notes_fts (rowid, title, body) VALUES (new.id, new.title, new.body);
END;
INSERT INTO notes_fts (notes_fts) VALUES ('rebuild');`,
}
// ---- repository -----------------------------------------------------------
var (
ErrNotFound = errors.New("note not found")
ErrConflict = errors.New("note was changed by someone else")
)
type Note struct {
ID int64
Title string
Body string
Version int64
Tags []string
}
type Store struct{ db *sql.DB }
// Open configures every pooled connection through the DSN: foreign keys are
// per connection, writers wait instead of failing, and BeginTx takes the write
// lock up front with BEGIN IMMEDIATE.
func Open(ctx context.Context, path string) (*Store, error) {
dsn := "file:" + 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
}
s := &Store{db: db}
if err := s.migrate(ctx); err != nil {
db.Close()
return nil, err
}
return s, nil
}
func (s *Store) Close() error {
s.db.Exec("PRAGMA optimize")
return s.db.Close()
}
func (s *Store) migrate(ctx context.Context) error {
var v int
if err := s.db.QueryRowContext(ctx, "PRAGMA user_version").Scan(&v); err != nil {
return err
}
if v > len(migrations) {
return fmt.Errorf("schema version %d is newer than this program", v)
}
for ; v < len(migrations); v++ {
err := s.inTx(ctx, func(tx *sql.Tx) error {
if _, err := tx.ExecContext(ctx, migrations[v]); err != nil {
return fmt.Errorf("migration %d: %w", v+1, err)
}
_, err := tx.ExecContext(ctx, fmt.Sprintf("PRAGMA user_version = %d", v+1))
return err
})
if err != nil {
return err
}
}
return nil
}
// inTx commits when fn succeeds and rolls back otherwise.
func (s *Store) inTx(ctx context.Context, fn func(*sql.Tx) error) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback() // a no-op after Commit
if err := fn(tx); err != nil {
return err
}
return tx.Commit()
}
func setTags(ctx context.Context, tx *sql.Tx, id int64, tags []string) error {
if _, err := tx.ExecContext(ctx, "DELETE FROM note_tags WHERE note_id = ?", id); err != nil {
return err
}
for _, tag := range tags {
if _, err := tx.ExecContext(ctx, "INSERT OR IGNORE INTO note_tags (note_id, tag) VALUES (?, ?)", id, strings.ToLower(tag)); err != nil {
return err
}
}
return nil
}
func (s *Store) Create(ctx context.Context, title, body string, tags ...string) (Note, error) {
n := Note{Title: title, Body: body}
err := s.inTx(ctx, func(tx *sql.Tx) error {
err := tx.QueryRowContext(ctx, "INSERT INTO notes (title, body) VALUES (?, ?) RETURNING id, version", title, body).
Scan(&n.ID, &n.Version)
if err != nil {
return err
}
return setTags(ctx, tx, n.ID, tags)
})
if err != nil {
return Note{}, err
}
return s.Get(ctx, n.ID)
}
func (s *Store) Get(ctx context.Context, id int64) (Note, error) {
var n Note
var tags sql.NullString
err := s.db.QueryRowContext(ctx, `
SELECT n.id, n.title, n.body, n.version,
(SELECT group_concat(tag, ',') FROM (SELECT tag FROM note_tags WHERE note_id = n.id ORDER BY tag))
FROM notes n WHERE n.id = ?`, id).Scan(&n.ID, &n.Title, &n.Body, &n.Version, &tags)
if errors.Is(err, sql.ErrNoRows) {
return Note{}, ErrNotFound
}
if tags.Valid {
n.Tags = strings.Split(tags.String, ",")
}
return n, err
}
// Update succeeds only if the caller saw the current version.
func (s *Store) Update(ctx context.Context, n Note) (Note, error) {
err := s.inTx(ctx, func(tx *sql.Tx) error {
var version int64
err := tx.QueryRowContext(ctx, `
UPDATE notes SET title = ?, body = ?, version = version + 1
WHERE id = ? AND version = ? RETURNING version`, n.Title, n.Body, n.ID, n.Version).Scan(&version)
if errors.Is(err, sql.ErrNoRows) {
var exists bool
if err := tx.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM notes WHERE id = ?)", n.ID).Scan(&exists); err != nil {
return err
}
if exists {
return ErrConflict
}
return ErrNotFound
}
if err != nil {
return err
}
return setTags(ctx, tx, n.ID, n.Tags)
})
if err != nil {
return Note{}, err
}
return s.Get(ctx, n.ID)
}
func (s *Store) Delete(ctx context.Context, id int64) error {
return s.inTx(ctx, func(tx *sql.Tx) error {
var gone int64
err := tx.QueryRowContext(ctx, "DELETE FROM notes WHERE id = ? RETURNING id", id).Scan(&gone)
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
return err
})
}
type Hit struct {
ID int64
Title string
Snippet string
}
// Search treats the input as plain words, never as FTS5 syntax.
func (s *Store) Search(ctx context.Context, input string, tag string) ([]Hit, error) {
var terms []string
for _, w := range strings.Fields(input) {
terms = append(terms, `"`+strings.ReplaceAll(w, `"`, `""`)+`"`)
}
if len(terms) == 0 {
return nil, nil
}
rows, err := s.db.QueryContext(ctx, `
SELECT n.id, n.title, snippet(notes_fts, 1, '[', ']', '...', 5)
FROM notes_fts JOIN notes n ON n.id = notes_fts.rowid
WHERE notes_fts MATCH ?
AND (? = '' OR EXISTS (SELECT 1 FROM note_tags t WHERE t.note_id = n.id AND t.tag = ?))
ORDER BY rank, n.id`, strings.Join(terms, " "), tag, tag)
if err != nil {
return nil, err
}
defer rows.Close()
var hits []Hit
for rows.Next() {
var h Hit
if err := rows.Scan(&h.ID, &h.Title, &h.Snippet); err != nil {
return nil, err
}
hits = append(hits, h)
}
return hits, rows.Err()
}
// ---- checks ---------------------------------------------------------------
func check(name string, ok bool, detail ...any) {
status := "PASS"
if !ok {
status = "FAIL"
}
fmt.Printf("%s %s", status, name)
if len(detail) > 0 {
fmt.Print(": ", fmt.Sprint(detail...))
}
fmt.Println()
}
func ids(hits []Hit) []int64 {
var out []int64
for _, h := range hits {
out = append(out, h.ID)
}
return out
}
func main() {
ctx := context.Background()
dir, err := os.MkdirTemp("", "notes")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "notes.db")
s, err := Open(ctx, path)
if err != nil {
panic(err)
}
var version int
s.db.QueryRow("PRAGMA user_version").Scan(&version)
check("migrations reach the latest version", version == len(migrations), version)
a, _ := s.Create(ctx, "Pool sizing", "SQLite allows one writer at a time; readers continue in WAL mode.", "sqlite", "Go")
b, _ := s.Create(ctx, "Context deadlines", "Every query takes a context so a slow writer cannot hang a request.", "go")
c, _ := s.Create(ctx, "Backups", "VACUUM INTO writes a consistent copy while writers continue.", "sqlite", "ops")
check("create returns ids and version 1", a.ID == 1 && b.ID == 2 && c.ID == 3 && a.Version == 1)
check("tags are normalised and sorted", slices.Equal(a.Tags, []string{"go", "sqlite"}), a.Tags)
_, err = s.Create(ctx, "", "empty title")
check("CHECK rejects an empty title and rolls back", err != nil && strings.Contains(err.Error(), "CHECK constraint failed"))
hits, _ := s.Search(ctx, "writer", "")
check("search finds both notes about writers", slices.Equal(ids(hits), []int64{1, 2}) || slices.Equal(ids(hits), []int64{2, 1}), ids(hits))
hits, _ = s.Search(ctx, "writer", "go")
check("search filters by tag", len(hits) == 2)
hits, _ = s.Search(ctx, "writers", "ops")
check("snippet marks the match", len(hits) == 1 && strings.Contains(hits[0].Snippet, "[writers]"), hits[0].Snippet)
hits, err = s.Search(ctx, `c++ "unbalanced OR`, "")
check("user input is never parsed as FTS5 syntax", err == nil && len(hits) == 0, err)
edit := a
edit.Body = "Use BEGIN IMMEDIATE so a transaction takes the write lock before it reads."
edit.Tags = []string{"sqlite", "transactions"}
updated, err := s.Update(ctx, edit)
check("update bumps the version", err == nil && updated.Version == 2, updated.Version)
hits, _ = s.Search(ctx, "immediate", "")
old, _ := s.Search(ctx, "readers", "")
check("triggers reindex the updated body", slices.Equal(ids(hits), []int64{1}) && len(old) == 0)
_, err = s.Update(ctx, edit) // edit still carries version 1
check("a stale version is a conflict", errors.Is(err, ErrConflict), err)
_, err = s.Update(ctx, Note{ID: 99, Title: "x", Version: 1})
check("updating a missing note is not found", errors.Is(err, ErrNotFound), err)
check("delete removes the note", s.Delete(ctx, c.ID) == nil)
var tagRows int
s.db.QueryRow("SELECT count(*) FROM note_tags WHERE note_id = ?", c.ID).Scan(&tagRows)
hits, _ = s.Search(ctx, "vacuum", "")
check("ON DELETE CASCADE removed its tags and the index entry", tagRows == 0 && len(hits) == 0)
check("deleting twice is not found", errors.Is(s.Delete(ctx, c.ID), ErrNotFound))
_, err = s.db.Exec("INSERT INTO note_tags (note_id, tag) VALUES (42, 'orphan')")
check("foreign keys are enforced on pooled connections", err != nil && strings.Contains(err.Error(), "FOREIGN KEY"))
s.Close()
s, err = Open(ctx, path)
if err != nil {
panic(err)
}
defer s.Close()
again, err := s.Get(ctx, a.ID)
check("reopening keeps data and skips applied migrations", err == nil && again.Version == 2 && slices.Equal(again.Tags, []string{"sqlite", "transactions"}), again.Tags)
}All seventeen checks pass. The migrations reach version 2, the three notes get ids 1 to 3 and Go is stored as go. An empty title fails the CHECK and leaves no row. writer matches notes 1 and 2, the tag filter keeps both, and the snippet brackets writers. Input with c++ and an unbalanced quote returns no rows and no error. Update moves note 1 to version 2 and the triggers reindex it; replaying version 1 is a conflict. Deleting note 3 cascades its tags and index entry, an orphan tag is refused, and the reopened store skips migrations.
Transactions stay short and owned
inTx begins, defers Rollback and commits only when the callback returns nil; Rollback after a successful Commit returns sql.ErrTxDone and changes nothing. Each transaction does a few statements and no network or user interaction, because in SQLite one open write transaction blocks every other writer. BEGIN IMMEDIATE means two concurrent updates queue on the busy timeout instead of both reading and then one failing with SQLITE_BUSY when it tries to write. Keep the *sql.Tx inside the callback; it is bound to one connection and must not be shared between goroutines.
Optimistic concurrency with a version column
A client reads a note, edits it for a minute and saves. Locking the row for that minute is impossible in SQLite and undesirable anywhere. Instead the client sends back the version it read, and the UPDATE matches only if that version is still current, incrementing it with RETURNING version. Zero rows means either someone else saved first or the note is gone; the repository checks which inside the same transaction and returns ErrConflict or ErrNotFound, sentinel errors callers test with errors.Is and map to HTTP 409 or 404.
Wiring it into a program
Open the store once at startup, fail fast when migrations fail or the file is newer than the code, and close it at shutdown, which runs PRAGMA optimize. Handlers receive the store, not the *sql.DB, so every query goes through the repository and its tests. In the next GopherForge update, a SQLite project can keep such a file under /sandbox with the project and inspect its tables, schema and rows in the per-project database browser.
func run(ctx context.Context) error {
store, err := notes.Open(ctx, "/sandbox/notes.db")
if err != nil {
return err // includes "schema version N is newer than this program"
}
defer store.Close() // runs PRAGMA optimize, then closes the pool
// hand store to handlers; never share *sql.Tx across goroutines
return serve(ctx, store)
}The path is the only environment-specific value. The error from Open already explains a schema that is too new, so the program can print it and exit instead of guessing. The deferred Close runs after serve returns, when no handler is still using the pool.
Where to take it next
Turn the checks in main into table-driven tests with the temporary-database helper from the previous lesson, add a test that runs every migration against a saved version-1 file, and add a concurrency test that holds one IMMEDIATE transaction while a second Update waits. Add a nightly VACUUM INTO backup with an integrity check. If reads grow, open a second, read-only pool with query_only for searches, and keep a single-connection pool for writes so writers never contend inside the process.
TAKE THIS WITH YOU
A good SQLite repository owns its pool and DSN, migrates with user_version at startup, writes in short IMMEDIATE transactions with RETURNING, guards edits with a version column, lets foreign keys and triggers keep related data consistent, and quotes every search term.
Check your understanding
Two people edit note 1, both having read version 1. The first save succeeds. What happens to the second?
Go to the source
Progress stays in this browser. No account needed.