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
use diesel::{migration::MigrationVersion, prelude::*};
use diesel_async::{pooled_connection::AsyncDieselConnectionManager, AsyncPgConnection};
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use dotenvy::dotenv;
use std::{env, fmt::Debug};

pub mod schema;

#[derive(Debug)]
pub struct DbError {
    pub message: String,
}

impl std::fmt::Display for DbError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "DbError: {}", self.message)
    }
}

pub type Result<T> = std::result::Result<T, DbError>;

pub type Pool = bb8::Pool<AsyncDieselConnectionManager<AsyncPgConnection>>;
pub type DBConnection<'a> =
    bb8::PooledConnection<'a, AsyncDieselConnectionManager<AsyncPgConnection>>;

pub type DBConnectionSync = diesel::pg::PgConnection;

pub fn get_db_url() -> String {
    dotenv().ok();

    env::var("DATABASE_URL").expect("DATABASE_URL must be set")
}

pub fn get_db_connection_sync() -> std::result::Result<DBConnectionSync, diesel::ConnectionError> {
    let db_url = get_db_url();
    diesel::pg::PgConnection::establish(&db_url)
}

pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();

pub fn run_migrations(
    conn: &mut impl MigrationHarness<diesel::pg::Pg>,
) -> Result<Vec<MigrationVersion>> {
    conn.run_pending_migrations(MIGRATIONS)
        .map_err(|e| DbError {
            message: format!("Error running migrations: {:?}", e),
        })
}