database.rs 1.2 KB

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