Listing users subcommand implementation

In the previous example of data insertion, we didn't use the generated users type, and used the table nested type only. To list users in the implementation of the list subcommand, we will use types from the dsl submodule.

If you build some documentation and look into the users::schema::users::dsl module, you will see the following items:

pub use super::columns::id;
pub use super::columns::name;
pub use super::columns::email;
pub use super::table as users;

All types are quite complex, and you can see all the features in the documentation. Since the users table type implements the AsQuery trait, we can use the load method of the RunQueryDsl trait for the users type. We set the associated type to model::Users to extract this type from the table. We also don't need any manual extractions like we did in the previous chapter. The load method expects a Connection that we get from a Pool instance:

(CMD_LIST, _) => {
use self::schema::users::dsl::*;
let conn = pool.get()?;
let mut items = users
.load::<models::User>(&conn)?;
for user in items {
println!("{:?}", user);
}
}

Now, we can simply iterate over the users collections. That's pretty simple.

If you want to construct more complex requests, you can use other DSL functions that are generated by the diesel crate during building. For example, you can filter users by domain name and limit the quantity of users in a list with the following DSL expression:

let mut items = users
.filter(email.like("%@example.com"))
.limit(10)
.load::<models::User>(&conn)?;

We have filtered all users by the example.com domain using the filter method with a parameter created by the like method call of the email column.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.93.175