Files
geniusrun/backend/internal/store/db.go

143 lines
3.9 KiB
Go
Raw Normal View History

// Package store is geniusrun's SQLite persistence layer: activities, laps,
// per-second samples, workout kind rule config, and classification history.
package store
import (
"database/sql"
"embed"
"fmt"
"io/fs"
"sort"
_ "modernc.org/sqlite"
)
//go:embed migrations/*.sql
var migrationsFS embed.FS
// DB wraps a *sql.DB opened against a geniusrun SQLite database file, with
// migrations already applied.
type DB struct {
*sql.DB
}
// Open opens (creating if needed) the SQLite database at path and applies
// any migrations that haven't run yet.
func Open(path string) (*DB, error) {
sqlDB, err := sql.Open("sqlite", path+"?_pragma=foreign_keys(1)")
if err != nil {
return nil, fmt.Errorf("open sqlite database: %w", err)
}
// SQLite only supports one writer at a time; a single connection avoids
// "database is locked" errors under any concurrent access from the app.
sqlDB.SetMaxOpenConns(1)
db := &DB{DB: sqlDB}
if err := db.migrate(); err != nil {
sqlDB.Close()
return nil, err
}
return db, nil
}
func (db *DB) migrate() error {
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
filename TEXT PRIMARY KEY,
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
)`); err != nil {
return fmt.Errorf("create schema_migrations table: %w", err)
}
applied := make(map[string]bool)
rows, err := db.Query(`SELECT filename FROM schema_migrations`)
if err != nil {
return fmt.Errorf("query applied migrations: %w", err)
}
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
rows.Close()
return fmt.Errorf("scan applied migration: %w", err)
}
applied[name] = true
}
rows.Close()
entries, err := fs.Glob(migrationsFS, "migrations/*.sql")
if err != nil {
return fmt.Errorf("glob migrations: %w", err)
}
sort.Strings(entries)
for _, entry := range entries {
name := entry[len("migrations/"):]
if applied[name] {
continue
}
content, err := migrationsFS.ReadFile(entry)
if err != nil {
return fmt.Errorf("read migration %s: %w", name, err)
}
store: fix migration 0026's silent-cascade-delete FK toggle bug Migration 0026 (activities table rebuild for the per-user unique constraint) issued its own PRAGMA foreign_keys = OFF/ON inside the migration's SQL content, but the whole migration file runs inside one db.go tx.Begin()/tx.Exec()/tx.Commit() transaction, and SQLite documents PRAGMA foreign_keys as a no-op once a transaction is open. As a result FK enforcement never actually got disabled, so DROP TABLE activities triggered SQLite's implicit DELETE FROM semantics, firing ON DELETE CASCADE on every row in laps, activity_samples, and kind_assignments for every activity -- silently, with no error. On a real upgrade with synced data this would have permanently destroyed all lap/sample/classification history. It was masked because every existing migration test runs migrations back-to-back on an empty temp database with no pre-existing child rows. Fix: add "0026_activities_unique_constraint.sql" to db.go's tableRebuildMigrations map so it gets the same autocommit-mode FK disable/enable toggle (before/after the transaction) already used for migrations 0023/0024/0025, and remove the now-redundant/misleading mid-transaction PRAGMA lines from the migration file itself, matching the established pattern. Also restore the DEFAULT '' on event_type_key in migration 0026's rebuilt activities table -- it was dropped from migration 0007's original column definition during the rebuild, which broke every insert that omits event_type_key and relies on that default (TestClaimLegacyOwner_BindsExistingSingletonRowsToOneNewUser and others). Extend TestRebuildMigrationsPreserveForeignKeyReferences to cover 0026: seed a laps row and an activity_samples row (in addition to the existing kind_assignments row) against a pre-existing activities row before the rebuild migrations run, then verify after 0023-0026 complete that all three child rows still exist and still reference the same activity, and that FK enforcement rejects bogus activity_id/workout_kind_id afterward. This is the regression guard that would have caught the original bug. Note: TestClaimLegacyOwner_NoOpOnGenuinelyFreshInstall still fails on this branch; verified it fails identically at the prior commit (d8b7228), so it's a pre-existing, unrelated bug in ClaimLegacyOwner (not migration 0026 or this FK-toggle bug) and out of scope for this fix. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-25 14:28:16 +02:00
// Migrations 0023, 0024, 0025, and 0026 rebuild tables that have
// incoming foreign keys (kind_assignments/workout_type_paces
// reference workout_kinds; sync_state is referenced by
// activities/sync_runs; laps/activity_samples/kind_assignments
// reference activities). These require temporary FK disable in
// autocommit mode (before the transaction begins) so the DROP
// TABLE succeeds; a mid-transaction PRAGMA is a no-op with
// modernc.org/sqlite.
tableRebuildMigrations := map[string]bool{
store: fix migration 0026's silent-cascade-delete FK toggle bug Migration 0026 (activities table rebuild for the per-user unique constraint) issued its own PRAGMA foreign_keys = OFF/ON inside the migration's SQL content, but the whole migration file runs inside one db.go tx.Begin()/tx.Exec()/tx.Commit() transaction, and SQLite documents PRAGMA foreign_keys as a no-op once a transaction is open. As a result FK enforcement never actually got disabled, so DROP TABLE activities triggered SQLite's implicit DELETE FROM semantics, firing ON DELETE CASCADE on every row in laps, activity_samples, and kind_assignments for every activity -- silently, with no error. On a real upgrade with synced data this would have permanently destroyed all lap/sample/classification history. It was masked because every existing migration test runs migrations back-to-back on an empty temp database with no pre-existing child rows. Fix: add "0026_activities_unique_constraint.sql" to db.go's tableRebuildMigrations map so it gets the same autocommit-mode FK disable/enable toggle (before/after the transaction) already used for migrations 0023/0024/0025, and remove the now-redundant/misleading mid-transaction PRAGMA lines from the migration file itself, matching the established pattern. Also restore the DEFAULT '' on event_type_key in migration 0026's rebuilt activities table -- it was dropped from migration 0007's original column definition during the rebuild, which broke every insert that omits event_type_key and relies on that default (TestClaimLegacyOwner_BindsExistingSingletonRowsToOneNewUser and others). Extend TestRebuildMigrationsPreserveForeignKeyReferences to cover 0026: seed a laps row and an activity_samples row (in addition to the existing kind_assignments row) against a pre-existing activities row before the rebuild migrations run, then verify after 0023-0026 complete that all three child rows still exist and still reference the same activity, and that FK enforcement rejects bogus activity_id/workout_kind_id afterward. This is the regression guard that would have caught the original bug. Note: TestClaimLegacyOwner_NoOpOnGenuinelyFreshInstall still fails on this branch; verified it fails identically at the prior commit (d8b7228), so it's a pre-existing, unrelated bug in ClaimLegacyOwner (not migration 0026 or this FK-toggle bug) and out of scope for this fix. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-25 14:28:16 +02:00
"0023_profile_user_scoped.sql": true,
"0024_workout_kinds_user_scoped.sql": true,
"0025_sync_state_user_scoped.sql": true,
"0026_activities_unique_constraint.sql": true,
}
needsFKToggle := tableRebuildMigrations[name]
if needsFKToggle {
if _, err := db.Exec(`PRAGMA foreign_keys = OFF`); err != nil {
return fmt.Errorf("disable foreign keys before migration %s: %w", name, err)
}
}
tx, err := db.Begin()
if err != nil {
if needsFKToggle {
db.Exec(`PRAGMA foreign_keys = ON`)
}
return fmt.Errorf("begin migration tx for %s: %w", name, err)
}
if _, err := tx.Exec(string(content)); err != nil {
tx.Rollback()
if needsFKToggle {
db.Exec(`PRAGMA foreign_keys = ON`)
}
return fmt.Errorf("apply migration %s: %w", name, err)
}
if _, err := tx.Exec(`INSERT INTO schema_migrations (filename) VALUES (?)`, name); err != nil {
tx.Rollback()
if needsFKToggle {
db.Exec(`PRAGMA foreign_keys = ON`)
}
return fmt.Errorf("record migration %s: %w", name, err)
}
if err := tx.Commit(); err != nil {
if needsFKToggle {
db.Exec(`PRAGMA foreign_keys = ON`)
}
return fmt.Errorf("commit migration %s: %w", name, err)
}
if needsFKToggle {
if _, err := db.Exec(`PRAGMA foreign_keys = ON`); err != nil {
return fmt.Errorf("enable foreign keys after migration %s: %w", name, err)
}
}
}
return nil
}