Hooks

The Hooks option allows adding custom logic before and after operations that mutate the graph.

Mutation

A mutation operation is an operation that mutates 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 ent.Mutation interface.

Hooks - 图1Support For Database Triggers Unlike database triggers, hooks are executed at the application level, not the database level. If you need to execute specific logic on the database level, use database triggers as explained in the schema migration guide. :::

Hooks

Hooks are functions that get an ent.Mutator and return a mutator back. They function as middleware between mutators. It’s similar to the popular HTTP middleware pattern.

  1. type (
  2. // Mutator is the interface that wraps the Mutate method.
  3. Mutator interface {
  4. // Mutate apply the given mutation on the graph.
  5. Mutate(context.Context, Mutation) (Value, error)
  6. }
  7. // Hook defines the "mutation middleware". A function that gets a Mutator
  8. // and returns a Mutator. For example:
  9. //
  10. // hook := func(next ent.Mutator) ent.Mutator {
  11. // return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
  12. // fmt.Printf("Type: %s, Operation: %s, ConcreteType: %T\n", m.Type(), m.Op(), m)
  13. // return next.Mutate(ctx, m)
  14. // })
  15. // }
  16. //
  17. Hook func(Mutator) Mutator
  18. )

There are 2 types of mutation hooks - schema hooks and runtime hooks. Schema hooks are mainly used for defining custom mutation logic in the schema, and runtime hooks are used for adding things like logging, metrics, tracing, etc. Let’s go over the 2 versions:

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. ctx := context.Background()
  8. // Run the auto migration tool.
  9. if err := client.Schema.Create(ctx); err != nil {
  10. log.Fatalf("failed creating schema resources: %v", err)
  11. }
  12. // Add a global hook that runs on all types and all operations.
  13. client.Use(func(next ent.Mutator) ent.Mutator {
  14. return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
  15. start := time.Now()
  16. defer func() {
  17. log.Printf("Op=%s\tType=%s\tTime=%s\tConcreteType=%T\n", m.Op(), m.Type(), time.Since(start), m)
  18. }()
  19. return next.Mutate(ctx, m)
  20. })
  21. })
  22. client.User.Create().SetName("a8m").SaveX(ctx)
  23. // Output:
  24. // 2020/03/21 10:59:10 Op=Create Type=User Time=46.23µs ConcreteType=*ent.UserMutation
  25. }

Global hooks are useful for adding traces, metrics, logs and more. But sometimes, users want more granularity:

  1. func main() {
  2. // <client was defined in the previous block>
  3. // Add a hook only on user mutations.
  4. client.User.Use(func(next ent.Mutator) ent.Mutator {
  5. // Use the "<project>/ent/hook" to get the concrete type of the mutation.
  6. return hook.UserFunc(func(ctx context.Context, m *ent.UserMutation) (ent.Value, error) {
  7. return next.Mutate(ctx, m)
  8. })
  9. })
  10. // Add a hook only on update operations.
  11. client.Use(hook.On(Logger(), ent.OpUpdate|ent.OpUpdateOne))
  12. // Reject delete operations.
  13. client.Use(hook.Reject(ent.OpDelete|ent.OpDeleteOne))
  14. }

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

Schema hooks

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.

  1. package schema
  2. import (
  3. "context"
  4. "fmt"
  5. gen "<project>/ent"
  6. "<project>/ent/hook"
  7. "entgo.io/ent"
  8. )
  9. // Card holds the schema definition for the CreditCard entity.
  10. type Card struct {
  11. ent.Schema
  12. }
  13. // Hooks of the Card.
  14. func (Card) Hooks() []ent.Hook {
  15. return []ent.Hook{
  16. // First hook.
  17. hook.On(
  18. func(next ent.Mutator) ent.Mutator {
  19. return hook.CardFunc(func(ctx context.Context, m *gen.CardMutation) (ent.Value, error) {
  20. if num, ok := m.Number(); ok && len(num) < 10 {
  21. return nil, fmt.Errorf("card number is too short")
  22. }
  23. return next.Mutate(ctx, m)
  24. })
  25. },
  26. // Limit the hook only for these operations.
  27. ent.OpCreate|ent.OpUpdate|ent.OpUpdateOne,
  28. ),
  29. // Second hook.
  30. func(next ent.Mutator) ent.Mutator {
  31. return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
  32. if s, ok := m.(interface{ SetName(string) }); ok {
  33. s.SetName("Boring")
  34. }
  35. v, err := next.Mutate(ctx, m)
  36. // Post mutation action.
  37. fmt.Println("new value:", v)
  38. return v, err
  39. })
  40. },
  41. }
  42. }

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.

  1. import _ "<project>/ent/runtime"

:::

Import Cycle Error

At the first attempt to set up schema hooks in your project, you may encounter an error like the following:

  1. entc/load: parse schema dir: import cycle not allowed: [ent/schema ent/hook ent/ ent/schema]
  2. To resolve this issue, move the custom types used by the generated code to a separate package: "Type1", "Type2"

The error may occur because the generated code relies on custom types defined in the ent/schema package, but this package also imports the ent/hook package. This indirect import of the ent package creates a loop, causing the error to occur. To resolve this issue, follow these instructions:

  • First, comment out any usage of hooks, privacy policy, or interceptors from the ent/schema.
  • Move the custom types defined in the ent/schema to a new package, for example, ent/schema/schematype.
  • Run go generate ./... to update the generated ent package to point to the new package. For example, schema.T becomes schematype.T.
  • Uncomment the hooks, privacy policy, or interceptors, and run go generate ./... again. The code generation should now pass without error.

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(...))).

Hook helpers

The generated hooks package provides several helpers that can help you control when a hook will be executed.

  1. package schema
  2. import (
  3. "context"
  4. "fmt"
  5. "<project>/ent/hook"
  6. "entgo.io/ent"
  7. "entgo.io/ent/schema/mixin"
  8. )
  9. type SomeMixin struct {
  10. mixin.Schema
  11. }
  12. func (SomeMixin) Hooks() []ent.Hook {
  13. return []ent.Hook{
  14. // Execute "HookA" only for the UpdateOne and DeleteOne operations.
  15. hook.On(HookA(), ent.OpUpdateOne|ent.OpDeleteOne),
  16. // Don't execute "HookB" on Create operation.
  17. hook.Unless(HookB(), ent.OpCreate),
  18. // Execute "HookC" only if the ent.Mutation is changing the "status" field,
  19. // and clearing the "dirty" field.
  20. hook.If(HookC(), hook.And(hook.HasFields("status"), hook.HasClearedFields("dirty"))),
  21. // Disallow changing the "password" field on Update (many) operation.
  22. hook.If(
  23. hook.FixedError(errors.New("password cannot be edited on update many")),
  24. hook.And(
  25. hook.HasOp(ent.OpUpdate),
  26. hook.Or(
  27. hook.HasFields("password"),
  28. hook.HasClearedFields("password"),
  29. ),
  30. ),
  31. ),
  32. }
  33. }

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