Skip to main content

rustorm_core/
pool.rs

1use crate::error::{OrmError, OrmResult};
2use sqlx::postgres::{PgPool, PgPoolOptions};
3use std::time::Duration;
4
5/// Обёртка над sqlx::PgPool с удобными методами подключения.
6pub struct OrmPool;
7
8impl OrmPool {
9    /// Подключиться к БД по URL.
10    ///
11    /// ```rust
12    /// let pool = OrmPool::connect("postgres://user:pass@localhost/mydb").await?;
13    /// ```
14    pub async fn connect(url: &str) -> OrmResult<PgPool> {
15        PgPoolOptions::new()
16            .max_connections(20)
17            .min_connections(2)
18            .acquire_timeout(Duration::from_secs(30))
19            .idle_timeout(Duration::from_secs(600))
20            .connect(url)
21            .await
22            .map_err(OrmError::from_sqlx)
23    }
24
25    /// Читает `DATABASE_URL` из переменных окружения.
26    ///
27    /// ```rust
28    /// let pool = OrmPool::from_env().await?;
29    /// ```
30    pub async fn from_env() -> OrmResult<PgPool> {
31        let url = std::env::var("DATABASE_URL")
32            .map_err(|_| OrmError::Config("DATABASE_URL не задан".into()))?;
33        Self::connect(&url).await
34    }
35
36    /// Подключение с явными параметрами пула.
37    pub async fn connect_with_options(url: &str, options: PoolOptions) -> OrmResult<PgPool> {
38        PgPoolOptions::new()
39            .max_connections(options.max_connections)
40            .min_connections(options.min_connections)
41            .acquire_timeout(Duration::from_secs(options.acquire_timeout_secs))
42            .idle_timeout(Duration::from_secs(options.idle_timeout_secs))
43            .connect(url)
44            .await
45            .map_err(OrmError::from_sqlx)
46    }
47}
48
49#[derive(Debug, Clone)]
50pub struct PoolOptions {
51    pub max_connections: u32,
52    pub min_connections: u32,
53    pub acquire_timeout_secs: u64,
54    pub idle_timeout_secs: u64,
55}
56
57impl Default for PoolOptions {
58    fn default() -> Self {
59        Self {
60            max_connections: 20,
61            min_connections: 2,
62            acquire_timeout_secs: 30,
63            idle_timeout_secs: 600,
64        }
65    }
66}