gorm/callbacks/transaction.go

33 lines
675 B
Go
Raw Normal View History

2020-02-02 14:32:27 +03:00
package callbacks
2020-05-31 18:55:56 +03:00
import (
2020-06-02 04:16:07 +03:00
"gorm.io/gorm"
2020-05-31 18:55:56 +03:00
)
2020-02-02 14:32:27 +03:00
func BeginTransaction(db *gorm.DB) {
if !db.Config.SkipDefaultTransaction && db.Error == nil {
if tx := db.Begin(); tx.Error == nil {
db.Statement.ConnPool = tx.Statement.ConnPool
db.InstanceSet("gorm:started_transaction", true)
} else if tx.Error == gorm.ErrInvalidTransaction {
tx.Error = nil
2021-04-16 14:27:23 +03:00
} else {
db.Error = tx.Error
}
2020-05-31 18:55:56 +03:00
}
2020-02-02 14:32:27 +03:00
}
func CommitOrRollbackTransaction(db *gorm.DB) {
if !db.Config.SkipDefaultTransaction {
if _, ok := db.InstanceGet("gorm:started_transaction"); ok {
if db.Error != nil {
db.Rollback()
} else {
db.Commit()
}
db.Statement.ConnPool = db.ConnPool
2020-05-31 18:55:56 +03:00
}
}
2020-02-02 14:32:27 +03:00
}