From 98d691603d913f76c1379886895375b7e23df2ae Mon Sep 17 00:00:00 2001 From: Lukas Jorg Date: Mon, 13 Sep 2021 08:30:27 +0200 Subject: [PATCH] Created transaction wrapper --- main.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/main.go b/main.go index 4be4bbec..12834f30 100644 --- a/main.go +++ b/main.go @@ -522,6 +522,17 @@ func (s *DB) Rollback() *DB { return s } +// WrapInTx wraps a method in a transaction +func (s *DB) WrapInTx(f func(tx *gorm.DB) (error)) error { + tx := s.Begin() + if err := f(tx); err != nil { + tx.Rollback() + return err + } + tx.Commit() + return nil +} + // NewRecord check if value's primary key is blank func (s *DB) NewRecord(value interface{}) bool { return s.NewScope(value).PrimaryKeyZero()