use puerto_core::RepositoryError;
use sqlx::migrate::Migrator;
use sqlx::{PgPool, postgres::PgPoolOptions};
use std::time::Duration;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DatabaseError {
#[error("database.connection_error")]
ConnectionError,
#[error("database.migration_error")]
MigrationError,
}
pub async fn create_postgres_pool(database_url: &str) -> Result<PgPool, DatabaseError> {
PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(30))
.connect(database_url)
.await
.map_err(|_| DatabaseError::ConnectionError)
}
pub async fn run_migrations(pool: &PgPool, migrator: &Migrator) -> Result<(), DatabaseError> {
migrator
.run(pool)
.await
.map_err(|_| DatabaseError::MigrationError)
}
pub async fn ping(pool: &PgPool) -> bool {
sqlx::query("SELECT 1").execute(pool).await.is_ok()
}
pub fn map_sqlx_error(err: &sqlx::Error) -> RepositoryError {
let unique_violation = err
.as_database_error()
.and_then(|db_err| db_err.code())
.is_some_and(|code| code == "23505");
if unique_violation {
RepositoryError::Duplicate
} else {
RepositoryError::Unavailable
}
}
#[cfg(test)]
mod tests {
use super::*;
fn unreachable_pool() -> PgPool {
PgPoolOptions::new()
.acquire_timeout(Duration::from_millis(200))
.connect_lazy("postgres://puerto@127.0.0.1:1/puerto")
.unwrap()
}
#[derive(Debug)]
struct FakeDbError(&'static str);
impl std::fmt::Display for FakeDbError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "SQLSTATE {}", self.0)
}
}
impl std::error::Error for FakeDbError {}
impl sqlx::error::DatabaseError for FakeDbError {
fn message(&self) -> &str {
self.0
}
fn code(&self) -> Option<std::borrow::Cow<'_, str>> {
Some(self.0.into())
}
fn as_error(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
self
}
fn as_error_mut(&mut self) -> &mut (dyn std::error::Error + Send + Sync + 'static) {
self
}
fn into_error(self: Box<Self>) -> Box<dyn std::error::Error + Send + Sync + 'static> {
self
}
fn kind(&self) -> sqlx::error::ErrorKind {
sqlx::error::ErrorKind::Other
}
}
fn database_error(code: &'static str) -> sqlx::Error {
sqlx::Error::Database(Box::new(FakeDbError(code)))
}
#[test]
fn should_map_a_unique_violation_to_duplicate() {
assert_eq!(
map_sqlx_error(&database_error("23505")),
RepositoryError::Duplicate
);
}
#[test]
fn should_map_another_database_error_to_unavailable() {
assert_eq!(
map_sqlx_error(&database_error("23503")),
RepositoryError::Unavailable
);
}
#[test]
fn should_map_a_non_database_error_to_unavailable() {
assert_eq!(
map_sqlx_error(&sqlx::Error::PoolTimedOut),
RepositoryError::Unavailable
);
}
#[tokio::test]
async fn should_report_not_ready_when_the_database_is_unreachable() {
assert!(!ping(&unreachable_pool()).await);
}
#[tokio::test]
async fn should_reject_a_database_url_that_is_not_one() {
let result = create_postgres_pool("not a database url").await;
assert!(matches!(result, Err(DatabaseError::ConnectionError)));
}
#[test]
fn should_keep_the_machine_readable_codes() {
assert_eq!(
DatabaseError::ConnectionError.to_string(),
"database.connection_error"
);
assert_eq!(
DatabaseError::MigrationError.to_string(),
"database.migration_error"
);
}
async fn test_database() -> Option<PgPool> {
let server = std::env::var("PUERTO_TEST_DATABASE_URL").ok()?;
Some(
create_postgres_pool(&format!("{server}/postgres"))
.await
.unwrap(),
)
}
#[tokio::test]
#[ignore = "needs Postgres: make test/db"]
async fn postgres_unique_violation_maps_to_duplicate() {
let Some(pool) = test_database().await else {
eprintln!("PUERTO_TEST_DATABASE_URL not set — skipping (run `make test/db`)");
return;
};
let mut conn = pool.acquire().await.unwrap();
sqlx::query("CREATE TEMPORARY TABLE skus (sku TEXT UNIQUE)")
.execute(&mut *conn)
.await
.unwrap();
sqlx::query("INSERT INTO skus VALUES ('A-1')")
.execute(&mut *conn)
.await
.unwrap();
let err = sqlx::query("INSERT INTO skus VALUES ('A-1')")
.execute(&mut *conn)
.await
.unwrap_err();
assert_eq!(map_sqlx_error(&err), RepositoryError::Duplicate);
}
#[tokio::test]
#[ignore = "needs Postgres: make test/db"]
async fn postgres_ping_reports_ready() {
let Some(pool) = test_database().await else {
eprintln!("PUERTO_TEST_DATABASE_URL not set — skipping (run `make test/db`)");
return;
};
assert!(ping(&pool).await);
}
}