58 lines
1.1 KiB
Go
58 lines
1.1 KiB
Go
|
|
package db
|
||
|
|
|
||
|
|
import (
|
||
|
|
"sync"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Action 事务操作
|
||
|
|
// 如果 action 返回 true 则提交事务;返回 false 则回滚
|
||
|
|
func (that *HoTimeDB) Action(action func(db HoTimeDB) (isSuccess bool)) (isSuccess bool) {
|
||
|
|
db := HoTimeDB{
|
||
|
|
DB: that.DB,
|
||
|
|
ContextBase: that.ContextBase,
|
||
|
|
DBName: that.DBName,
|
||
|
|
HoTimeCache: that.HoTimeCache,
|
||
|
|
Log: that.Log,
|
||
|
|
Type: that.Type,
|
||
|
|
Prefix: that.Prefix,
|
||
|
|
LastQuery: that.LastQuery,
|
||
|
|
LastData: that.LastData,
|
||
|
|
ConnectFunc: that.ConnectFunc,
|
||
|
|
LastErr: that.LastErr,
|
||
|
|
limit: that.limit,
|
||
|
|
Tx: that.Tx,
|
||
|
|
SlaveDB: that.SlaveDB,
|
||
|
|
Mode: that.Mode,
|
||
|
|
Dialect: that.Dialect,
|
||
|
|
mu: sync.RWMutex{},
|
||
|
|
limitMu: sync.Mutex{},
|
||
|
|
}
|
||
|
|
|
||
|
|
tx, err := db.Begin()
|
||
|
|
|
||
|
|
if err != nil {
|
||
|
|
that.LastErr.SetError(err)
|
||
|
|
return isSuccess
|
||
|
|
}
|
||
|
|
|
||
|
|
db.Tx = tx
|
||
|
|
|
||
|
|
isSuccess = action(db)
|
||
|
|
|
||
|
|
if !isSuccess {
|
||
|
|
err = db.Tx.Rollback()
|
||
|
|
if err != nil {
|
||
|
|
that.LastErr.SetError(err)
|
||
|
|
return isSuccess
|
||
|
|
}
|
||
|
|
return isSuccess
|
||
|
|
}
|
||
|
|
|
||
|
|
err = db.Tx.Commit()
|
||
|
|
if err != nil {
|
||
|
|
that.LastErr.SetError(err)
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
return true
|
||
|
|
}
|