diff options
Diffstat (limited to 'model/database.go')
-rw-r--r-- | model/database.go | 62 |
1 files changed, 34 insertions, 28 deletions
diff --git a/model/database.go b/model/database.go index d816163..44792fe 100644 --- a/model/database.go +++ b/model/database.go @@ -4,6 +4,7 @@ import ( "database/sql" "embed" "log" + "fmt" _ "github.com/mattn/go-sqlite3" ) @@ -35,37 +36,53 @@ func InitDatabase(path string) { log.Fatal(err) } - // FIXME roll back migration on error query, err := GetSql(`migrate`) if err != nil { log.Fatal(err) } - _, err = db.Exec(query) + + err = Transaction(func(tx *sql.Tx) error { + _, err := tx.Exec(query) + if err != nil { + return err + } + return nil + }) if err != nil { - log.Fatal(err) + log.Fatalf("Migration failed: %v\n", err) } } -func InjectTestRecipes() { - recipes := RecipeTestData() - - tx, err := NewTx() +func Transaction(f func(*sql.Tx) error) error { + tx, err := db.Begin() if err != nil { - log.Fatalf("Failed to inject test recipes: %v\n", err) + return err } - for _, recipe := range recipes { - err = recipe.Create(tx) - if err != nil { - Rollback(tx) - log.Fatalf("Failed to inject test recipe: %v\n", err) + err = f(tx) + if err != nil { + rollbackErr := tx.Rollback() + if rollbackErr != nil { + return fmt.Errorf("Failed rollback '%w' after failed transaction '%w'", rollbackErr, err) } } - err = tx.Commit() - if err != nil { - log.Fatalf("Failed to inject test recipe: %v\n", err) - } + return tx.Commit() +} + +func InjectTestRecipes() { + Transaction(func(tx *sql.Tx) error { + recipes := RecipeTestData() + + for _, recipe := range recipes { + err := recipe.Create(tx) + if err != nil { + return err + } + } + + return nil + }) } func CloseDatabase() { @@ -76,14 +93,3 @@ func CloseDatabase() { log.Println("Closed database") } } - -func NewTx() (*sql.Tx, error) { - return db.Begin() -} - -func Rollback(tx *sql.Tx) { - err := tx.Rollback() - if err != nil { - log.Printf("Failed to rollback transaction: %v\n", err) - } -} |