Skip to main content

shared/infrastructure/database/postgres/
repository.rs

1use crate::error::Result;
2use sqlx::{Pool, Postgres, postgres::PgPoolOptions};
3
4pub struct PostgreSQL {
5    pub pool: Pool<Postgres>,
6}
7impl PostgreSQL {
8    pub async fn start(conn: &str) -> Result<Self> {
9        let pool = PgPoolOptions::new()
10            .max_connections(5)
11            .connect(conn)
12            .await
13            .inspect_err(|e| {
14                tracing::error!(
15                    error_code = "InternalError::Database",
16                    "Failed to connect to database - {e}"
17                );
18            })?;
19
20        Ok(Self { pool })
21    }
22
23    pub async fn create_database(&self, name: &str) -> Result<()> {
24        sqlx::query(&format!("CREATE DATABASE \"{}\"", name))
25            .execute(&self.pool)
26            .await
27            .inspect_err(|e| {
28                tracing::error!(
29                    error_code = "InternalError::Database",
30                    "Failed to connect to database - {e}"
31                );
32            })?;
33
34        self.pool.close().await;
35
36        Ok(())
37    }
38
39    pub async fn run_migrations(&self) -> Result<()> {
40        let path = std::path::Path::new("../../migrations/postgres");
41        if path.exists() {
42            let migrator = sqlx::migrate::Migrator::new(path).await?;
43            migrator
44                .run(&self.pool)
45                .await
46                .inspect_err(|e| tracing::error!("Failed to run migrations - {e}"))?;
47        }
48
49        Ok(())
50    }
51}