use crate::error::DbError;
use crate::mysql::query_builder::QueryBuilder;
use crate::mysql::transaction::Transaction;
use crate::{BackendCapabilities, PoolStatus, MYSQL_CAPABILITIES};
use sqlx::mysql::MySqlPool;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct DatabaseConfig {
pub max_connections: u32,
pub connect_timeout: u64,
pub idle_timeout: u64,
pub enable_logging: bool,
pub min_connections: u32,
pub max_lifetime: Option<u64>,
pub test_before_acquire: bool,
}
impl Default for DatabaseConfig {
fn default() -> Self {
Self {
max_connections: 10,
connect_timeout: 30,
idle_timeout: 600,
enable_logging: false,
min_connections: 0,
max_lifetime: None,
test_before_acquire: false,
}
}
}
impl DatabaseConfig {
pub fn with_max_connections(mut self, n: u32) -> Self {
self.max_connections = n;
self
}
pub fn with_connect_timeout(mut self, secs: u64) -> Self {
self.connect_timeout = secs;
self
}
pub fn with_idle_timeout(mut self, secs: u64) -> Self {
self.idle_timeout = secs;
self
}
pub fn with_enable_logging(mut self, enabled: bool) -> Self {
self.enable_logging = enabled;
self
}
pub fn with_min_connections(mut self, n: u32) -> Self {
self.min_connections = n;
self
}
pub fn with_max_lifetime(mut self, secs: Option<u64>) -> Self {
self.max_lifetime = secs;
self
}
pub fn with_test_before_acquire(mut self, enabled: bool) -> Self {
self.test_before_acquire = enabled;
self
}
pub fn validate(&self) -> std::result::Result<(), DbError> {
if self.max_connections == 0 {
return Err(DbError::InvalidArgument(
"MySQL max_connections 必须大于 0".to_string(),
));
}
if self.min_connections > self.max_connections {
return Err(DbError::InvalidArgument(format!(
"MySQL min_connections({}) 不能大于 max_connections({})",
self.min_connections, self.max_connections
)));
}
if self.connect_timeout == 0 {
return Err(DbError::InvalidArgument(
"MySQL connect_timeout 必须大于 0 秒".to_string(),
));
}
if self.idle_timeout == 0 {
return Err(DbError::InvalidArgument(
"MySQL idle_timeout 必须大于 0 秒".to_string(),
));
}
if self.idle_timeout <= self.connect_timeout {
return Err(DbError::InvalidArgument(format!(
"MySQL idle_timeout({}) 必须大于 connect_timeout({})",
self.idle_timeout, self.connect_timeout
)));
}
if matches!(self.max_lifetime, Some(0)) {
return Err(DbError::InvalidArgument(
"MySQL max_lifetime 为 Some 时必须大于 0 秒".to_string(),
));
}
Ok(())
}
}
pub struct Database {
pool: MySqlPool,
config: DatabaseConfig,
}
impl Clone for Database {
fn clone(&self) -> Self {
Self {
pool: self.pool.clone(),
config: self.config.clone(),
}
}
}
impl Database {
pub const fn capabilities() -> &'static BackendCapabilities {
&MYSQL_CAPABILITIES
}
pub async fn connect(url: &str) -> Result<Self, DbError> {
Self::connect_with_config(url, DatabaseConfig::default()).await
}
pub async fn connect_with_config(url: &str, config: DatabaseConfig) -> Result<Self, DbError> {
use sqlx::mysql::MySqlPoolOptions;
use std::time::Duration;
config.validate()?;
let mut options = MySqlPoolOptions::new()
.max_connections(config.max_connections)
.min_connections(config.min_connections)
.acquire_timeout(Duration::from_secs(config.connect_timeout))
.idle_timeout(Duration::from_secs(config.idle_timeout))
.test_before_acquire(config.test_before_acquire);
if let Some(secs) = config.max_lifetime {
options = options.max_lifetime(Duration::from_secs(secs));
}
let pool = options.connect(url).await?;
Ok(Self { pool, config })
}
pub fn from_pool(pool: MySqlPool, config: DatabaseConfig) -> Result<Self, DbError> {
config.validate()?;
Ok(Self { pool, config })
}
pub fn table(&self, table: &crate::TableRef) -> QueryBuilder<'_> {
QueryBuilder::new(&self.pool, table.as_str(), self.config.enable_logging)
}
pub fn pool(&self) -> &MySqlPool {
&self.pool
}
pub fn pool_status(&self) -> PoolStatus {
PoolStatus {
max_size: self.config.max_connections as usize,
size: self.pool.size() as usize,
available: self.pool.num_idle(),
waiting: 0,
}
}
pub async fn health_check(&self) -> Result<bool, DbError> {
sqlx::query("SELECT 1").execute(&self.pool).await?;
Ok(true)
}
pub async fn close(&self) {
self.pool.close().await;
}
pub fn is_closed(&self) -> bool {
self.pool.is_closed()
}
#[deprecated(
since = "0.1.0",
note = "使用 query_with_params 替代,避免 SQL 注入风险"
)]
pub async fn query<T>(&self, sql: &str) -> Result<Vec<T>, DbError>
where
T: for<'r> sqlx::FromRow<'r, sqlx::mysql::MySqlRow> + Send + Unpin,
{
if self.config.enable_logging {
log::debug!("执行原生查询: {}", sql);
}
let rows = sqlx::query_as::<_, T>(sql).fetch_all(&self.pool).await?;
Ok(rows)
}
#[deprecated(
since = "0.1.0",
note = "使用 execute_with_params 替代,避免 SQL 注入风险"
)]
pub async fn execute(&self, sql: &str) -> Result<u64, DbError> {
if self.config.enable_logging {
log::debug!("执行原生语句: {}", sql);
}
let result = sqlx::query(sql).execute(&self.pool).await?;
Ok(result.rows_affected())
}
pub async fn transaction(&self) -> Result<Transaction, DbError> {
let tx = self.pool.begin().await?;
Ok(Transaction::new(tx, self.config.enable_logging))
}
pub async fn transaction_with_isolation(
&self,
isolation: crate::isolation::IsolationLevel,
) -> Result<Transaction, DbError> {
let sql = format!(
"SET TRANSACTION ISOLATION LEVEL {}; START TRANSACTION",
isolation.as_sql()
);
if self.config.enable_logging {
log::debug!("设置 MySQL 事务隔离级别: {}", sql);
}
let tx = self.pool.begin_with(sql).await?;
Ok(Transaction::new(tx, self.config.enable_logging))
}
pub async fn read_only_transaction(&self) -> Result<Transaction, DbError> {
let tx = self
.pool
.begin_with(
"SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY",
)
.await?;
Ok(Transaction::new(tx, self.config.enable_logging))
}
#[deprecated(
since = "0.1.4",
note = "分号切割无法正确处理存储过程/触发器;请使用逐 migration 语句或专用脚本执行器"
)]
#[allow(deprecated)]
pub async fn init(&self, sql_script: &str) -> Result<(), DbError> {
let statements: Vec<&str> = sql_script
.split(';')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.collect();
for statement in statements {
self.execute(statement).await?;
}
Ok(())
}
#[allow(deprecated)]
pub async fn create_table(&self, create_sql: &str) -> Result<(), DbError> {
self.execute(create_sql).await?;
Ok(())
}
#[allow(deprecated)]
pub async fn drop_table(&self, table_name: &crate::TableRef) -> Result<(), DbError> {
let quoted = crate::mysql::identifier::quote_identifier(table_name.as_str())?;
let sql = format!("DROP TABLE IF EXISTS {}", quoted);
self.execute(&sql).await?;
Ok(())
}
pub async fn table_exists(&self, table_name: &crate::TableRef) -> Result<bool, DbError> {
let sql = "SELECT COUNT(*) as count FROM information_schema.tables \
WHERE table_schema = DATABASE() AND table_name = ?";
let row: (i64,) = sqlx::query_as(sql)
.bind(table_name.as_str())
.fetch_one(&self.pool)
.await?;
Ok(row.0 > 0)
}
pub async fn query_with_params<T>(
&self,
sql: &str,
params: Vec<serde_json::Value>,
) -> Result<Vec<T>, DbError>
where
T: for<'r> sqlx::FromRow<'r, sqlx::mysql::MySqlRow> + Send + Unpin,
{
if self.config.enable_logging {
log::debug!("执行参数化查询: {}, 参数数量: {}", sql, params.len());
}
let mut query = sqlx::query_as::<_, T>(sql);
for param in ¶ms {
query = bind_json_param_as(query, param);
}
let rows = query.fetch_all(&self.pool).await?;
Ok(rows)
}
pub async fn execute_with_params(
&self,
sql: &str,
params: Vec<serde_json::Value>,
) -> Result<u64, DbError> {
if self.config.enable_logging {
log::debug!("执行参数化语句: {}, 参数数量: {}", sql, params.len());
}
let mut query = sqlx::query(sql);
for param in ¶ms {
query = bind_json_param(query, param);
}
let result = query.execute(&self.pool).await?;
Ok(result.rows_affected())
}
}
macro_rules! bind_json_value {
($query:expr, $param:expr) => {
match $param {
serde_json::Value::String(s) => $query.bind(s.clone()),
serde_json::Value::Number(n) => match crate::json_param::classify_json_number(n) {
Some(crate::json_param::JsonNumber::Int(i)) => $query.bind(i),
Some(crate::json_param::JsonNumber::Uint(u)) => $query.bind(u.to_string()),
Some(crate::json_param::JsonNumber::Float(f)) => $query.bind(f.to_string()),
None => $query.bind(Option::<String>::None),
},
serde_json::Value::Bool(b) => $query.bind(*b),
serde_json::Value::Null => $query.bind(Option::<String>::None),
other => $query.bind(other.to_string()),
}
};
}
fn bind_json_param_as<'q, T>(
query: sqlx::query::QueryAs<'q, sqlx::MySql, T, sqlx::mysql::MySqlArguments>,
param: &serde_json::Value,
) -> sqlx::query::QueryAs<'q, sqlx::MySql, T, sqlx::mysql::MySqlArguments>
where
T: for<'r> sqlx::FromRow<'r, sqlx::mysql::MySqlRow>,
{
bind_json_value!(query, param)
}
fn bind_json_param<'q>(
query: sqlx::query::Query<'q, sqlx::MySql, sqlx::mysql::MySqlArguments>,
param: &serde_json::Value,
) -> sqlx::query::Query<'q, sqlx::MySql, sqlx::mysql::MySqlArguments> {
bind_json_value!(query, param)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_database_config_validate_accepts_default_config() {
let config = DatabaseConfig::default();
assert!(config.validate().is_ok());
}
#[test]
fn test_database_config_validate_rejects_invalid_pool_size() {
assert!(matches!(
DatabaseConfig::default().with_max_connections(0).validate(),
Err(DbError::InvalidArgument(_))
));
assert!(matches!(
DatabaseConfig::default()
.with_max_connections(2)
.with_min_connections(3)
.validate(),
Err(DbError::InvalidArgument(_))
));
}
#[test]
fn test_database_config_validate_rejects_invalid_timeouts() {
for config in [
DatabaseConfig::default().with_connect_timeout(0),
DatabaseConfig::default().with_idle_timeout(0),
DatabaseConfig::default().with_max_lifetime(Some(0)),
] {
assert!(matches!(
config.validate(),
Err(DbError::InvalidArgument(_))
));
}
assert!(matches!(
DatabaseConfig::default()
.with_connect_timeout(30)
.with_idle_timeout(30)
.validate(),
Err(DbError::InvalidArgument(_))
));
}
#[tokio::test]
async fn test_connect_with_config_rejects_invalid_config_before_connecting() {
let config = DatabaseConfig::default().with_max_connections(0);
let result =
Database::connect_with_config("mysql://root:bad@127.0.0.1:1/test", config).await;
assert!(matches!(result, Err(DbError::InvalidArgument(_))));
}
#[tokio::test]
async fn health_check_propagates_closed_pool_error() -> Result<(), sqlx::Error> {
let pool = sqlx::mysql::MySqlPoolOptions::new()
.connect_lazy("mysql://root:test@127.0.0.1:3306/test")?;
let db = Database {
pool,
config: DatabaseConfig::default(),
};
db.close().await;
assert!(db.is_closed());
assert!(matches!(db.health_check().await, Err(DbError::PoolClosed)));
Ok(())
}
}