Query hooks
Wrap every executed statement with QueryHook — observe SQL, duration, and errors, and propagate context from before to after.
Where model hooks run per row inside CRUD chains, query hooks run once
per executed statement — every Exec, Query, and QueryRow the ORM
performs, raw SQL included. This is the seam for metrics, distributed
tracing, and audit logs.
// QueryHook observes statements around execution. BeforeQuery may replace the
// context used for the I/O call; AfterQuery receives the completed event.
type QueryHook interface {
BeforeQuery(ctx context.Context, event *QueryEvent) context.Context
AfterQuery(ctx context.Context, event *QueryEvent)
}Two methods, in order:
BeforeQueryruns before the I/O call. Whatever context it returns is the context the statement actually executes under.AfterQueryruns after execution completes, with the event filled in. It fires even when the statement failed.
QueryEvent
// QueryEvent carries the details of one executed statement to QueryHooks.
// Vars are the bound parameters; RowsAffected is -1 when unknown.
type QueryEvent struct {
Context context.Context
SQL string
Vars []any
RowsAffected int64
Error error
StartTime time.Time
Duration time.Duration
Statement *Statement
}Varscontains the bound parameters. Treat them as secrets: the built-inSlogQueryHookdeliberately never logs them (see below).RowsAffectedis-1when unknown — queries that return rows (Query/QueryRow) do not report a count, and a failedExecmay not either.DurationandErrorare only meaningful inAfterQuery.Statementpoints at the executing chain's statement.
The execution path
Every I/O call builds an event, fans out to BeforeQuery, executes, then
fans out to AfterQuery through finishQuery — which traces the statement
through the logger before invoking hooks:
func finishQuery(db *DB, ctx context.Context, event *QueryEvent, begin time.Time, rows int64, err error) {
event.Context = ctx
event.RowsAffected = rows
event.Error = err
event.Duration = time.Since(begin)
trace(db, ctx, begin, event.SQL, event.Vars, err)
for _, hook := range db.QueryHooks {
if hook != nil {
hook.AfterQuery(ctx, event)
}
}
}Hooks run in registration order. Exec populates RowsAffected from the
sql.Result; Query and QueryRow leave it at -1.
QueryRow events carry no error
QueryRow defers its error until row.Scan, so the event an AfterQuery
hook sees for a row query has Error == nil and RowsAffected == -1
regardless of what the database returned. Only Exec and Query report
their error in the event.
Installing a hook
Two ways. The QueryHook chainable appends to a derivative's config
(copy-on-write — the receiver is untouched):
// QueryHook registers an observability hook on a derivative session.
func (db *DB) QueryHook(hook QueryHook) *DB {
tx := db.getInstance()
config := *tx.Config
config.QueryHooks = append(append([]QueryHook(nil), config.QueryHooks...), hook)
tx.Config = &config
return tx
}tx := db.QueryHook(hook).Exec(`CREATE TABLE hook_users (id INTEGER PRIMARY KEY, name TEXT)`)
if tx.Error != nil {
t.Fatal(tx.Error)
}
if err := db.QueryHook(hook).Exec(`INSERT INTO hook_users (name) VALUES (?)`, "alice").Error; err != nil {Or register globally through the config before Open:
// QueryHooks observes statements around execution.
QueryHooks []QueryHookdb, err := fusion.Open(sqlite.Open("app.db"),
&fusion.Config{QueryHooks: []fusion.QueryHook{hook}})A counting hook, end to end
type countingQueryHook struct {
calls int
}
func (h *countingQueryHook) BeforeQuery(ctx context.Context, _ *fusion.QueryEvent) context.Context {
return ctx
}
func (h *countingQueryHook) AfterQuery(context.Context, *fusion.QueryEvent) {
h.calls++
}hook := &countingQueryHook{}
db := e.session.QueryHook(hook)
exampleMust(db.Create(&exampleUser{Name: "Ada"}).Error)
fmt.Println(hook.calls > 0)
// Output: trueContext propagation
BeforeQuery's return value is not decoration: it becomes the context of
the I/O call and the context handed to AfterQuery. This is how you
move span handles or deadlines from before to after without globals.
func (h *testQueryHook) BeforeQuery(ctx context.Context, event *QueryEvent) context.Context {
h.before = append(h.before, event.SQL)
return context.WithValue(ctx, hookKey{}, "propagated")
}if last.Context.Value(hookKey{}) != "propagated" {
t.Error("BeforeQuery context did not reach AfterQuery")
}If a hook returns a nil context, the engine substitutes context.TODO().
SlogQueryHook: built-in structured logging
SlogQueryHook logs each completed statement through log/slog at the
level you choose:
// SlogQueryHook logs completed statements through log/slog without recording
// bound parameter values.
type SlogQueryHook struct {
Logger *slog.Logger
Level slog.Level
}attrs := []any{
"sql", event.SQL,
"duration_ms", float64(event.Duration.Microseconds()) / 1000,
"rows", event.RowsAffected,
}
if event.Error != nil {
attrs = append(attrs, "error", event.Error.Error())
}
h.Logger.Log(nonNilContext(ctx), h.Level, "query", attrs...)Setup:
hook := &SlogQueryHook{Logger: slog.New(slog.NewTextHandler(&out, nil)), Level: slog.LevelInfo}It never logs bound parameters. The event's Vars are dropped at the
door; only SQL text, duration, row count, and error string reach the
handler. The test suite proves the guarantee by executing a secret-looking
bind value and asserting it is absent from the output:
if err := db.QueryHook(hook).Exec(`INSERT INTO slog_users (name) VALUES (?)`, "secret-value").Error; err == nil {
t.Fatal("expected error for missing table")
}
if strings.Contains(out.String(), "secret-value") {
t.Errorf("bound parameter leaked: %q", out.String())
}The zero value of Level is slog.LevelInfo (slog's own zero), so set
Level explicitly when you want a different gate. A nil Logger makes the
hook a no-op.