From 221f8963db6e575d106449eca1e2b018221e3ba9 Mon Sep 17 00:00:00 2001 From: Gerhard Gruber Date: Wed, 27 Oct 2021 12:22:54 +0200 Subject: [PATCH] Added sub-transaction detection to WrapInTx --- main.go | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/main.go b/main.go index 21af629c..92e7643f 100644 --- a/main.go +++ b/main.go @@ -523,14 +523,20 @@ func (s *DB) Rollback() *DB { } // WrapInTx wraps a method in a transaction -func (s *DB) WrapInTx(f func(tx *DB) (error)) error { - tx := s.Begin() - if err := f(tx); err != nil { - tx.Rollback() - return err +func (s *DB) WrapInTx(f func(tx *DB) error) error { + if _, ok := s.db.(*sql.Tx); ok { + // Already in a transaction + return f(s) + } else { + // Lets start a new transaction + tx := s.Begin() + if err := f(tx); err != nil { + tx.Rollback() + return err + } + tx.Commit() + return nil } - tx.Commit() - return nil } // SkipAssocSave disables saving of associations