mirror of
https://github.com/ent/ent.git
synced 2026-04-29 22:20:54 +03:00
doc: add transaction hooks to entgo.io (#600)
This commit is contained in:
@@ -131,3 +131,39 @@ func Do(ctx context.Context, client *ent.Client) {
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Hooks
|
||||
|
||||
Same as [schema hooks](hooks.md#schema-hooks) and [runtime hooks](hooks.md#runtime-hooks), hooks can be registered on
|
||||
active transactions, and will be executed on `Tx.Commit` or `Tx.Rollback`:
|
||||
|
||||
```go
|
||||
func Do(ctx context.Context, client *ent.Client) error {
|
||||
tx, err := client.Tx(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Add a hook on Tx.Commit.
|
||||
tx.OnCommit(func(next ent.Committer) ent.Committer {
|
||||
return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
|
||||
// Code before the actual commit.
|
||||
err := next.Commit(ctx, tx)
|
||||
// Code after the transaction was committed.
|
||||
return err
|
||||
})
|
||||
})
|
||||
// Add a hook on Tx.Rollback.
|
||||
tx.OnRollback(func(next ent.Rollbacker) ent.Rollbacker {
|
||||
return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
|
||||
// Code before the actual rollback.
|
||||
err := next.Rollback(ctx, tx)
|
||||
// Code after the transaction was rolled back.
|
||||
return err
|
||||
})
|
||||
})
|
||||
//
|
||||
// <Code goes here>
|
||||
//
|
||||
return err
|
||||
}
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user