Skip to main content

shaperail_runtime/db/
pool.rs

1use shaperail_core::ShaperailError;
2use sqlx::postgres::PgPoolOptions;
3use sqlx::PgPool;
4
5/// Creates a PostgreSQL connection pool from the given database URL.
6pub async fn create_pool(
7    database_url: &str,
8    max_connections: u32,
9) -> Result<PgPool, ShaperailError> {
10    PgPoolOptions::new()
11        .max_connections(max_connections)
12        .connect(database_url)
13        .await
14        .map_err(|e| ShaperailError::Internal(format!("Failed to connect to database: {e}")))
15}
16
17/// Runs a simple `SELECT 1` health check against the pool.
18pub async fn health_check(pool: &PgPool) -> Result<(), ShaperailError> {
19    sqlx::query_scalar::<_, i32>("SELECT 1")
20        .fetch_one(pool)
21        .await
22        .map_err(|e| ShaperailError::Internal(format!("Database health check failed: {e}")))?;
23    Ok(())
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[test]
31    fn pool_rejects_invalid_url() {
32        let rt = tokio::runtime::Runtime::new().unwrap();
33        let result = rt.block_on(create_pool("postgresql://bad:bad@localhost:59999/nope", 1));
34        assert!(result.is_err());
35        if let Err(ShaperailError::Internal(msg)) = result {
36            assert!(msg.contains("Failed to connect"));
37        }
38    }
39}