use std::time::Duration;
use sqlx::any::{install_default_drivers, AnyPoolOptions};
use sqlx::AnyPool;
use crate::config::DatabaseConfig;
use crate::error::CoreResult;
use crate::migration::DbBackend;
#[derive(Clone)]
pub struct Db {
pub pool: AnyPool,
pub backend: DbBackend,
}
impl Db {
pub fn new(pool: AnyPool, backend: DbBackend) -> Self {
Self { pool, backend }
}
}
pub async fn connect(cfg: &DatabaseConfig) -> CoreResult<Db> {
install_default_drivers();
let backend = DbBackend::from_url(&cfg.url)?;
let pool = AnyPoolOptions::new()
.max_connections(cfg.max_connections)
.acquire_timeout(Duration::from_secs(cfg.acquire_timeout_secs))
.connect(&cfg.url)
.await?;
Ok(Db { pool, backend })
}