loveyu-kit 0.2.0

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

use sqlx::postgres::PgConnectOptions;

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

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

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

impl PostgresConnector {
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            name: "pgsql".to_owned(),
            enabled: true,
            url: url.into(),
            pool_options: PoolOptions::default(),
        }
    }

    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
    }
}

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

impl ConnectionSpec for PostgresConnector {
    type Connection = PgPool;
    type Error = ConnectionError;

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

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

impl Connect for PostgresConnector {
    fn connect(&self) -> BoxConnectionFuture<'_, Self::Connection, Self::Error> {
        Box::pin(async move {
            let pool_options = self.pool_options.validate()?;
            let options = PgConnectOptions::from_str(&self.url)?;
            let pool = sqlx::postgres::PgPoolOptions::new()
                .min_connections(pool_options.min_connections)
                .max_connections(pool_options.max_connections)
                .acquire_timeout(pool_options.acquire_timeout)
                .connect_with(options)
                .await?;
            Ok(pool.into())
        })
    }
}

impl Verify for PostgresConnector {
    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 PostgresConnector {
    fn close(&self, connection: Self::Connection) -> BoxConnectionFuture<'_, (), Self::Error> {
        Box::pin(async move {
            connection.close().await;
            Ok(())
        })
    }
}