2018-05-19 07:39:59 +00:00
|
|
|
use diesel::{
|
|
|
|
pg::PgConnection,
|
2018-06-23 16:36:11 +00:00
|
|
|
r2d2::{ConnectionManager, Pool, PooledConnection}
|
2018-05-19 07:39:59 +00:00
|
|
|
};
|
|
|
|
use rocket::{Request, State, Outcome, http::Status, request::{self, FromRequest}};
|
2018-04-24 09:21:39 +00:00
|
|
|
use std::ops::Deref;
|
2018-04-22 13:35:37 +00:00
|
|
|
|
2018-06-23 16:36:11 +00:00
|
|
|
pub type PgPool = Pool<ConnectionManager<PgConnection>>;
|
2018-06-20 18:22:34 +00:00
|
|
|
|
2018-04-22 13:35:37 +00:00
|
|
|
// From rocket documentation
|
|
|
|
|
|
|
|
// Connection request guard type: a wrapper around an r2d2 pooled connection.
|
|
|
|
pub struct DbConn(pub PooledConnection<ConnectionManager<PgConnection>>);
|
|
|
|
|
|
|
|
/// Attempts to retrieve a single connection from the managed database pool. If
|
|
|
|
/// no pool is currently managed, fails with an `InternalServerError` status. If
|
|
|
|
/// no connections are available, fails with a `ServiceUnavailable` status.
|
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
|
|
|
|
type Error = ();
|
|
|
|
|
|
|
|
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
2018-06-20 18:22:34 +00:00
|
|
|
let pool = request.guard::<State<PgPool>>()?;
|
2018-04-22 13:35:37 +00:00
|
|
|
match pool.get() {
|
|
|
|
Ok(conn) => Outcome::Success(DbConn(conn)),
|
|
|
|
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// For the convenience of using an &DbConn as an &PgConnection.
|
|
|
|
impl Deref for DbConn {
|
|
|
|
type Target = PgConnection;
|
|
|
|
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
}
|