Files
db/exec/query_hooks.go
T
what 6ed2803158 feat: Hooks 新增 UseTx,Before/After 改用类型化的 HookError
之前 Hooks.Before/After 返回裸 error,调用方没法区分"钩子本身失败"和"SQL
执行失败"。改成返回 *HookError(包一层 exec.HookError),配合 errors.As
能精确识别。

同时给 Hooks 加一个 UseTx(dataset) (QueryFactory, error) 方法,在 Before
之前调用,允许钩子在写操作真正执行前替换掉默认连接(比如需要自动开事务包住
写操作和写后回调的场景),返回 nil, nil 表示沿用默认连接。目前只有
InsertDataset/UpdateDataset/DeleteDataset 会调用 UseTx,SelectDataset
(只读)不需要。
2026-08-20 17:08:29 +08:00

27 lines
856 B
Go

package exec
import "fmt"
// HookError 是 Hooks.Before/After 失败时必须返回的类型,外部通过 db.HookError 引用。
type HookError struct {
Err error
}
func (e *HookError) Error() string {
return fmt.Sprintf("hook error: %s", e.Err)
}
func (e *HookError) Unwrap() error {
return e.Err
}
// Hooks 钩子实例
type Hooks interface {
Before(dataset interface{}) *HookError
After(dataset interface{}, result interface{}) *HookError
// UseTx 在 Before 之前调用,dataset 是即将执行的 *InsertDataset/*UpdateDataset/*DeleteDataset
// (类型与 Before 收到的一致),此时数据集尚未绑定要执行的连接。返回非 nil 的 QueryFactory 时,
// 调用方会用它替换默认连接来执行这次写操作;返回 nil, nil 表示沿用默认连接。
UseTx(dataset interface{}) (QueryFactory, error)
}