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:

  1. func main() {
  2. client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
  3. if err != nil {
  4. log.Fatalf("failed opening connection to sqlite: %v", err)
  5. }
  6. defer client.Close()
  7. // Run the auto migration tool.
  8. if err := client.Schema.Create(ctx); err != nil {
  9. log.Fatalf("failed creating schema resources: %v", err)
  10. }
  11. // Add a global hook that runs on all types and all operations.
  12. client.Use(func(next ent.Mutator) ent.Mutator {
  13. return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
  14. start := time.Now()
  15. defer func() {
  16. log.Printf("Op=%s\tType=%s\tTime=%s\tConcreteType=%T\n", m.Op(), m.Type(), time.Since(start), m)
  17. return next.Mutate(ctx, m)
  18. })
  19. })
  20. client.User.Create().SetName("a8m").SaveX(ctx)
  21. // Output:
  22. // 2020/03/21 10:59:10 Op=Create Type=Card Time=46.23µs ConcreteType=*ent.UserMutation
  23. }

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:

  1. // Option 1: use type assertion.
  2. client.Use(func(next ent.Mutator) ent.Mutator {
  3. type NameSetter interface {
  4. }
  5. return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
  6. // A schema with a "name" field must implement the NameSetter interface.
  7. if ns, ok := m.(NameSetter); ok {
  8. ns.SetName("Ariel Mashraki")
  9. }
  10. return next.Mutate(ctx, m)
  11. })
  12. })
  13. client.Use(func(next ent.Mutator) ent.Mutator {
  14. return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
  15. if err := m.SetField("name", "Ariel Mashraki"); err != nil {
  16. // An error is returned, if the field is not defined in
  17. // the schema, or if the type mismatch the field type.
  18. }
  19. return next.Mutate(ctx, m)
  20. })
  21. })

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
  1. 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.