Files
workspace/code/allapp/allapp-go-v3/pkg/db/tx.go
T
2026-04-24 22:37:52 +08:00

39 lines
554 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package db
import (
"context"
)
func (c *Client) WithTx(ctx context.Context, fn func(tx *Client) error) error {
tx, err := c.pool.Begin(ctx)
if err != nil {
return err
}
// 创建事务 client
txClient := &Client{
pool: c.pool,
tx: tx,
}
// rollback 兜底(防 panic / 提前 return)
defer func() {
_ = tx.Rollback(ctx)
}()
// 执行业务
if err := fn(txClient); err != nil {
_ = tx.Rollback(ctx)
return err
}
// commit
if err := tx.Commit(ctx); err != nil {
_ = tx.Rollback(ctx)
return err
}
return nil
}