Composing queries
Builder methods return a new query, so one query can be the base for others.
Reuse a query
adults := db.Users.Where(ant.Gt(&Users.Age, 18)).OrderBy(&Users.Name)
alice, err := adults.Where(ant.Eq(&Users.Name, "Alice")).All(ctx)
// SELECT ... FROM "users" WHERE "users"."age" > $1 AND "users"."name" = $2 ORDER BY "users"."name"
carol, err := adults.Where(ant.Eq(&Users.Name, "Carol")).All(ctx)
// adults is unchanged, and can run again.
everyone, err := adults.All(ctx)
// SELECT ... FROM "users" WHERE "users"."age" > $1 ORDER BY "users"."name"
Add parts only when needed
When applies a function to the query only if its condition is true.
func search(ctx context.Context, name string, adultsOnly bool) ([]*User, error) {
return db.Users.
OrderBy(&Users.Name).
When(name != "", func(q *ant.Query[User]) *ant.Query[User] {
return q.Where(ant.Eq(&Users.Name, name))
}).
When(adultsOnly, func(q *ant.Query[User]) *ant.Query[User] {
return q.Where(ant.Gte(&Users.Age, 18))
}).
All(ctx)
}
With no name and adultsOnly false, the query has no conditions. With both set:
users, err := search(ctx, "Bob", true)
// SELECT ... FROM "users" WHERE "users"."name" = $1 AND "users"."age" >= $2 ORDER BY "users"."name"
Name a reusable piece with a scope
A scope is a function from a query to a query. Scope takes any number of them.
func Adults(q *ant.Query[User]) *ant.Query[User] {
return q.Where(ant.Gte(&Users.Age, 18))
}
func OlderFirst(q *ant.Query[User]) *ant.Query[User] {
return q.OrderByDesc(&Users.Age)
}
users, err := db.Users.Scope(Adults, OlderFirst).All(ctx)
// SELECT ... FROM "users" WHERE "users"."age" >= $1 ORDER BY "users"."age" DESC
For a scope with parameters, write a function that returns one:
func OlderThan(age int) func(*ant.Query[User]) *ant.Query[User] {
return func(q *ant.Query[User]) *ant.Query[User] {
return q.Where(ant.Gt(&Users.Age, age))
}
}
users, err := db.Users.Scope(OlderThan(30)).All(ctx)
// SELECT ... FROM "users" WHERE "users"."age" > $1
Scopes apply only where you call them. For a condition on every query of a model, use a global filter.
See it tested: tests/features/querying/when_test.go