Skip to Content
fusion-orm

Generics: G[T]

A compile-time-checked typed facade over the same query engine — same clauses, same callbacks, same SQL.

fusion.G[T] wraps a *DB chain in a typed facade: chain methods keep returning the facade, finishers return your type directly. It is sugar over the same engine — same clauses, same callbacks, same SQL as the reflection API — never a second engine.

Your first query

users := fusion.G[exampleUser](e.session)
exampleMust(users.Create(&exampleUser{Name: "Ada"}))
found, err := users.Where("name = ?", "Ada").Find()
fmt.Println(len(found), found[0].Name)
// Output: 1 Ada

G[T](db, opts...) derives a fresh session from the receiver — the original is never mutated — and applies any fusion.Option values to it (generics.go:71). The returned *Generic[T] is the facade.

Checked interfaces

The facade's surface is expressed as three interfaces, so code that accepts a generic handle can name exactly what it needs (generics.go:11, generics.go:33, generics.go:55):

// Interface is the complete checked generics surface.
type Interface[T any] interface {
	ChainInterface[T]
	ExecInterface[T]
}

The package asserts the concrete type satisfies it at compile time (generics.go:67):

var _ Interface[struct{}] = (*Generic[struct{}])(nil)

Chain methods

ChainInterface[T] mirrors the reflection API's chainables — each returns *Generic[T] (generics.go:11):

MethodNotes
Model(value any)Sets the model used to derive metadata.
Table(name string)Overrides the table name.
Select(columns ...string)Restricts selected columns.
Distinct()Adds DISTINCT.
Where(query any, args ...any)AND condition.
Or(query any, args ...any)OR condition.
Order(value string)Adds ORDER BY.
Limit(n int) / Offset(n int)Pagination.
Joins(query string, args ...any)Raw or relation join.
Preload(query string, args ...any)Batched relation load.
Scopes(funcs ...func(*DB) *DB)Query scopes.
Clauses(conds ...clause.Interface)Custom clause builders.
Unscoped()Disables soft-delete handling.
WithContext(ctx)Propagates the context.
WithResult(value T)Reuses a backing value — see below.
Session(config *Session) / Debug()Session controls.

Finishers

ExecInterface[T] turns finishers into typed returns — (T, error) for single rows, ([]T, error) for slices (generics.go:33):

MethodSignature
Create(*T) / Save(*T)error
Find(conds ...any)([]T, error)
First / Take / Last(conds ...any)(T, error)
Update(column string, value any) / Updates(values any)error
Delete(conds ...any)error
Count(*int64) / Pluck(string, any) / Scan(any)error
FindInBatches([]T, int, func(*Generic[T], int) error)error
FirstOrInit / FirstOrCreate(conds ...any)(T, error)
Row() / Rows()*sql.Row / (*sql.Rows, error)
ToSQL(func(*DB) *DB)string

There is no shared error slot on the facade: the error comes back as the value's second return, exactly where you'd expect it. First, Take, and Last still return ErrRecordNotFound when nothing matches (generics_test.go:66).

Group/Having

The generic facade does not expose Group/Having — the reflection API does not implement them as chainables either.

WithResult

First/Take/Last return a fresh zero T and scan into it. Pass WithResult(value) to reuse a backing value instead — the scanned row is copied into the value you supplied and returned (generics.go:155, generics_test.go:47):

withResult := fusion.G[genUser](db).WithResult(genUser{})
got, err := withResult.First(u.ID)

SQL parity

The facade adds zero behavior. A generic chain and its reflection-API equivalent render byte-identical SQL, and the package tests assert this with golden comparisons (generics_test.go:71):

func TestGenericsSQLParity(t *testing.T) {
	db := setupGenerics(t)
	reflection := db.ToSQL(func(tx *DB) *DB {
		var out []genUser
		return tx.Model(&genUser{}).Where("age > ?", 18).Order("id").Find(&out)
	})
	generic := G[genUser](db).Where("age > ?", 18).Order("id").ToSQL(func(tx *DB) *DB {
		var out []genUser
		return tx.Find(&out)
	})
	if reflection == "" || generic != reflection {
		t.Errorf("generic SQL = %q, reflection SQL = %q", generic, reflection)
	}
}

Because both APIs drive the same statement and callback pipeline, plugins, hooks, soft delete, and logging behave identically either way.

Which API when?

  • Reflection API (db.Model(&User{})...) — dynamic queries, columns chosen at runtime, code that builds statements programmatically.
  • G[T] — application code with a known model type: the compiler checks the chain, and results come back typed.

They interoperate freely: Scopes still accepts func(*DB) *DB, and ToSQL exposes the underlying *DB chain.

Next

On this page