use std::collections::HashMap;
use diesel::{
mysql::MysqlConnection,
r2d2::{self, ConnectionManager},
};
use serde_json::Value;
use crate::errors::RvError;
type MysqlDbPool = r2d2::Pool<ConnectionManager<MysqlConnection>>;
pub mod mysql_backend;
pub fn new(conf: &HashMap<String, Value>) -> Result<MysqlDbPool, RvError> {
let pool = establish_mysql_connection(conf);
match pool {
Ok(pool) => Ok(pool),
Err(e) => Err(e),
}
}
fn establish_mysql_connection(conf: &HashMap<String, Value>) -> Result<MysqlDbPool, RvError> {
let address = conf.get("address").and_then(|v| v.as_str()).ok_or(RvError::ErrDatabaseConnectionInfoInvalid)?;
let database = conf.get("database").and_then(|v| v.as_str()).unwrap_or("vault");
let username = conf.get("username").and_then(|v| v.as_str()).ok_or(RvError::ErrDatabaseConnectionInfoInvalid)?;
let password = conf.get("password").and_then(|v| v.as_str()).ok_or(RvError::ErrDatabaseConnectionInfoInvalid)?;
let database_url = format!("mysql://{}:{}@{}/{}", username, password, address, database);
let manager = ConnectionManager::<MysqlConnection>::new(database_url);
match r2d2::Pool::builder().build(manager) {
Ok(pool) => Ok(pool),
Err(e) => {
log::error!("Error: {:?}", e);
Err(RvError::ErrConnectionPoolCreate { source: (e) })
}
}
}
#[cfg(test)]
mod test {
use std::collections::HashMap;
use super::*;
#[test]
fn test_establish_mysql_connection() {
let mut conf: HashMap<String, Value> = HashMap::new();
conf.insert("address".to_string(), Value::String("127.0.0.1:3306".to_string()));
conf.insert("username".to_string(), Value::String("root".to_string()));
conf.insert("password".to_string(), Value::String("password".to_string()));
let pool = establish_mysql_connection(&conf);
assert!(pool.is_ok());
}
}