You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
857 B
Smarty
39 lines
857 B
Smarty
1 year ago
|
package entx
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
|
||
|
"git.noahlan.cn/noahlan/ntool/nlog"
|
||
|
|
||
|
"{{.package}}/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 {
|
||
|
nlog.Errorw("failed to start transaction", nlog.Field("err", 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)
|
||
|
}
|
||
|
nlog.Errorw("errors occur in transaction", nlog.Field("err", err.Error()))
|
||
|
return err
|
||
|
}
|
||
|
if err := tx.Commit(); err != nil {
|
||
|
nlog.Errorw("failed to commit transaction", nlog.Field("err", err.Error()))
|
||
|
return err
|
||
|
}
|
||
|
return nil
|
||
|
}
|