37 lines
927 B
Rust
37 lines
927 B
Rust
use dotenvy::dotenv;
|
|
use sqlx::{postgres::PgPoolOptions, PgPool};
|
|
use std::{env, error::Error};
|
|
|
|
pub mod models;
|
|
|
|
/// DatabaseHandler is a struct that can hold a database connection pool.
|
|
/// TODO: This might actually be an unnecessary abstraction, however it is 0-cost I believe...
|
|
pub struct DatabaseHandler {
|
|
pub pool: PgPool,
|
|
}
|
|
|
|
impl DatabaseHandler {
|
|
pub async fn create() -> Result<Self, Box<dyn Error>> {
|
|
// Load the env file
|
|
dotenv().ok();
|
|
|
|
// Load in the environment variables
|
|
let db_url = &env::var("DATABASE_URL")?;
|
|
|
|
let pool = PgPoolOptions::new()
|
|
.max_connections(10)
|
|
.connect(db_url)
|
|
.await?;
|
|
|
|
// Sanity check
|
|
let row: (i64,) = sqlx::query_as("SELECT $1")
|
|
.bind(150_i64)
|
|
.fetch_one(&pool)
|
|
.await?;
|
|
|
|
assert_eq!(row.0, 150);
|
|
|
|
Ok(DatabaseHandler { pool })
|
|
}
|
|
}
|