-
-
Notifications
You must be signed in to change notification settings - Fork 267
/
ent_tx.go
37 lines (33 loc) · 900 Bytes
/
ent_tx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package entx
import (
"context"
"fmt"
"github.com/zeromicro/go-zero/core/logx"
"github.com/suyuan32/simple-admin-core/rpc/ent"
)
// WithTx uses transaction in ent.
func WithTx(ctx context.Context, client *ent.Client, fn func(tx *ent.Tx) error) error {
tx, err := client.Tx(ctx)
if err != nil {
logx.Errorw("failed to start transaction", logx.Field("detail", err.Error()))
return err
}
defer func() {
if v := recover(); v != nil {
_ = tx.Rollback()
panic(v)
}
}()
if err := fn(tx); err != nil {
if rollBackErr := tx.Rollback(); rollBackErr != nil {
err = fmt.Errorf("%w: rolling back transaction: %v", err, rollBackErr)
}
logx.Errorw("errors occur in transaction", logx.Field("detail", err.Error()))
return err
}
if err := tx.Commit(); err != nil {
logx.Errorw("failed to commit transaction", logx.Field("detail", err.Error()))
return err
}
return nil
}