Migrating from Bun
Tag mapping, builder-to-chain translation, hooks, transactions, soft delete, and migrations for moving a bun codebase onto fusion-orm.
bun is where fusion-orm's engine comes from, so the concepts — query
builder, relations, hooks, migrations — translate directly. The API
surface differs: bun chains a standalone builder per query and passes
ctx on every call; fusion-orm chains a copy-on-write *DB and carries
the context from WithContext. This page maps the two, side by side.
Tag mapping
bun tags spell options with the same vocabulary; the structural change is
that bun carries the table name and alias inside the base tag, while
fusion-orm uses a TableName() method.
| bun tag | fusion tag | Notes |
|---|---|---|
pk | pk | Same |
autoincrement | autoincrement | Same |
notnull | notnull | Same |
nullzero | nullzero | Same (schema/tag.go:45) |
default:VALUE | default:VALUE | Same |
unique | unique | Same |
bun:"table:users" | TableName() string method | fusion has no table: tag key and no alias concept; implement schema.Tabler (schema/naming.go:15-18) |
rel:has-many / rel:has-one / rel:belongs-to | rel:has-many / rel:has-one / rel:belongs-to | Same keywords (schema/tag_test.go:25) |
rel:m2m,jointable:... | rel:many2many,many2many:TABLE | fusion spells the keyword many2many, not m2m |
join:on:user_id | foreignKey:FIELD / references:FIELD | bun's inline join spec becomes two named tags (schema/tag.go:46-47) |
bun:",json_use_zero" and JSON columns | serializer:json (or bare json) | Marshals through encoding/json (schema/field.go:209) |
scanonly | - (skip) plus raw SQL | fusion has no scanonly; use fusion:"-" and raw SQL for read-only projections |
type User struct {
bun.BaseModel `bun:"table:users,alias:u"`
ID int64 `bun:"id,pk,autoincrement"`
Name string `bun:"name,notnull"`
Email string `bun:",nullzero,default:''"`
Posts []Post `bun:"rel:has-many,join:on:author_id"`
}No aliases
fusion-orm renders one table per model and derives join aliases itself
(profile__avatar-style dotted columns). There is no alias:u to carry
over — query fragments reference real table and column names.
Query style: builder → chain
bun builds a query object and executes it with an explicit context;
fusion-orm chains clauses on a *DB derivative and the context comes from
WithContext. Every pairing below is the same statement.
Select
users := []User{}
err := db.NewSelect().Model(&users).
Where("name = ?", "Ada").
Order("name ASC").
Limit(10).
Scan(ctx)Find scans into the destination and returns an empty slice on a miss;
First/Take/Last return ErrRecordNotFound on a miss.
Insert
user := User{Name: "Ada"}
_, err := db.NewInsert().Model(&user).Exec(ctx)For batches, CreateBatchSize(n) chunks the slice
(chainable_api.go:285-289) — bun's &bun.RunInTx-wrapped bulk inserts
become one chain:
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 {
// ...
}Update
_, err := db.NewUpdate().Model(&User{}).
Set("age = ?", 31).
Where("name = ?", "Ada").
Exec(ctx)Delete
_, err := db.NewDelete().Model(&User{}).
Where("name = ?", "Ada").
Exec(ctx)Delete soft-deletes when the model embeds a soft-delete field; the
global-write guard rejects statement with no conditions at all — add a
Where, or opt in with Session(&fusion.Session{AllowGlobalUpdate: true})
(crud_test.go:146-157).
Count and exists
n, err := db.NewSelect().Model(&User{}).Where("age > ?", 30).Count(ctx)
ok, err := db.NewSelect().Model(&User{}).Where("age > ?", 30).Exists(ctx)No Exists finisher
fusion-orm has no Exists finisher (finisher_api.go). Use Count for
the count, or a single-column LIMIT 1 scan for a boolean probe.
Relation loading: Relation() → Preload()
bun's .Relation("Profile") eager-loads one query per relation level;
fusion-orm's Preload does the same, batched, with nested dotted paths
and apply functions (chainable_api.go:69-76):
err := db.NewSelect().Model(&user).
Relation("Profile").
Relation("Posts").
Where("user.id = ?", id).
Scan(ctx)exampleMust(e.session.Model(&exampleUser{}).
Preload("Profile").Preload("Posts").
First(&got, user.ID).Error)Hooks: bun.QueryHook → fusion.QueryHook
The shape is identical — BeforeQuery may replace the context, and
AfterQuery receives the completed event (hook.go:66-69):
// QueryHook observes statements around execution. BeforeQuery may replace the
// context used for the I/O call; AfterQuery receives the completed event.A bun hook's BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context body ports almost verbatim; the event type swaps to
*fusion.QueryEvent with the same fields (hook.go:51-62). fusion also
ships SlogQueryHook so simple statement logging needs no custom hook
(query_hook.go:75-99).
Transactions: RunInTx → Transaction
The biggest ergonomic change: fusion's Transaction takes no context —
the context travels with the session via WithContext, and fc receives
a transactional *DB (transaction.go:16-21):
err := bun.RunInTx(ctx, &sql.TxOptions{...}, func(ctx context.Context, tx bun.Tx) error {
return doWork(ctx, tx)
})func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err error)Commit on nil error, rollback on error or panic, savepoint nesting inside
an open transaction (transaction.go:16-20) — both semantics match.
Soft deletes
bun's soft_delete field option becomes an embedded (or softdelete
tagged) field plus explicit Unscoped/Restore:
type Post struct {
DeletedAt time.Time `bun:",soft_delete,nullzero"`
}// DeletedAt is a nullable soft-delete timestamp. Its zero value means the row
// is live; Value renders it as NULL so the default query condition is
// "deleted_at IS NULL".db.Where("id = ?", id).Delete(&post) // sets deleted_at
db.Unscoped().Where("id = ?", id).Delete(&post) // hard delete
db.Restore(&post) // clears deleted_at (soft_delete.go:227)Migrations
bun's migration registry becomes migrator.Migration values registered on
the runner, plus SQL-file loading:
migrations.MustRegister(func(ctx context.Context, db *bun.DB) error { ... },
func(ctx context.Context, db *bun.DB) error { ... }, migrator.Up)type Migration struct {
Version int64
Name string
Up func(*sql.DB) error
Down func(*sql.DB) error
}m.Register(Migration{Version: 1, Name: "create_users", Up: up, Down: down})Numbered 1_name.up.sql / 1_name.down.sql pairs load through
migrator.LoadSQLFiles(dir) (migrator/migrator.go:694). Note the
signature change: fusion migration functions take *sql.DB, not a
context plus the ORM handle — the runner supplies the context.
Not in fusion-orm
| bun feature | Status in fusion-orm |
|---|---|
bun/dbfixture fixtures package | Not implemented |
| MySQL / MSSQL dialects | Not shipped — SQLite and PostgreSQL only |
NewRaw-style standalone expression builder | Not implemented; raw SQL goes through Exec/Row/Rows/Scan on a *DB |
bun's With CTE builder on the select query | Not implemented as a chainable; CTEs go through clause.With{CTEName, Subquery} via Clauses (clause/query.go:170-188) |
With{CTEName: "active", Subquery: "SELECT 1"},renders WITH "active" AS (SELECT 1) — register it with
db.Clauses(clause.With{...}).