bbox_core/
pg_ds.rs

1use crate::config::DsPostgisCfg;
2use log::info;
3use sqlx::postgres::{PgPool, PgPoolOptions};
4use thiserror::Error;
5
6#[derive(Error, Debug)]
7pub enum Error {
8    #[error(transparent)]
9    DbError(#[from] sqlx::Error),
10}
11
12pub type Result<T> = std::result::Result<T, Error>;
13
14#[derive(Clone, Debug)]
15pub struct PgDatasource {
16    pub pool: PgPool,
17}
18
19impl PgDatasource {
20    pub async fn from_config(ds: &DsPostgisCfg, envvar: Option<String>) -> Result<Self> {
21        Self::new_pool(&envvar.unwrap_or(ds.url.clone())).await
22    }
23    pub async fn new_pool(url: &str) -> Result<Self> {
24        info!("Connecting to {url}");
25        let pool = PgPoolOptions::new()
26            .min_connections(0)
27            .max_connections(8)
28            .connect(url)
29            .await?;
30        Ok(PgDatasource { pool })
31    }
32}