Scopes and scoped models
A scope is a named query on a model: “the open loans”, “the stations of
a region”, “the reservations a user made”. In Django you would write a
method on a custom manager or a queryset, Loan.objects.open(). In rind
it is a plain function on the model that returns a Query.
This page shows how to write scopes, how to combine them, and what a scoped model is: a model that has no default query at all.
A first scope
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-models/src/lib.rs
impl Reservation {
/// The reservations a user made.
pub fn made_by(user: &Identity) -> Query<Reservation> {
Query::new().filter(Reservation::booked_by_id().eq(user.id))
}
}
}
There is nothing special about it: an associated function, in the model’s crate, that builds a query. It does not run anything. The caller runs it, or narrows it further:
#![allow(unused)]
fn main() {
// every reservation of the user
let all = db.all(&Reservation::made_by(&user)).await?;
// only the booked ones, newest first
let booked = Reservation::made_by(&user)
.filter(Reservation::status().eq("booked"))
.order_by([Reservation::created().desc()]);
let page = db.all(&booked.limit(20)).await?;
}
A Query is a value: filtering it gives a new query, and the scope
itself is not changed.
Why scopes are worth writing
- They have a name.
Loan::open()says what it means; a filter onreturned_on IS NULLrepeated in ten places does not, and one of the ten will be wrong. - They are tested without HTTP. A scope is a function: a test builds a few rows, runs the scope and checks what comes back.
- The API uses them. A permission mode is a
scope:
#[mode(LoanMode::Own, query = Loan::of(user))]. So is a filter’s method, and a nested field’s query. - They live with the model. Every crate that uses the model gets the same definition.
Scopes with parameters
A scope takes what it needs as arguments: a user, an id, a date.
#![allow(unused)]
fn main() {
impl Station {
/// The stations of a region, or of any region inside it.
pub fn in_region(region: i64) -> Query<Station> {
Query::new().filter(Station::region_id().in_sub(Region::subtree(region)))
}
/// The stations opened on or before a day.
pub fn opened_by(day: NaiveDate) -> Query<Station> {
Query::new().filter(Station::opened().le(day))
}
}
}
Combining scopes
A scope returns a Query, and a query takes more filters, but two
queries cannot be merged into one. To combine scopes, write the
conditions as functions too, and build the queries from them:
#![allow(unused)]
fn main() {
impl Loan {
/// Not given back yet.
pub fn is_out() -> Cond {
Loan::returned_on().is_null()
}
/// The loans not given back yet.
pub fn out() -> Query<Loan> {
Query::new().filter(Loan::is_out())
}
/// A user's loans not given back yet.
pub fn out_for(user: &Identity) -> Query<Loan> {
Loan::of(user).filter(Loan::is_out())
}
}
}
A Cond (a condition) combines with & (and), | (or) and ! (not),
like Django’s Q objects: see Queries.
Scoped models
Some tables hold rows that most code must not read: drafts, rows waiting for a validation, rejected imports, soft-deleted rows. In Django you give the model a default manager that filters them out:
class Loan(models.Model):
objects = OpenLoanManager() # hides the returned loans
all_objects = models.Manager()
and you hope nobody uses Loan._base_manager, a related manager, or the
admin, which do not use your default manager.
In rind, you mark the model scoped. It then has no default query:
#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Model)]
#[model(table = "library_loan", scoped)]
pub struct Loan {
pub id: i64,
pub returned: bool,
// …
}
impl Loan {
/// The loans not returned yet.
pub fn open() -> Query<Loan> {
Query::all().filter(Loan::returned().eq(false))
}
}
}
Query::<Loan>::new(), which reads every row of an ordinary model, does
not compile for a scoped one:
error[E0277]: `Loan` is a scoped model: it has no default query
|
| Query::<Loan>::new()
| ^^^^^^^^^^^^^^^^^^^^ use one of the scopes `Loan` defines, or `Query::all()` for every row
Every use of the model must say what it reads:
- one of its scopes,
Loan::open(); - or
Query::all(), when it really means every row: a report, a migration of data, an admin tool.all()is easy to find in a review.
Scopes of a scoped model start from Query::all(), since Query::new()
is not available to them either.
Coming from Django: a default manager filters silently, and is bypassed silently. A scoped model never filters by itself: every query names its scope in the code, so a reader sees what is read, and a forgotten filter is a compile error.
Where the compiler stops, and where it does not
scoped protects the queries that start from the model. A query that
reaches the model through a relation (Book::loans().any(..)) or a
nested field of a serializer also reads its rows. Give those a query too:
a nested field of a scoped model needs query = Loan::open(), and the
derive refuses it otherwise (Serializers).
Scopes and the API
The rows a resource works on are a scope as well, given in one of two places:
#[resource(.., query = Loan::open())]makes every request of the resource start from a scope: Django’s viewsetqueryset =;- or, when the resource has permission modes,
each mode gives its own:
#[mode(.., query = Reservation::made_by(user))]. The two are exclusive: with modes, a resource’squeryis refused, and each mode must have one.
Without either, the resource reads Query::new(), every row; for a
scoped model that does not compile, so its resource must say which rows
it serves. A query that uses user matches no row for an anonymous
request.
Next: Sharing fields.