Skip to Content
fusion-orm
Guides

Quick reference

A cheat sheet — one short, source-verified snippet per common task, with the traditional and generics APIs side by side.

Every snippet below is copied or trimmed from the repository source; the provenance comment names the file and line it came from.

Open and migrate

db, err := fusion.Open(sqlite.Open("app.db"))
if err != nil {
	panic(err)
}
m, err := db.Migrator()
if err != nil {
	panic(err)
}
if err := m.AutoMigrate(context.Background(), &User{}); err != nil {
	panic(err)
}

One *DB is safe for concurrent use — chain derivatives off it, never mutate it.

Define a model

type userWithUUIDModel struct {
	UUIDModel
	Email string
}

func (userWithUUIDModel) TableName() string { return "base_uuid_users" }

Embed fusion.Model (autoincrement ID, timestamps, soft delete) or fusion.UUIDModel (UUIDv7 PK) when you want those defaults; TableName() is optional but explicit beats the naming strategy.

Create

user := User{Name: "Ada"}
if err := db.Create(&user).Error; err != nil {
	panic(err)
}

Batch create

users := make([]crudUser, 7)
for i := range users {
	users[i].Name = fmt.Sprintf("u%d", i)
}
if err := db.CreateBatchSize(3).Create(&users).Error; err != nil {
	// ...
}

CreateBatchSize(n) caps the rows per INSERT statement; PKs are backfilled per row.

Query one / many

chain
db.Model(&User{}).
  Where("age > ?", 18).
  Order("id DESC").
  Limit(5).
  Find(&users)
SQL
SELECT * FROM "users"
WHERE age > $1
ORDER BY id DESC
LIMIT 5
postgres · $n placeholders1 round-trip
u := crudUser{Name: "dave", Age: 22}
if err := db.Create(&u).Error; err != nil {
	// ...
}
var got crudUser
if err := db.First(&got, u.ID).Error; err != nil {
	// ...
}

var all []crudUser
if err := db.Find(&all).Error; err != nil {
	// ...
}

First returns ErrRecordNotFound on a miss; Find returns an empty slice and a nil error.

Update

db.Model(&crudUser{}).Where("name = ?", "alice").Update("age", 34)

Update sets one column; Updates takes a map or struct. UpdateColumn(s) skips hooks and automatic timestamps.

A WHERE clause is required unless Config.AllowGlobalUpdate is set.

Delete and soft delete

if err := db.Delete(&softUser{}, all[0].ID).Error; err != nil {
	// ...
}

Soft delete activates when the model has a DeletedAt field (or a softdelete tag): Delete sets it, queries filter deleted_at IS NULL. Unscoped() reads past the filter; Restore undeletes.

Count and Pluck

var visible int64
exampleMust(e.session.Model(&exampleSoftUser{}).Count(&visible).Error)

Pluck scans one column into a slice (scan_test.go:59).

Transactions

err := db.Transaction(func(tx *DB) error {
	return tx.Exec("INSERT INTO users (name) VALUES (?)", "alice").Error
})

Commit on nil error, rollback on error or panic. Nested Transaction calls run through savepoints automatically (transaction_test.go:110).

Preload

exampleMust(e.session.Model(&exampleUser{}).
	Preload("Profile").Preload("Posts").
	First(&got, user.ID).Error)

One batched query per relation, nested paths with Preload("A.B") — never an N+1 (relation_test.go:185).

FindInBatches

result := db.FindInBatches(&[]crudUser{}, 2, func(tx *DB, batch int) error {
	var rows []crudUser
	if err := tx.Find(&rows).Error; err != nil {
		return err
	}
	// process rows
	return nil
})

Paginates by primary key; the callback gets a fresh tx per batch.

Raw SQL

tx := db.Exec("UPDATE users SET active = ?", true)
if tx.Error != nil { /* ... */ }
row := db.Model(&crudUser{}).Where("name = ?", "alice").Select("age").Row()
var age int
if err := row.Scan(&age); err != nil {
	// ...
}

Rows() returns a raw *sql.Rows (close it yourself); Scan(dest) scans the built query into a struct, map, or scalar.

Upsert

upsert := clause.OnConflict{UpdateColumns: []string{"name", "age"}}
if err := db.Clauses(upsert).Create(&upsertUser{ID: 1, Name: "b", Age: 11}).Error; err != nil {
	// ...
}

OnConflict{DoNothing: true} or UpdateAll: true are the other shapes; both dialects support it.

See the SQL

sql := e.session.ToSQL(func(tx *fusion.DB) *fusion.DB {
	return tx.Model(&exampleUser{}).Where("name = ?", "Ada").Find(&[]exampleUser{})
})

Session(&Session{DryRun: true}) captures without executing; Debug() traces every statement at Info level.

Where next

On this page