summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorxengineering <me@xengineering.eu>2024-05-09 11:13:46 +0200
committerxengineering <me@xengineering.eu>2024-05-09 11:13:46 +0200
commitfd7ee91110cf1de780f3c46822dd69385b3b6318 (patch)
treea995ff74fc46fed094c921f320b31df53212acff
parenta2038b0ea35d1466c84e6e04a2e4597fc038815a (diff)
downloadceres-fd7ee91110cf1de780f3c46822dd69385b3b6318.tar
ceres-fd7ee91110cf1de780f3c46822dd69385b3b6318.tar.zst
ceres-fd7ee91110cf1de780f3c46822dd69385b3b6318.zip
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
-rw-r--r--model/database.go15
1 files 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")
}
}