loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
use std::{fmt, str::FromStr};

use sqlx::mysql::MySqlConnectOptions;

use super::{
    BoxConnectionFuture, Close, Connect, ConnectionError, ConnectionSpec, PoolOptions, Verify,
};

#[cfg(not(feature = "logging"))]
pub use sqlx::MySqlPool;
/// 启用日志功能时,默认记录 SQLx 失败的 MySQL 连接池。
#[cfg(feature = "logging")]
pub type MySqlPool = super::SqlLoggingPool<sqlx::MySql>;

/// `MySQL` 连接器默认使用的北京时间偏移量。
pub const DEFAULT_MYSQL_TIME_ZONE: &str = "+08:00";

/// `MySQL` 连接器默认使用的会话 `SQL Mode`。
pub const DEFAULT_MYSQL_SQL_MODE: &str = "ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION";

/// `MySQL` 连接池连接器。
#[derive(Clone)]
#[must_use = "连接器配置需要传给 connect 才会生效"]
pub struct MySqlConnector {
    name: String,
    enabled: bool,
    url: String,
    pool_options: PoolOptions,
    time_zone: Option<String>,
    sql_mode: Option<String>,
}

impl MySqlConnector {
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            name: "mysql".to_owned(),
            enabled: true,
            url: url.into(),
            pool_options: PoolOptions::default(),
            time_zone: Some(DEFAULT_MYSQL_TIME_ZONE.to_owned()),
            sql_mode: Some(DEFAULT_MYSQL_SQL_MODE.to_owned()),
        }
    }

    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    pub const fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    pub const fn with_pool_options(mut self, pool_options: PoolOptions) -> Self {
        self.pool_options = pool_options;
        self
    }

    pub fn with_time_zone(mut self, time_zone: impl Into<String>) -> Self {
        let time_zone = time_zone.into();
        // 空配置通常来自可选环境变量,此时继续使用北京时间。
        self.time_zone = Some(if time_zone.trim().is_empty() {
            DEFAULT_MYSQL_TIME_ZONE.to_owned()
        } else {
            time_zone
        });
        self
    }

    /// 不设置会话时区,完全沿用 `MySQL` 服务端配置。
    pub fn without_time_zone(mut self) -> Self {
        self.time_zone = None;
        self
    }

    pub fn with_sql_mode(mut self, sql_mode: impl Into<String>) -> Self {
        let sql_mode = sql_mode.into();
        // 空配置通常来自可选环境变量,此时继续使用安全的默认严格模式。
        self.sql_mode = Some(if sql_mode.trim().is_empty() {
            DEFAULT_MYSQL_SQL_MODE.to_owned()
        } else {
            sql_mode
        });
        self
    }

    /// 不设置会话 `SQL Mode`,完全沿用 `MySQL` 服务端配置。
    pub fn without_sql_mode(mut self) -> Self {
        self.sql_mode = None;
        self
    }
}

impl fmt::Debug for MySqlConnector {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("MySqlConnector")
            .field("name", &self.name)
            .field("enabled", &self.enabled)
            .field("url", &"[已隐藏]")
            .field("pool_options", &self.pool_options)
            .field("time_zone", &self.time_zone)
            .field("sql_mode", &self.sql_mode)
            .finish()
    }
}

impl ConnectionSpec for MySqlConnector {
    type Connection = MySqlPool;
    type Error = ConnectionError;

    fn name(&self) -> &str {
        &self.name
    }

    fn enabled(&self) -> bool {
        self.enabled
    }
}

impl Connect for MySqlConnector {
    fn connect(&self) -> BoxConnectionFuture<'_, Self::Connection, Self::Error> {
        Box::pin(async move {
            let pool_options = self.pool_options.validate()?;
            let options = MySqlConnectOptions::from_str(&self.url)?;
            let mut builder = sqlx::mysql::MySqlPoolOptions::new()
                .min_connections(pool_options.min_connections)
                .max_connections(pool_options.max_connections)
                .acquire_timeout(pool_options.acquire_timeout);

            if self.time_zone.is_some() || self.sql_mode.is_some() {
                let time_zone = self.time_zone.clone();
                let sql_mode = self.sql_mode.clone();
                builder = builder.after_connect(move |connection, _metadata| {
                    let time_zone = time_zone.clone();
                    let sql_mode = sql_mode.clone();
                    Box::pin(async move {
                        if let Some(time_zone) = time_zone {
                            sqlx::query("SET time_zone = ?")
                                .bind(time_zone)
                                .execute(&mut *connection)
                                .await?;
                        }
                        if let Some(sql_mode) = sql_mode {
                            sqlx::query("SET SESSION sql_mode = ?")
                                .bind(sql_mode)
                                .execute(&mut *connection)
                                .await?;
                        }
                        Ok(())
                    })
                });
            }

            let pool = builder.connect_with(options).await?;
            Ok(pool.into())
        })
    }
}

impl Verify for MySqlConnector {
    fn verify<'a>(
        &'a self,
        connection: &'a Self::Connection,
    ) -> BoxConnectionFuture<'a, (), Self::Error> {
        Box::pin(async move {
            sqlx::query("SELECT 1").execute(connection).await?;
            Ok(())
        })
    }
}

impl Close for MySqlConnector {
    fn close(&self, connection: Self::Connection) -> BoxConnectionFuture<'_, (), Self::Error> {
        Box::pin(async move {
            connection.close().await;
            Ok(())
        })
    }
}

#[cfg(test)]
mod tests {
    use super::{DEFAULT_MYSQL_SQL_MODE, DEFAULT_MYSQL_TIME_ZONE, MySqlConnector};

    #[test]
    fn 默认使用北京时间() {
        let connector = MySqlConnector::new("mysql://127.0.0.1/app");

        assert_eq!(
            connector.time_zone.as_deref(),
            Some(DEFAULT_MYSQL_TIME_ZONE)
        );
    }

    #[test]
    fn 空时区回退到北京时间() {
        for time_zone in ["", "   ", "\n\t"] {
            let connector = MySqlConnector::new("mysql://127.0.0.1/app").with_time_zone(time_zone);

            assert_eq!(
                connector.time_zone.as_deref(),
                Some(DEFAULT_MYSQL_TIME_ZONE)
            );
        }
    }

    #[test]
    fn 可以显式沿用服务端时区() {
        let connector = MySqlConnector::new("mysql://127.0.0.1/app").without_time_zone();

        assert_eq!(connector.time_zone, None);
    }

    #[test]
    fn 默认使用严格_sql_mode() {
        let connector = MySqlConnector::new("mysql://127.0.0.1/app");

        assert_eq!(connector.sql_mode.as_deref(), Some(DEFAULT_MYSQL_SQL_MODE));
    }

    #[test]
    fn 空_sql_mode_回退到默认值() {
        for sql_mode in ["", "   ", "\n\t"] {
            let connector = MySqlConnector::new("mysql://127.0.0.1/app").with_sql_mode(sql_mode);

            assert_eq!(connector.sql_mode.as_deref(), Some(DEFAULT_MYSQL_SQL_MODE));
        }
    }

    #[test]
    fn 可以显式沿用服务端_sql_mode() {
        let connector = MySqlConnector::new("mysql://127.0.0.1/app").without_sql_mode();

        assert_eq!(connector.sql_mode, None);
    }
}