Files
verdande/internal/store/store.go
T
Kristian WindandClaude Opus 5 dff86dd23d feat(api): projects, sections, tasks, quick add, views and live sync
Completes the MVP surface: project and section CRUD, task CRUD with
sub-trees, drag-and-drop ordering, the quick-add endpoint over the
natural-language parser, Today and Upcoming, search, sharing with roles,
an activity log and a WebSocket for live updates.

Permission checks are route middleware rather than a first line in each
handler, so an endpoint is guarded by where it sits instead of by the
author remembering. Anything the caller may not see answers 404, never
403 — a 403 confirms the thing exists. Visibility is enforced inside the
list query, so another user's project cannot be reached by filtering or
searching at it.

Ordering is a float, so a drop writes one row instead of renumbering the
list. When repeated drops into one gap exhaust the precision, the
section is spread out again and the move retried — in a separate
transaction, since the attempt that discovered the problem rolls back.

The connection pool is not 1: a single connection makes the pool a lock,
and a query run while an earlier result set is still open then waits for
a connection it is itself holding. The store now closes its rows before
querying again, and the pool leaves that mistake slow rather than fatal.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 23:44:55 +02:00

164 lines
4.5 KiB
Go

// Package store owns the SQLite database: connection settings, schema migrations,
// and the query helpers the rest of verdande builds on.
package store
import (
"context"
"database/sql"
"embed"
"fmt"
"io/fs"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
_ "modernc.org/sqlite" // pure-Go driver: no cgo, so the binary stays static
)
//go:embed migrations/*.sql
var migrationFS embed.FS
type DB struct {
*sql.DB
path string
}
// Open prepares the database at path and brings the schema up to date.
//
// SQLite is a single file, but it is being driven by an HTTP server with concurrent
// readers and a WebSocket fan-out, so the pragmas below matter more than usual:
// WAL lets readers run while a write is in flight, busy_timeout turns the "database
// is locked" race into a short wait, and foreign_keys is off by default in SQLite
// and has to be asked for on every connection.
func Open(path string) (*DB, error) {
dsn := "file:" + filepath.ToSlash(path) + "?" + strings.Join([]string{
"_pragma=journal_mode(WAL)",
"_pragma=busy_timeout(5000)",
"_pragma=foreign_keys(ON)",
"_pragma=synchronous(NORMAL)",
// Keep the temp b-trees FTS5 and ORDER BY build in memory rather than
// spilling them into the data volume.
"_pragma=temp_store(MEMORY)",
}, "&")
sqlDB, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, fmt.Errorf("open sqlite: %w", err)
}
// SQLite serialises writes whatever the pool does, so this is sized for readers.
// In WAL mode they run concurrently with a write in flight, and busy_timeout
// absorbs the contention between writers.
//
// Not 1. A single connection makes the pool a lock, and any code that runs a
// query while an earlier *sql.Rows is still open then waits forever for a
// connection it is itself holding — a deadlock rather than a slow query, and
// one that only appears once a list has rows in it. The store closes its result
// sets before querying again, and this leaves room for the mistake to be slow
// instead of fatal if it is ever made again.
sqlDB.SetMaxOpenConns(max(4, runtime.NumCPU()))
sqlDB.SetMaxIdleConns(4)
sqlDB.SetConnMaxLifetime(time.Hour)
if err := sqlDB.PingContext(context.Background()); err != nil {
sqlDB.Close()
return nil, fmt.Errorf("ping sqlite: %w", err)
}
db := &DB{DB: sqlDB, path: path}
if err := db.migrate(context.Background()); err != nil {
sqlDB.Close()
return nil, err
}
return db, nil
}
func (db *DB) Path() string { return db.path }
// migrate applies every embedded migration that has not run yet, in filename order,
// each inside its own transaction. A migration that fails leaves the schema at the
// last version that succeeded rather than half-applied.
func (db *DB) migrate(ctx context.Context) error {
if _, err := db.ExecContext(ctx, `
CREATE TABLE IF NOT EXISTS schema_migrations (
name TEXT PRIMARY KEY,
applied_at INTEGER NOT NULL
)`); err != nil {
return fmt.Errorf("create schema_migrations: %w", err)
}
applied := map[string]bool{}
rows, err := db.QueryContext(ctx, `SELECT name FROM schema_migrations`)
if err != nil {
return fmt.Errorf("read schema_migrations: %w", err)
}
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
rows.Close()
return err
}
applied[name] = true
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
entries, err := fs.Glob(migrationFS, "migrations/*.sql")
if err != nil {
return err
}
sort.Strings(entries)
for _, entry := range entries {
name := filepath.Base(entry)
if applied[name] {
continue
}
body, err := migrationFS.ReadFile(entry)
if err != nil {
return err
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
if _, err := tx.ExecContext(ctx, string(body)); err != nil {
tx.Rollback()
return fmt.Errorf("migration %s: %w", name, err)
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO schema_migrations (name, applied_at) VALUES (?, unixepoch())`, name); err != nil {
tx.Rollback()
return fmt.Errorf("record migration %s: %w", name, err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit migration %s: %w", name, err)
}
}
return nil
}
// Tx runs fn inside a transaction, rolling back on error or panic.
func (db *DB) Tx(ctx context.Context, fn func(*sql.Tx) error) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p)
}
}()
if err := fn(tx); err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}