87098a9180
- 在 HoTimeDB 中新增 testMu 互斥锁,确保 testTx 的串行访问,解决并发冲突问题 - 在 BeginTestTx 中初始化 testMu,确保测试事务的安全性 - 在 HoTimeCache 中新增 DisableDbCache 方法,测试模式下禁用 DB 和 Redis 缓存,避免锁等待超时 - 更新 Select 方法,确保在 testTx 激活时跳过缓存逻辑,提升测试稳定性 - 优化 Swagger 生成逻辑,支持模块化输出和导航页生成 - 移除冗余的调试日志代码,提升代码整洁性
84 lines
2.0 KiB
Go
84 lines
2.0 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,
|
|
testMu: that.testMu,
|
|
}
|
|
|
|
if that.testTx != nil {
|
|
spName := fmt.Sprintf("sp_%d", atomic.AddUint64(&savepointCounter, 1))
|
|
if that.testMu != nil { that.testMu.Lock() }
|
|
_, _ = that.testTx.Exec("SAVEPOINT " + spName)
|
|
if that.testMu != nil { that.testMu.Unlock() }
|
|
db.Tx = that.testTx
|
|
isSuccess = action(db)
|
|
if !isSuccess {
|
|
if that.testMu != nil { that.testMu.Lock() }
|
|
_, _ = that.testTx.Exec("ROLLBACK TO SAVEPOINT " + spName)
|
|
if that.testMu != nil { that.testMu.Unlock() }
|
|
} else {
|
|
if that.testMu != nil { that.testMu.Lock() }
|
|
_, _ = that.testTx.Exec("RELEASE SAVEPOINT " + spName)
|
|
if that.testMu != nil { that.testMu.Unlock() }
|
|
}
|
|
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
|
|
}
|