/// Postgres Connector // use sqlx::postgres::PgPoolOptions; use anyhow::{Result,anyhow}; use async_trait::async_trait; use crate::defs::{StoreSettings,PoolHandle}; #[derive(Default)] pub struct PostgresPool { pub id: String, pub client: Option>, pub conn: Option>, } impl std::fmt::Debug for PostgresPool { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { write!(fmt, "PostgresPool client: {:?}", self.client) } } impl PostgresPool { pub async fn new(pool_settings: StoreSettings,key: &str) -> Self { let url = pool_settings.url_db(key); let debug = envmnt::get_isize("DEBUG",0); if debug > 0 { println!("Open Postgres {}: {}",pool_settings.id, &url); } match PgPoolOptions::new().max_connections(pool_settings.max_conn) // .connect_lazy(&url); .connect(&url).await { Ok(cli) => Self { id: pool_settings.id, client: Some(cli), conn: None, }, Err(e) => { eprintln!("Error Postgres new pool: {}",e); Self::default() }, } } pub async fn connect_pool(self) -> Self { self.connect().await } pub async fn get_conn(self) -> Result> { if let Some(pool) = self.conn { Ok(pool) } else { let cli=self.connect_pool().await; if let Some(pool) = cli.conn { Ok(pool) } else { Err(anyhow!("Postgres pool not available")) } } } } #[async_trait] impl PoolHandle for PostgresPool { async fn connect(&self) -> Self { let cli = self; let mut conn = None; // DataPool::NoPool; if let Some(client) = &cli.client { if let Some(cli_pool) = client.try_acquire() { let debug = envmnt::get_isize("DEBUG",0); if debug > 0 { println!("Got Postgres connection"); } conn = Some(cli_pool); } else { eprintln!("Error Postgres connection "); } } Self { id: cli.id.to_owned(), client: cli.client.to_owned(), conn, } } }