Go Gorm Scopes
In this tutorial, you'll learn about GORM Scopes: Query Reuse. We cover key concepts, practical examples, and best practices.
GORM query scopes -- Create reusable query filters to avoid duplicating common WHERE conditions across your codebase.
The Problem
Without scopes, common filters like "active records" are repeated everywhere. GORM scopes are functions returning func(*gorm.DB) *gorm.DB.
Wrong
db.Where("deleted_at IS NULL").Where("status = ?", "active").Find(&users)
db.Where("deleted_at IS NULL").Where("status = ?", "active").First(&user, id)
Output:
// Same condition duplicated everywhere
Right
func Active(db *gorm.DB) *gorm.DB {
return db.Where("status = ?", "active")
}
db.Scopes(Active, WithoutDeleted).Find(&users)
db.Scopes(Active, WithoutDeleted).First(&user, id)
Output:
// Consistent, reusable filters
Prevention
- Define scopes as func(*gorm.DB) *gorm.DB
- Chain multiple scopes: db.Scopes(Scope1, Scope2)
- Use closures for parameterized scopes
- Combine with Preload, Joins
- Work on any query: Find, First, Count, Delete
Common Mistakes with gorm scopes
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro