u
This commit is contained in:
1 parent
f08db1959b
commit
c6671c8a8c
68 files changed
+13904
-1131
No files matched your search
@@ -0,0 +1,34 @@
|
||||
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)
|
||||
}
|
||||
Reference in new issue
Block a user