database.rs 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. use crate::{
  2. errors::*,
  3. pool::{ConnectionManager, ConnectionPool, PoolConfig},
  4. };
  5. use r2d2::PooledConnection;
  6. pub struct Database {
  7. uri: String,
  8. pool: ConnectionPool,
  9. }
  10. pub type DBConnection = PooledConnection<ConnectionManager>;
  11. impl Database {
  12. pub fn new(dir: &str, name: &str, pool_config: PoolConfig) -> Result<Self> {
  13. let uri = db_file_uri(dir, name);
  14. if !std::path::PathBuf::from(dir).exists() {
  15. log::error!("Create database failed. {} not exists", &dir);
  16. }
  17. let pool = ConnectionPool::new(pool_config, &uri)?;
  18. Ok(Self { uri, pool })
  19. }
  20. pub fn get_uri(&self) -> &str { &self.uri }
  21. pub fn get_connection(&self) -> Result<DBConnection> {
  22. let conn = self.pool.get()?;
  23. Ok(conn)
  24. }
  25. }
  26. pub fn db_file_uri(dir: &str, name: &str) -> String {
  27. use std::path::MAIN_SEPARATOR;
  28. let mut uri = dir.to_owned();
  29. if !uri.ends_with(MAIN_SEPARATOR) {
  30. uri.push(MAIN_SEPARATOR);
  31. }
  32. uri.push_str(name);
  33. uri
  34. }