database.rs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 {
  25. &self.uri
  26. }
  27. pub fn get_connection(&self) -> Result<DBConnection> {
  28. let conn = self.pool.get()?;
  29. Ok(conn)
  30. }
  31. pub fn get_pool(&self) -> Arc<ConnectionPool> {
  32. self.pool.clone()
  33. }
  34. }
  35. pub fn db_file_uri(dir: &str, name: &str) -> String {
  36. use std::path::MAIN_SEPARATOR;
  37. let mut uri = dir.to_owned();
  38. if !uri.ends_with(MAIN_SEPARATOR) {
  39. uri.push(MAIN_SEPARATOR);
  40. }
  41. uri.push_str(name);
  42. uri
  43. }