store: collapse migrations into a single schema.sql, drop legacy-owner path
Pre-production app, no need to preserve incremental migration history: replace the 26 migration files with one current-state schema.sql (the schema.sql comments are now the living documentation), simplify db.go to apply it once instead of tracking/rebuilding through schema_migrations, and make user_id NOT NULL everywhere now that there's no staged migration to accommodate a nullable backfill window. This removes the reason ClaimLegacyOwner/GENIUSRUN_LEGACY_OWNER_OIDC_SUB existed (binding a pre-existing singleton-schema database to one account across a staged migration), so that whole path is gone too -- the existing dev database was wiped and reseeded fresh under the new schema. Add cmd/dumpschema, which regenerates docs/DATABASE.md straight from the live schema (via store.Open + sqlite_master introspection) so the database documentation can never drift out of sync with reality. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,25 +4,25 @@ package store
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"embed"
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationsFS embed.FS
|
||||
//go:embed schema.sql
|
||||
var schemaSQL string
|
||||
|
||||
// DB wraps a *sql.DB opened against a geniusrun SQLite database file, with
|
||||
// migrations already applied.
|
||||
// the schema 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.
|
||||
// schema.sql if it hasn't been applied yet. There is no migration history --
|
||||
// this is a pre-production app with no compatibility obligation to older
|
||||
// database files. Edit schema.sql directly to change the schema.
|
||||
func Open(path string) (*DB, error) {
|
||||
sqlDB, err := sql.Open("sqlite", path+"?_pragma=foreign_keys(1)")
|
||||
if err != nil {
|
||||
@@ -33,110 +33,32 @@ func Open(path string) (*DB, error) {
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
|
||||
db := &DB{DB: sqlDB}
|
||||
if err := db.migrate(); err != nil {
|
||||
if err := db.applySchema(); 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)
|
||||
// applySchema runs schema.sql once, the first time this database file is
|
||||
// opened -- detected by checking whether the users table already exists.
|
||||
func (db *DB) applySchema() error {
|
||||
var alreadyApplied int
|
||||
if err := db.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='users'`).Scan(&alreadyApplied); err != nil {
|
||||
return fmt.Errorf("check existing schema: %w", err)
|
||||
}
|
||||
if alreadyApplied > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
applied := make(map[string]bool)
|
||||
rows, err := db.Query(`SELECT filename FROM schema_migrations`)
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return fmt.Errorf("query applied migrations: %w", err)
|
||||
return fmt.Errorf("begin schema tx: %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
|
||||
defer tx.Rollback()
|
||||
|
||||
if _, err := tx.Exec(schemaSQL); err != nil {
|
||||
return fmt.Errorf("apply schema: %w", err)
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
// 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{
|
||||
"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
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user