Skip to Content
fusion-orm

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

ModuleResponsibility
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.goStatement 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.goRow scanning through compiled scanners; handles struct (embedded + joined alias__column), slice, map, and scalar destinations.
logger/, migrator/, hook.go, prepared_stmt.goSupporting 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

  1. A chainable method calls getInstance() — fresh statement on a root or NewDB session, cloned statement mid-chain — and mutates Statement.Clauses.
  2. A finisher runs the processor's Execute(db): scopes are applied, BuildClauses renders the statement, the model is parsed and its reflect values resolved, then the compiled callback chain runs and the logger traces the statement.
  3. Callbacks build SQL: the clause registry renders each clause in BuildClauses order into a reused []byte; placeholders are bound as []any vars.
  4. resolveConn() hands the statement to the ConnPool (root pool, transaction, or prepared-statement cache) — QueryContext / ExecContext with context cancellation.
  5. Rows are scanned via per-field ScannerFuncs — no reflection per row — into Dest; hooks fire (AfterFind and friends); the error slot is updated.

State model

StateScopeOwner
Statement (clauses, model, dest, vars, settings)Per-chainOwned by the chain instance; never mutated across Session boundaries.
DB (Config, dialect, logger, callback processors, conn pool)SharedImmutable after Open, except through explicit plugin registration.
Schema cache (per-type *Table metadata)GlobalBuilt once, two-phase init for recursive relations, safe for concurrent reads.
Runtime (cancel registry, prepared-stmt LRU, migration lock rows)ProcessCancellation 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 CONFLICT vs INSERT IGNORE), with no parallel query-type hierarchy.
  • Precompiled field closures — Appender/Scanner are 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.Feature bitset (flags like Returning, OnConflict, Savepoint, CompositeIn) branches rendering; adding another dialect later is flags plus quotes.
  • Field-type clause injection for soft delete — the DeletedAt field participates through clause injection; callbacks never special-case it.
  • Single error slot with wrapping — AddError keeps the first error as wrap head; TranslateError maps driver constraint errors onto sentinels (ErrDuplicatedKey, ErrForeignKeyViolated).
  • pgx/v5 + modernc.org/sqlite — actively maintained, CGO-free drivers for PostgreSQL and SQLite.

Error handling

CaseBehavior
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 TranslateErrorErrDuplicatedKey / ErrForeignKeyViolated / ErrCheckConstraintViolated via dialector translation.
Unknown column/field at build timeBuild error naming model + field; never silently dropped.
Context cancel / timeoutError wrapped with action context; statement marked canceled in logs.
Hook errorFlows 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_DSN and 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/sql semantics: PostgreSQL RETURNING and SQLite LastInsertID backfill share one callback, gated by feature flags.
  • Composite-IN relation 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 AutoMigrate assumes 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 Dialector plus feature flags and quotes in a new dialect/<name>/ package; Open picks 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 AutoMigrate share the migrator interface; per-dialect inspectors plug in through feature flags.

Where next

On this page