Rocket/examples/todo/src/db.rs

41 lines
1.1 KiB
Rust
Raw Normal View History

2017-02-03 02:15:24 +00:00
use std::ops::Deref;
use diesel::sqlite::SqliteConnection;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
2017-02-03 02:15:24 +00:00
use rocket::http::Status;
use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
pub type SqlitePool = Pool<ConnectionManager<SqliteConnection>>;
2017-02-03 02:15:24 +00:00
pub const DATABASE_URL: &'static str = env!("DATABASE_URL");
2017-02-03 02:15:24 +00:00
pub fn init_pool() -> SqlitePool {
let manager = ConnectionManager::<SqliteConnection>::new(DATABASE_URL);
Pool::new(manager).expect("db pool")
2017-02-03 02:15:24 +00:00
}
pub struct Conn(pub PooledConnection<ConnectionManager<SqliteConnection>>);
2017-02-03 02:15:24 +00:00
impl Deref for Conn {
type Target = SqliteConnection;
2017-05-26 23:44:53 +00:00
#[inline(always)]
2017-02-03 02:15:24 +00:00
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a, 'r> FromRequest<'a, 'r> for Conn {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<Conn, ()> {
let pool = request.guard::<State<SqlitePool>>()?;
2017-02-03 02:15:24 +00:00
match pool.get() {
Ok(conn) => Outcome::Success(Conn(conn)),
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ()))
}
}
}