Chaining & copy-on-write
Every chainable method returns a derivative *DB; the receiver is never mutated.
The contract
Every chainable method — Model, Where, Order, Preload, Session,
WithContext, Debug — returns a derivative *DB. The receiver is
never mutated. This is what makes a root *DB safe for concurrent use:
goroutines chain off the same root without stepping on each other.
// 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.Mechanically, each chainable calls getInstance(), which clones the
per-chain Statement before mutating it. The shared parts — Config,
dialect, logger, callback processors, connection pool — are immutable after
Open (except through explicit plugin registration).
What travels on the chain
A derivative carries:
Statement— clauses, model, dest, vars, settings. Owned by the chain.Error/RowsAffected— set by the last finisher on this chain.- Session config —
DryRun, logger, context, hooks (fromSession).
It does not carry: schema cache, callback processors, or the connection pool — those live on the shared root and are read-only.
Errors accumulate, they don't throw
There are no panics for user errors. A finisher records the first error in
the chain's single error slot and keeps the wrap head, so errors.Is
continues to match the original sentinel.
// 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.res := db.Model(&User{}).Where(42).Find(&users) // invalid condition
if res.Error != nil {
// errors.Is(res.Error, fusion.ErrInvalidValue) == true
}Seeing the SQL
Two escape hatches keep the chain honest:
ToSQL— render a chain to a string with vars interpolated and escaped for display.DryRun— capture SQL and vars onStatementwithout executing.
tx := db.Session(&Session{DryRun: true}).Exec("SELECT * FROM users WHERE id = ?", 7)
// tx.Statement.SQL == "SELECT * FROM users WHERE id = ?"
// tx.Statement.Vars == []any{7}
// the root config is untouched: db.Config.DryRun == falseSettings are per-chain
Session, WithContext, and Debug clone the config onto the derivative.
The root *DB never changes — DryRun on a session does not leak back.