1use crate::datasource::DatasourceId;
12use crate::error::BaseError;
13use std::future::Future;
14use std::sync::Arc;
15use std::time::Duration;
16use yang_db::{
17 BackendCapabilities, BackendCapability, BackendKind, DbError, PoolStatus, SqlErrorKind,
18};
19
20#[derive(Clone)]
25#[non_exhaustive]
26pub struct AnyDatabase {
27 id: DatasourceId,
28 inner: AnyDatabaseKind,
29}
30
31#[allow(clippy::large_enum_variant)]
37#[derive(Clone)]
38enum AnyDatabaseKind {
39 #[cfg(feature = "mysql")]
40 MySql(yang_db::mysql::Database),
41 #[cfg(feature = "postgres")]
42 PostgreSql(yang_db::postgres::Database),
43}
44
45impl std::fmt::Debug for AnyDatabase {
46 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 formatter
48 .debug_struct("AnyDatabase")
49 .field("backend", &self.backend())
50 .field("closed", &self.is_closed())
51 .finish()
52 }
53}
54
55impl AnyDatabase {
56 #[cfg(feature = "mysql")]
58 pub fn mysql(database: yang_db::mysql::Database) -> Self {
59 Self::mysql_on(DatasourceId::default_source(), database)
60 }
61
62 #[cfg(feature = "mysql")]
64 pub(crate) fn mysql_on(id: DatasourceId, database: yang_db::mysql::Database) -> Self {
65 Self {
66 id,
67 inner: AnyDatabaseKind::MySql(database),
68 }
69 }
70
71 #[cfg(feature = "postgres")]
73 pub fn postgres(database: yang_db::postgres::Database) -> Self {
74 Self::postgres_on(DatasourceId::default_source(), database)
75 }
76
77 #[cfg(feature = "postgres")]
79 pub(crate) fn postgres_on(id: DatasourceId, database: yang_db::postgres::Database) -> Self {
80 Self {
81 id,
82 inner: AnyDatabaseKind::PostgreSql(database),
83 }
84 }
85
86 pub fn id(&self) -> &DatasourceId {
88 &self.id
89 }
90
91 #[must_use]
93 pub(crate) fn with_id(mut self, id: DatasourceId) -> Self {
94 self.id = id;
95 self
96 }
97
98 pub fn backend(&self) -> BackendKind {
100 match &self.inner {
101 #[cfg(feature = "mysql")]
102 AnyDatabaseKind::MySql(_) => BackendKind::MySql,
103 #[cfg(feature = "postgres")]
104 AnyDatabaseKind::PostgreSql(_) => BackendKind::PostgreSql,
105 }
106 }
107
108 pub fn capabilities(&self) -> &'static BackendCapabilities {
110 match &self.inner {
111 #[cfg(feature = "mysql")]
112 AnyDatabaseKind::MySql(_) => yang_db::mysql::Database::capabilities(),
113 #[cfg(feature = "postgres")]
114 AnyDatabaseKind::PostgreSql(_) => yang_db::postgres::Database::capabilities(),
115 }
116 }
117
118 pub fn require_capabilities(&self, required: &[BackendCapability]) -> Result<(), BaseError> {
134 let capabilities = self.capabilities();
135 for capability in required {
136 if !capabilities.supports(*capability) {
137 return Err(BaseError::UnsupportedCapability(format!(
138 "后端 {:?} 缺少必需能力: {capability:?}",
139 self.backend()
140 )));
141 }
142 }
143 Ok(())
144 }
145
146 pub fn is_closed(&self) -> bool {
148 match &self.inner {
149 #[cfg(feature = "mysql")]
150 AnyDatabaseKind::MySql(database) => database.is_closed(),
151 #[cfg(feature = "postgres")]
152 AnyDatabaseKind::PostgreSql(database) => database.is_closed(),
153 }
154 }
155
156 pub async fn health_check(&self) -> Result<bool, DbError> {
158 match &self.inner {
159 #[cfg(feature = "mysql")]
160 AnyDatabaseKind::MySql(database) => database.health_check().await,
161 #[cfg(feature = "postgres")]
162 AnyDatabaseKind::PostgreSql(database) => database.health_check().await,
163 }
164 }
165
166 pub async fn close(&self) {
168 match &self.inner {
169 #[cfg(feature = "mysql")]
170 AnyDatabaseKind::MySql(database) => database.close().await,
171 #[cfg(feature = "postgres")]
172 AnyDatabaseKind::PostgreSql(database) => database.close().await,
173 }
174 }
175
176 pub fn pool_status(&self) -> PoolStatus {
178 match &self.inner {
179 #[cfg(feature = "mysql")]
180 AnyDatabaseKind::MySql(database) => database.pool_status(),
181 #[cfg(feature = "postgres")]
182 AnyDatabaseKind::PostgreSql(database) => database.pool_status(),
183 }
184 }
185
186 #[cfg(feature = "mysql")]
188 pub fn as_mysql(&self) -> Option<&yang_db::mysql::Database> {
189 match &self.inner {
190 AnyDatabaseKind::MySql(database) => Some(database),
191 #[cfg(feature = "postgres")]
192 AnyDatabaseKind::PostgreSql(_) => None,
193 }
194 }
195
196 #[cfg(feature = "postgres")]
198 pub fn as_postgres(&self) -> Option<&yang_db::postgres::Database> {
199 match &self.inner {
200 #[cfg(feature = "mysql")]
201 AnyDatabaseKind::MySql(_) => None,
202 AnyDatabaseKind::PostgreSql(database) => Some(database),
203 }
204 }
205
206 pub fn pool(&self) -> AnyPool {
211 match &self.inner {
212 #[cfg(feature = "mysql")]
213 AnyDatabaseKind::MySql(database) => AnyPool::MySql(Arc::new(database.pool().clone())),
214 #[cfg(feature = "postgres")]
215 AnyDatabaseKind::PostgreSql(database) => {
216 AnyPool::Postgres(Arc::new(database.pool().clone()))
217 }
218 }
219 }
220
221 pub fn source_pool(&self) -> PoolHandle {
223 PoolHandle {
224 source: self.id.clone(),
225 pool: self.pool(),
226 }
227 }
228
229 pub async fn begin(&self) -> Result<AnyTransaction, DbError> {
235 match &self.inner {
236 #[cfg(feature = "mysql")]
237 AnyDatabaseKind::MySql(database) => database
238 .transaction()
239 .await
240 .map(|transaction| AnyTransaction::MySql(transaction).with_source(self.id.clone())),
241 #[cfg(feature = "postgres")]
242 AnyDatabaseKind::PostgreSql(database) => {
243 database.transaction().await.map(|transaction| {
244 AnyTransaction::Postgres(transaction).with_source(self.id.clone())
245 })
246 }
247 }
248 }
249
250 pub async fn retry_transaction<T, F, Fut>(
275 &self,
276 max_attempts: u32,
277 backoff: Duration,
278 mut operation: F,
279 ) -> Result<T, DbError>
280 where
281 F: FnMut() -> Fut,
282 Fut: Future<Output = Result<T, DbError>>,
283 {
284 let max_attempts = max_attempts.max(1);
285 let mut attempt = 1u32;
286 loop {
287 match operation().await {
288 Ok(value) => return Ok(value),
289 Err(error) if attempt < max_attempts && is_retryable_transaction_error(&error) => {
290 let delay = backoff.saturating_mul(1u32 << (attempt - 1).min(5));
291 if !delay.is_zero() {
292 tokio::time::sleep(delay).await;
293 }
294 attempt += 1;
295 }
296 Err(error) => return Err(error),
297 }
298 }
299 }
300}
301
302fn is_retryable_transaction_error(error: &DbError) -> bool {
308 matches!(
309 error.sql_error().map(|info| info.kind()),
310 Some(SqlErrorKind::SerializationFailure | SqlErrorKind::DeadlockDetected)
311 )
312}
313
314#[derive(Clone)]
319pub enum AnyPool {
320 #[cfg(feature = "mysql")]
322 MySql(Arc<sqlx::MySqlPool>),
323 #[cfg(feature = "postgres")]
325 Postgres(Arc<sqlx::PgPool>),
326}
327
328impl std::fmt::Debug for AnyPool {
329 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
330 formatter
331 .debug_tuple("AnyPool")
332 .field(&self.backend())
333 .finish()
334 }
335}
336
337impl AnyPool {
338 pub fn backend(&self) -> BackendKind {
340 match self {
341 #[cfg(feature = "mysql")]
342 Self::MySql(_) => BackendKind::MySql,
343 #[cfg(feature = "postgres")]
344 Self::Postgres(_) => BackendKind::PostgreSql,
345 }
346 }
347
348 #[cfg(feature = "mysql")]
350 pub fn as_mysql(&self) -> Option<&sqlx::MySqlPool> {
351 match self {
352 Self::MySql(pool) => Some(pool.as_ref()),
353 #[cfg(feature = "postgres")]
354 Self::Postgres(_) => None,
355 }
356 }
357
358 #[cfg(feature = "postgres")]
360 pub fn as_postgres(&self) -> Option<&sqlx::PgPool> {
361 match self {
362 #[cfg(feature = "mysql")]
363 Self::MySql(_) => None,
364 Self::Postgres(pool) => Some(pool.as_ref()),
365 }
366 }
367}
368
369#[derive(Clone)]
373pub struct PoolHandle {
374 source: DatasourceId,
375 pool: AnyPool,
376}
377
378impl std::fmt::Debug for PoolHandle {
379 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
380 formatter
381 .debug_struct("PoolHandle")
382 .field("source", &self.source)
383 .field("backend", &self.pool.backend())
384 .finish()
385 }
386}
387
388impl PoolHandle {
389 pub(crate) fn new(source: DatasourceId, pool: AnyPool) -> Self {
391 Self { source, pool }
392 }
393
394 pub fn source(&self) -> &DatasourceId {
396 &self.source
397 }
398
399 pub fn pool(&self) -> &AnyPool {
401 &self.pool
402 }
403
404 pub fn backend(&self) -> BackendKind {
406 self.pool.backend()
407 }
408}
409
410pub struct AnyTransaction {
416 source: Option<DatasourceId>,
417 kind: AnyTransactionKind,
418}
419
420impl std::fmt::Debug for AnyTransaction {
421 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
422 formatter
423 .debug_struct("AnyTransaction")
424 .field("source", &self.source)
425 .field("backend", &self.backend())
426 .finish()
427 }
428}
429
430pub(crate) enum AnyTransactionKind {
432 #[cfg(feature = "mysql")]
434 MySql(yang_db::mysql::Transaction),
435 #[cfg(feature = "postgres")]
437 Postgres(yang_db::postgres::Transaction),
438}
439
440impl AnyTransaction {
441 #[cfg(feature = "mysql")]
443 #[allow(non_snake_case)]
444 pub fn MySql(transaction: yang_db::mysql::Transaction) -> Self {
445 Self {
446 source: None,
447 kind: AnyTransactionKind::MySql(transaction),
448 }
449 }
450
451 #[cfg(feature = "postgres")]
453 #[allow(non_snake_case)]
454 pub fn Postgres(transaction: yang_db::postgres::Transaction) -> Self {
455 Self {
456 source: None,
457 kind: AnyTransactionKind::Postgres(transaction),
458 }
459 }
460
461 #[must_use]
463 pub(crate) fn with_source(mut self, source: DatasourceId) -> Self {
464 self.source = Some(source);
465 self
466 }
467
468 pub fn source(&self) -> Option<&DatasourceId> {
470 self.source.as_ref()
471 }
472
473 pub fn backend(&self) -> BackendKind {
475 match &self.kind {
476 #[cfg(feature = "mysql")]
477 AnyTransactionKind::MySql(_) => BackendKind::MySql,
478 #[cfg(feature = "postgres")]
479 AnyTransactionKind::Postgres(_) => BackendKind::PostgreSql,
480 }
481 }
482
483 pub(crate) fn kind_mut(&mut self) -> &mut AnyTransactionKind {
485 &mut self.kind
486 }
487
488 #[cfg(feature = "mysql")]
490 pub fn as_mysql(&mut self) -> Option<&mut yang_db::mysql::Transaction> {
491 match &mut self.kind {
492 AnyTransactionKind::MySql(transaction) => Some(transaction),
493 #[cfg(feature = "postgres")]
494 AnyTransactionKind::Postgres(_) => None,
495 }
496 }
497
498 #[cfg(feature = "postgres")]
500 pub fn as_postgres(&mut self) -> Option<&mut yang_db::postgres::Transaction> {
501 match &mut self.kind {
502 #[cfg(feature = "mysql")]
503 AnyTransactionKind::MySql(_) => None,
504 AnyTransactionKind::Postgres(transaction) => Some(transaction),
505 }
506 }
507
508 pub async fn commit(self) -> Result<(), DbError> {
510 match self.kind {
511 #[cfg(feature = "mysql")]
512 AnyTransactionKind::MySql(transaction) => transaction.commit().await,
513 #[cfg(feature = "postgres")]
514 AnyTransactionKind::Postgres(transaction) => transaction.commit().await,
515 }
516 }
517
518 pub async fn savepoint(&mut self, name: &str) -> Result<(), DbError> {
524 match &mut self.kind {
525 #[cfg(feature = "mysql")]
526 AnyTransactionKind::MySql(transaction) => {
527 let sql = mysql_savepoint_statement("SAVEPOINT", name)?;
528 mysql_execute_control(transaction, &sql).await
529 }
530 #[cfg(feature = "postgres")]
531 AnyTransactionKind::Postgres(transaction) => transaction.savepoint(name).await,
532 }
533 }
534
535 pub async fn rollback_to(&mut self, name: &str) -> Result<(), DbError> {
539 match &mut self.kind {
540 #[cfg(feature = "mysql")]
541 AnyTransactionKind::MySql(transaction) => {
542 let sql = mysql_savepoint_statement("ROLLBACK TO SAVEPOINT", name)?;
543 mysql_execute_control(transaction, &sql).await
544 }
545 #[cfg(feature = "postgres")]
546 AnyTransactionKind::Postgres(transaction) => transaction.rollback_to(name).await,
547 }
548 }
549
550 pub async fn release(&mut self, name: &str) -> Result<(), DbError> {
552 match &mut self.kind {
553 #[cfg(feature = "mysql")]
554 AnyTransactionKind::MySql(transaction) => {
555 let sql = mysql_savepoint_statement("RELEASE SAVEPOINT", name)?;
556 mysql_execute_control(transaction, &sql).await
557 }
558 #[cfg(feature = "postgres")]
559 AnyTransactionKind::Postgres(transaction) => transaction.release_savepoint(name).await,
560 }
561 }
562
563 pub async fn rollback(self) -> Result<(), DbError> {
565 match self.kind {
566 #[cfg(feature = "mysql")]
567 AnyTransactionKind::MySql(transaction) => transaction.rollback().await,
568 #[cfg(feature = "postgres")]
569 AnyTransactionKind::Postgres(transaction) => transaction.rollback().await,
570 }
571 }
572}
573
574#[cfg(feature = "mysql")]
580fn mysql_savepoint_statement(keyword: &str, name: &str) -> Result<String, DbError> {
581 let valid = !name.is_empty()
582 && name.len() <= 128
583 && name.bytes().enumerate().all(|(index, byte)| {
584 if index == 0 {
585 byte == b'_' || byte.is_ascii_alphabetic()
586 } else {
587 byte == b'_' || byte.is_ascii_alphanumeric()
588 }
589 });
590 if !valid {
591 return Err(DbError::InvalidArgument(format!(
592 "MySQL 保存点名非法: {name:?}(1..=128 字节,字母/下划线开头,仅字母/数字/下划线)"
593 )));
594 }
595 Ok(format!("{keyword} {name}"))
596}
597
598#[cfg(feature = "mysql")]
600async fn mysql_execute_control(
601 transaction: &mut yang_db::mysql::Transaction,
602 sql: &str,
603) -> Result<(), DbError> {
604 let connection = transaction
605 .executor()
606 .ok_or_else(|| DbError::TransactionError("事务已提交或回滚".to_string()))?;
607 sqlx::query(sql).execute(connection).await?;
608 Ok(())
609}
610
611#[cfg(test)]
612mod tests {
613 use super::*;
614
615 #[cfg(feature = "mysql")]
617 fn mysql_database() -> AnyDatabase {
618 let pool = sqlx::MySqlPool::connect_lazy("mysql://root:test@127.0.0.1:3306/test")
619 .expect("惰性 MySQL 连接池应创建成功");
620 let database =
621 yang_db::mysql::Database::from_pool(pool, yang_db::mysql::DatabaseConfig::default())
622 .expect("默认 MySQL 配置应通过校验");
623 AnyDatabase::mysql(database)
624 }
625
626 #[cfg(feature = "postgres")]
628 fn postgres_database() -> AnyDatabase {
629 let pool = sqlx::PgPool::connect_lazy("postgres://postgres:postgres@127.0.0.1:55432/test")
630 .expect("惰性 PostgreSQL 连接池应创建成功");
631 let database = yang_db::postgres::Database::from_pool(
632 pool,
633 yang_db::postgres::DatabaseConfig::default(),
634 )
635 .expect("默认 PostgreSQL 配置应通过校验");
636 AnyDatabase::postgres(database)
637 }
638
639 #[cfg(feature = "mysql")]
640 #[tokio::test]
641 async fn mysql_backend_exposes_identity_capabilities_and_downcast() {
642 let database = mysql_database();
643
644 assert_eq!(database.backend(), BackendKind::MySql);
645 assert!(database.capabilities().relational);
646 assert!(database.as_mysql().is_some());
647 assert!(!database.is_closed());
648 assert_eq!(
649 database.pool_status().max_size,
650 yang_db::mysql::DatabaseConfig::default().max_connections as usize
651 );
652
653 database.close().await;
654 assert!(database.is_closed());
655 }
656
657 #[cfg(feature = "postgres")]
658 #[tokio::test]
659 async fn postgres_backend_exposes_identity_capabilities_and_downcast() {
660 let database = postgres_database();
661
662 assert_eq!(database.backend(), BackendKind::PostgreSql);
663 assert!(database.capabilities().relational);
664 assert!(database.as_postgres().is_some());
665 assert!(!database.is_closed());
666 assert_eq!(
667 database.pool_status().max_size,
668 yang_db::postgres::DatabaseConfig::default().max_connections as usize
669 );
670
671 database.close().await;
672 assert!(database.is_closed());
673 }
674
675 #[cfg(all(feature = "mysql", feature = "postgres"))]
677 #[tokio::test]
678 async fn downcasts_are_backend_exclusive() {
679 let mysql = mysql_database();
680 let postgres = postgres_database();
681
682 assert!(mysql.as_postgres().is_none());
683 assert!(postgres.as_mysql().is_none());
684
685 mysql.close().await;
686 postgres.close().await;
687 }
688
689 #[cfg(feature = "mysql")]
691 #[tokio::test]
692 async fn mysql_pool_view_keeps_backend_identity() {
693 let database = mysql_database();
694 let pool = database.pool();
695
696 assert_eq!(pool.backend(), BackendKind::MySql);
697 assert!(pool.as_mysql().is_some());
698 #[cfg(feature = "postgres")]
699 assert!(pool.as_postgres().is_none());
700 }
701
702 #[cfg(feature = "postgres")]
704 #[tokio::test]
705 async fn postgres_pool_view_keeps_backend_identity() {
706 let database = postgres_database();
707 let pool = database.pool();
708
709 assert_eq!(pool.backend(), BackendKind::PostgreSql);
710 assert!(pool.as_postgres().is_some());
711 #[cfg(feature = "mysql")]
712 assert!(pool.as_mysql().is_none());
713 }
714
715 #[cfg(feature = "mysql")]
717 #[tokio::test]
718 async fn require_capabilities_reports_missing_capability_by_name() {
719 let database = mysql_database();
720
721 database
722 .require_capabilities(&[BackendCapability::Select, BackendCapability::Insert])
723 .expect("MySQL 应支持基础 CRUD 能力");
724
725 let error = database
726 .require_capabilities(&[BackendCapability::Savepoint])
727 .expect_err("MySQL 能力矩阵未声明 Savepoint,应 fail-fast");
728 assert!(matches!(error, BaseError::UnsupportedCapability(_)));
729 assert!(
730 error.to_string().contains("Savepoint"),
731 "错误消息应包含缺失能力名,实得: {error}"
732 );
733 }
734
735 #[cfg(feature = "postgres")]
737 #[tokio::test]
738 async fn postgres_declares_savepoint_capability() {
739 let database = postgres_database();
740 database
741 .require_capabilities(&[BackendCapability::Savepoint])
742 .expect("PostgreSQL 应声明保存点能力");
743 }
744
745 fn retryable_error() -> DbError {
746 sqlstate_error(
747 "40001",
748 "could not serialize access due to concurrent update",
749 )
750 }
751
752 fn sqlstate_error(code: &str, message: &str) -> DbError {
753 DbError::DatabaseError(Box::new(yang_db::SqlErrorInfo::new(code, message)))
754 }
755
756 fn non_retryable_error() -> DbError {
757 DbError::QueryError("syntax error".to_string())
758 }
759
760 #[tokio::test]
762 async fn retry_transaction_retries_retryable_errors() {
763 let database = instantiate_for_retry();
764
765 let mut attempts = 0;
766 let result = database
767 .retry_transaction(3, Duration::ZERO, || {
768 attempts += 1;
769 let attempt = attempts;
770 async move {
771 if attempt < 3 {
772 Err(retryable_error())
773 } else {
774 Ok(attempt)
775 }
776 }
777 })
778 .await;
779
780 assert_eq!(result.expect("第三次应成功"), 3);
781 assert_eq!(attempts, 3);
782 }
783
784 #[tokio::test]
786 async fn retry_transaction_returns_non_retryable_error_immediately() {
787 let database = instantiate_for_retry();
788
789 let mut attempts = 0;
790 let error = database
791 .retry_transaction(5, Duration::ZERO, || {
792 attempts += 1;
793 async move { Err::<(), _>(non_retryable_error()) }
794 })
795 .await
796 .expect_err("不可重试错误应直接返回");
797
798 assert!(matches!(error, DbError::QueryError(_)));
799 assert_eq!(attempts, 1);
800 }
801
802 #[tokio::test]
804 async fn retry_transaction_stops_after_max_attempts() {
805 let database = instantiate_for_retry();
806
807 let mut attempts = 0;
808 let error = database
809 .retry_transaction(2, Duration::ZERO, || {
810 attempts += 1;
811 async move { Err::<(), _>(retryable_error()) }
812 })
813 .await
814 .expect_err("用尽次数后应返回错误");
815
816 assert!(error.is_retryable());
817 assert_eq!(attempts, 2);
818 }
819
820 #[tokio::test]
822 async fn retry_transaction_retries_deadlock() {
823 let database = instantiate_for_retry();
824
825 let mut attempts = 0;
826 let result = database
827 .retry_transaction(3, Duration::ZERO, || {
828 attempts += 1;
829 let attempt = attempts;
830 async move {
831 if attempt < 3 {
832 Err(sqlstate_error("40P01", "deadlock detected"))
833 } else {
834 Ok(attempt)
835 }
836 }
837 })
838 .await;
839
840 assert_eq!(result.expect("第三次应成功"), 3);
841 assert_eq!(attempts, 3);
842 }
843
844 #[tokio::test]
846 async fn retry_transaction_does_not_retry_unique_violation() {
847 let database = instantiate_for_retry();
848
849 let mut attempts = 0;
850 let error = database
851 .retry_transaction(5, Duration::ZERO, || {
852 attempts += 1;
853 async move { Err::<(), _>(sqlstate_error("23505", "duplicate key value")) }
854 })
855 .await
856 .expect_err("唯一约束冲突不应重试");
857
858 assert_eq!(error.sqlstate(), Some("23505"));
859 assert_eq!(attempts, 1);
860 }
861
862 #[tokio::test]
864 async fn retry_transaction_does_not_retry_connection_errors() {
865 let database = instantiate_for_retry();
866
867 let mut attempts = 0;
868 let error = database
869 .retry_transaction(5, Duration::ZERO, || {
870 attempts += 1;
871 async move {
872 Err::<(), _>(DbError::ConnectionError(
873 "connection closed during commit".to_string(),
874 ))
875 }
876 })
877 .await
878 .expect_err("连接错误不应重试");
879
880 assert!(matches!(error, DbError::ConnectionError(_)));
881 assert_eq!(attempts, 1);
882 }
883
884 #[tokio::test]
886 async fn retry_transaction_does_not_retry_connection_class_sqlstate() {
887 let database = instantiate_for_retry();
888
889 let mut attempts = 0;
890 let error = database
891 .retry_transaction(5, Duration::ZERO, || {
892 attempts += 1;
893 async move { Err::<(), _>(sqlstate_error("08006", "connection failure")) }
894 })
895 .await
896 .expect_err("08 类连接失败不应重试");
897
898 assert_eq!(error.sqlstate(), Some("08006"));
899 assert_eq!(attempts, 1);
900 }
901
902 #[tokio::test]
904 async fn retry_transaction_zero_max_attempts_runs_once() {
905 let database = instantiate_for_retry();
906
907 let mut attempts = 0;
908 let error = database
909 .retry_transaction(0, Duration::ZERO, || {
910 attempts += 1;
911 async move { Err::<(), _>(retryable_error()) }
912 })
913 .await
914 .expect_err("零次数仍应执行一次并返回错误");
915
916 assert!(error.is_retryable());
917 assert_eq!(attempts, 1);
918 }
919
920 fn instantiate_for_retry() -> AnyDatabase {
922 #[cfg(feature = "mysql")]
923 {
924 mysql_database()
925 }
926 #[cfg(all(feature = "postgres", not(feature = "mysql")))]
927 {
928 postgres_database()
929 }
930 }
931
932 #[cfg(feature = "mysql")]
934 #[test]
935 fn mysql_savepoint_statement_validates_names() {
936 assert_eq!(
937 mysql_savepoint_statement("SAVEPOINT", "sp_1").expect("合法名称应通过"),
938 "SAVEPOINT sp_1"
939 );
940 for invalid in ["", "1sp", "sp-1", "sp; DROP TABLE t", "名字"] {
941 assert!(
942 matches!(
943 mysql_savepoint_statement("SAVEPOINT", invalid),
944 Err(DbError::InvalidArgument(_))
945 ),
946 "非法保存点名 {invalid:?} 应被拒绝"
947 );
948 }
949 }
950}