2018-02-10 01:00:55 +01:00
|
|
|
use std::ops::Deref;
|
|
|
|
|
2018-03-07 18:41:34 +01:00
|
|
|
use diesel::r2d2;
|
|
|
|
use diesel::r2d2::ConnectionManager;
|
2019-05-20 21:12:41 +02:00
|
|
|
use diesel::mysql::MysqlConnection;
|
2018-12-30 23:34:31 +01:00
|
|
|
use diesel::{Connection as DieselConnection, ConnectionError};
|
2018-02-10 01:00:55 +01:00
|
|
|
|
|
|
|
use rocket::http::Status;
|
|
|
|
use rocket::request::{self, FromRequest};
|
|
|
|
use rocket::{Outcome, Request, State};
|
|
|
|
|
2018-12-07 02:05:45 +01:00
|
|
|
use crate::CONFIG;
|
2018-02-10 01:00:55 +01:00
|
|
|
|
|
|
|
/// An alias to the database connection used
|
2019-05-20 19:53:14 +02:00
|
|
|
type Connection = MysqlConnection;
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2019-05-20 19:53:14 +02:00
|
|
|
/// An alias to the type for a pool of Diesel MySQL connections.
|
2018-02-10 01:00:55 +01:00
|
|
|
type Pool = r2d2::Pool<ConnectionManager<Connection>>;
|
|
|
|
|
|
|
|
/// Connection request guard type: a wrapper around an r2d2 pooled connection.
|
|
|
|
pub struct DbConn(pub r2d2::PooledConnection<ConnectionManager<Connection>>);
|
|
|
|
|
|
|
|
pub mod models;
|
2018-12-30 23:34:31 +01:00
|
|
|
pub mod schema;
|
2018-02-10 01:00:55 +01:00
|
|
|
|
|
|
|
/// Initializes a database pool.
|
|
|
|
pub fn init_pool() -> Pool {
|
2019-01-25 18:23:51 +01:00
|
|
|
let manager = ConnectionManager::new(CONFIG.database_url());
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2018-12-30 23:34:31 +01:00
|
|
|
r2d2::Pool::builder().build(manager).expect("Failed to create pool")
|
2018-02-10 01:00:55 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get_connection() -> Result<Connection, ConnectionError> {
|
2019-05-20 21:12:41 +02:00
|
|
|
let url = CONFIG.database_url();
|
|
|
|
println!("{}", url.to_string());
|
|
|
|
Connection::establish(&url)
|
2018-02-10 01:00:55 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// 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)),
|
2018-12-30 23:34:31 +01:00
|
|
|
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())),
|
2018-02-10 01:00:55 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// For the convenience of using an &DbConn as a &Database.
|
|
|
|
impl Deref for DbConn {
|
|
|
|
type Target = Connection;
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
}
|