Skip to main content

Hooks and observers

A hook is a method on your model that runs inside the write. An observer runs after the commit and cannot change the write.

Add a hook​

Name the method for the hook and use a pointer receiver so changes to the entity are saved. This one lowercases emails on insert:

type Member struct {
ID int64
Name string
Email string
}

func (m *Member) BeforeInsert(ctx context.Context) error {
m.Email = strings.ToLower(m.Email)

return nil
}
HookRuns
ValidateBefore every insert and update
BeforeInsert, AfterInsertAround an insert, and around an Upsert whichever way it goes
BeforeUpdate, AfterUpdateAround a save that changed the entity
BeforeDelete, AfterDeleteAround a delete
AfterLoadAfter a row is read
AfterIncludeAfter its relations are loaded

Refuse a write​

An error from a before hook stops the write. An error from an after hook undoes it, because hooks run inside the transaction.

func (m *Member) BeforeDelete(ctx context.Context) error {
if m.Name == "protected" {
return errors.New("cannot delete")
}

return nil
}

For field rules, see validation. To inspect or refuse a whole save, including a single Insert, before anything is written, use a SaveInterceptor.

Query from a hook​

When the context has change tracking, a hook shares the operation's claim on the tracker through its ctx. Run hook queries with that context:

func (m *Member) BeforeInsert(ctx context.Context) error {
taken, err := db.Members.Where(ant.Eq(&Members.Email, m.Email)).Exists(ctx)
if err != nil {
return err
}

if taken {
return errors.New("email is taken")
}

return nil
}

A query with another context, such as context.Background(), counts as a second operation on the tracker and returns ant.ErrConcurrentUse. Goroutines started with the hook's context share the claim and must not use the tracker concurrently.

What runs no hooks​

Bulk Update and Delete, InsertMany, UpdateMany, Merge and Raw run no hooks, since they load no entity. A save with nothing to save runs none either.

ant.WithoutHooks skips hooks for one call:

err := db.Members.Insert(ant.WithoutHooks(ctx), member)
A hook cannot reach the transaction

A hook only gets a context.Context, so use it to check or refuse a write, not to write rows. For that, see auditing.

Observe committed writes​

ant.Observe registers functions for one model. They run once the outermost transaction has committed, so an observer never sees a write that rolled back. Sessions made from the context share the observer.

err := ant.Observe(db, ant.Observer[Member]{
Inserted: func(ctx context.Context, m *Member) { welcome(m) },
Updated: func(ctx context.Context, m *Member) { refresh(m) },
Deleted: func(ctx context.Context, m *Member) { refresh(m) },
})

Any of the three can be left nil.

Write an audit log​

An observer fires only for kept changes, so it suits a log line:

err := ant.Observe(db, ant.Observer[Member]{
Inserted: func(ctx context.Context, m *Member) {
slog.InfoContext(ctx, "audit", "action", "insert", "model", "Member", "id", m.ID)
},
Deleted: func(ctx context.Context, m *Member) {
slog.InfoContext(ctx, "audit", "action", "delete", "model", "Member", "id", m.ID)
},
})

Limits​

  • An observer runs in your process. If the process crashes between the commit and the call, it never runs. For anything that must not be lost, write an outbox row in the same transaction.
  • A transaction from UseTx ends where ant cannot see it, so ant queues no observers for it and they never run. Writes in it are kept at once.