Files
workspace/code/allapp/allapp-go-v3/pkg/db/tx.go
T
2026-04-06 21:15:11 +08:00

35 lines
522 B
Go

package db
import (
"context"
"github.com/jackc/pgx/v5"
)
// WithTx 开启事务(在当前 client 上)
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,
}
defer func(tx pgx.Tx, ctx context.Context) {
err := tx.Rollback(ctx)
if err != nil {
}
}(tx, ctx)
if err := fn(txClient); err != nil {
return err
}
return tx.Commit(ctx)
}