shaperail_runtime/db/
pool.rs1use shaperail_core::ShaperailError;
2use sqlx::postgres::PgPoolOptions;
3use sqlx::PgPool;
4
5pub 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
17pub 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}