package store import ( "database/sql" "fmt" "os" "path/filepath" _ "modernc.org/sqlite" "git.cloudinit.dev/coreci/orca/internal/certpaths" ) func Open(path string) (*sql.DB, error) { if path == "" { path = certpaths.DBPath() } if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return nil, fmt.Errorf("create db dir: %w", err) } db, err := sql.Open("sqlite", path+"?_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)&_pragma=busy_timeout(5000)") if err != nil { return nil, fmt.Errorf("open sqlite: %w", err) } // REQ-156 / P07 T1: SQLite is a single-writer database. Cap the // connection pool at 1 so concurrent goroutines serialize on the // busy_timeout(5000) above instead of racing for the WAL writer // lock and surfacing spurious SQLITE_BUSY errors to callers. db.SetMaxOpenConns(1) if err := db.Ping(); err != nil { _ = db.Close() return nil, fmt.Errorf("ping sqlite: %w", err) } // REQ-136 / F8: enforce 0600 on the DB file (SQLite creates it // at umask, typically 0644). We chmod after open+ping (the file // exists at this point). Non-fatal if chmod fails (e.g. the DB // is at a path we don't own); the caller is warned via vet. if err := os.Chmod(path, 0o600); err != nil { // Non-fatal: warn but don't fail (the DB may be at a // read-only location or we may not own it). _ = err } if err := migrate(db); err != nil { _ = db.Close() return nil, fmt.Errorf("migrate: %w", err) } return db, nil }