bd20af0c89
- 在 HoTimeDB 中新增测试事务功能,允许在测试模式下使用事务进行操作 - 实现 BeginTestTx 和 RollbackTestTx 方法,支持测试事务的开启和回滚 - 在 Action 方法中集成保存点管理,确保在测试模式下的嵌套事务处理 - 更新 README.md,添加 API 测试框架的相关说明,提升文档完整性
77 lines
1.7 KiB
Go
77 lines
1.7 KiB
Go
package db
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
"sync/atomic"
|
|
)
|
|
|
|
var savepointCounter uint64
|
|
|
|
// Action 事务操作
|
|
// 如果 action 返回 true 则提交事务;返回 false 则回滚
|
|
// 测试模式下(testTx != nil),使用 SAVEPOINT 代替真事务,确保嵌套事务不会绕过外层测试事务
|
|
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{},
|
|
testTx: that.testTx,
|
|
}
|
|
|
|
if that.testTx != nil {
|
|
spName := fmt.Sprintf("sp_%d", atomic.AddUint64(&savepointCounter, 1))
|
|
_, _ = that.testTx.Exec("SAVEPOINT " + spName)
|
|
db.Tx = that.testTx
|
|
isSuccess = action(db)
|
|
if !isSuccess {
|
|
_, _ = that.testTx.Exec("ROLLBACK TO SAVEPOINT " + spName)
|
|
} else {
|
|
_, _ = that.testTx.Exec("RELEASE SAVEPOINT " + spName)
|
|
}
|
|
return isSuccess
|
|
}
|
|
|
|
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
|
|
}
|