Skip to content

Instantly share code, notes, and snippets.

@lholden
Created January 10, 2017 22:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lholden/a9126184923def301e2b7b436f2f65cb to your computer and use it in GitHub Desktop.
Save lholden/a9126184923def301e2b7b436f2f65cb to your computer and use it in GitHub Desktop.
use std::env;
use std::time::Duration;
use postgres::tls::openssl::OpenSsl;
use r2d2::{self, PooledConnection};
use r2d2_postgres::{TlsMode, PostgresConnectionManager};
use rocket::Request;
use rocket::request::{Outcome, FromRequest};
use rocket::Outcome::{Success, Failure};
use rocket::http::Status;
use error::Error;
lazy_static! {
static ref DB_POOL: r2d2::Pool<PostgresConnectionManager> = {
let database_url = env::var("DATABASE_URL").expect("Find DATABASE_URL environment variable");
let config = r2d2::Config::builder()
.pool_size(10)
.connection_timeout(Duration::from_secs(5))
.build();
let manager = PostgresConnectionManager::new(
database_url,
TlsMode::Prefer(Box::new(OpenSsl::new().unwrap()))
).unwrap();
r2d2::Pool::new(config, manager).expect("Create database pool")
};
}
pub struct DBConnection(PooledConnection<PostgresConnectionManager>);
impl DBConnection {
pub fn get(&self) -> &PooledConnection<PostgresConnectionManager> {
&self.0
}
}
impl<'a, 'r> FromRequest<'a, 'r> for DBConnection {
type Error = Error;
fn from_request(_: &'a Request<'r>) -> Outcome<Self, Self::Error> {
match DB_POOL.get() {
Ok(conn) => Success(DBConnection(conn)),
Err(e) => Failure((Status::InternalServerError, Error::from(e))),
}
}
}
/*
And then from a controller:
#[get("/")]
fn bla(conn: DBConnection) -> &'static str {
// conn.get().execute(blablabla)
...
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment