fish_lib/
database.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use crate::game::errors::database::GameDatabaseError;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use diesel::PgConnection;
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};

pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations");

pub struct Database {
    connection_pool: Option<Pool<ConnectionManager<PgConnection>>>,
}

impl Default for Database {
    fn default() -> Self {
        Self::new()
    }
}

impl Database {
    pub fn new() -> Self {
        Self {
            connection_pool: None,
        }
    }

    pub fn connect(&mut self, postgres_url: &str) -> Result<(), GameDatabaseError> {
        let connection_manager = ConnectionManager::<PgConnection>::new(postgres_url);
        let pool = Pool::builder()
            .build(connection_manager)
            .map_err(|e| GameDatabaseError::connection_failed(&e.to_string()))?;
        self.connection_pool = Some(pool);
        self.run_migrations()?;
        Ok(())
    }

    pub fn run_migrations(&self) -> Result<(), GameDatabaseError> {
        let mut connection = self.get_connection()?;
        connection
            .run_pending_migrations(MIGRATIONS)
            .map_err(|e| GameDatabaseError::migrations_failed(&e.to_string()))?;
        Ok(())
    }

    pub fn get_connection(
        &self,
    ) -> Result<PooledConnection<ConnectionManager<PgConnection>>, GameDatabaseError> {
        match &self.connection_pool {
            Some(pool) => pool
                .get()
                .map_err(|e| GameDatabaseError::connection_failed(&e.to_string())),
            None => Err(GameDatabaseError::missing_connection()),
        }
    }

    pub fn clear(&self) -> Result<(), GameDatabaseError> {
        let mut connection = self.get_connection()?;

        connection
            .revert_all_migrations(MIGRATIONS)
            .map_err(|e| GameDatabaseError::migrations_failed(&e.to_string()))?;

        connection
            .run_pending_migrations(MIGRATIONS)
            .map_err(|e| GameDatabaseError::migrations_failed(&e.to_string()))?;

        Ok(())
    }
}