From 22171c6aee45bde33ddcf32b9dc212d569970588 Mon Sep 17 00:00:00 2001 From: mrasheduzzaman Date: Mon, 20 Nov 2023 12:05:20 +0600 Subject: [PATCH] Add database connection module --- .vscode/settings.json | 3 +++ src/common/database.rs | 55 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 .vscode/settings.json create mode 100644 src/common/database.rs diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..0c2abb7 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "rust-analyzer.showUnlinkedFileNotification": false +} diff --git a/src/common/database.rs b/src/common/database.rs new file mode 100644 index 0000000..12784e0 --- /dev/null +++ b/src/common/database.rs @@ -0,0 +1,55 @@ +use diesel::r2d2::{self, ConnectionManager, PooledConnection}; +use once_cell::sync::OnceCell; + +#[cfg(feature = "database_postgres")] +type DbCon = diesel::PgConnection; + +#[cfg(all(feature = "database_postgres", debug_assertions))] +#[allow(dead_code)] +pub type DieselBackend = diesel::pg::Pg; + + +pub type Pool = r2d2::Pool>; +pub type Connection = PooledConnection>; + +/// wrapper function for a database pool +#[derive(Clone)] +pub struct Database { + pub pool: &'static Pool, +} + +impl Default for Database { + fn default() -> Self { + Self::new() + } +} + +impl Database { + pub fn new() -> Database { + Database { + pool: Self::get_or_init_pool(), + } + } + + pub fn get_connection(&self) -> Connection { + self.pool.get().unwrap() + } + + fn get_or_init_pool() -> &'static Pool { + #[cfg(debug_assertions)] + crate::load_env_vars(); + + static POOL: OnceCell = OnceCell::new(); + + POOL.get_or_init(|| { + Pool::builder() + .connection_timeout(std::time::Duration::from_secs(5)) + .build(ConnectionManager::::new(Self::connection_url())) + .unwrap() + }) + } + + pub fn connection_url() -> String { + std::env::var("DATABASE_URL").expect("DATABASE_URL environment variable expected.") + } +}