From fd7ee91110cf1de780f3c46822dd69385b3b6318 Mon Sep 17 00:00:00 2001 From: xengineering Date: Thu, 9 May 2024 11:13:46 +0200 Subject: model: Use defer for tx.Rollback() A committed transaction cannot be rolled back. Using defer to roll back guarantees that the transaction is always rolled back if not the commit in the last line of model.Transaction was excuted. [1]: https://go.dev/doc/database/execute-transactions --- model/database.go | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/model/database.go b/model/database.go index 8b66bb5..d6d6c16 100644 --- a/model/database.go +++ b/model/database.go @@ -4,7 +4,6 @@ import ( "database/sql" "embed" "log" - "fmt" _ "github.com/mattn/go-sqlite3" ) @@ -40,15 +39,19 @@ func ConnectDatabase(path string) { func Transaction(f func(*sql.Tx) error) error { tx, err := db.Begin() if err != nil { + log.Printf("Failed to start database transaction: %v", err) return err } + defer func() { + if tx.Rollback() == nil { + log.Println("Rolled back transaction") + } + }() err = f(tx) if err != nil { - rollbackErr := tx.Rollback() - if rollbackErr != nil { - return fmt.Errorf("Failed rollback '%w' after failed transaction '%w'", rollbackErr, err) - } + log.Printf("Failed transaction: %v", err) + return err } return tx.Commit() @@ -68,7 +71,7 @@ func MigrateDatabase() { return nil }) if err != nil { - log.Fatalf("Migration failed: %v\n", err) + log.Fatalf("Fatal: Database migration failed") } } -- cgit v1.2.3-70-g09d2