use crate::error::BaseError;
use std::sync::OnceLock;
use yang_db::{Database, DatabaseConfig, QueryBuilder, Transaction};
static GLOBAL_DB: OnceLock<Database> = OnceLock::new();
pub struct GlobalDatabase;
impl GlobalDatabase {
pub async fn init(url: &str, config: DatabaseConfig) -> Result<(), BaseError> {
let db = Database::connect_with_config(url, config)
.await
.map_err(BaseError::DatabaseConnectionFailed)?;
GLOBAL_DB
.set(db)
.map_err(|_| BaseError::DatabaseAlreadyInitialized)?;
log::info!("全局数据库已初始化");
Ok(())
}
pub fn get() -> Result<&'static Database, BaseError> {
GLOBAL_DB.get().ok_or(BaseError::DatabaseNotInitialized)
}
pub fn table(table_name: &str) -> Result<QueryBuilder<'static>, BaseError> {
Ok(Self::get()?.table(table_name))
}
#[allow(deprecated)]
pub async fn query<T>(sql: &str) -> Result<Vec<T>, BaseError>
where
T: for<'r> sqlx::FromRow<'r, sqlx::mysql::MySqlRow> + Send + Unpin,
{
Self::get()?
.query(sql)
.await
.map_err(BaseError::DatabaseQueryFailed)
}
pub async fn query_with_params<T>(
sql: &str,
params: Vec<serde_json::Value>,
) -> Result<Vec<T>, BaseError>
where
T: for<'r> sqlx::FromRow<'r, sqlx::mysql::MySqlRow> + Send + Unpin,
{
Self::get()?
.query_with_params(sql, params)
.await
.map_err(BaseError::DatabaseQueryFailed)
}
#[allow(deprecated)]
pub async fn execute(sql: &str) -> Result<u64, BaseError> {
Self::get()?
.execute(sql)
.await
.map_err(BaseError::DatabaseExecuteFailed)
}
pub async fn execute_with_params(
sql: &str,
params: Vec<serde_json::Value>,
) -> Result<u64, BaseError> {
Self::get()?
.execute_with_params(sql, params)
.await
.map_err(BaseError::DatabaseExecuteFailed)
}
pub async fn transaction() -> Result<Transaction, BaseError> {
Self::get()?
.transaction()
.await
.map_err(BaseError::DatabaseTransactionFailed)
}
pub async fn health_check() -> Result<bool, BaseError> {
let rows = Self::query::<(i64,)>("SELECT 1").await?;
Ok(!rows.is_empty())
}
pub fn pool_status() -> Result<yang_db::PoolStatus, BaseError> {
Ok(Self::get()?.pool_status())
}
pub async fn close() {
if let Some(db) = GLOBAL_DB.get() {
db.close().await;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_database_not_initialized() {
let result = GlobalDatabase::get();
assert!(result.is_err());
assert!(matches!(result, Err(BaseError::DatabaseNotInitialized)));
}
#[test]
fn test_table_not_initialized() {
let result = GlobalDatabase::table("users");
assert!(result.is_err());
assert!(matches!(result, Err(BaseError::DatabaseNotInitialized)));
}
#[tokio::test]
async fn test_query_with_params_not_initialized() {
let result = GlobalDatabase::query_with_params::<(i32,)>(
"SELECT id FROM users WHERE id = ?",
vec![serde_json::json!(1)],
)
.await;
assert!(result.is_err());
assert!(matches!(result, Err(BaseError::DatabaseNotInitialized)));
}
#[tokio::test]
async fn test_execute_with_params_not_initialized() {
let result = GlobalDatabase::execute_with_params(
"DELETE FROM users WHERE id = ?",
vec![serde_json::json!(1)],
)
.await;
assert!(result.is_err());
assert!(matches!(result, Err(BaseError::DatabaseNotInitialized)));
}
}