Server-rendered apps with Go, templ and HTMX
Persistence with SQLite
database/sql with a pure-Go SQLite driver: schema setup, a store behind the same methods, mapping database errors, and contexts with deadlines.
- lesson
- 06 of 08
- read
- 16 min
The store from lesson 2 forgets everything on restart. This lesson replaces its insides with SQLite through database/sql. The store’s methods already take a context and return an error, so the handlers change in one place only, where the database introduces a failure that memory never had.
Choose a driver
database/sql is the standard interface, and a driver does the work behind it. For SQLite there are two kinds. One binds to the C library, which needs cgo and a C compiler wherever you build. The other, modernc.org/sqlite, is SQLite’s C source translated to Go. This course uses the second: go build stays self-contained, and cross-compiling in lesson 8 is a matter of setting environment variables. The price is speed on CPU-heavy queries, which the driver’s documentation quantifies. A reading list will not notice.
go get modernc.org/sqlite@v1.63.0go: downloading modernc.org/sqlite v1.63.0
...
go: added modernc.org/sqlite v1.63.0This version bundles SQLite 3.54.1. It also adds modernc.org/libc to go.mod as an indirect dependency. The driver’s documentation asks you to keep that module at the exact version the driver was released with, so do not upgrade it on its own.
The store
Replace store.go entirely. The types and method signatures are the ones the handlers already use.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"modernc.org/sqlite"
sqlite3 "modernc.org/sqlite/lib"
)
type Link struct {
ID int64
URL string
Title string
Note string
Read bool
CreatedAt time.Time
}
// Filter narrows List. The zero value matches every link.
type Filter struct {
Query string // substring of the title, URL or note
Status string // "unread" or "read"; anything else means both
}
var (
ErrNotFound = errors.New("link not found")
ErrDuplicate = errors.New("link already saved")
)
const schema = `
CREATE TABLE IF NOT EXISTS links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
note TEXT NOT NULL DEFAULT '',
read INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
) STRICT;`
// Store keeps links in a SQLite database.
type Store struct {
db *sql.DB
}
// OpenStore opens the database file at path, creating it and its schema if
// they do not exist yet.
func OpenStore(ctx context.Context, path string) (*Store, error) {
db, err := sql.Open("sqlite", path+"?_busy_timeout=5000&_journal_mode=WAL")
if err != nil {
return nil, err
}
db.SetMaxOpenConns(4)
if _, err := db.ExecContext(ctx, schema); err != nil {
db.Close()
return nil, fmt.Errorf("create schema: %w", err)
}
return &Store{db: db}, nil
}
func (s *Store) Close() error {
return s.db.Close()
}
const linkColumns = `id, url, title, note, read, created_at`
// scanLink reads one link from a *sql.Row or *sql.Rows.
func scanLink(row interface{ Scan(dest ...any) error }) (Link, error) {
var l Link
var created int64
err := row.Scan(&l.ID, &l.URL, &l.Title, &l.Note, &l.Read, &created)
l.CreatedAt = time.Unix(created, 0)
return l, err
}
func (s *Store) List(ctx context.Context, f Filter) ([]Link, error) {
status := "all"
if f.Status == "read" || f.Status == "unread" {
status = f.Status
}
rows, err := s.db.QueryContext(ctx, `
SELECT `+linkColumns+`
FROM links
WHERE (@status = 'all' OR read = (@status = 'read'))
AND (@q = '' OR instr(lower(title || ' ' || url || ' ' || note), lower(@q)) > 0)
ORDER BY id DESC`,
sql.Named("status", status), sql.Named("q", f.Query))
if err != nil {
return nil, err
}
defer rows.Close()
var links []Link
for rows.Next() {
l, err := scanLink(rows)
if err != nil {
return nil, err
}
links = append(links, l)
}
return links, rows.Err()
}
func (s *Store) Get(ctx context.Context, id int64) (Link, error) {
row := s.db.QueryRowContext(ctx,
`SELECT `+linkColumns+` FROM links WHERE id = ?`, id)
return found(scanLink(row))
}
func (s *Store) Create(ctx context.Context, url, title, note string) (Link, error) {
row := s.db.QueryRowContext(ctx, `
INSERT INTO links (url, title, note, created_at)
VALUES (?, ?, ?, ?)
RETURNING `+linkColumns,
url, title, note, time.Now().Unix())
l, err := scanLink(row)
if isUniqueViolation(err) {
return Link{}, ErrDuplicate
}
return l, err
}
func (s *Store) ToggleRead(ctx context.Context, id int64) (Link, error) {
row := s.db.QueryRowContext(ctx,
`UPDATE links SET read = NOT read WHERE id = ? RETURNING `+linkColumns, id)
return found(scanLink(row))
}
func (s *Store) Delete(ctx context.Context, id int64) error {
res, err := s.db.ExecContext(ctx, `DELETE FROM links WHERE id = ?`, id)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
return nil
}
// found turns "no rows" into ErrNotFound for single-row statements.
func found(l Link, err error) (Link, error) {
if errors.Is(err, sql.ErrNoRows) {
return Link{}, ErrNotFound
}
return l, err
}
func isUniqueViolation(err error) bool {
var se *sqlite.Error
return errors.As(err, &se) && se.Code() == sqlite3.SQLITE_CONSTRAINT_UNIQUE
}The schema runs on every start, which is enough for one table that does not change. Three choices in it deserve a reason. STRICT makes SQLite reject a value of the wrong type instead of storing it anyway (strict tables). AUTOINCREMENT guarantees that an id is never reused. Ids end up in URLs and in pages that stay open for hours, and a reused id would let a stale Delete button remove a different link. created_at is a Unix timestamp in an INTEGER column, which avoids any driver-specific handling of time values.
OpenStore appends two parameters to the file name. _busy_timeout=5000 makes a connection wait up to five seconds for a lock instead of failing at once. _journal_mode=WAL switches to write-ahead logging, in which readers and the writer do not block each other. They are in the connection string for a reason: sql.DB is a pool, a setting such as the busy timeout belongs to one connection, and the driver applies these parameters to every connection it opens. An Exec("PRAGMA ...") after opening would configure whichever connection happened to run it. The pool is unbounded by default, and the driver’s documentation recommends a limit, hence SetMaxOpenConns.
The queries follow a few rules.
Values always travel as parameters, never as parts of the SQL string. List uses named parameters so that one static statement covers every filter: each condition switches itself off when its parameter has the neutral value.
Search uses instr rather than LIKE. With LIKE, a % or _ typed by the user would act as a wildcard unless escaped. With instr they are ordinary characters, and a search for % returns nothing. SQLite’s built-in lower folds ASCII letters only, a limit the last exercise returns to.
RETURNING hands back the affected row in the same statement. ToggleRead is therefore one atomic UPDATE and not a read followed by a write.
Errors are translated at the boundary. found turns sql.ErrNoRows into ErrNotFound. isUniqueViolation recognizes the driver’s error for a violated UNIQUE constraint, and Create turns it into ErrDuplicate. No handler ever sees a SQLite error code.
One new failure
In createLink, handle the duplicate before the generic error:
l, err := a.store.Create(r.Context(), form.URL, form.Title, form.Note)
+ if errors.Is(err, ErrDuplicate) {
+ form.Errors["url"] = "This link is already on the list."
+ a.invalidForm(w, r, form)
+ return
+ }
if err != nil {The rule is enforced by the constraint and reported through the form, with the machinery from lesson 5. Checking with a SELECT before the INSERT would look simpler and be wrong: two requests arriving together can both pass the check. Only the constraint closes that gap.
Wiring
package main
import (
"context"
"flag"
"fmt"
"log/slog"
"net/http"
"os"
)
func main() {
addr := flag.String("addr", "localhost:8792", "address to listen on")
dbPath := flag.String("db", "readinglist.db", "path to the SQLite database file")
flag.Parse()
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
if err := run(*addr, *dbPath, logger); err != nil {
logger.Error("exiting", "err", err)
os.Exit(1)
}
}
func run(addr, dbPath string, logger *slog.Logger) error {
store, err := OpenStore(context.Background(), dbPath)
if err != nil {
return fmt.Errorf("open store: %w", err)
}
defer store.Close()
a := &app{logger: logger, store: store}
logger.Info("listening", "addr", addr, "db", dbPath)
return http.ListenAndServe(addr, a.routes())
}seed is gone. The work moved from main into run, which returns an error. That is what makes the defer useful: os.Exit does not run deferred calls, so a function that defers cleanup must not be the one that exits. For now this covers a failed start. Lesson 8 extends it to a normal stop.
Deadlines
Every store method passes its context to the database. r.Context() is canceled when the client goes away, which already stops work nobody is waiting for. A middleware adds an upper bound (it needs the context import):
// deadline cancels the request context after d, which stops any database
// query still running for the request.
func deadline(d time.Duration, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), d)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}In routes.go, wrap the chain with it and import time:
return deadline(5*time.Second, a.logRequests(a.recoverPanic(mux)))When the deadline passes, the driver interrupts the statement that is running and the store method returns an error that satisfies errors.Is(err, context.DeadlineExceeded). The handler treats it like any other failure and answers 500.
The position in the chain matters. r.WithContext returns a copy of the request, and the mux records the matched pattern on the request it is given. With deadline placed inside logRequests, the logger kept the original request and every record showed pattern="". Placed outermost, the logger and the mux see the same copy.
Check that it persists
go run .time=2026-11-29T00:06:16.542+02:00 level=INFO msg=listening addr=localhost:8792 db=readinglist.dbCreate two links, mark the first as read, then try the second URL again:
curl -s -o /dev/null -w '%{http_code}\n' -d url=https://go.dev/blog/routing-enhancements -d 'title=Routing Enhancements for Go 1.22' localhost:8792/links
curl -s -o /dev/null -w '%{http_code}\n' -d url=https://sqlite.org/wal.html -d 'title=Write-Ahead Logging' localhost:8792/links
curl -s -o /dev/null -w '%{http_code}\n' -X POST localhost:8792/links/1/toggle
curl -s -H 'HX-Request-Type: partial' -d url=https://sqlite.org/wal.html -d 'title=WAL again' localhost:8792/links | grep -o '<small class="error">[^<]*</small>'303
303
303
<small class="error">This link is already on the list.</small>If the sqlite3 shell is installed, look at the file directly:
sqlite3 readinglist.db 'SELECT id, url, read, created_at FROM links'1|https://go.dev/blog/routing-enhancements|1|1795903579
2|https://sqlite.org/wal.html|0|1795903579Stop the server with Ctrl+C, start it again and ask for the page:
curl -s localhost:8792/links | grep -o 'id="link-[0-9]*"'id="link-2"
id="link-1"While the server runs, readinglist.db-wal and readinglist.db-shm sit next to the database file. They belong to WAL mode. Keep all three out of version control.
With data that survives, the application is ready for the interactions that make it pleasant to use: searching as you type, editing in place, deleting, and a counter that stays correct through all of it.
Exercises
- Prove to yourself that a deadline stops a query. Give
Storea temporary method that runsWITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM c) SELECT count(*) FROM c, which never finishes, and call it with a context fromcontext.WithTimeout(ctx, 100*time.Millisecond). A correct result returns after about 100 ms with an error for whicherrors.Is(err, context.DeadlineExceeded)is true. Remove the method afterwards. - With the server running, insert a row from the
sqlite3shell (useunixepoch()forcreated_at) and reload the page. The new link should appear at the top without a restart, because the server holds no copy of the data. Then try an insert with the text'yesterday'ascreated_atand read the error thatSTRICTproduces. - Add a link titled
Éclair recipesand search foréclair. It is not found, whileRECIPESis, becauseloweronly folds ASCII. Fix it by folding case in Go: store a lowercased search text in its own column, written byCreate, and compare it with the lowercased query. A correct result finds the link foréclair,ÉCLAIRandÉclair. The schema change means deleting the database file, which is acceptable at this stage.