From b3980358cf5aa5790afa2edff73cdec7183a0a07 Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Wed, 27 Nov 2024 23:10:50 +0100 Subject: fix(tfstated): rollack transaction in case of panic --- pkg/database/db.go | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) (limited to 'pkg') 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 -- cgit v1.2.3