refactor (backend-rs): separate postgresql connector from database/mod.rs
This commit is contained in:
parent
3b89a8bfa6
commit
e60898b4b0
2 changed files with 36 additions and 34 deletions
|
@ -1,34 +1,2 @@
|
|||
use crate::config::server::CONFIG;
|
||||
use sea_orm::{Database, DbConn, DbErr};
|
||||
|
||||
static DB_CONN: once_cell::sync::OnceCell<DbConn> = 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;
|
||||
|
|
34
packages/backend-rs/src/database/postgresql.rs
Normal file
34
packages/backend-rs/src/database/postgresql.rs
Normal file
|
@ -0,0 +1,34 @@
|
|||
use crate::config::server::CONFIG;
|
||||
use sea_orm::{Database, DbConn, DbErr};
|
||||
|
||||
static DB_CONN: once_cell::sync::OnceCell<DbConn> = 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());
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue