Allow temporarily disable default transaction

This commit is contained in:
Jinzhu 2020-07-16 18:05:55 +08:00
parent e83e210971
commit b8692c7671
2 changed files with 26 additions and 17 deletions

View File

@ -5,6 +5,7 @@ import (
) )
func BeginTransaction(db *gorm.DB) { func BeginTransaction(db *gorm.DB) {
if !db.Config.SkipDefaultTransaction {
if tx := db.Begin(); tx.Error == nil { if tx := db.Begin(); tx.Error == nil {
db.Statement.ConnPool = tx.Statement.ConnPool db.Statement.ConnPool = tx.Statement.ConnPool
db.InstanceSet("gorm:started_transaction", true) db.InstanceSet("gorm:started_transaction", true)
@ -12,8 +13,10 @@ func BeginTransaction(db *gorm.DB) {
tx.Error = nil tx.Error = nil
} }
} }
}
func CommitOrRollbackTransaction(db *gorm.DB) { func CommitOrRollbackTransaction(db *gorm.DB) {
if !db.Config.SkipDefaultTransaction {
if _, ok := db.InstanceGet("gorm:started_transaction"); ok { if _, ok := db.InstanceGet("gorm:started_transaction"); ok {
if db.Error == nil { if db.Error == nil {
db.Commit() db.Commit()
@ -23,3 +26,4 @@ func CommitOrRollbackTransaction(db *gorm.DB) {
db.Statement.ConnPool = db.ConnPool db.Statement.ConnPool = db.ConnPool
} }
} }
}

View File

@ -60,6 +60,7 @@ type Session struct {
DryRun bool DryRun bool
PrepareStmt bool PrepareStmt bool
WithConditions bool WithConditions bool
SkipDefaultTransaction bool
Context context.Context Context context.Context
Logger logger.Interface Logger logger.Interface
NowFunc func() time.Time NowFunc func() time.Time
@ -145,6 +146,10 @@ func (db *DB) Session(config *Session) *DB {
} }
) )
if config.SkipDefaultTransaction {
tx.Config.SkipDefaultTransaction = true
}
if config.Context != nil { if config.Context != nil {
tx.Statement = tx.Statement.clone() tx.Statement = tx.Statement.clone()
tx.Statement.DB = tx tx.Statement.DB = tx