use std::time;
use sqlx::{pool, postgres};
use crate::SGBD;
pub type PgPool = sqlx::PgPool;
#[derive(Clone)]
pub struct PostgresSGBD {
connection_url: String,
database_pool: PgPool,
}
impl PostgresSGBD {
const MAX_IDLE: u64 = 8;
const MAX_OPEN: u32 = 32;
const TIMEOUT_SECONDS: u64 = 15;
pub fn connection_url(&self) -> &str {
&self.connection_url
}
}
#[async_trait::async_trait]
impl SGBD for PostgresSGBD {
type Pool = PgPool;
async fn new(
connection_url: impl AsRef<str> + ToString + Send + Sync,
) -> Result<Self, crate::Error> {
let pool = Self::create_pool(&connection_url).await?;
Ok(Self {
connection_url: connection_url.to_string(),
database_pool: pool,
})
}
async fn create_pool(
url: impl AsRef<str> + Send + Sync,
) -> Result<Self::Pool, crate::Error> {
let options: pool::PoolOptions<_> = postgres::PgPoolOptions::new()
.idle_timeout(time::Duration::from_secs(Self::MAX_IDLE))
.max_connections(Self::MAX_OPEN)
.acquire_timeout(time::Duration::from_secs(Self::TIMEOUT_SECONDS));
let pool: Self::Pool = options.connect(url.as_ref()).await?;
Ok(pool)
}
fn pool(&self) -> &Self::Pool {
&self.database_pool
}
}