GORM Keyset Pagination PostgreSQL
Paginate PostgreSQL result sets with GORM using keyset conditions on indexed sort columns, stable under concurrent inserts.
Code
// PostgreSQL keyset pagination with gorm
package main
import (
"fmt"
"log"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type Invoice struct {
ID uint `gorm:"primaryKey"`
Customer string `gorm:"index:idx_customer_created,priority:1"`
CreatedAt int64 `gorm:"index:idx_customer_created,priority:2;autoCreateTime:false"`
Amount int
}
type Page struct {
Items []Invoice
NextID uint
NextAt int64
HasNext bool
}
func keysetPage(db *gorm.DB, customer string, limit int,
afterID uint, afterAt int64,
) (Page, error) {
query := db.Where("customer = ?", customer).
Order("created_at DESC, id DESC")
if afterID != 0 {
// 复合键条件:严格晚于锚点 (created_at, id)
query = query.Where(
"(created_at < ?) OR (created_at = ? AND id < ?)",
afterAt, afterAt, afterID,
)
}
rows := make([]Invoice, 0, limit+1)
if err := query.Limit(limit + 1).Find(&rows).Error; err != nil {
return Page{}, fmt.Errorf("keyset query: %w", err)
}
hasNext := len(rows) > limit
if hasNext {
rows = rows[:limit]
}
page := Page{Items: rows, HasNext: hasNext}
if len(rows) > 0 {
last := rows[len(rows)-1]
page.NextID = last.ID
page.NextAt = last.CreatedAt
}
return page, nil
}
func main() {
db, err := gorm.Open(postgres.Open(
"host=localhost user=app dbname=billing"),
&gorm.Config{Logger: logger.Discard},
)
if err != nil {
log.Fatal(err)
}
page, err := keysetPage(db, "acme", 20, 0, 0)
if err != nil {
log.Fatal(err)
}
next, err := keysetPage(db, "acme", 20, page.NextID, page.NextAt)
fmt.Println(len(page.Items), page.HasNext, len(next.Items), next.HasNext, err)
}Inside the snippet
The working surface is the functions keysetPage and main — everything else is wiring.
Every fallible call checks err != nil (3 sites), so an error is handled where it happens rather than bubbling invisibly.
What to watch for
gorm.io/driver/postgres,gorm.io/gormandgorm.io/gorm/loggermust be installed first — the snippet imports them directly.- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Using it
The main signature reads func keysetPage(db *gorm.DB, customer string, limit int, afterID uint, afterAt int64, ) (Page, error)
main sequences keysetPage; executing the file runs that flow once.
Key statements
return Page{}, fmt.Errorf("keyset query: %w", err)
if err != nil {
log.Fatal(err)
}
rows := make([]Invoice, 0, limit+1)
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- How do errors reach the caller?
- By return value: each fallible call hands back an `error`, checked at 3 places here.
- Are there third-party dependencies?
- `gorm.io/driver/postgres`, `gorm.io/gorm` and `gorm.io/gorm/logger` — install them with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.