Skip to Content
fusion-orm
Core Concepts

The DB session

The *DB handle — root, derivatives, the finisher contract, and the single error slot.

*DB is the only type your code holds. It is a session handle: the root instance returned by Open, or a derivative produced by chaining, Session, WithContext, Debug, or Begin.

// DB is a session handle: the root instance returned by Open, or a
// derivative produced by chaining, Session, WithContext, Debug, or
// Begin. A *DB is safe for concurrent use; every chainable method returns
// a derivative and never mutates the receiver.

The struct

type DB struct {
	*Config
	// Error is the single error slot for the chain (see AddError).
	Error error
	// RowsAffected is set by finishers that execute DML.
	RowsAffected int64
	// Statement holds the chain's per-statement state. It is embedded by
	// value so a chain hop (getInstance) costs one allocation, not two;
	// copy-on-write semantics are unchanged (clone deep-copies maps and
	// slices).
	Statement Statement
	// clone selects getInstance's behavior: 1 = fresh statement on next
	// use (root/pristine), 2 = clone the current statement (mid-chain).
	clone int
}

Four things to internalize:

  1. *Config is embedded. A derivative carries a copy of the root's config, so session flags (DryRun, a different logger, a context) apply per-chain and never mutate the root.
  2. Statement is embedded by value. A chain hop costs one allocation.
  3. clone is internal plumbing — it tells getInstance() whether the next chainable builds a fresh statement (root, NewDB session) or clones the current one (mid-chain).
  4. The shared parts — schema cache, callback processors, dialect, pool — live on the config and are immutable after Open except through explicit plugin registration.

Root vs derivatives

The root *DB from Open is pristine: its clone is 1, so the first chainable call starts a fresh Statement. Every subsequent chainable call on that derivative clones the statement first. This is why you can keep using the root forever — each finisher call gets its own isolated chain:

tx1 := db.Exec("SELECT 1")
tx2 := db.Exec("SELECT 2")

if tx1 == tx2 || &tx1.Statement == &tx2.Statement {
	t.Fatal("chains must not share a Statement")
}

Concurrent use

Because chaining never mutates the receiver, a root *DB is safe for concurrent use — goroutines chain off it independently. Each chain owns its own Statement, error slot, and RowsAffected; only the read-only parts (config, dialect, caches, pool) are shared:

db, err := fusion.Open(sqlite.Open("app.db"))
if err != nil {
	panic(err)
}
var wg sync.WaitGroup
wg.Add(2)
go func() {
	defer wg.Done()
	var a User
	db.WithContext(ctx).First(&a, 1)
}()
go func() {
	defer wg.Done()
	var users []User
	db.Model(&User{}).Where("active = ?", true).Find(&users)
}()
wg.Wait()

The finisher contract

Finishers (Create, Find, Update, Delete, Count, …) execute. They never panic and never throw: the result is exactly two fields on the returned *DB.

  • Error — the single error slot; nil when the statement succeeded.
  • RowsAffected — set by finishers that execute DML (Count fills an *int64 you pass in, not the slot).
tx := db.Exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
if tx.Error != nil {
	t.Fatalf("CREATE: %v", tx.Error)
}

tx = db.Exec("INSERT INTO users (name) VALUES (?), (?)", "alice", "bob")
if tx.Error != nil {
	t.Fatalf("INSERT: %v", tx.Error)
}
if tx.RowsAffected != 2 {
	t.Errorf("RowsAffected = %d, want 2", tx.RowsAffected)
}

// Root instance stays clean: Exec never mutates the receiver.
if db.Error != nil || db.RowsAffected != 0 {
	t.Errorf("root mutated: Error=%v RowsAffected=%d", db.Error, db.RowsAffected)
}

Errors accumulate, they don't throw

When a step fails mid-chain, the error is recorded and the chain continues; the finisher returns it. AddError uses wrap-chain semantics:

// AddError records err on db's single error slot using wrap-chain
// semantics: the first error is kept as the wrap head so errors.Is
// continues to match it, and subsequent errors are appended with "; %w"
// so every cause stays branchable. Returns the full chain (nil when err
// is nil).
//
// When Config.TranslateError is set and the dialector implements
// ErrorTranslator, err is translated before being recorded.
func (db *DB) AddError(err error) error

The practical consequence: the first error stays branchable even when later steps pile on.

res := db.Model(&User{}).Where(42).Find(&users) // invalid condition
if errors.Is(res.Error, fusion.ErrInvalidValue) {
	// the original sentinel still matches
}

Every branchable condition is a sentinel — see /docs/api-reference/errors-reference.

What a session can do

Beyond chaining, *DB exposes the administrative surface:

  • db.Use(plugin) (fusion.go:315) — register a Plugin; the name must be unique or you get fusion.ErrRegistered. Initialize runs before the plugin is stored.
  • db.Callback() (callbacks.go:236) — the session's callback manager. Registration changes are shared by all derivatives of the session.
  • db.Parse(model) (fusion.go:344) — cached schema metadata for a model, using this session's naming strategy and tag strictness.
  • db.Migrator(opts...) (fusion.go:373) — a migration runner over the session's pool; it also invalidates prepared-statement caches before DDL.
  • db.QueryHook(hook) (query_hook.go:102) — append an observability QueryHook to the derivative's config (the root is untouched).

Next

On this page