Models

Schema declaration defines a table structure only. To map tables to Rust types, you have to add a module with models that will be used to convert records from the users table to native Rust types. Let's create one and call it models.rs. It will contain the following code:

use serde_derive::Serialize;
use super::schema::users;

#[derive(Debug, Serialize, Queryable)]
pub struct User {
pub id: String,
pub name: String,
pub email: String,
}

#[derive(Insertable)]
#[table_name = "users"]
pub struct NewUser<'a> {
pub id: &'a str,
pub name: &'a str,
pub email: &'a str,
}

We declared two models here: User to represent a user in a database and NewUser for creating a new record of a user. We derive the necessary traits for the User struct. The Queryable trait is implemented to allow you get this type from a database using queries.

There is the Insertable trait, which is derived from the NewUser struct. This trait allows a struct to be inserted as a new row in a table. This derivation requires an annotation with the name of the table. We can set it to the users table with the #[table_name = "users"] annotation.

The database structure has been prepared, and we can start to use the database from an application.

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

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