macro_rules! query { ($db:expr, ($( $($model:ident)::+.$($field:ident).+ $(($($args:tt)?))? $(as $patch:ty)? ),+$(,)?)) => { ... }; ($db:expr, $patch:ty) => { ... }; }
Expand description
Create a SELECT query.
-
Give a reference to your db and the patch to query. If you just need a few fields and don’t want to create a patch for it, you can specify these fields directly as a tuple as well.
query!(&db, MyModelType)
query!(&db, (MyModelType::F.some_field, MyModelType::F.another_field, ))
-
Set a condition which rows to query.
.condition(MyModelType::F.some_field.equals("some_value"))
-
Optionally add a limit or offset to restrict your query size.
.limit(5)
.offset(2)
.range(2..7)
-
Finally specify how to get the queries results. This will also execute the query.
-
Get
all
matching rows in a vector..all().await
-
Get all matching rows in an async
stream
..stream()
-
Just get exactly
one
row..one().await
-
Get one row if any. (
optional
).optional().await
Each of these methods decodes the database’s rows into the patch you specified in step 1. If you want to work with raw rows, each of the methods in step 4 has a
*_as_row
twin. -
Example:
pub async fn shame_users(db: &Database) {
for (id, password) in query!(db, (User::F.id, User::F.password)).all().await.unwrap() {
if password == "password" {
let user = query!(db, User)
.condition(User::F.id.equals(id))
.one()
.await
.unwrap();
shame_user(&user).await;
}
}
}