Skip to Content
fusion-orm
Hooks & Observability

Model hooks

The eight model hook interfaces, name-based detection at schema parse time, SkipHooks, and how hook errors flow into the error slot.

Model hooks let a struct participate in its own persistence: stamping fields before an insert, denormalizing data after a find, vetoing a delete. Hooks are per-row — for a slice destination they run once per element — and they run inside the default CRUD callback chains, between the build and execute steps.

fusion-orm detects hooks in two equivalent forms:

  1. Name-detected methods — gorm-compatible. Define BeforeCreate(tx *fusion.DB) error on your model; the schema parser finds it by name at parse time.
  2. Compile-time-safe interfaces — the same eight hooks declared as Go interfaces, so a typo is a compile error instead of a silent no-op.

The eight hooks

// The hook interfaces below are the compile-time-safe forms of the methods
// schema detects by name at parse time. A model may implement any subset.
InterfaceMethodFires
fusion.BeforeCreaterBeforeCreate(tx *DB) errorbefore a record is created
fusion.AfterCreaterAfterCreate(tx *DB) errorafter a record is created
fusion.BeforeUpdaterBeforeUpdate(tx *DB) errorbefore a record is updated
fusion.AfterUpdaterAfterUpdate(tx *DB) errorafter a record is updated
fusion.BeforeDeleterBeforeDelete(tx *DB) errorbefore a record is deleted
fusion.AfterDeleterAfterDelete(tx *DB) errorafter a record is deleted
fusion.BeforeFinderBeforeFind(tx *DB) errorbefore a query
fusion.AfterFinderAfterFind(tx *DB) errorafter a query

Every interface carries exactly one method with the same signature: Method(tx *DB) error. The tx argument is the session executing the statement — a derivative *DB, so you can chain on it or read its Statement without touching the root.

type BeforeCreater interface {
	BeforeCreate(tx *DB) error
}

Define hooks on the pointer receiver

Detection checks methods on reflect.PointerTo(typ) — the same rule Go uses for interface satisfaction. func (u User) BeforeCreate(...) is not seen; func (u *User) BeforeCreate(...) is.

Detection happens at parse time

The schema parser records which of the eight names are present on the model's pointer type, once, the first time the model is used:

// Hooks records which model hook methods are present, detected at parse
// time.
var hookNames = []string{
	"BeforeCreate", "AfterCreate", "BeforeUpdate", "AfterUpdate",
	"BeforeDelete", "AfterDelete", "BeforeFind", "AfterFind",
}

At runtime, each default CRUD chain carries a namedHook callback that checks the recorded set first:

// Hook dispatch is opt-in by method presence: skip the reflection
// (modelValues + MethodByName) entirely for models without hooks.
table, err := db.modelTable()
if err != nil {
	return
}
if !table.Hooks.Has(name) {
	return
}

A model without hooks pays one map-free boolean check per statement — no reflection, no allocation.

A model with hooks

type hookUser struct {
	ID        int64 `fusion:"pk,autoincrement"`
	Name      string
	CreatedAt time.Time
	UpdatedAt time.Time
	Events    []string `fusion:"-"`
}

func (hookUser) TableName() string { return "hook_users" }

func (*hookUser) BeforeCreate(*DB) error {
	hookEvents = append(hookEvents, "before_create")
	return nil
}

func (*hookUser) AfterCreate(*DB) error {
	hookEvents = append(hookEvents, "after_create")
	return nil
}

func (*hookUser) AfterFind(*DB) error {
	hookEvents = append(hookEvents, "after_find")
	return nil
}

A realistic BeforeCreate derives a value before the INSERT renders; an AfterFind post-processes scanned rows. Both see the fully hydrated struct through the session tx. The compile-time-safe interfaces let you pin the contract in code — a signature drift becomes a build failure:

var _ fusion.BeforeCreater = (*User)(nil)
var _ fusion.AfterFinder   = (*User)(nil)

Hooks are ordered per operation

For one Create, BeforeCreate fires before the row write and AfterCreate after it. The test suite asserts the exact sequence on a single record: [before_create after_create after_find].

u := hookUser{Name: "hooked"}
if err := db.Create(&u).Error; err != nil {
	t.Fatalf("Create: %v", err)
}
var found []hookUser
if err := db.Find(&found).Error; err != nil {
	t.Fatalf("Find: %v", err)
}
want := "[before_create after_create after_find]"

Errors abort at that callback

A hook returns error. The error goes into the chain's single error slot and the remaining callbacks for that statement are skipped — the write never happens if BeforeCreate fails.

results := method.Call([]reflect.Value{reflect.ValueOf(db)})
for _, result := range results {
	if err, ok := result.Interface().(error); ok {
		db.AddError(err)
	}
}
func callHooksOnValues(db *DB, values []reflect.Value, name string) {
	for i := range values {
		callHook(db, values[i].Addr().Interface(), name)
		if db.Error != nil {
			return
		}
	}
}

Because errors travel through AddError with wrap-chain semantics, your sentinel errors stay branchable: errors.Is(res.Error, my.ErrInvalidSlug) works as usual. See the error slot.

SkipHooks

Statement.SkipHooks suppresses model hooks for one statement. Two places in the library set it for you:

  • UpdateColumn / UpdateColumns — "Updates without hooks or automatic timestamps". They set SkipHooks and SkipTimestamps, then delegate to Updates.
// UpdateColumns is Updates without hooks or automatic timestamps.
func (db *DB) UpdateColumns(values any) *DB {
	tx := db.getInstance()
	tx.Statement.SkipHooks = true
	tx.Statement.SkipTimestamps = true
	return tx.Updates(values)
}
  • Association record creation — join rows created behind the scenes while associating objects set SkipHooks so incidental writes do not trigger your hooks.
tx := a.db.Session(&Session{NewDB: true}).getInstance()
tx.Statement.SkipHooks = true
tx.Statement.Set("fusion:skip_associations", true)

You can set the flag on your own sessions too — it is an ordinary Statement field consulted by callHook before dispatch:

func callHook(db *DB, model any, name string) {
	if db.Statement.SkipHooks || model == nil {
		return
	}

Next

On this page