Last active
August 1, 2018 07:28
-
-
Save Gurpartap/2b555113a41b15bd22b07a8a0573d076 to your computer and use it in GitHub Desktop.
diesel example w/ r2d2 pool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use diesel::prelude::*; | |
use diesel::r2d2::{ConnectionManager, Pool}; | |
use diesel::result::Error as DieselError; | |
use models::User; | |
use schema::users; | |
pub fn establish_connection(database_url: String) -> Pool<ConnectionManager<PgConnection>> { | |
let manager = ConnectionManager::<PgConnection>::new(database_url); | |
Pool::builder() | |
.max_size(5) | |
.build(manager) | |
.expect("database connection pool") | |
} | |
pub fn get_user(conn: &PgConnection, id: i64) -> Result<Account, DieselError> { | |
users::table | |
.filter(users::id.eq(&id)) | |
.first::<User>(conn) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use chrono::prelude::*; | |
use pb::pbservice as pb; | |
use prost_types; | |
use schema::users; | |
use std::time; | |
#[derive(Debug, Identifiable, Queryable)] | |
#[table_name = "users"] | |
pub struct User { | |
pub id: i64, | |
pub created_at: Option<DateTime<Utc>>, | |
pub updated_at: Option<DateTime<Utc>>, | |
pub username: String, | |
pub country: Option<String>, | |
} | |
impl From<User> for pb::User { | |
fn from(user: User) -> Self { | |
pb::User { | |
id: user.id, | |
created_at: user.created_at | |
.map(|t| time::SystemTime::from(t)) | |
.map(|t| prost_types::Timestamp::from(t)), | |
updated_at: user.updated_at | |
.map(|t| time::SystemTime::from(t)) | |
.map(|t| prost_types::Timestamp::from(t)), | |
username: user.username, | |
country: user.country, | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
table! { | |
users (id) { | |
id -> Int8, | |
created_at -> Nullable<Timestamptz>, | |
updated_at -> Nullable<Timestamptz>, | |
username -> Varchar, | |
country -> Nullable<Varchar>, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment