Files
supermarket/internal/db/migrate_hook_test.go
T
davidandClaude Opus 5.5 5313369328 Phase 6 part 1: database backups
Backups with SQLite's VACUUM INTO into <data>/backups: on request
(Settings → Backups, supermarket backup [note]), before every schema
migration, and daily, keeping 7 dailies and 4 weeklies. Listed with size
and schema; downloadable and deletable. The old app.db.pre-* copies are
moved in, with their -wal files folded in first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:38:23 -07:00

62 lines
1.7 KiB
Go

package db
import (
"database/sql"
"errors"
"fmt"
"path/filepath"
"strings"
"testing"
)
func TestBeforeMigrate(t *testing.T) {
defer func() { BeforeMigrate = nil }()
var calls []string
BeforeMigrate = func(d *sql.DB, from, to int) error {
var n int
d.QueryRow(`PRAGMA user_version`).Scan(&n)
calls = append(calls, fmt.Sprintf("%d→%d at %d", from, to, n))
return nil
}
dir := t.TempDir()
// A new database: nothing to back up.
d, err := Open(filepath.Join(dir, "new.db"))
if err != nil {
t.Fatal(err)
}
d.Close()
// Already current: nothing either.
d, _ = Open(filepath.Join(dir, "new.db"))
d.Close()
if len(calls) != 0 {
t.Fatalf("called for a new or current database: %v", calls)
}
// One migration behind: backed up first, before the migration runs.
old := filepath.Join(dir, "old.db")
raw, _ := sql.Open("sqlite", "file:"+old)
for _, m := range migrations[:len(migrations)-1] {
if _, err := raw.Exec(m); err != nil {
t.Fatal(err)
}
}
raw.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, len(migrations)-1))
raw.Close()
d, err = Open(old)
if err != nil {
t.Fatal(err)
}
d.Close()
want := fmt.Sprintf("%d→%d at %d", len(migrations)-1, len(migrations), len(migrations)-1)
if len(calls) != 1 || calls[0] != want || Schema() != len(migrations) {
t.Errorf("calls: %v, want %s", calls, want)
}
// A failed backup stops the migration.
raw, _ = sql.Open("sqlite", "file:"+old)
raw.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, len(migrations)-1))
raw.Close()
BeforeMigrate = func(*sql.DB, int, int) error { return errors.New("disk full") }
if _, err := Open(old); err == nil || !strings.Contains(err.Error(), "disk full") {
t.Errorf("open: %v", err)
}
}