Pagination
Three pagination strategies — offset, keyset via FindInBatches, and a hand-rolled cursor — with trade-offs and golden SQL.
fusion-orm gives you three ways to page through a table. They differ in how they behave when rows are inserted mid-scroll, how expensive page N is, and whether they can order by more than one column. Pick by access pattern, not by habit.
Offset: LIMIT + OFFSET
The chainables compose naturally — offset pagination is Limit and
Offset on an ordered query:
fn := func(tx *DB) *DB {
return tx.Model(&crudUser{}).Where("age > ?", 18).Order("id DESC").Limit(5).Find(&[]crudUser{})
}
first := db.ToSQL(fn)
second := db.ToSQL(fn)
want := `SELECT * FROM "crud_users" WHERE age > 18 ORDER BY id DESC LIMIT 5`SELECT * FROM "crud_users" WHERE age > 18 ORDER BY id DESC LIMIT 5This is the test suite's stability golden (crud_test.go:297): the test
also asserts first == second, because ToSQL is byte-identical across
calls — what keeps the prepared-statement cache effective for page links.
Both values bind as variables, not literals — LIMIT ? / OFFSET ? on
SQLite, LIMIT $1 / OFFSET $2 on PostgreSQL (clause/query.go:129,
clause/query.go:146). A page link is then just arithmetic:
page, per := 4, 20
db.Model(&User{}).Order("id DESC").Limit(per).Offset((page - 1) * per).Find(&users)Trade-offs. The database must still produce and discard all
OFFSET rows, so page cost grows linearly with depth — page 10,000 on a
20-row page scans 200,000 rows. And under concurrent inserts or deletes,
rows shift between pages: a user can see the same row twice, or miss one.
Fine for admin tables and dashboards; wrong for feeds and exports.
Keyset: FindInBatches
FindInBatches queries in primary-key order and calls your callback once
per batch (finisher_api.go:378). Mechanically it is keyset pagination:
each batch appends WHERE pk > last, ORDER BY pk ASC, LIMIT batch
(finisher_api.go:428), so it walks the index — no skipped or repeated rows,
no deep-scan cost.
var seen []string
result := db.FindInBatches(&[]crudUser{}, 2, func(tx *DB, batch int) error {
var rows []crudUser
if err := tx.Find(&rows).Error; err != nil {
return err
}
for _, row := range rows {
seen = append(seen, row.Name)
}
return nil
})The batch tx is a normal chain: inside the callback, the rows of the
current batch are re-queried with Find, or you can act on them and let
an error abort the walk. Each batch runs its own statement, so memory stays
bounded no matter how large the table is.
Composite primary keys
For a model with a composite primary key, the cursor is a row-value
comparison — (a, b) > (?, ?) walks the tuple order without skipping or
repeating rows across batch boundaries (finisher_api.go:426). This variant
is gated on the RowValues feature flag; both in-tree dialects declare it
(dialect/sqlite/sqlite.go:53, dialect/postgres/postgres.go:57):
if err := db.FindInBatches(&[]cpkRow{}, 3, func(tx *DB, batch int) error {
pages++
var rows []cpkRow
if err := tx.Find(&rows).Error; err != nil {
return err
}
got = append(got, rows...)
return nil
}).Error; err != nil {
t.Fatal(err)
}The test asserts every row is visited exactly once, in tuple order
(composite_pk_test.go:149). A dialect without RowValues fails the call
with ErrUnsupportedFeature naming the flag (finisher_api.go:395).
FindInBatches walks the whole table
FindInBatches is a batch processor: one call consumes every row,
batch by batch. Its keyset mechanics are exactly what cursor pagination
needs, but for "page 3 of the feed" APIs where the client asks for one
page at a time, hand-roll the cursor — next section.
A single batch's SQL — the statement the loop in finisher_api.go:428-434 builds after the first batch:
sql := db.ToSQL(func(tx *DB) *DB {
return tx.Model(&crudUser{}).Where("id > ?", 2).Order("id ASC").Limit(2).Find(&[]crudUser{})
})SELECT * FROM "crud_users" WHERE id > 2 ORDER BY id ASC LIMIT 2Hand-rolled cursor: WHERE id > lastID
When the client pulls one page per request, keep the last ID as the cursor
and hand it back with the page. Every piece is a verified chainable —
Where, Order, Limit, Find (chainable_api.go:144, chainable_api.go:233,
chainable_api.go:242, finisher_api.go:81):
func listAfter(db *fusion.DB, lastID int64, limit int) ([]User, int64, error) {
var page []User
tx := db.Model(&User{}).
Where("id > ?", lastID).
Order("id").
Limit(limit).
Find(&page)
if tx.Error != nil {
return nil, 0, tx.Error
}
if len(page) == 0 {
return nil, 0, nil
}
// next cursor: the last row's ID; empty page means end of stream
return page, page[len(page)-1].ID, nil
}Find on an exhausted stream returns an empty slice and a nil error — no
ErrRecordNotFound to special-case. Encoding the cursor is up to you
(base64 of the ID, or an opaque token that maps back to one). The same
shape generalizes to any unique, ordered column — created_at plus id
as a tiebreaker keeps the order stable when timestamps repeat:
tx := db.Model(&User{}).
Where("created_at > ? OR (created_at = ? AND id > ?)", lastAt, lastAt, lastID).
Order("created_at, id").
Limit(limit).
Find(&page)Order is additive (chainable_api.go:238), so both columns land in one
ORDER BY. Note this two-column variant is hand-written here because
FindInBatches orders by the primary key; a timestamp cursor must include
the tiebreaker yourself.
Choosing
| Offset | FindInBatches | Hand-rolled cursor | |
|---|---|---|---|
| Consistent under concurrent inserts/deletes | No — rows shift between pages | Yes — index walk | Yes — index walk |
| Cost at deep pages | Grows with OFFSET depth | Constant per batch | Constant per page |
| Composite keys | N/A | Yes, via row values (RowValues feature) | Yes, if you write the tuple predicate |
| Random page access | Yes (?page=N) | No — sequential walk | No — sequential walk |
| Total page count for UI | Yes, via Count | No | No |
Guidance:
- Admin tables, search results, anything with "jump to page N" — offset. Deep-page cost is acceptable when nobody scrolls to page 10,000.
- Exports, migrations, backfills, batch jobs —
FindInBatches. It is the only strategy that processes the entire table in bounded memory with composite-key support built in. - Feeds, timelines, infinite scroll — hand-rolled cursor. Stable under writes, constant cost, and the client holds an opaque cursor instead of a page number.
Cursor + soft delete
A cursor over id is immune to inserts, but soft-deleted rows vanish
mid-stream just like offset pages. If rows are deleted while a client
scrolls, the cursor still moves forward correctly — the next row with
id > last is simply the next live one.