Hooks
A mutation operation is an operation that mutate the database. For example, adding a new node to the graph, remove an edge between 2 nodes or delete multiple nodes.
There are 5 types of mutations:
Create
- Create node in the graph.UpdateOne
- Update a node in the graph. For example, increment its field.Update
- Update multiple nodes in the graph that match a predicate.DeleteOne
- Delete a node from the graph.Delete
- Delete all nodes that match a predicate.
Each generated node type has its own type of mutation. For example, all User builders, share the same generated UserMutation
object.
However, all builder types implement the generic interface.
Hooks
Hooks are functions that get an and return a mutator back. They function as middleware between mutators. It’s similar to the popular HTTP middleware pattern.
Runtime hooks
Let’s start with a short example that logs all mutation operations of all types:
func main() {
client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
if err != nil {
log.Fatalf("failed opening connection to sqlite: %v", err)
}
defer client.Close()
// Run the auto migration tool.
if err := client.Schema.Create(ctx); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
// Add a global hook that runs on all types and all operations.
client.Use(func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
start := time.Now()
defer func() {
log.Printf("Op=%s\tType=%s\tTime=%s\tConcreteType=%T\n", m.Op(), m.Type(), time.Since(start), m)
return next.Mutate(ctx, m)
})
})
client.User.Create().SetName("a8m").SaveX(ctx)
// Output:
// 2020/03/21 10:59:10 Op=Create Type=Card Time=46.23µs ConcreteType=*ent.UserMutation
}
Global hooks are useful for adding traces, metrics, logs and more. But sometimes, users want more granularity:
Assume you want to share a hook that mutate a field between multiple types (e.g. Group
and User
). There are ~2 ways to do this:
// Option 1: use type assertion.
client.Use(func(next ent.Mutator) ent.Mutator {
type NameSetter interface {
}
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
// A schema with a "name" field must implement the NameSetter interface.
if ns, ok := m.(NameSetter); ok {
ns.SetName("Ariel Mashraki")
}
return next.Mutate(ctx, m)
})
})
client.Use(func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if err := m.SetField("name", "Ariel Mashraki"); err != nil {
// An error is returned, if the field is not defined in
// the schema, or if the type mismatch the field type.
}
return next.Mutate(ctx, m)
})
})
Schema hooks are defined in the type schema and applied only on mutations that match the schema type. The motivation for defining hooks in the schema is to gather all logic regarding the node type in one place, which is the schema.
Hooks Registration
When using schema hooks, there’s a chance of a cyclic import between the schema package, and the generated ent package. To avoid this scenario, ent generates an ent/runtime
package which is responsible for registering the schema-hooks at runtime.
important
import _ "<project>/ent/runtime"
Evaluation order
Hooks are called in the order they were registered to the client. Thus, client.Use(f, g, h)
executes f(g(h(...)))
on mutations.
Also note, that runtime hooks are called before schema hooks. That is, if g
, and h
were defined in the schema, and f
was registered using client.Use(...)
, they will be executed as follows: f(g(h(...)))
.
The generated hooks package provides several helpers that can help you control when a hook will be executed.
Transaction Hooks
Hooks can also be registered on active transactions, and will be executed on Tx.Commit
or Tx.Rollback
. For more information, read about it in the transactions page.
Codegen Hooks
The package provides an option to add a list of hooks (middlewares) to the code-generation phase. For more information, read about it in the codegen page.