| 1 |
package callbacks |
| 2 |
|
| 3 |
import ( |
| 4 |
"gorm.io/gorm" |
| 5 |
) |
| 6 |
|
| 7 |
func BeginTransaction(db *gorm.DB) { |
| 8 |
if !db.Config.SkipDefaultTransaction && db.Error == nil { |
| 9 |
if tx := db.Begin(); tx.Error == nil { |
| 10 |
db.Statement.ConnPool = tx.Statement.ConnPool |
| 11 |
db.InstanceSet("gorm:started_transaction", true) |
| 12 |
} else if tx.Error == gorm.ErrInvalidTransaction { |
| 13 |
tx.Error = nil |
| 14 |
} else { |
| 15 |
db.Error = tx.Error |
| 16 |
} |
| 17 |
} |
| 18 |
} |
| 19 |
|
| 20 |
func CommitOrRollbackTransaction(db *gorm.DB) { |
| 21 |
if !db.Config.SkipDefaultTransaction { |
| 22 |
if _, ok := db.InstanceGet("gorm:started_transaction"); ok { |
| 23 |
if db.Error != nil { |
| 24 |
db.Rollback() |
| 25 |
} else { |
| 26 |
db.Commit() |
| 27 |
} |
| 28 |
|
| 29 |
db.Statement.ConnPool = db.ConnPool |
| 30 |
} |
| 31 |
} |
| 32 |
} |