fix(store): put the pragmas in the DSN so every connection has them

- foreign_keys, busy_timeout(5000) and WAL now come from the DSN, not from
  an Exec on one connection
- test: every connection of a 2-connection pool, in memory and on disk
This commit is contained in:
tgiachi 2026-11-10 11:48:51 +01:00
commit d43c47ea08
2 changed files with 49 additions and 5 deletions

View file

@ -215,16 +215,18 @@ CREATE TABLE IF NOT EXISTS settings (
// Open opens (and migrates) the database at path. Use ":memory:" for tests.
func Open(path string) (*Store, error) {
db, err := sql.Open("sqlite", path)
// The pragmas are in the DSN so that every connection of the pool has them.
sep := "?"
if strings.Contains(path, "?") {
sep = "&"
}
dsn := path + sep + "_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)"
db, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, err
}
// An in-memory database is per-connection: keep a single one.
db.SetMaxOpenConns(1)
if _, err := db.Exec("PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL;"); err != nil {
db.Close()
return nil, err
}
if err := migrate(db); err != nil {
db.Close()
return nil, fmt.Errorf("migrate: %w", err)

View file

@ -1,7 +1,10 @@
package store
import (
"context"
"database/sql"
"errors"
"path/filepath"
"testing"
)
@ -124,3 +127,42 @@ func TestRemoveMember(t *testing.T) {
t.Fatalf("want ErrNotFound, got %v", err)
}
}
// Every connection of the pool must enforce foreign keys and wait on a busy
// database, not only the first one: the pragmas live in the DSN.
func TestEveryConnectionHasThePragmas(t *testing.T) {
for _, path := range []string{":memory:", filepath.Join(t.TempDir(), "p.db")} {
s, err := Open(path)
if err != nil {
t.Fatalf("open %s: %v", path, err)
}
s.db.SetMaxOpenConns(2)
ctx := context.Background()
c1, err := s.db.Conn(ctx)
if err != nil {
t.Fatal(err)
}
c2, err := s.db.Conn(ctx)
if err != nil {
t.Fatal(err)
}
for i, c := range []*sql.Conn{c1, c2} {
var fk, busy int
if err := c.QueryRowContext(ctx, "PRAGMA foreign_keys").Scan(&fk); err != nil || fk != 1 {
t.Errorf("%s conn %d: foreign_keys = %d, %v", path, i, fk, err)
}
if err := c.QueryRowContext(ctx, "PRAGMA busy_timeout").Scan(&busy); err != nil || busy != 5000 {
t.Errorf("%s conn %d: busy_timeout = %d, %v", path, i, busy, err)
}
if path != ":memory:" {
var mode string
if err := c.QueryRowContext(ctx, "PRAGMA journal_mode").Scan(&mode); err != nil || mode != "wal" {
t.Errorf("%s conn %d: journal_mode = %q, %v", path, i, mode, err)
}
}
}
c1.Close()
c2.Close()
s.Close()
}
}