Skip to Content
fusion-orm
Querying

Scopes

Reusable named query fragments, applied lazily at finisher time.

What a scope is

A scope is a plain function func(*DB) *DB — a reusable query fragment you can name, test, and compose. Scopes registers them on the statement; they run when a finisher executes, not when you call Scopes.

// Scopes applies chain functions lazily at finisher time (gorm-compatible).
func (db *DB) Scopes(funcs ...func(*DB) *DB) *DB {
	tx := db.getInstance()
	var all []func(*DB) *DB
	if prev, ok := tx.Statement.Get("fusion:scopes"); ok {
		all = append(all, prev.([]func(*DB) *DB)...)
	}
	all = append(all, funcs...)
	tx.Statement.Set("fusion:scopes", all)
	return tx
}

Scopes accumulate: calling Scopes twice keeps both sets, in order.

Define and use

The canonical example — a named "adults" filter:

adults := func(tx *DB) *DB { return tx.Where("age >= ?", 30) }
var users []crudUser
if err := db.Scopes(adults).Find(&users).Error; err != nil {
	t.Fatalf("Scopes Find: %v", err)
}
if len(users) != 2 {
	t.Errorf("adults = %d", len(users))
}

Inside a scope, tx is the in-flight chain — chain Where, Order, Select, anything, and return it. A scope is just a function, so it can take parameters:

func olderThan(age int) func(*DB) *DB {
	return func(tx *DB) *DB { return tx.Where("age > ?", age) }
}

db.Scopes(olderThan(30)).Find(&users)

Applied at finisher time

Scopes are stored as a statement setting (fusion:scopes) and applied by applyScopes when a finisher runs — Find, First, Take, Last, Row, Rows, and Scan all apply them:

func applyScopes(db *DB) {
	value, ok := db.Statement.Get("fusion:scopes")
	if !ok {
		return
	}
	for _, fn := range value.([]func(*DB) *DB) {
		if fn == nil {
			continue
		}
		next := fn(db)
		if next == nil {
			continue
		}
		if next != db {
			db.Statement = next.Statement
			// Scopes run on their own instance; carry their error back so
			// it reaches the finisher chain instead of being dropped
			// (GORM #6283 class). First error wins.
			if next.Error != nil && db.Error == nil {
				db.Error = next.Error
			}
		}
	}
}

Two consequences:

  • Lazy — registering a scope on a chain you never finish costs nothing.
  • Ordered — scopes run in registration order, after any conditions you chained directly.

Scope errors reach the finisher

An invalid condition raised inside a scope is not dropped — it is carried back onto the finisher chain (GORM #6283 class):

func TestAuditScopeErrorsPropagate(t *testing.T) {
	db := setupSoftDelete(t)
	var out []softUser
	res := db.Model(&softUser{}).
		Scopes(func(d *DB) *DB { return d.Where(42) }). // invalid condition inside scope
		Find(&out)
	if res.Error == nil {
		t.Error("error raised inside a scope was dropped by applyScopes (GORM #6283 class)")
	}
}

Composing scopes

Scopes compose by accumulation — pass several, or call Scopes twice:

active := func(tx *DB) *DB { return tx.Where("active = ?", true) }
recent := func(tx *DB) *DB { return tx.Order("created_at DESC").Limit(10) }

db.Model(&crudUser{}).Scopes(active, recent).Find(&users)

Each scope sees the statement as shaped by the previous one, so a scope may also consume what an earlier scope produced.

Scopes and Preload apply functions

Preload accepts the same function type as an argument — an apply function shapes the query used to load the relation:

// Preload requests a relation (or nested dotted path) to be loaded in one
// batched query after the main query. Args may be a func(*DB) *DB apply
// function, a SQL condition with args, or primary-key values.
db.Preload("Posts", func(tx *DB) *DB {
	return tx.Order("created_at DESC").Limit(5)
}).Find(&users)

The mechanics are shared: both are func(*DB) *DB fragments applied before execution. The difference is scope — Scopes shapes the main query, a Preload apply function shapes one relation's batched query. See Preload for the relation machinery.

Next

On this page