aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorHarald Eilertsen <haraldei@anduin.net>2017-10-01 22:12:36 +0200
committerHarald Eilertsen <haraldei@anduin.net>2017-10-01 22:12:36 +0200
commitb62344371e4ce07aa19da5e7faeef322e907653e (patch)
treedcf6d55a6620d657938d6092d7ba449371243f3d
parent370790ab51a542cf9b56d21548451c84e741701e (diff)
downloadrocket-blog-b62344371e4ce07aa19da5e7faeef322e907653e.tar.gz
rocket-blog-b62344371e4ce07aa19da5e7faeef322e907653e.tar.bz2
rocket-blog-b62344371e4ce07aa19da5e7faeef322e907653e.zip
Get database connection on request
-rw-r--r--src/lib.rs33
-rw-r--r--src/main.rs2
2 files changed, 34 insertions, 1 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 5152ae5..0c2d440 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -5,6 +5,7 @@ extern crate diesel_codegen;
extern crate dotenv;
extern crate r2d2_diesel;
extern crate r2d2;
+extern crate rocket;
use diesel::pg::PgConnection;
use r2d2_diesel::ConnectionManager;
@@ -25,3 +26,35 @@ pub fn init_db_pool() -> Pool {
let manager = ConnectionManager::<PgConnection>::new(dburl);
r2d2::Pool::new(config, manager).expect("db pool")
}
+
+use std::ops::Deref;
+use rocket::http::Status;
+use rocket::request::{self, FromRequest};
+use rocket::{Request, State, Outcome};
+
+// Connection request guard type: a wrapper around an r2d2 pooled connection.
+pub struct DbConn(pub r2d2::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<DbConn, ()> {
+ let pool = request.guard::<State<Pool>>()?;
+ match pool.get() {
+ Ok(conn) => Outcome::Success(DbConn(conn)),
+ Err(_) => Outcome::Failure((Status::ServiceUnavailable, ()))
+ }
+ }
+}
+
+// For the convenience of using an &DbConn as an &SqliteConnection.
+impl Deref for DbConn {
+ type Target = PgConnection;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index d9747c9..711c343 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -5,7 +5,7 @@ extern crate rocket;
extern crate rocket_blog;
#[get("/")]
-fn index() -> &'static str {
+fn index(conn: rocket_blog::DbConn) -> &'static str {
"Hallo, for faen!"
}