2021-07-09 08:34:50 +00:00
|
|
|
use crate::{
|
|
|
|
errors::*,
|
2021-07-09 15:31:44 +00:00
|
|
|
pool::{ConnectionManager, ConnectionPool, PoolConfig},
|
2021-07-09 08:34:50 +00:00
|
|
|
};
|
|
|
|
use r2d2::PooledConnection;
|
|
|
|
|
2021-07-10 08:27:20 +00:00
|
|
|
pub struct Database {
|
2021-07-09 08:34:50 +00:00
|
|
|
uri: String,
|
|
|
|
pool: ConnectionPool,
|
|
|
|
}
|
|
|
|
|
2021-07-09 15:31:44 +00:00
|
|
|
pub type DBConnection = PooledConnection<ConnectionManager>;
|
|
|
|
|
2021-07-10 08:27:20 +00:00
|
|
|
impl Database {
|
2021-07-09 08:34:50 +00:00
|
|
|
pub fn new(dir: &str, name: &str, pool_config: PoolConfig) -> Result<Self> {
|
|
|
|
let uri = db_file_uri(dir, name);
|
2021-07-10 08:27:20 +00:00
|
|
|
|
|
|
|
if !std::path::PathBuf::from(dir).exists() {
|
|
|
|
log::error!("Create database failed. {} not exists", &dir);
|
|
|
|
}
|
|
|
|
|
2021-07-09 08:34:50 +00:00
|
|
|
let pool = ConnectionPool::new(pool_config, &uri)?;
|
|
|
|
Ok(Self { uri, pool })
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get_uri(&self) -> &str { &self.uri }
|
|
|
|
|
2021-07-09 15:31:44 +00:00
|
|
|
pub fn get_connection(&self) -> Result<DBConnection> {
|
2021-07-09 08:34:50 +00:00
|
|
|
let conn = self.pool.get()?;
|
|
|
|
Ok(conn)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn db_file_uri(dir: &str, name: &str) -> String {
|
|
|
|
use std::path::MAIN_SEPARATOR;
|
|
|
|
|
|
|
|
let mut uri = dir.to_owned();
|
|
|
|
if !uri.ends_with(MAIN_SEPARATOR) {
|
|
|
|
uri.push(MAIN_SEPARATOR);
|
|
|
|
}
|
|
|
|
uri.push_str(name);
|
|
|
|
uri
|
|
|
|
}
|