diff options
author | Julien Dessaux | 2024-11-27 23:10:50 +0100 |
---|---|---|
committer | Julien Dessaux | 2024-11-27 23:10:50 +0100 |
commit | 77f8b48928555c54d499a244392456d78d9569f0 (patch) | |
tree | 4797c0ff52f093de7e2f479eb978e9f312942e55 /pkg/database | |
parent | chore(tfstated): implement a transaction wrapper (diff) | |
download | tfstated-77f8b48928555c54d499a244392456d78d9569f0.tar.gz tfstated-77f8b48928555c54d499a244392456d78d9569f0.tar.bz2 tfstated-77f8b48928555c54d499a244392456d78d9569f0.zip |
fix(tfstated): rollack transaction in case of panic
Diffstat (limited to 'pkg/database')
-rw-r--r-- | pkg/database/db.go | 21 |
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 |