use crate::datasource::DatasourceId;
use crate::error::BaseError;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use yang_db::{
BackendCapabilities, BackendCapability, BackendKind, DbError, PoolStatus, SqlErrorKind,
};
#[derive(Clone)]
#[non_exhaustive]
pub struct AnyDatabase {
id: DatasourceId,
inner: AnyDatabaseKind,
}
#[allow(clippy::large_enum_variant)]
#[derive(Clone)]
enum AnyDatabaseKind {
#[cfg(feature = "mysql")]
MySql(yang_db::mysql::Database),
#[cfg(feature = "postgres")]
PostgreSql(yang_db::postgres::Database),
}
impl std::fmt::Debug for AnyDatabase {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("AnyDatabase")
.field("backend", &self.backend())
.field("closed", &self.is_closed())
.finish()
}
}
impl AnyDatabase {
#[cfg(feature = "mysql")]
pub fn mysql(database: yang_db::mysql::Database) -> Self {
Self::mysql_on(DatasourceId::default_source(), database)
}
#[cfg(feature = "mysql")]
pub(crate) fn mysql_on(id: DatasourceId, database: yang_db::mysql::Database) -> Self {
Self {
id,
inner: AnyDatabaseKind::MySql(database),
}
}
#[cfg(feature = "postgres")]
pub fn postgres(database: yang_db::postgres::Database) -> Self {
Self::postgres_on(DatasourceId::default_source(), database)
}
#[cfg(feature = "postgres")]
pub(crate) fn postgres_on(id: DatasourceId, database: yang_db::postgres::Database) -> Self {
Self {
id,
inner: AnyDatabaseKind::PostgreSql(database),
}
}
pub fn id(&self) -> &DatasourceId {
&self.id
}
#[must_use]
pub(crate) fn with_id(mut self, id: DatasourceId) -> Self {
self.id = id;
self
}
pub fn backend(&self) -> BackendKind {
match &self.inner {
#[cfg(feature = "mysql")]
AnyDatabaseKind::MySql(_) => BackendKind::MySql,
#[cfg(feature = "postgres")]
AnyDatabaseKind::PostgreSql(_) => BackendKind::PostgreSql,
}
}
pub fn capabilities(&self) -> &'static BackendCapabilities {
match &self.inner {
#[cfg(feature = "mysql")]
AnyDatabaseKind::MySql(_) => yang_db::mysql::Database::capabilities(),
#[cfg(feature = "postgres")]
AnyDatabaseKind::PostgreSql(_) => yang_db::postgres::Database::capabilities(),
}
}
pub fn require_capabilities(&self, required: &[BackendCapability]) -> Result<(), BaseError> {
let capabilities = self.capabilities();
for capability in required {
if !capabilities.supports(*capability) {
return Err(BaseError::UnsupportedCapability(format!(
"后端 {:?} 缺少必需能力: {capability:?}",
self.backend()
)));
}
}
Ok(())
}
pub fn is_closed(&self) -> bool {
match &self.inner {
#[cfg(feature = "mysql")]
AnyDatabaseKind::MySql(database) => database.is_closed(),
#[cfg(feature = "postgres")]
AnyDatabaseKind::PostgreSql(database) => database.is_closed(),
}
}
pub async fn health_check(&self) -> Result<bool, DbError> {
match &self.inner {
#[cfg(feature = "mysql")]
AnyDatabaseKind::MySql(database) => database.health_check().await,
#[cfg(feature = "postgres")]
AnyDatabaseKind::PostgreSql(database) => database.health_check().await,
}
}
pub async fn close(&self) {
match &self.inner {
#[cfg(feature = "mysql")]
AnyDatabaseKind::MySql(database) => database.close().await,
#[cfg(feature = "postgres")]
AnyDatabaseKind::PostgreSql(database) => database.close().await,
}
}
pub fn pool_status(&self) -> PoolStatus {
match &self.inner {
#[cfg(feature = "mysql")]
AnyDatabaseKind::MySql(database) => database.pool_status(),
#[cfg(feature = "postgres")]
AnyDatabaseKind::PostgreSql(database) => database.pool_status(),
}
}
#[cfg(feature = "mysql")]
pub fn as_mysql(&self) -> Option<&yang_db::mysql::Database> {
match &self.inner {
AnyDatabaseKind::MySql(database) => Some(database),
#[cfg(feature = "postgres")]
AnyDatabaseKind::PostgreSql(_) => None,
}
}
#[cfg(feature = "postgres")]
pub fn as_postgres(&self) -> Option<&yang_db::postgres::Database> {
match &self.inner {
#[cfg(feature = "mysql")]
AnyDatabaseKind::MySql(_) => None,
AnyDatabaseKind::PostgreSql(database) => Some(database),
}
}
pub fn pool(&self) -> AnyPool {
match &self.inner {
#[cfg(feature = "mysql")]
AnyDatabaseKind::MySql(database) => AnyPool::MySql(Arc::new(database.pool().clone())),
#[cfg(feature = "postgres")]
AnyDatabaseKind::PostgreSql(database) => {
AnyPool::Postgres(Arc::new(database.pool().clone()))
}
}
}
pub fn source_pool(&self) -> PoolHandle {
PoolHandle {
source: self.id.clone(),
pool: self.pool(),
}
}
pub async fn begin(&self) -> Result<AnyTransaction, DbError> {
match &self.inner {
#[cfg(feature = "mysql")]
AnyDatabaseKind::MySql(database) => database
.transaction()
.await
.map(|transaction| AnyTransaction::MySql(transaction).with_source(self.id.clone())),
#[cfg(feature = "postgres")]
AnyDatabaseKind::PostgreSql(database) => {
database.transaction().await.map(|transaction| {
AnyTransaction::Postgres(transaction).with_source(self.id.clone())
})
}
}
}
pub async fn retry_transaction<T, F, Fut>(
&self,
max_attempts: u32,
backoff: Duration,
mut operation: F,
) -> Result<T, DbError>
where
F: FnMut() -> Fut,
Fut: Future<Output = Result<T, DbError>>,
{
let max_attempts = max_attempts.max(1);
let mut attempt = 1u32;
loop {
match operation().await {
Ok(value) => return Ok(value),
Err(error) if attempt < max_attempts && is_retryable_transaction_error(&error) => {
let delay = backoff.saturating_mul(1u32 << (attempt - 1).min(5));
if !delay.is_zero() {
tokio::time::sleep(delay).await;
}
attempt += 1;
}
Err(error) => return Err(error),
}
}
}
}
fn is_retryable_transaction_error(error: &DbError) -> bool {
matches!(
error.sql_error().map(|info| info.kind()),
Some(SqlErrorKind::SerializationFailure | SqlErrorKind::DeadlockDetected)
)
}
#[derive(Clone)]
pub enum AnyPool {
#[cfg(feature = "mysql")]
MySql(Arc<sqlx::MySqlPool>),
#[cfg(feature = "postgres")]
Postgres(Arc<sqlx::PgPool>),
}
impl std::fmt::Debug for AnyPool {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_tuple("AnyPool")
.field(&self.backend())
.finish()
}
}
impl AnyPool {
pub fn backend(&self) -> BackendKind {
match self {
#[cfg(feature = "mysql")]
Self::MySql(_) => BackendKind::MySql,
#[cfg(feature = "postgres")]
Self::Postgres(_) => BackendKind::PostgreSql,
}
}
#[cfg(feature = "mysql")]
pub fn as_mysql(&self) -> Option<&sqlx::MySqlPool> {
match self {
Self::MySql(pool) => Some(pool.as_ref()),
#[cfg(feature = "postgres")]
Self::Postgres(_) => None,
}
}
#[cfg(feature = "postgres")]
pub fn as_postgres(&self) -> Option<&sqlx::PgPool> {
match self {
#[cfg(feature = "mysql")]
Self::MySql(_) => None,
Self::Postgres(pool) => Some(pool.as_ref()),
}
}
}
#[derive(Clone)]
pub struct PoolHandle {
source: DatasourceId,
pool: AnyPool,
}
impl std::fmt::Debug for PoolHandle {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("PoolHandle")
.field("source", &self.source)
.field("backend", &self.pool.backend())
.finish()
}
}
impl PoolHandle {
pub(crate) fn new(source: DatasourceId, pool: AnyPool) -> Self {
Self { source, pool }
}
pub fn source(&self) -> &DatasourceId {
&self.source
}
pub fn pool(&self) -> &AnyPool {
&self.pool
}
pub fn backend(&self) -> BackendKind {
self.pool.backend()
}
}
pub struct AnyTransaction {
source: Option<DatasourceId>,
kind: AnyTransactionKind,
}
impl std::fmt::Debug for AnyTransaction {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("AnyTransaction")
.field("source", &self.source)
.field("backend", &self.backend())
.finish()
}
}
pub(crate) enum AnyTransactionKind {
#[cfg(feature = "mysql")]
MySql(yang_db::mysql::Transaction),
#[cfg(feature = "postgres")]
Postgres(yang_db::postgres::Transaction),
}
impl AnyTransaction {
#[cfg(feature = "mysql")]
#[allow(non_snake_case)]
pub fn MySql(transaction: yang_db::mysql::Transaction) -> Self {
Self {
source: None,
kind: AnyTransactionKind::MySql(transaction),
}
}
#[cfg(feature = "postgres")]
#[allow(non_snake_case)]
pub fn Postgres(transaction: yang_db::postgres::Transaction) -> Self {
Self {
source: None,
kind: AnyTransactionKind::Postgres(transaction),
}
}
#[must_use]
pub(crate) fn with_source(mut self, source: DatasourceId) -> Self {
self.source = Some(source);
self
}
pub fn source(&self) -> Option<&DatasourceId> {
self.source.as_ref()
}
pub fn backend(&self) -> BackendKind {
match &self.kind {
#[cfg(feature = "mysql")]
AnyTransactionKind::MySql(_) => BackendKind::MySql,
#[cfg(feature = "postgres")]
AnyTransactionKind::Postgres(_) => BackendKind::PostgreSql,
}
}
pub(crate) fn kind_mut(&mut self) -> &mut AnyTransactionKind {
&mut self.kind
}
#[cfg(feature = "mysql")]
pub fn as_mysql(&mut self) -> Option<&mut yang_db::mysql::Transaction> {
match &mut self.kind {
AnyTransactionKind::MySql(transaction) => Some(transaction),
#[cfg(feature = "postgres")]
AnyTransactionKind::Postgres(_) => None,
}
}
#[cfg(feature = "postgres")]
pub fn as_postgres(&mut self) -> Option<&mut yang_db::postgres::Transaction> {
match &mut self.kind {
#[cfg(feature = "mysql")]
AnyTransactionKind::MySql(_) => None,
AnyTransactionKind::Postgres(transaction) => Some(transaction),
}
}
pub async fn commit(self) -> Result<(), DbError> {
match self.kind {
#[cfg(feature = "mysql")]
AnyTransactionKind::MySql(transaction) => transaction.commit().await,
#[cfg(feature = "postgres")]
AnyTransactionKind::Postgres(transaction) => transaction.commit().await,
}
}
pub async fn savepoint(&mut self, name: &str) -> Result<(), DbError> {
match &mut self.kind {
#[cfg(feature = "mysql")]
AnyTransactionKind::MySql(transaction) => {
let sql = mysql_savepoint_statement("SAVEPOINT", name)?;
mysql_execute_control(transaction, &sql).await
}
#[cfg(feature = "postgres")]
AnyTransactionKind::Postgres(transaction) => transaction.savepoint(name).await,
}
}
pub async fn rollback_to(&mut self, name: &str) -> Result<(), DbError> {
match &mut self.kind {
#[cfg(feature = "mysql")]
AnyTransactionKind::MySql(transaction) => {
let sql = mysql_savepoint_statement("ROLLBACK TO SAVEPOINT", name)?;
mysql_execute_control(transaction, &sql).await
}
#[cfg(feature = "postgres")]
AnyTransactionKind::Postgres(transaction) => transaction.rollback_to(name).await,
}
}
pub async fn release(&mut self, name: &str) -> Result<(), DbError> {
match &mut self.kind {
#[cfg(feature = "mysql")]
AnyTransactionKind::MySql(transaction) => {
let sql = mysql_savepoint_statement("RELEASE SAVEPOINT", name)?;
mysql_execute_control(transaction, &sql).await
}
#[cfg(feature = "postgres")]
AnyTransactionKind::Postgres(transaction) => transaction.release_savepoint(name).await,
}
}
pub async fn rollback(self) -> Result<(), DbError> {
match self.kind {
#[cfg(feature = "mysql")]
AnyTransactionKind::MySql(transaction) => transaction.rollback().await,
#[cfg(feature = "postgres")]
AnyTransactionKind::Postgres(transaction) => transaction.rollback().await,
}
}
}
#[cfg(feature = "mysql")]
fn mysql_savepoint_statement(keyword: &str, name: &str) -> Result<String, DbError> {
let valid = !name.is_empty()
&& name.len() <= 128
&& name.bytes().enumerate().all(|(index, byte)| {
if index == 0 {
byte == b'_' || byte.is_ascii_alphabetic()
} else {
byte == b'_' || byte.is_ascii_alphanumeric()
}
});
if !valid {
return Err(DbError::InvalidArgument(format!(
"MySQL 保存点名非法: {name:?}(1..=128 字节,字母/下划线开头,仅字母/数字/下划线)"
)));
}
Ok(format!("{keyword} {name}"))
}
#[cfg(feature = "mysql")]
async fn mysql_execute_control(
transaction: &mut yang_db::mysql::Transaction,
sql: &str,
) -> Result<(), DbError> {
let connection = transaction
.executor()
.ok_or_else(|| DbError::TransactionError("事务已提交或回滚".to_string()))?;
sqlx::query(sql).execute(connection).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "mysql")]
fn mysql_database() -> AnyDatabase {
let pool = sqlx::MySqlPool::connect_lazy("mysql://root:test@127.0.0.1:3306/test")
.expect("惰性 MySQL 连接池应创建成功");
let database =
yang_db::mysql::Database::from_pool(pool, yang_db::mysql::DatabaseConfig::default())
.expect("默认 MySQL 配置应通过校验");
AnyDatabase::mysql(database)
}
#[cfg(feature = "postgres")]
fn postgres_database() -> AnyDatabase {
let pool = sqlx::PgPool::connect_lazy("postgres://postgres:postgres@127.0.0.1:55432/test")
.expect("惰性 PostgreSQL 连接池应创建成功");
let database = yang_db::postgres::Database::from_pool(
pool,
yang_db::postgres::DatabaseConfig::default(),
)
.expect("默认 PostgreSQL 配置应通过校验");
AnyDatabase::postgres(database)
}
#[cfg(feature = "mysql")]
#[tokio::test]
async fn mysql_backend_exposes_identity_capabilities_and_downcast() {
let database = mysql_database();
assert_eq!(database.backend(), BackendKind::MySql);
assert!(database.capabilities().relational);
assert!(database.as_mysql().is_some());
assert!(!database.is_closed());
assert_eq!(
database.pool_status().max_size,
yang_db::mysql::DatabaseConfig::default().max_connections as usize
);
database.close().await;
assert!(database.is_closed());
}
#[cfg(feature = "postgres")]
#[tokio::test]
async fn postgres_backend_exposes_identity_capabilities_and_downcast() {
let database = postgres_database();
assert_eq!(database.backend(), BackendKind::PostgreSql);
assert!(database.capabilities().relational);
assert!(database.as_postgres().is_some());
assert!(!database.is_closed());
assert_eq!(
database.pool_status().max_size,
yang_db::postgres::DatabaseConfig::default().max_connections as usize
);
database.close().await;
assert!(database.is_closed());
}
#[cfg(all(feature = "mysql", feature = "postgres"))]
#[tokio::test]
async fn downcasts_are_backend_exclusive() {
let mysql = mysql_database();
let postgres = postgres_database();
assert!(mysql.as_postgres().is_none());
assert!(postgres.as_mysql().is_none());
mysql.close().await;
postgres.close().await;
}
#[cfg(feature = "mysql")]
#[tokio::test]
async fn mysql_pool_view_keeps_backend_identity() {
let database = mysql_database();
let pool = database.pool();
assert_eq!(pool.backend(), BackendKind::MySql);
assert!(pool.as_mysql().is_some());
#[cfg(feature = "postgres")]
assert!(pool.as_postgres().is_none());
}
#[cfg(feature = "postgres")]
#[tokio::test]
async fn postgres_pool_view_keeps_backend_identity() {
let database = postgres_database();
let pool = database.pool();
assert_eq!(pool.backend(), BackendKind::PostgreSql);
assert!(pool.as_postgres().is_some());
#[cfg(feature = "mysql")]
assert!(pool.as_mysql().is_none());
}
#[cfg(feature = "mysql")]
#[tokio::test]
async fn require_capabilities_reports_missing_capability_by_name() {
let database = mysql_database();
database
.require_capabilities(&[BackendCapability::Select, BackendCapability::Insert])
.expect("MySQL 应支持基础 CRUD 能力");
let error = database
.require_capabilities(&[BackendCapability::Savepoint])
.expect_err("MySQL 能力矩阵未声明 Savepoint,应 fail-fast");
assert!(matches!(error, BaseError::UnsupportedCapability(_)));
assert!(
error.to_string().contains("Savepoint"),
"错误消息应包含缺失能力名,实得: {error}"
);
}
#[cfg(feature = "postgres")]
#[tokio::test]
async fn postgres_declares_savepoint_capability() {
let database = postgres_database();
database
.require_capabilities(&[BackendCapability::Savepoint])
.expect("PostgreSQL 应声明保存点能力");
}
fn retryable_error() -> DbError {
sqlstate_error(
"40001",
"could not serialize access due to concurrent update",
)
}
fn sqlstate_error(code: &str, message: &str) -> DbError {
DbError::DatabaseError(Box::new(yang_db::SqlErrorInfo::new(code, message)))
}
fn non_retryable_error() -> DbError {
DbError::QueryError("syntax error".to_string())
}
#[tokio::test]
async fn retry_transaction_retries_retryable_errors() {
let database = instantiate_for_retry();
let mut attempts = 0;
let result = database
.retry_transaction(3, Duration::ZERO, || {
attempts += 1;
let attempt = attempts;
async move {
if attempt < 3 {
Err(retryable_error())
} else {
Ok(attempt)
}
}
})
.await;
assert_eq!(result.expect("第三次应成功"), 3);
assert_eq!(attempts, 3);
}
#[tokio::test]
async fn retry_transaction_returns_non_retryable_error_immediately() {
let database = instantiate_for_retry();
let mut attempts = 0;
let error = database
.retry_transaction(5, Duration::ZERO, || {
attempts += 1;
async move { Err::<(), _>(non_retryable_error()) }
})
.await
.expect_err("不可重试错误应直接返回");
assert!(matches!(error, DbError::QueryError(_)));
assert_eq!(attempts, 1);
}
#[tokio::test]
async fn retry_transaction_stops_after_max_attempts() {
let database = instantiate_for_retry();
let mut attempts = 0;
let error = database
.retry_transaction(2, Duration::ZERO, || {
attempts += 1;
async move { Err::<(), _>(retryable_error()) }
})
.await
.expect_err("用尽次数后应返回错误");
assert!(error.is_retryable());
assert_eq!(attempts, 2);
}
#[tokio::test]
async fn retry_transaction_retries_deadlock() {
let database = instantiate_for_retry();
let mut attempts = 0;
let result = database
.retry_transaction(3, Duration::ZERO, || {
attempts += 1;
let attempt = attempts;
async move {
if attempt < 3 {
Err(sqlstate_error("40P01", "deadlock detected"))
} else {
Ok(attempt)
}
}
})
.await;
assert_eq!(result.expect("第三次应成功"), 3);
assert_eq!(attempts, 3);
}
#[tokio::test]
async fn retry_transaction_does_not_retry_unique_violation() {
let database = instantiate_for_retry();
let mut attempts = 0;
let error = database
.retry_transaction(5, Duration::ZERO, || {
attempts += 1;
async move { Err::<(), _>(sqlstate_error("23505", "duplicate key value")) }
})
.await
.expect_err("唯一约束冲突不应重试");
assert_eq!(error.sqlstate(), Some("23505"));
assert_eq!(attempts, 1);
}
#[tokio::test]
async fn retry_transaction_does_not_retry_connection_errors() {
let database = instantiate_for_retry();
let mut attempts = 0;
let error = database
.retry_transaction(5, Duration::ZERO, || {
attempts += 1;
async move {
Err::<(), _>(DbError::ConnectionError(
"connection closed during commit".to_string(),
))
}
})
.await
.expect_err("连接错误不应重试");
assert!(matches!(error, DbError::ConnectionError(_)));
assert_eq!(attempts, 1);
}
#[tokio::test]
async fn retry_transaction_does_not_retry_connection_class_sqlstate() {
let database = instantiate_for_retry();
let mut attempts = 0;
let error = database
.retry_transaction(5, Duration::ZERO, || {
attempts += 1;
async move { Err::<(), _>(sqlstate_error("08006", "connection failure")) }
})
.await
.expect_err("08 类连接失败不应重试");
assert_eq!(error.sqlstate(), Some("08006"));
assert_eq!(attempts, 1);
}
#[tokio::test]
async fn retry_transaction_zero_max_attempts_runs_once() {
let database = instantiate_for_retry();
let mut attempts = 0;
let error = database
.retry_transaction(0, Duration::ZERO, || {
attempts += 1;
async move { Err::<(), _>(retryable_error()) }
})
.await
.expect_err("零次数仍应执行一次并返回错误");
assert!(error.is_retryable());
assert_eq!(attempts, 1);
}
fn instantiate_for_retry() -> AnyDatabase {
#[cfg(feature = "mysql")]
{
mysql_database()
}
#[cfg(all(feature = "postgres", not(feature = "mysql")))]
{
postgres_database()
}
}
#[cfg(feature = "mysql")]
#[test]
fn mysql_savepoint_statement_validates_names() {
assert_eq!(
mysql_savepoint_statement("SAVEPOINT", "sp_1").expect("合法名称应通过"),
"SAVEPOINT sp_1"
);
for invalid in ["", "1sp", "sp-1", "sp; DROP TABLE t", "名字"] {
assert!(
matches!(
mysql_savepoint_statement("SAVEPOINT", invalid),
Err(DbError::InvalidArgument(_))
),
"非法保存点名 {invalid:?} 应被拒绝"
);
}
}
}