fix (backend-rs): use tokio::sync::OnceCell for connection pools

This commit is contained in:
naskya 2024-07-09 16:37:05 +09:00
parent f13fd3aed0
commit 892ff73cc5
No known key found for this signature in database
GPG key ID: 712D413B3A9FED5C
2 changed files with 15 additions and 8 deletions

View file

@ -1,12 +1,12 @@
//! PostgreSQL interface
use crate::config::CONFIG;
use once_cell::sync::OnceCell;
use sea_orm::{ConnectOptions, Database, DbConn, DbErr};
use std::time::Duration;
use tokio::sync::OnceCell;
use tracing::log::LevelFilter;
static DB_CONN: OnceCell<DbConn> = OnceCell::new();
static DB_CONN: OnceCell<DbConn> = OnceCell::const_new();
async fn init_conn() -> Result<&'static DbConn, DbErr> {
let database_uri = format!(
@ -22,10 +22,14 @@ async fn init_conn() -> Result<&'static DbConn, DbErr> {
.sqlx_slow_statements_logging_settings(LevelFilter::Warn, Duration::from_secs(3))
.to_owned();
tracing::info!("initializing connection");
let conn = DB_CONN
.get_or_try_init(|| async {
tracing::info!("initializing connection");
Database::connect(option).await
})
.await?;
let conn = Database::connect(option).await?;
Ok(DB_CONN.get_or_init(move || conn))
Ok(conn)
}
/// Returns an async PostgreSQL connection that can be used with [sea_orm] utilities.

View file

@ -72,10 +72,13 @@ async fn init_conn_pool() -> Result<(), RedisError> {
tracing::info!("initializing connection manager");
let manager = RedisConnectionManager::new(redis_url)?;
tracing::info!("creating connection pool");
let pool = Pool::builder().build(manager).await?;
CONN_POOL
.get_or_try_init(|| async {
tracing::info!("creating connection pool");
Pool::builder().build(manager).await
})
.await?;
CONN_POOL.get_or_init(|| async { pool }).await;
Ok(())
}