summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJulien Dessaux2024-11-27 23:10:50 +0100
committerJulien Dessaux2024-12-17 23:19:22 +0100
commitb3980358cf5aa5790afa2edff73cdec7183a0a07 (patch)
tree4797c0ff52f093de7e2f479eb978e9f312942e55
parentchore(tfstated): implement a transaction wrapper (diff)
downloadtfstated-b3980358cf5aa5790afa2edff73cdec7183a0a07.tar.gz
tfstated-b3980358cf5aa5790afa2edff73cdec7183a0a07.tar.bz2
tfstated-b3980358cf5aa5790afa2edff73cdec7183a0a07.zip
fix(tfstated): rollack transaction in case of panic
-rw-r--r--pkg/database/db.go21
1 files changed, 13 insertions, 8 deletions
diff --git a/pkg/database/db.go b/pkg/database/db.go
index 5501a82..0777556 100644
--- a/pkg/database/db.go
+++ b/pkg/database/db.go
@@ -108,15 +108,20 @@ func (db *DB) SetVersionsHistoryLimit(n int) {
func (db *DB) WithTransaction(f func(tx *sql.Tx) error) error {
tx, err := db.writeDB.Begin()
if err != nil {
- return err
+ return fmt.Errorf("failed to begin transaction: %w", err)
}
- err = f(tx)
- if err == nil {
- err = tx.Commit()
- }
- if err != nil {
- if err2 := tx.Rollback(); err2 != nil {
- panic(fmt.Sprintf("failed to rollback transaction: %+v. Reason for rollback: %+v", err2, err))
+ defer func() {
+ if err != nil {
+ if err2 := tx.Rollback(); err2 != nil {
+ panic(fmt.Sprintf("failed to rollback transaction: %+v. Reason for rollback: %+v", err2, err))
+ }
+ }
+ }()
+ if err = f(tx); err != nil {
+ return fmt.Errorf("failed to execute function inside transaction: %w", err)
+ } else {
+ if err = tx.Commit(); err != nil {
+ err = fmt.Errorf("failed to commit transaction: %w", err)
}
}
return err