From e60898b4b056726aff09d120b055d3205bbcb3b6 Mon Sep 17 00:00:00 2001 From: naskya Date: Sat, 20 Apr 2024 02:11:41 +0900 Subject: [PATCH] refactor (backend-rs): separate postgresql connector from database/mod.rs --- packages/backend-rs/src/database/mod.rs | 36 ++----------------- .../backend-rs/src/database/postgresql.rs | 34 ++++++++++++++++++ 2 files changed, 36 insertions(+), 34 deletions(-) create mode 100644 packages/backend-rs/src/database/postgresql.rs diff --git a/packages/backend-rs/src/database/mod.rs b/packages/backend-rs/src/database/mod.rs index a60d20af9c..26db81c644 100644 --- a/packages/backend-rs/src/database/mod.rs +++ b/packages/backend-rs/src/database/mod.rs @@ -1,34 +1,2 @@ -use crate::config::server::CONFIG; -use sea_orm::{Database, DbConn, DbErr}; - -static DB_CONN: once_cell::sync::OnceCell = once_cell::sync::OnceCell::new(); - -async fn init_database() -> Result<&'static DbConn, DbErr> { - let database_uri = format!( - "postgres://{}:{}@{}:{}/{}", - CONFIG.db.user, - urlencoding::encode(&CONFIG.db.pass), - CONFIG.db.host, - CONFIG.db.port, - CONFIG.db.db, - ); - let conn = Database::connect(database_uri).await?; - Ok(DB_CONN.get_or_init(move || conn)) -} - -pub async fn db_conn() -> Result<&'static DbConn, DbErr> { - match DB_CONN.get() { - Some(conn) => Ok(conn), - None => init_database().await, - } -} - -#[cfg(test)] -mod unit_test { - use super::db_conn; - - #[tokio::test] - async fn connect_test() { - assert!(db_conn().await.is_ok()); - } -} +pub use postgresql::db_conn; +pub mod postgresql; diff --git a/packages/backend-rs/src/database/postgresql.rs b/packages/backend-rs/src/database/postgresql.rs new file mode 100644 index 0000000000..a60d20af9c --- /dev/null +++ b/packages/backend-rs/src/database/postgresql.rs @@ -0,0 +1,34 @@ +use crate::config::server::CONFIG; +use sea_orm::{Database, DbConn, DbErr}; + +static DB_CONN: once_cell::sync::OnceCell = once_cell::sync::OnceCell::new(); + +async fn init_database() -> Result<&'static DbConn, DbErr> { + let database_uri = format!( + "postgres://{}:{}@{}:{}/{}", + CONFIG.db.user, + urlencoding::encode(&CONFIG.db.pass), + CONFIG.db.host, + CONFIG.db.port, + CONFIG.db.db, + ); + let conn = Database::connect(database_uri).await?; + Ok(DB_CONN.get_or_init(move || conn)) +} + +pub async fn db_conn() -> Result<&'static DbConn, DbErr> { + match DB_CONN.get() { + Some(conn) => Ok(conn), + None => init_database().await, + } +} + +#[cfg(test)] +mod unit_test { + use super::db_conn; + + #[tokio::test] + async fn connect_test() { + assert!(db_conn().await.is_ok()); + } +}