Skip to main content

cc_core/
mysql.rs

1//! MySQL 连接的初始化与多连接管理。
2
3use std::collections::HashMap;
4
5use sqlx::mysql::{MySqlConnectOptions, MySqlPool, MySqlPoolOptions, MySqlSslMode};
6
7use crate::config::{Config, IntoMysqlName, MysqlConfig};
8
9/// 把配置里的字符串 ssl_mode 映射到 sqlx 的枚举(无法识别时回退 Preferred)。
10pub fn ssl_mode_from_str(s: &str) -> MySqlSslMode {
11    match s.trim().to_ascii_lowercase().as_str() {
12        "disabled" | "disable" | "off" => MySqlSslMode::Disabled,
13        "required" | "require" => MySqlSslMode::Required,
14        "verify-ca" | "verify_ca" => MySqlSslMode::VerifyCa,
15        "verify-identity" | "verify_identity" => MySqlSslMode::VerifyIdentity,
16        _ => MySqlSslMode::Preferred,
17    }
18}
19
20/// 根据配置构造连接选项。
21pub fn connect_options(cfg: &MysqlConfig) -> MySqlConnectOptions {
22    let mut opts = MySqlConnectOptions::new()
23        .host(&cfg.host)
24        .port(cfg.port)
25        .username(&cfg.user)
26        .password(&cfg.password)
27        .ssl_mode(ssl_mode_from_str(&cfg.ssl_mode));
28
29    if !cfg.database.is_empty() {
30        opts = opts.database(&cfg.database);
31    }
32    opts
33}
34
35/// 用单个配置建立连接池。
36pub async fn connect(cfg: &MysqlConfig) -> anyhow::Result<MySqlPool> {
37    let pool = MySqlPoolOptions::new()
38        .max_connections(cfg.max_connections)
39        .connect_with(connect_options(cfg))
40        .await?;
41    Ok(pool)
42}
43
44/// 多个命名 MySQL 连接池的容器。
45pub struct MysqlPools {
46    pools: HashMap<String, MySqlPool>,
47}
48
49impl MysqlPools {
50    /// 为配置里声明的每个 `[mysql.<名字>]` 建立连接池。
51    pub async fn from_config(cfg: &Config) -> anyhow::Result<Self> {
52        let mut pools = HashMap::new();
53        for (name, mc) in &cfg.mysql {
54            pools.insert(name.clone(), connect(mc).await?);
55        }
56        Ok(Self { pools })
57    }
58
59    /// 按名取连接池。
60    pub fn get(&self, name: impl IntoMysqlName) -> Option<&MySqlPool> {
61        self.pools.get(&name.into_name())
62    }
63
64    /// 按名取连接池,不存在时报错。
65    pub fn require(&self, name: impl IntoMysqlName) -> anyhow::Result<&MySqlPool> {
66        let name = name.into_name();
67        self.pools
68            .get(&name)
69            .ok_or_else(|| anyhow::anyhow!("未找到名为 `{}` 的 MySQL 连接", name))
70    }
71
72    /// 获取默认连接池(名字为 "default")。
73    pub fn default(&self) -> anyhow::Result<&MySqlPool> {
74        self.require("default")
75    }
76}