summaryrefslogtreecommitdiff
path: root/server/src/db.rs
blob: 43c3bd908bd640ef09c480096f336f92f6b63154 (plain)
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
use crate::errors::AppError;

use sqlx::postgres::PgPool;

/// Static variable used to manage the database connection. Called with value = None raises a panic
/// error.
static mut CONNECTION: Option<PgPool> = None;

/// Setup database connection. Get variable `DATABASE_URL` from the environment. Sqlx crate already
/// defines an error for environments without DATABASE_URL.
pub async fn setup() -> Result<(), AppError> {
    let database_url =
        std::env::var("DATABASE_URL").expect("Define `DATABASE_URL` environment variable.");

    unsafe {
        CONNECTION = Some(PgPool::connect(&database_url).await?);
    }

    Ok(())
}

/// Get connection. Raises an error if `setup()` has not been called yet.
/// Managing static `CONNECTION` is an unsafe operation.
pub unsafe fn get_client() -> &'static PgPool {
    match &CONNECTION {
        Some(client) => client,
        None => panic!("Connection not established!"),
    }
}