sql_middleware/postgres/
config.rs

1use crate::middleware::{ConfigAndPool, DatabaseType, MiddlewarePool, SqlMiddlewareDbError};
2use deadpool_postgres::Config as PgConfig;
3use tokio_postgres::NoTls;
4
5impl ConfigAndPool {
6    /// Asynchronous initializer for `ConfigAndPool` with Postgres
7    ///
8    /// # Errors
9    /// Returns `SqlMiddlewareDbError::ConfigError` if required config fields are missing or `SqlMiddlewareDbError::ConnectionError` if pool creation fails.
10    #[allow(clippy::unused_async)]
11    pub async fn new_postgres(pg_config: PgConfig) -> Result<Self, SqlMiddlewareDbError> {
12        // Validate all required config fields are present
13        if pg_config.dbname.is_none() {
14            return Err(SqlMiddlewareDbError::ConfigError(
15                "dbname is required".to_string(),
16            ));
17        }
18
19        if pg_config.host.is_none() {
20            return Err(SqlMiddlewareDbError::ConfigError(
21                "host is required".to_string(),
22            ));
23        }
24        if pg_config.port.is_none() {
25            return Err(SqlMiddlewareDbError::ConfigError(
26                "port is required".to_string(),
27            ));
28        }
29        if pg_config.user.is_none() {
30            return Err(SqlMiddlewareDbError::ConfigError(
31                "user is required".to_string(),
32            ));
33        }
34        if pg_config.password.is_none() {
35            return Err(SqlMiddlewareDbError::ConfigError(
36                "password is required".to_string(),
37            ));
38        }
39
40        // Attempt to create connection pool
41        let pg_pool = pg_config
42            .create_pool(Some(deadpool_postgres::Runtime::Tokio1), NoTls)
43            .map_err(|e| {
44                SqlMiddlewareDbError::ConnectionError(format!(
45                    "Failed to create Postgres pool: {e}"
46                ))
47            })?;
48
49        Ok(ConfigAndPool {
50            pool: MiddlewarePool::Postgres(pg_pool),
51            db_type: DatabaseType::Postgres,
52        })
53    }
54}