Patterns & best practices
Field-tested conventions for models, error handling, transactions, context, and the use cases they enable.
Model definition
Embed fusion.Model or fusion.UUIDModel by value when you want
timestamps and soft delete for free — the embedded fields carry an
autoincrement (or UUIDv7) primary key, automatic CreatedAt/UpdatedAt,
and a DeletedAt that enables soft delete.
type userWithUUIDModel struct {
UUIDModel
Email string
}
func (userWithUUIDModel) TableName() string { return "base_uuid_users" }TableName() is optional (the naming strategy pluralizes the struct name),
but an explicit method keeps the mapping stable across renames.
Tag tips, from the parser's actual semantics (schema/field.go:228):
notnull— a realNOT NULLcolumn; put it on required fields so bad writes fail at the database, not silently.pk,autoincrement— only needed on hand-declared keys; a field namedIDis already a primary key, anduuid.UUIDPKs generate UUIDv7 at create time withoutautoincrement.index/unique— declared on filtered columns;index:custom_nameoverrides the generated name.type:uuid— nativeuuidon PostgreSQL,TEXTon SQLite.->/<-/-— read-only / write-only / ignored fields.
DeletedAt is detected by name
Soft delete activates when a model has a field named DeletedAt — including
fields you didn't embed from fusion.Model (schema/field.go:212). If a
column named deleted_at means something else in your schema, rename the
field or use the softdelete tag deliberately.
Error handling
Every branchable failure is a sentinel. Branch with errors.Is, never by
string matching.
var got User
err := db.First(&got, id).Error
if errors.Is(err, fusion.ErrRecordNotFound) {
// no row matched → 404
}Constraint failures reach the sentinels only when TranslateError is on
and the dialector implements ErrorTranslator — both in-tree dialects do:
db, err := fusion.Open(sqlite.Open("app.db"), &fusion.Config{TranslateError: true})err := db.Exec(`INSERT INTO uniq_users (email) VALUES ('a')`).Error
if !errors.Is(err, ErrDuplicatedKey) {
t.Errorf("error = %v, want ErrDuplicatedKey", err)
}Wrap with context at the call site so logs point at the operation, not the library:
if err := s.db.Create(&u).Error; err != nil {
if errors.Is(err, fusion.ErrDuplicatedKey) {
return nil, ErrEmailTaken // domain sentinel
}
return nil, fmt.Errorf("create user %s: %w", u.Email, err)
}The chain's error slot uses wrap-chain semantics — the first error stays
the errors.Is wrap head (errors_test.go:25), so sentinels survive
further wrapping.
Transactions
Default to callback-style Transaction for any multi-statement unit: it
commits on nil error and rolls back on error or panic — the panic still
propagates after rollback (transaction.go:16).
err := db.Transaction(func(tx *DB) error {
return tx.Exec("INSERT INTO users (name) VALUES (?)", "alice").Error
})Reach for Begin/Commit only when a transaction must span call
boundaries you cannot express as a callback — and remember the returned
*DB is not safe to hand across goroutines mid-flight.
Nesting is free
A Transaction call inside an active transaction runs through a savepoint
(sp1, sp2, …) — ROLLBACK TO on failure, RELEASE on success — unless
DisableNestedTransaction runs it inline (transaction_test.go:110).
Helper functions that write can each open their own Transaction safely.
Context discipline
Always WithContext in request handlers: the context rides every
QueryContext/ExecContext call, so cancellation and deadlines cancel the
SQL — not just your handler.
if err := db.WithContext(ctx).Unscoped().First(&hidden, "id = ?", user.ID).Error; err != nil {
// ...
}Derivatives isolate context: WithContext on a chain never leaks back to
the root (fusion_test.go:183). For a service with a long-lived root *DB,
the pattern is one derivative per request.
Use cases
REST handler sketch
Status codes come straight from the sentinels — no string sniffing:
func (s *Server) getUser(w http.ResponseWriter, r *http.Request) error {
var user User
if err := s.db.WithContext(r.Context()).First(&user, r.PathValue("id")).Error; err != nil {
if errors.Is(err, fusion.ErrRecordNotFound) {
http.Error(w, "not found", http.StatusNotFound)
return nil
}
return fmt.Errorf("get user: %w", err) // 500
}
return json.NewEncoder(w).Encode(user)
}func (s *Server) createUser(w http.ResponseWriter, r *http.Request) error {
var user User
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return nil
}
if err := s.db.WithContext(r.Context()).Create(&user).Error; err != nil {
if errors.Is(err, fusion.ErrDuplicatedKey) {
http.Error(w, "already exists", http.StatusConflict)
return nil
}
return fmt.Errorf("create user: %w", err)
}
w.WriteHeader(http.StatusCreated)
return nil
}Batch import job
FindInBatches paginates by primary key and hands each batch a fresh
session — constant memory over arbitrarily large tables:
result := db.FindInBatches(&[]crudUser{}, 500, func(tx *DB, batch int) error {
var rows []crudUser
if err := tx.Find(&rows).Error; err != nil {
return err
}
for _, row := range rows {
// transform / index row
}
return nil
})Analytics read
For a global aggregate, project the expression and scan a scalar. Select
entries with parentheses render verbatim:
var ages []int64
if err := db.Model(&crudUser{}).Order("id").Pluck("age", &ages).Error; err != nil {
// ...
}
var total int64
if err := db.Model(&crudUser{}).Select(`COUNT(*) AS total`).Scan(&total).Error; err != nil {
// ...
}This is the documented workaround while Group()/Having() are not
implemented — see GROUP BY & HAVING for
the full picture, including what does not work.