mirror of https://github.com/go-gorm/gorm.git
Allow temporarily disable default transaction
This commit is contained in:
parent
e83e210971
commit
b8692c7671
|
@ -5,21 +5,25 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func BeginTransaction(db *gorm.DB) {
|
func BeginTransaction(db *gorm.DB) {
|
||||||
if tx := db.Begin(); tx.Error == nil {
|
if !db.Config.SkipDefaultTransaction {
|
||||||
db.Statement.ConnPool = tx.Statement.ConnPool
|
if tx := db.Begin(); tx.Error == nil {
|
||||||
db.InstanceSet("gorm:started_transaction", true)
|
db.Statement.ConnPool = tx.Statement.ConnPool
|
||||||
} else {
|
db.InstanceSet("gorm:started_transaction", true)
|
||||||
tx.Error = nil
|
} else {
|
||||||
|
tx.Error = nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func CommitOrRollbackTransaction(db *gorm.DB) {
|
func CommitOrRollbackTransaction(db *gorm.DB) {
|
||||||
if _, ok := db.InstanceGet("gorm:started_transaction"); ok {
|
if !db.Config.SkipDefaultTransaction {
|
||||||
if db.Error == nil {
|
if _, ok := db.InstanceGet("gorm:started_transaction"); ok {
|
||||||
db.Commit()
|
if db.Error == nil {
|
||||||
} else {
|
db.Commit()
|
||||||
db.Rollback()
|
} else {
|
||||||
|
db.Rollback()
|
||||||
|
}
|
||||||
|
db.Statement.ConnPool = db.ConnPool
|
||||||
}
|
}
|
||||||
db.Statement.ConnPool = db.ConnPool
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
17
gorm.go
17
gorm.go
|
@ -57,12 +57,13 @@ type DB struct {
|
||||||
|
|
||||||
// Session session config when create session with Session() method
|
// Session session config when create session with Session() method
|
||||||
type Session struct {
|
type Session struct {
|
||||||
DryRun bool
|
DryRun bool
|
||||||
PrepareStmt bool
|
PrepareStmt bool
|
||||||
WithConditions bool
|
WithConditions bool
|
||||||
Context context.Context
|
SkipDefaultTransaction bool
|
||||||
Logger logger.Interface
|
Context context.Context
|
||||||
NowFunc func() time.Time
|
Logger logger.Interface
|
||||||
|
NowFunc func() time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
// Open initialize db session based on dialector
|
// 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 {
|
if config.Context != nil {
|
||||||
tx.Statement = tx.Statement.clone()
|
tx.Statement = tx.Statement.clone()
|
||||||
tx.Statement.DB = tx
|
tx.Statement.DB = tx
|
||||||
|
|
Loading…
Reference in New Issue