1use crate::error::BaseError;
12use std::future::Future;
13use std::sync::Arc;
14use std::time::Duration;
15use yang_db::{
16 BackendCapabilities, BackendCapability, BackendKind, DbError, PoolStatus, SqlErrorKind,
17};
18
19#[non_exhaustive]
24pub struct AnyDatabase {
25 inner: AnyDatabaseKind,
26}
27
28#[allow(clippy::large_enum_variant)]
34enum AnyDatabaseKind {
35 #[cfg(feature = "mysql")]
36 MySql(yang_db::mysql::Database),
37 #[cfg(feature = "postgres")]
38 PostgreSql(yang_db::postgres::Database),
39}
40
41impl std::fmt::Debug for AnyDatabase {
42 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 formatter
44 .debug_struct("AnyDatabase")
45 .field("backend", &self.backend())
46 .field("closed", &self.is_closed())
47 .finish()
48 }
49}
50
51impl AnyDatabase {
52 #[cfg(feature = "mysql")]
54 pub fn mysql(database: yang_db::mysql::Database) -> Self {
55 Self {
56 inner: AnyDatabaseKind::MySql(database),
57 }
58 }
59
60 #[cfg(feature = "postgres")]
62 pub fn postgres(database: yang_db::postgres::Database) -> Self {
63 Self {
64 inner: AnyDatabaseKind::PostgreSql(database),
65 }
66 }
67
68 pub fn backend(&self) -> BackendKind {
70 match &self.inner {
71 #[cfg(feature = "mysql")]
72 AnyDatabaseKind::MySql(_) => BackendKind::MySql,
73 #[cfg(feature = "postgres")]
74 AnyDatabaseKind::PostgreSql(_) => BackendKind::PostgreSql,
75 }
76 }
77
78 pub fn capabilities(&self) -> &'static BackendCapabilities {
80 match &self.inner {
81 #[cfg(feature = "mysql")]
82 AnyDatabaseKind::MySql(_) => yang_db::mysql::Database::capabilities(),
83 #[cfg(feature = "postgres")]
84 AnyDatabaseKind::PostgreSql(_) => yang_db::postgres::Database::capabilities(),
85 }
86 }
87
88 pub fn require_capabilities(&self, required: &[BackendCapability]) -> Result<(), BaseError> {
104 let capabilities = self.capabilities();
105 for capability in required {
106 if !capabilities.supports(*capability) {
107 return Err(BaseError::UnsupportedCapability(format!(
108 "后端 {:?} 缺少必需能力: {capability:?}",
109 self.backend()
110 )));
111 }
112 }
113 Ok(())
114 }
115
116 pub fn is_closed(&self) -> bool {
118 match &self.inner {
119 #[cfg(feature = "mysql")]
120 AnyDatabaseKind::MySql(database) => database.is_closed(),
121 #[cfg(feature = "postgres")]
122 AnyDatabaseKind::PostgreSql(database) => database.is_closed(),
123 }
124 }
125
126 pub async fn health_check(&self) -> Result<bool, DbError> {
128 match &self.inner {
129 #[cfg(feature = "mysql")]
130 AnyDatabaseKind::MySql(database) => database.health_check().await,
131 #[cfg(feature = "postgres")]
132 AnyDatabaseKind::PostgreSql(database) => database.health_check().await,
133 }
134 }
135
136 pub async fn close(&self) {
138 match &self.inner {
139 #[cfg(feature = "mysql")]
140 AnyDatabaseKind::MySql(database) => database.close().await,
141 #[cfg(feature = "postgres")]
142 AnyDatabaseKind::PostgreSql(database) => database.close().await,
143 }
144 }
145
146 pub fn pool_status(&self) -> PoolStatus {
148 match &self.inner {
149 #[cfg(feature = "mysql")]
150 AnyDatabaseKind::MySql(database) => database.pool_status(),
151 #[cfg(feature = "postgres")]
152 AnyDatabaseKind::PostgreSql(database) => database.pool_status(),
153 }
154 }
155
156 #[cfg(feature = "mysql")]
158 pub fn as_mysql(&self) -> Option<&yang_db::mysql::Database> {
159 match &self.inner {
160 AnyDatabaseKind::MySql(database) => Some(database),
161 #[cfg(feature = "postgres")]
162 AnyDatabaseKind::PostgreSql(_) => None,
163 }
164 }
165
166 #[cfg(feature = "postgres")]
168 pub fn as_postgres(&self) -> Option<&yang_db::postgres::Database> {
169 match &self.inner {
170 #[cfg(feature = "mysql")]
171 AnyDatabaseKind::MySql(_) => None,
172 AnyDatabaseKind::PostgreSql(database) => Some(database),
173 }
174 }
175
176 pub fn pool(&self) -> AnyPool {
181 match &self.inner {
182 #[cfg(feature = "mysql")]
183 AnyDatabaseKind::MySql(database) => AnyPool::MySql(Arc::new(database.pool().clone())),
184 #[cfg(feature = "postgres")]
185 AnyDatabaseKind::PostgreSql(database) => {
186 AnyPool::Postgres(Arc::new(database.pool().clone()))
187 }
188 }
189 }
190
191 pub async fn begin(&self) -> Result<AnyTransaction, DbError> {
197 match &self.inner {
198 #[cfg(feature = "mysql")]
199 AnyDatabaseKind::MySql(database) => {
200 database.transaction().await.map(AnyTransaction::MySql)
201 }
202 #[cfg(feature = "postgres")]
203 AnyDatabaseKind::PostgreSql(database) => {
204 database.transaction().await.map(AnyTransaction::Postgres)
205 }
206 }
207 }
208
209 pub async fn retry_transaction<T, F, Fut>(
234 &self,
235 max_attempts: u32,
236 backoff: Duration,
237 mut operation: F,
238 ) -> Result<T, DbError>
239 where
240 F: FnMut() -> Fut,
241 Fut: Future<Output = Result<T, DbError>>,
242 {
243 let max_attempts = max_attempts.max(1);
244 let mut attempt = 1u32;
245 loop {
246 match operation().await {
247 Ok(value) => return Ok(value),
248 Err(error) if attempt < max_attempts && is_retryable_transaction_error(&error) => {
249 let delay = backoff.saturating_mul(1u32 << (attempt - 1).min(5));
250 if !delay.is_zero() {
251 tokio::time::sleep(delay).await;
252 }
253 attempt += 1;
254 }
255 Err(error) => return Err(error),
256 }
257 }
258 }
259}
260
261fn is_retryable_transaction_error(error: &DbError) -> bool {
267 matches!(
268 error.sql_error().map(|info| info.kind()),
269 Some(SqlErrorKind::SerializationFailure | SqlErrorKind::DeadlockDetected)
270 )
271}
272
273#[derive(Clone)]
278pub enum AnyPool {
279 #[cfg(feature = "mysql")]
281 MySql(Arc<sqlx::MySqlPool>),
282 #[cfg(feature = "postgres")]
284 Postgres(Arc<sqlx::PgPool>),
285}
286
287impl std::fmt::Debug for AnyPool {
288 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289 formatter
290 .debug_tuple("AnyPool")
291 .field(&self.backend())
292 .finish()
293 }
294}
295
296impl AnyPool {
297 pub fn backend(&self) -> BackendKind {
299 match self {
300 #[cfg(feature = "mysql")]
301 Self::MySql(_) => BackendKind::MySql,
302 #[cfg(feature = "postgres")]
303 Self::Postgres(_) => BackendKind::PostgreSql,
304 }
305 }
306
307 #[cfg(feature = "mysql")]
309 pub fn as_mysql(&self) -> Option<&sqlx::MySqlPool> {
310 match self {
311 Self::MySql(pool) => Some(pool.as_ref()),
312 #[cfg(feature = "postgres")]
313 Self::Postgres(_) => None,
314 }
315 }
316
317 #[cfg(feature = "postgres")]
319 pub fn as_postgres(&self) -> Option<&sqlx::PgPool> {
320 match self {
321 #[cfg(feature = "mysql")]
322 Self::MySql(_) => None,
323 Self::Postgres(pool) => Some(pool.as_ref()),
324 }
325 }
326}
327
328pub enum AnyTransaction {
333 #[cfg(feature = "mysql")]
335 MySql(yang_db::mysql::Transaction),
336 #[cfg(feature = "postgres")]
338 Postgres(yang_db::postgres::Transaction),
339}
340
341impl AnyTransaction {
342 pub fn backend(&self) -> BackendKind {
344 match self {
345 #[cfg(feature = "mysql")]
346 Self::MySql(_) => BackendKind::MySql,
347 #[cfg(feature = "postgres")]
348 Self::Postgres(_) => BackendKind::PostgreSql,
349 }
350 }
351
352 #[cfg(feature = "mysql")]
354 pub fn as_mysql(&mut self) -> Option<&mut yang_db::mysql::Transaction> {
355 match self {
356 Self::MySql(transaction) => Some(transaction),
357 #[cfg(feature = "postgres")]
358 Self::Postgres(_) => None,
359 }
360 }
361
362 #[cfg(feature = "postgres")]
364 pub fn as_postgres(&mut self) -> Option<&mut yang_db::postgres::Transaction> {
365 match self {
366 #[cfg(feature = "mysql")]
367 Self::MySql(_) => None,
368 Self::Postgres(transaction) => Some(transaction),
369 }
370 }
371
372 pub async fn commit(self) -> Result<(), DbError> {
374 match self {
375 #[cfg(feature = "mysql")]
376 Self::MySql(transaction) => transaction.commit().await,
377 #[cfg(feature = "postgres")]
378 Self::Postgres(transaction) => transaction.commit().await,
379 }
380 }
381
382 pub async fn savepoint(&mut self, name: &str) -> Result<(), DbError> {
388 match self {
389 #[cfg(feature = "mysql")]
390 Self::MySql(transaction) => {
391 let sql = mysql_savepoint_statement("SAVEPOINT", name)?;
392 mysql_execute_control(transaction, &sql).await
393 }
394 #[cfg(feature = "postgres")]
395 Self::Postgres(transaction) => transaction.savepoint(name).await,
396 }
397 }
398
399 pub async fn rollback_to(&mut self, name: &str) -> Result<(), DbError> {
403 match self {
404 #[cfg(feature = "mysql")]
405 Self::MySql(transaction) => {
406 let sql = mysql_savepoint_statement("ROLLBACK TO SAVEPOINT", name)?;
407 mysql_execute_control(transaction, &sql).await
408 }
409 #[cfg(feature = "postgres")]
410 Self::Postgres(transaction) => transaction.rollback_to(name).await,
411 }
412 }
413
414 pub async fn release(&mut self, name: &str) -> Result<(), DbError> {
416 match self {
417 #[cfg(feature = "mysql")]
418 Self::MySql(transaction) => {
419 let sql = mysql_savepoint_statement("RELEASE SAVEPOINT", name)?;
420 mysql_execute_control(transaction, &sql).await
421 }
422 #[cfg(feature = "postgres")]
423 Self::Postgres(transaction) => transaction.release_savepoint(name).await,
424 }
425 }
426
427 pub async fn rollback(self) -> Result<(), DbError> {
429 match self {
430 #[cfg(feature = "mysql")]
431 Self::MySql(transaction) => transaction.rollback().await,
432 #[cfg(feature = "postgres")]
433 Self::Postgres(transaction) => transaction.rollback().await,
434 }
435 }
436}
437
438#[cfg(feature = "mysql")]
444fn mysql_savepoint_statement(keyword: &str, name: &str) -> Result<String, DbError> {
445 let valid = !name.is_empty()
446 && name.len() <= 128
447 && name.bytes().enumerate().all(|(index, byte)| {
448 if index == 0 {
449 byte == b'_' || byte.is_ascii_alphabetic()
450 } else {
451 byte == b'_' || byte.is_ascii_alphanumeric()
452 }
453 });
454 if !valid {
455 return Err(DbError::InvalidArgument(format!(
456 "MySQL 保存点名非法: {name:?}(1..=128 字节,字母/下划线开头,仅字母/数字/下划线)"
457 )));
458 }
459 Ok(format!("{keyword} {name}"))
460}
461
462#[cfg(feature = "mysql")]
464async fn mysql_execute_control(
465 transaction: &mut yang_db::mysql::Transaction,
466 sql: &str,
467) -> Result<(), DbError> {
468 let connection = transaction
469 .executor()
470 .ok_or_else(|| DbError::TransactionError("事务已提交或回滚".to_string()))?;
471 sqlx::query(sql).execute(connection).await?;
472 Ok(())
473}
474
475#[cfg(test)]
476mod tests {
477 use super::*;
478
479 #[cfg(feature = "mysql")]
481 fn mysql_database() -> AnyDatabase {
482 let pool = sqlx::MySqlPool::connect_lazy("mysql://root:test@127.0.0.1:3306/test")
483 .expect("惰性 MySQL 连接池应创建成功");
484 let database =
485 yang_db::mysql::Database::from_pool(pool, yang_db::mysql::DatabaseConfig::default())
486 .expect("默认 MySQL 配置应通过校验");
487 AnyDatabase::mysql(database)
488 }
489
490 #[cfg(feature = "postgres")]
492 fn postgres_database() -> AnyDatabase {
493 let pool = sqlx::PgPool::connect_lazy("postgres://postgres:postgres@127.0.0.1:55432/test")
494 .expect("惰性 PostgreSQL 连接池应创建成功");
495 let database = yang_db::postgres::Database::from_pool(
496 pool,
497 yang_db::postgres::DatabaseConfig::default(),
498 )
499 .expect("默认 PostgreSQL 配置应通过校验");
500 AnyDatabase::postgres(database)
501 }
502
503 #[cfg(feature = "mysql")]
504 #[tokio::test]
505 async fn mysql_backend_exposes_identity_capabilities_and_downcast() {
506 let database = mysql_database();
507
508 assert_eq!(database.backend(), BackendKind::MySql);
509 assert!(database.capabilities().relational);
510 assert!(database.as_mysql().is_some());
511 assert!(!database.is_closed());
512 assert_eq!(
513 database.pool_status().max_size,
514 yang_db::mysql::DatabaseConfig::default().max_connections as usize
515 );
516
517 database.close().await;
518 assert!(database.is_closed());
519 }
520
521 #[cfg(feature = "postgres")]
522 #[tokio::test]
523 async fn postgres_backend_exposes_identity_capabilities_and_downcast() {
524 let database = postgres_database();
525
526 assert_eq!(database.backend(), BackendKind::PostgreSql);
527 assert!(database.capabilities().relational);
528 assert!(database.as_postgres().is_some());
529 assert!(!database.is_closed());
530 assert_eq!(
531 database.pool_status().max_size,
532 yang_db::postgres::DatabaseConfig::default().max_connections as usize
533 );
534
535 database.close().await;
536 assert!(database.is_closed());
537 }
538
539 #[cfg(all(feature = "mysql", feature = "postgres"))]
541 #[tokio::test]
542 async fn downcasts_are_backend_exclusive() {
543 let mysql = mysql_database();
544 let postgres = postgres_database();
545
546 assert!(mysql.as_postgres().is_none());
547 assert!(postgres.as_mysql().is_none());
548
549 mysql.close().await;
550 postgres.close().await;
551 }
552
553 #[cfg(feature = "mysql")]
555 #[tokio::test]
556 async fn mysql_pool_view_keeps_backend_identity() {
557 let database = mysql_database();
558 let pool = database.pool();
559
560 assert_eq!(pool.backend(), BackendKind::MySql);
561 assert!(pool.as_mysql().is_some());
562 #[cfg(feature = "postgres")]
563 assert!(pool.as_postgres().is_none());
564 }
565
566 #[cfg(feature = "postgres")]
568 #[tokio::test]
569 async fn postgres_pool_view_keeps_backend_identity() {
570 let database = postgres_database();
571 let pool = database.pool();
572
573 assert_eq!(pool.backend(), BackendKind::PostgreSql);
574 assert!(pool.as_postgres().is_some());
575 #[cfg(feature = "mysql")]
576 assert!(pool.as_mysql().is_none());
577 }
578
579 #[cfg(feature = "mysql")]
581 #[tokio::test]
582 async fn require_capabilities_reports_missing_capability_by_name() {
583 let database = mysql_database();
584
585 database
586 .require_capabilities(&[BackendCapability::Select, BackendCapability::Insert])
587 .expect("MySQL 应支持基础 CRUD 能力");
588
589 let error = database
590 .require_capabilities(&[BackendCapability::Savepoint])
591 .expect_err("MySQL 能力矩阵未声明 Savepoint,应 fail-fast");
592 assert!(matches!(error, BaseError::UnsupportedCapability(_)));
593 assert!(
594 error.to_string().contains("Savepoint"),
595 "错误消息应包含缺失能力名,实得: {error}"
596 );
597 }
598
599 #[cfg(feature = "postgres")]
601 #[tokio::test]
602 async fn postgres_declares_savepoint_capability() {
603 let database = postgres_database();
604 database
605 .require_capabilities(&[BackendCapability::Savepoint])
606 .expect("PostgreSQL 应声明保存点能力");
607 }
608
609 fn retryable_error() -> DbError {
610 sqlstate_error(
611 "40001",
612 "could not serialize access due to concurrent update",
613 )
614 }
615
616 fn sqlstate_error(code: &str, message: &str) -> DbError {
617 DbError::DatabaseError(Box::new(yang_db::SqlErrorInfo::new(code, message)))
618 }
619
620 fn non_retryable_error() -> DbError {
621 DbError::QueryError("syntax error".to_string())
622 }
623
624 #[tokio::test]
626 async fn retry_transaction_retries_retryable_errors() {
627 let database = instantiate_for_retry();
628
629 let mut attempts = 0;
630 let result = database
631 .retry_transaction(3, Duration::ZERO, || {
632 attempts += 1;
633 let attempt = attempts;
634 async move {
635 if attempt < 3 {
636 Err(retryable_error())
637 } else {
638 Ok(attempt)
639 }
640 }
641 })
642 .await;
643
644 assert_eq!(result.expect("第三次应成功"), 3);
645 assert_eq!(attempts, 3);
646 }
647
648 #[tokio::test]
650 async fn retry_transaction_returns_non_retryable_error_immediately() {
651 let database = instantiate_for_retry();
652
653 let mut attempts = 0;
654 let error = database
655 .retry_transaction(5, Duration::ZERO, || {
656 attempts += 1;
657 async move { Err::<(), _>(non_retryable_error()) }
658 })
659 .await
660 .expect_err("不可重试错误应直接返回");
661
662 assert!(matches!(error, DbError::QueryError(_)));
663 assert_eq!(attempts, 1);
664 }
665
666 #[tokio::test]
668 async fn retry_transaction_stops_after_max_attempts() {
669 let database = instantiate_for_retry();
670
671 let mut attempts = 0;
672 let error = database
673 .retry_transaction(2, Duration::ZERO, || {
674 attempts += 1;
675 async move { Err::<(), _>(retryable_error()) }
676 })
677 .await
678 .expect_err("用尽次数后应返回错误");
679
680 assert!(error.is_retryable());
681 assert_eq!(attempts, 2);
682 }
683
684 #[tokio::test]
686 async fn retry_transaction_retries_deadlock() {
687 let database = instantiate_for_retry();
688
689 let mut attempts = 0;
690 let result = database
691 .retry_transaction(3, Duration::ZERO, || {
692 attempts += 1;
693 let attempt = attempts;
694 async move {
695 if attempt < 3 {
696 Err(sqlstate_error("40P01", "deadlock detected"))
697 } else {
698 Ok(attempt)
699 }
700 }
701 })
702 .await;
703
704 assert_eq!(result.expect("第三次应成功"), 3);
705 assert_eq!(attempts, 3);
706 }
707
708 #[tokio::test]
710 async fn retry_transaction_does_not_retry_unique_violation() {
711 let database = instantiate_for_retry();
712
713 let mut attempts = 0;
714 let error = database
715 .retry_transaction(5, Duration::ZERO, || {
716 attempts += 1;
717 async move { Err::<(), _>(sqlstate_error("23505", "duplicate key value")) }
718 })
719 .await
720 .expect_err("唯一约束冲突不应重试");
721
722 assert_eq!(error.sqlstate(), Some("23505"));
723 assert_eq!(attempts, 1);
724 }
725
726 #[tokio::test]
728 async fn retry_transaction_does_not_retry_connection_errors() {
729 let database = instantiate_for_retry();
730
731 let mut attempts = 0;
732 let error = database
733 .retry_transaction(5, Duration::ZERO, || {
734 attempts += 1;
735 async move {
736 Err::<(), _>(DbError::ConnectionError(
737 "connection closed during commit".to_string(),
738 ))
739 }
740 })
741 .await
742 .expect_err("连接错误不应重试");
743
744 assert!(matches!(error, DbError::ConnectionError(_)));
745 assert_eq!(attempts, 1);
746 }
747
748 #[tokio::test]
750 async fn retry_transaction_does_not_retry_connection_class_sqlstate() {
751 let database = instantiate_for_retry();
752
753 let mut attempts = 0;
754 let error = database
755 .retry_transaction(5, Duration::ZERO, || {
756 attempts += 1;
757 async move { Err::<(), _>(sqlstate_error("08006", "connection failure")) }
758 })
759 .await
760 .expect_err("08 类连接失败不应重试");
761
762 assert_eq!(error.sqlstate(), Some("08006"));
763 assert_eq!(attempts, 1);
764 }
765
766 #[tokio::test]
768 async fn retry_transaction_zero_max_attempts_runs_once() {
769 let database = instantiate_for_retry();
770
771 let mut attempts = 0;
772 let error = database
773 .retry_transaction(0, Duration::ZERO, || {
774 attempts += 1;
775 async move { Err::<(), _>(retryable_error()) }
776 })
777 .await
778 .expect_err("零次数仍应执行一次并返回错误");
779
780 assert!(error.is_retryable());
781 assert_eq!(attempts, 1);
782 }
783
784 fn instantiate_for_retry() -> AnyDatabase {
786 #[cfg(feature = "mysql")]
787 {
788 mysql_database()
789 }
790 #[cfg(all(feature = "postgres", not(feature = "mysql")))]
791 {
792 postgres_database()
793 }
794 }
795
796 #[cfg(feature = "mysql")]
798 #[test]
799 fn mysql_savepoint_statement_validates_names() {
800 assert_eq!(
801 mysql_savepoint_statement("SAVEPOINT", "sp_1").expect("合法名称应通过"),
802 "SAVEPOINT sp_1"
803 );
804 for invalid in ["", "1sp", "sp-1", "sp; DROP TABLE t", "名字"] {
805 assert!(
806 matches!(
807 mysql_savepoint_statement("SAVEPOINT", invalid),
808 Err(DbError::InvalidArgument(_))
809 ),
810 "非法保存点名 {invalid:?} 应被拒绝"
811 );
812 }
813 }
814}