#[cfg(feature = "postgres")]
use crate::error::Error;
#[cfg(feature = "postgres")]
use crate::config::DatabaseConfig;
#[cfg(feature = "postgres")]
use sqlx::{PgPool, Pool, Postgres};
#[cfg(feature = "postgres")]
use tracing::error;
pub fn build_pgsql_url(host: &str, port: i32, user: &str, password: &str, db: &str) -> String {
format!("postgres://{user}:{password}@{host}:{port}/{db}")
}
#[cfg(feature = "postgres")]
pub struct PgClient {
pub conn_pool: Pool<Postgres>,
pub url: String,
}
#[cfg(feature = "postgres")]
impl PgClient {
pub async fn new() -> Result<Self, Error> {
let config = DatabaseConfig::from_env()?;
PgClient::from_config(config).await
}
pub async fn from_config(config: DatabaseConfig) -> Result<Self, Error> {
let db_url = build_pgsql_url(
&config.host,
config.port,
&config.user,
&config.password,
&config.name,
);
let connection_pool = match PgPool::connect(&db_url).await {
Ok(new_pool) => new_pool,
Err(e) => {
error!(
"Failed to obtain a connection pool for the PostgreSQL database server: {e}"
);
return Err(Error::PgConnectError(e.to_string()));
}
};
Ok(PgClient {
conn_pool: connection_pool,
url: db_url,
})
} }