Architecture
How fusion-orm is layered — from the byte-slice clause core to the session/callback API — and the decisions behind it.
fusion-orm is a Go library with a strict layer split: a high-performance
dialect/clause core (bun's engine model), a reflection-cached schema layer,
and a gorm-style session/callback API on top. The core never knows about
chaining; the API layer never assembles SQL directly. SQL is built as
[]byte through per-dialect appenders and executed through database/sql
(or the prepared-statement cache wrapper).
System overview
[user code] → [chainable_api / finisher_api / generics G[T]]
↓ getInstance() (copy-on-write)
[Statement + clause registry]
↓ finisher triggers
[callback processor: create|query|update|delete|row|raw]
↓ ordered callbacks
[clause/ builders] → []byte via [dialect appenders]
↓ resolveConn()
[ConnPool | PreparedStmtDB cache] → database/sql
↑ scan via compiled ScannerFuncs
[schema layer: cached tables/fields/relations]Module responsibilities
| Module | Responsibility |
|---|---|
dialect/ | The Dialector interface (Initialize, DataTypeOf, BindVarTo, QuoteTo, ErrorTranslator) plus feature bitflags; owns identifier quoting; DSN-free — drivers are supplied by the caller. Must not import schema types beyond field metadata. |
schema/ | Cached per-type reflection (tables, fields, relations, hooks); owns tag parsing, naming, and precompiled Appender/Scanner/IsZero closures. Must not import DB, statement, or callback types. |
clause/ | Pure SQL clause builders: func(b []byte) []byte appends with vars bound through the statement. No I/O, no schema imports. |
statement.go + fusion.go | Statement assembly, clause registry, session/config/clone semantics; owns the single error slot. |
callbacks/ | The only place that knows CRUD order; each callback is a func(*DB); drivers and plugins may register or replace. |
scan.go | Row scanning through compiled scanners; handles struct (embedded + joined alias__column), slice, map, and scalar destinations. |
logger/, migrator/, hook.go, prepared_stmt.go | Supporting pieces; never imported by clause/ or schema/ internals. |
Nothing outside dialect/ may contain dialect-specific strings.
At the top level, the root package is organized as: fusion.go (config,
DB, Open, sessions), chainable_api.go and finisher_api.go (the
public chain and finishers), statement.go (clause registry, byte
builder), callbacks.go (processor manager), generics.go (G[T]),
soft_delete.go, errors.go (sentinels + translation), scan.go,
association.go, hook.go, prepared_stmt.go — with schema/,
clause/, dialect/ (containing sqlite/ and postgres/), logger/,
migrator/, and callbacks/ as subpackages.
Data flow
- A chainable method calls
getInstance()— fresh statement on a root orNewDBsession, cloned statement mid-chain — and mutatesStatement.Clauses. - A finisher runs the processor's
Execute(db): scopes are applied,BuildClausesrenders the statement, the model is parsed and its reflect values resolved, then the compiled callback chain runs and the logger traces the statement. - Callbacks build SQL: the clause registry renders each clause in
BuildClausesorder into a reused[]byte; placeholders are bound as[]anyvars. resolveConn()hands the statement to theConnPool(root pool, transaction, or prepared-statement cache) —QueryContext/ExecContextwith context cancellation.- Rows are scanned via per-field
ScannerFuncs — no reflection per row — intoDest; hooks fire (AfterFindand friends); the error slot is updated.
State model
| State | Scope | Owner |
|---|---|---|
Statement (clauses, model, dest, vars, settings) | Per-chain | Owned by the chain instance; never mutated across Session boundaries. |
DB (Config, dialect, logger, callback processors, conn pool) | Shared | Immutable after Open, except through explicit plugin registration. |
Schema cache (per-type *Table metadata) | Global | Built once, two-phase init for recursive relations, safe for concurrent reads. |
| Runtime (cancel registry, prepared-stmt LRU, migration lock rows) | Process | Cancellation flows only via context.Context. |
Key decisions
- Callback pipeline over direct builders — chaining accumulates clauses; finishers trigger processors. This gets bun's zero-alloc build path with gorm's extensibility: plugins register callbacks, not forks.
- Clause registry, not bun-style query structs — one statement
representation, and dialect feature flags decide rendering (e.g.
ON CONFLICTvsINSERT IGNORE), with no parallel query-type hierarchy. - Precompiled field closures —
Appender/Scannerare resolved once at table init; the scanning and build hot paths are type-dispatched function pointers, not per-row reflection. - Feature bitflags over per-dialect forks — a
dialect.Featurebitset (flags likeReturning,OnConflict,Savepoint,CompositeIn) branches rendering; adding another dialect later is flags plus quotes. - Field-type clause injection for soft delete — the
DeletedAtfield participates through clause injection; callbacks never special-case it. - Single error slot with wrapping —
AddErrorkeeps the first error as wrap head;TranslateErrormaps driver constraint errors onto sentinels (ErrDuplicatedKey,ErrForeignKeyViolated). - pgx/v5 + modernc.org/sqlite — actively maintained, CGO-free drivers for PostgreSQL and SQLite.
Error handling
| Case | Behavior |
|---|---|
No-WHERE Update/Delete (global) | ErrMissingWhereClause; explicit AllowGlobalUpdate or a Where/WherePK is required. |
Record not found (First/Take/Last) | ErrRecordNotFound; Find returns an empty slice instead. |
Constraint violation with TranslateError | ErrDuplicatedKey / ErrForeignKeyViolated / ErrCheckConstraintViolated via dialector translation. |
| Unknown column/field at build time | Build error naming model + field; never silently dropped. |
| Context cancel / timeout | Error wrapped with action context; statement marked canceled in logs. |
| Hook error | Flows into the error slot; the operation aborts at that callback. |
Errors are wrapped with %w — never swallowed or only logged. See
Error handling for the caller-facing contract.
Testing strategy
- Unit — tag parsing, naming strategy, clause rendering per dialect (golden SQL strings), scanner/append round-trips, guard semantics (no-WHERE blocked), statement clone isolation.
- Integration — full CRUD, relations, soft delete, and migration
round-trips against real SQLite temp files, no daemons; the PostgreSQL
suite is env-gated behind
FUSION_TEST_PG_DSNand skips cleanly when unset. - Benchmarks — batch inserts and large scans, with allocation-count tests that enforce zero per-row reflection.
Required checks: go test ./... and go vet ./....
Constraints and limits
database/sqlsemantics: PostgreSQLRETURNINGand SQLiteLastInsertIDbackfill share one callback, gated by feature flags.- Composite-
INrelation loading falls back to OR-equation batches where a dialect lacks it (feature.CompositeIn). - The prepared-statement cache purges on
driver.ErrBadConn; it is LRU bounded with an optional TTL. - Metadata/diff-based
AutoMigrateassumes single-writer DDL; destructive diffs (drop column) require explicit operations. - Oracle-style quirks (uppercasing,
ROWNUM) are out of scope until an Oracle dialect is declared.
Extension points
- New dialect — implement
Dialectorplus feature flags and quotes in a newdialect/<name>/package;Openpicks it up, no core changes. - New callback behavior — register against the default chains via
db.Callback().Create().Before("fusion:create", ...); the default chains remain replaceable. - Observability plugins — implement
QueryHook(an slog hook ships in-tree); otel-style plugins need no core changes. - Custom serializers / field types — implement the clause interfaces on field types, the way soft delete does.
- Migrations — versioned migrations and
AutoMigrateshare the migrator interface; per-dialect inspectors plug in through feature flags.