From f65b11a5b3011f370df5b4d32239225f3708ecd5 Mon Sep 17 00:00:00 2001 From: xengineering Date: Sat, 6 Apr 2024 13:12:17 +0200 Subject: model: Always pass *sql.Tx to CRUD methods When nesting objects like steps into other objects like recipes it is required to pass a *sql.Tx value to the CRUD methods of the inner object to be able to roll back the whole transaction. The top level object used to be responsible for the creation of this *sql.Tx inside its CRUD methods. This is now moved to the caller of the CRUD methods (here the HTTP handler function). The advantage is that all CRUD methods now accept a *sql.Tx as only argument which makes those methods more consistent. --- model/database.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) (limited to 'model/database.go') diff --git a/model/database.go b/model/database.go index 7021181..3d8a0c4 100644 --- a/model/database.go +++ b/model/database.go @@ -52,12 +52,23 @@ func InitDatabase() { func InjectTestRecipes() { recipes := RecipeTestData() + tx, err := NewTx() + if err != nil { + log.Fatalf("Failed to inject test recipes: %v\n", err) + } + for _, recipe := range recipes { - err := recipe.Create() + err = recipe.Create(tx) if err != nil { + Rollback(tx) log.Fatalf("Failed to inject test recipe: %v\n", err) } } + + err = tx.Commit() + if err != nil { + log.Fatalf("Failed to inject test recipe: %v\n", err) + } } func CloseDatabase() { @@ -69,7 +80,11 @@ func CloseDatabase() { } } -func rollback(tx *sql.Tx) { +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) -- cgit v1.2.3-70-g09d2