Skip to content

Instantly share code, notes, and snippets.

@timxor
Created July 19, 2018 05:59
Show Gist options
  • Save timxor/c912866e79098c175fd65b91f91e1f05 to your computer and use it in GitHub Desktop.
Save timxor/c912866e79098c175fd65b91f91e1f05 to your computer and use it in GitHub Desktop.
use diesel;
use diesel::prelude::*;
use diesel::PgConnection;
use schema::users;
#[derive(Queryable, Deserialize, Serialize)]
pub struct User {
pub id: Option<i32>,
pub first_name: String,
pub last_name: String,
pub user_name: String,
pub cell_number: String,
pub cell_verified: bool,
pub email: String,
pub public_key: String,
pub private_key: String,
pub eth_address: String
}
#[derive(Insertable, Deserialize, Serialize)]
#[table_name="users"]
pub struct NewUser<'a> {
pub id: Option<i32>,
pub first_name: &'a str,
pub last_name: &'a str,
pub user_name: &'a str,
pub cell_number: i32,
pub cell_verified: bool,
pub email: &'a str,
pub public_key: &'a str,
pub private_key: &'a str,
pub eth_address: &'a str
}
// this is called in main.rs create() function
impl User {
pub fn create(user: User, connection: &PgConnection) -> User {
diesel::insert_into(users::table)
.values(&user)
.execute(connection)
.expect("Error creating new user");
users::table.order(users::id.desc()).first(connection).unwrap()
}
pub fn read(connection: &PgConnection) -> Vec<User> {
users::table.order(users::id.asc())
.load::<User>(connection)
.unwrap()
}
pub fn update(id: i32, user: User, connection: &PgConnection) -> bool {
diesel::update(users::table.find(id)).set(&user).execute(connection).is_ok()
}
pub fn delete(id: i32, connection: &PgConnection) -> bool {
diesel::delete(users::table.find(id))
.execute(connection)
.is_ok()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment