Skip to main content

Interceptors and events

An interceptor sees every statement a context runs, bulk writes and raw SQL included. Logging, metrics and tracing are interceptors. An ant.Option can install one, which is how plugins are written.

Write an interceptor​

Before runs ahead of the statement. It can return a new context, as tracing needs, and change the statement. An error from it stops the statement. After receives the outcome.

type Timer struct{}

func (Timer) Before(ctx context.Context, s *ant.Statement) (context.Context, error) {
return ctx, nil
}

func (Timer) After(ctx context.Context, s *ant.Statement, o ant.Outcome) {
slog.Info("query", "sql", s.SQL, "took", o.Duration)
}

db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn, ant.WithInterceptor(Timer{}))

s.Replica says whether the statement ran on a replica, and o.Err is the failure, if any. o.Duration ends when the database answers, before rows are read. s.Args holds real values. Several interceptors run in the order given, and After runs in reverse order.

Log slow queries​

To log only statements over a limit, with the caller's context for request and trace IDs:

type SlowLog struct {
Limit time.Duration
}

func (SlowLog) Before(ctx context.Context, s *ant.Statement) (context.Context, error) {
return ctx, nil
}

func (l SlowLog) After(ctx context.Context, s *ant.Statement, o ant.Outcome) {
if o.Duration >= l.Limit {
slog.WarnContext(ctx, "slow query", "sql", s.SQL, "took", o.Duration)
}
}

db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn,
ant.WithInterceptor(SlowLog{Limit: 200 * time.Millisecond}),
)

ant's own logger does this with ant.SlowThreshold.

Refuse a statement​

This one keeps a context read-only. A write that starts with WITH gets past its check, so treat it as a guard against mistakes:

type ReadOnly struct{}

func (ReadOnly) Before(ctx context.Context, s *ant.Statement) (context.Context, error) {
verb, _, _ := strings.Cut(strings.TrimSpace(s.SQL), " ")

switch strings.ToUpper(verb) {
case "INSERT", "UPDATE", "DELETE":
return ctx, errors.New("this context is read-only")
}

return ctx, nil
}

func (ReadOnly) After(context.Context, *ant.Statement, ant.Outcome) {}

Watch saves​

An interceptor that also has a SavingChanges method is an ant.SaveInterceptor. It sees each SaveChanges before anything is written, as whole entities and field names. An error cancels the save. A single-entity Insert is reported too, as one change in state Added. Bulk Update and Delete, InsertMany and raw SQL are not; the plain interceptor methods see those statements.

type Audit struct {
Timer
}

func (Audit) SavingChanges(ctx context.Context, changes []ant.Change) error {
for _, c := range changes {
slog.Info("saving", "model", c.Model, "state", c.State.String(), "fields", c.Changed)
}

return nil
}

Follow the unit of work​

Events are callbacks on the unit of work as a whole. They cannot stop anything. A nil callback is skipped. Tracked and StateChanged must not call back into the context.

db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn,
ant.WithEvents(ant.Events{
Saving: func(ctx context.Context, changes []ant.Change) {},
Saved: func(ctx context.Context, changes []ant.Change) {},
SaveFailed: func(ctx context.Context, err error) {},
Tracked: func(model string, entity any) {},
StateChanged: func(model string, entity any, from, to ant.State) {
slog.Info("state", "model", model, "from", from.String(), "to", to.String())
},
}),
)

Which one to use​

You needUse
Every statement, including raw SQLInterceptor
To refuse or rewrite a statementInterceptor.Before
To inspect or refuse a saveSaveInterceptor
To follow the unit of workEvents
To react to one model, after commitObserver