Skip to Content
fusion-orm
Guides

Why fusion-orm

What fusion-orm takes from bun's SQL-first engine and gorm's fluent API, feature by feature — and when to choose it.

fusion-orm is a Go ORM built on database/sql. It pairs bun's SQL-first query engine — zero-allocation byte-slice builders, dialect feature bitflags, precompiled field closures, cached schema reflection — with gorm's fluent chaining and callback pipeline: copy-on-write sessions, a clause registry, model hooks, sentinel errors, and a generics facade. It is original code, not a fork of either: the engine never knows about chaining, and the chaining layer never assembles SQL directly.

db, err := fusion.Open(sqlite.Open("app.db"))

SQLite (modernc.org/sqlite, pure Go) and PostgreSQL (pgx/v5) ship in-tree. Dialects declare capabilities as a feature bitset; query builders branch on capability, never on dialect-name strings.

What it takes from each

From bun: the engine. SQL is assembled into a reused []byte through per-dialect appenders; schema reflection is parsed once and cached; field build/scan run through precompiled closures so there is no reflection per row; dialect differences are declared as feature bitflags rather than scattered if dialect == ... branches.

From gorm: the surface. A fluent chain of derivative *DB values, a clause registry under Clauses, a callback pipeline under db.Callback(), copy-on-write sessions, model hooks, a single error slot with errors.Is sentinels, and a G[T] generics facade with checked interfaces.

The same read, in both APIs — the generated SQL is identical:

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

Feature checklist

Every claim below is backed by a test in this repository — the cited file is the proof, not a promise.

FeatureAPITested by
Chainable query build (Where/Or/Order/Limit/Offset/Select/Distinct)db.Model(&User{}).Where(...)fusion_test.go:101, crud_test.go:297
Struct, map, and SQL-string conditionsWhere(map[string]any{...})chainable_api.go:164
Batch insert with PK backfilldb.CreateBatchSize(n).Create(&users)crud_test.go:83
FindInBatches (keyset pagination, composite-key aware)db.FindInBatches(&dest, n, fc)crud_test.go:251
FirstOrInit / FirstOrCreate with Attrs/Assigndb.Attrs(...).FirstOrCreate(&u, cond)crud_test.go:273
Upsert via Clauses(clause.OnConflict{...})db.Clauses(upsert).Create(&row)audit_fixes_test.go:489
Save, Update, Updates, UpdateColumn(s)db.Model(&u).Update("name", v)crud_test.go:363, crud_test.go:450
Global Update/Delete guardno WHERE → ErrMissingWhereClausecrud_test.go:146
Soft delete + Unscoped + Restoreembed fusion.DeletedAtsoft_delete_test.go:49
Hooks (Before/AfterCreate/Update/Delete/Find)implement the interface on your modelcrud_test.go:420
Eager Preload (batched, nested, apply functions)Preload("Profile").Preload("Posts")relation_test.go:156, N+1 check at relation_test.go:185
Inline relation Joins (dotted-column scan)Joins("Profile")relation_test.go:198
Association APIFind/Append/Replace/Delete/Clear/Countrelation_test.go:230
Polymorphic relationsfusion:"rel:...,polymorphic:..."relation_test.go:385
Many-to-many + SetupJoinTabledb.SetupJoinTable(...), rel:many2manyrelation_test.go:302
Transactions + nested savepointsTransaction(func(tx *DB) error)transaction_test.go:49, transaction_test.go:110
Context propagation and cancellationdb.WithContext(ctx)fusion_test.go:183
Prepared-statement mode (LRU + TTL)Config{PrepareStmt: true}prepared_stmt_test.go:25, prepared_stmt_test.go:84
DryRun / ToSQL SQL captureSession(&Session{DryRun: true})fusion_test.go:115
Scopes and raw Clausesdb.Scopes(func(tx *DB) *DB { ... })crud_test.go:199
Composite primary keysscalar-id addressing errors, tuple orderingcomposite_pk_test.go:59
Locking (FOR UPDATE)db.Locking(true)clause/clause_test.go:67
AutoMigrate (inspect/diff/ALTER)db.Migrator().AutoMigrate(ctx, &User{})migration_test.go:47
Versioned Go + numbered SQL migrations, lock tablem.Migrate(ctx, v, up, down)migration_test.go:92
Plugin + callback registrationdb.Use(plugin), db.Callback().Create()fusion_test.go:264, crud_test.go:310
QueryHook observability + slog adapterdb.QueryHook(fusion.SlogQueryHook{})query_hook_test.go:29, query_hook_test.go:63
Error sentinels + TranslateErrorerrors.Is(err, fusion.ErrDuplicatedKey)errors_test.go:88, errors_test.go:112
Generics facade fusion.G[T]G[User](db).Where(...).Find()generics_test.go:71

How it works

A query moves through four layers — the same path the rest of the docs follow:

  1. Chain — chainables accumulate clauses on a per-chain Statement through copy-on-write getInstance().
  2. Finish — a finisher (Create, Find, Delete, …) triggers a callback processor.
  3. Build — the processor renders the registered clauses, in a fixed build order, into a reused []byte through per-dialect appenders.
  4. Execute — the statement runs through database/sql (or the prepared-statement cache), and rows scan back through compiled per-field closures — no reflection per row.

Because SQL is built as bytes and rendered by the dialect, you can always ask what will run before it runs:

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

The full layer split, state model, and extension points live in Architecture.

When to choose fusion-orm

Choose it when you want all of the following; otherwise gorm, bun, or plain database/sql may serve you better:

  • A gorm-style chained API (Model/Where/Preload/Session) with gorm's extensibility — model hooks, registerable callbacks, plugins — but a bun-style engine under the hood: byte-slice SQL building, feature bitflags, precompiled scanners.
  • Built-in migrations: AutoMigrate plus versioned Go and numbered SQL migrations guarded by a lock table — bun has no in-tree equivalent.
  • Built-in prepared statements: an LRU+TTL cache with ErrBadConn recovery and transaction-aware wrappers, enabled by a config flag.
  • A generics facade (fusion.G[T]) whose SQL is byte-for-byte identical to the reflection API — verified by a dedicated parity test.
  • Sentinel errors end to end: every branchable failure is an errors.Is-compatible value, with driver constraint translation.

And the honest limits, stated plainly:

  • Dialect scope is SQLite + PostgreSQL. No MySQL or MSSQL dialect ships today. The feature-flag design means adding one is mostly flags plus identifier quoting (Dialects), but no such dialect exists in this repository — don't wait for it.
  • No Group()/Having() chainables. Grouped aggregation is done with Select aggregates + Scan (the honest write-up).
  • Destructive AutoMigrate diffs require opt-in, and metadata-based migration assumes single-writer DDL (Migrations).

Where next

On this page