Skip to main content

yang_db/
backend_api.rs

1//! 跨后端统一管理面 trait。
2//!
3//! 让编排层用同一组调用处理 MySQL / PostgreSQL / Redis 的健康检查、连接池
4//! 状态与关闭,而不必按后端逐个 match。
5
6use crate::{DbError, PoolStatus};
7
8/// 数据库后端统一管理面。
9#[async_trait::async_trait]
10pub trait Backend: Send + Sync {
11    /// 后端名称(`mysql` / `postgres` / `redis`)。
12    fn backend_name(&self) -> &'static str;
13
14    /// 连接池状态。
15    fn pool_status(&self) -> PoolStatus;
16
17    /// 健康检查。
18    async fn health_check(&self) -> Result<bool, DbError>;
19
20    /// 关闭连接池(幂等)。
21    async fn close(&self);
22}
23
24#[cfg(feature = "redis")]
25#[async_trait::async_trait]
26impl Backend for crate::RedisClient {
27    fn backend_name(&self) -> &'static str {
28        "redis"
29    }
30
31    fn pool_status(&self) -> PoolStatus {
32        crate::RedisClient::pool_status(self)
33    }
34
35    async fn health_check(&self) -> Result<bool, DbError> {
36        crate::RedisClient::health_check(self).await
37    }
38
39    async fn close(&self) {
40        crate::RedisClient::close(self).await;
41    }
42}
43
44#[cfg(feature = "mysql")]
45#[async_trait::async_trait]
46impl Backend for crate::mysql::Database {
47    fn backend_name(&self) -> &'static str {
48        "mysql"
49    }
50
51    fn pool_status(&self) -> PoolStatus {
52        crate::mysql::Database::pool_status(self)
53    }
54
55    async fn health_check(&self) -> Result<bool, DbError> {
56        crate::mysql::Database::health_check(self).await
57    }
58
59    async fn close(&self) {
60        crate::mysql::Database::close(self).await;
61    }
62}
63
64#[cfg(feature = "postgres")]
65#[async_trait::async_trait]
66impl Backend for crate::postgres::Database {
67    fn backend_name(&self) -> &'static str {
68        "postgres"
69    }
70
71    fn pool_status(&self) -> PoolStatus {
72        crate::postgres::Database::pool_status(self)
73    }
74
75    async fn health_check(&self) -> Result<bool, DbError> {
76        crate::postgres::Database::health_check(self).await
77    }
78
79    async fn close(&self) {
80        crate::postgres::Database::close(self).await;
81    }
82}