diff --git a/src/database.rs b/src/database.rs new file mode 100644 index 0000000..a90de44 --- /dev/null +++ b/src/database.rs @@ -0,0 +1,51 @@ +use cfg_if::cfg_if; + +cfg_if! { +if #[cfg(feature = "ssr")] { + +use lazy_static::lazy_static; +use std::env; +use diesel::{ + pg::PgConnection, + r2d2::ConnectionManager, + r2d2::PooledConnection, + r2d2::Pool, +}; + +// See https://leward.eu/notes-on-diesel-a-rust-orm/ + +// Define some types to make it easier to work with Diesel +type PgPool = Pool>; +pub type PgPooledConn = PooledConnection>; + +// Keep a global instance of the pool +lazy_static! { + static ref DB_POOL: PgPool = init_db_pool(); +} + +/// Initialize the database pool +/// +/// Will panic if the DATABASE_URL environment variable is not set, or if there is an error creating the pool. +/// +/// # Returns +/// A database pool object, which can be used to get pooled connections +fn init_db_pool() -> PgPool { + let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); + let manager = ConnectionManager::::new(database_url); + PgPool::builder() + .build(manager) + .expect("Failed to create pool.") +} + +/// Get a pooled connection to the database +/// +/// Will panic if there is an error getting a connection from the pool. +/// +/// # Returns +/// A pooled connection to the database +pub fn get_db_conn() -> PgPooledConn { + DB_POOL.get().expect("Failed to get a database connection from the pool.") +} + +} +} diff --git a/src/lib.rs b/src/lib.rs index 17add12..4be1145 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,7 @@ pub mod app; pub mod songdata; pub mod playstatus; pub mod playbar; +pub mod database; use cfg_if::cfg_if; cfg_if! {