diff --git a/callbacks/transaction.go b/callbacks/transaction.go index 14d31a62..3171b5bb 100644 --- a/callbacks/transaction.go +++ b/callbacks/transaction.go @@ -5,21 +5,25 @@ import ( ) func BeginTransaction(db *gorm.DB) { - if tx := db.Begin(); tx.Error == nil { - db.Statement.ConnPool = tx.Statement.ConnPool - db.InstanceSet("gorm:started_transaction", true) - } else { - tx.Error = nil + if !db.Config.SkipDefaultTransaction { + if tx := db.Begin(); tx.Error == nil { + db.Statement.ConnPool = tx.Statement.ConnPool + db.InstanceSet("gorm:started_transaction", true) + } else { + tx.Error = nil + } } } func CommitOrRollbackTransaction(db *gorm.DB) { - if _, ok := db.InstanceGet("gorm:started_transaction"); ok { - if db.Error == nil { - db.Commit() - } else { - db.Rollback() + if !db.Config.SkipDefaultTransaction { + if _, ok := db.InstanceGet("gorm:started_transaction"); ok { + if db.Error == nil { + db.Commit() + } else { + db.Rollback() + } + db.Statement.ConnPool = db.ConnPool } - db.Statement.ConnPool = db.ConnPool } } diff --git a/gorm.go b/gorm.go index 1c6d3383..e3b1dd35 100644 --- a/gorm.go +++ b/gorm.go @@ -57,12 +57,13 @@ type DB struct { // Session session config when create session with Session() method type Session struct { - DryRun bool - PrepareStmt bool - WithConditions bool - Context context.Context - Logger logger.Interface - NowFunc func() time.Time + DryRun bool + PrepareStmt bool + WithConditions bool + SkipDefaultTransaction bool + Context context.Context + Logger logger.Interface + NowFunc func() time.Time } // Open initialize db session based on dialector @@ -145,6 +146,10 @@ func (db *DB) Session(config *Session) *DB { } ) + if config.SkipDefaultTransaction { + tx.Config.SkipDefaultTransaction = true + } + if config.Context != nil { tx.Statement = tx.Statement.clone() tx.Statement.DB = tx