Skip to main content

backbone_orm/
connection.rs

1//! Database connection management
2
3use anyhow::Result;
4use sqlx::{PgPool, postgres::PgPoolOptions};
5use std::time::Duration;
6
7/// Database connection manager
8pub struct ConnectionManager {
9    pool: PgPool,
10}
11
12impl ConnectionManager {
13    /// Create new connection pool
14    pub async fn new(database_url: &str) -> Result<Self> {
15        let pool = PgPoolOptions::new()
16            .max_connections(20)
17            .min_connections(5)
18            .acquire_timeout(Duration::from_secs(30))
19            .idle_timeout(Duration::from_secs(600))
20            .max_lifetime(Duration::from_secs(1800))
21            .connect(database_url)
22            .await?;
23
24        Ok(Self { pool })
25    }
26
27    /// Get connection pool
28    pub fn pool(&self) -> &PgPool {
29        &self.pool
30    }
31
32    /// Close all connections
33    pub async fn close(&self) -> Result<()> {
34        self.pool.close().await;
35        Ok(())
36    }
37
38    /// Test database connection
39    pub async fn test_connection(&self) -> Result<()> {
40        sqlx::query("SELECT 1")
41            .fetch_one(&self.pool)
42            .await?;
43        Ok(())
44    }
45}