Skip to main content

yang_base/database/
backend.rs

1//! 运行时数据库后端容器。
2//!
3//! [`AnyDatabase`] 把编译期可选的 MySQL / PostgreSQL 连接池收敛为一个运行时值,
4//! 供 [`crate::tools::Tools`] 以同一槽位持有;[`AnyPool`] 是它的可克隆连接池视图,
5//! [`AnyTransaction`] 是两种后端事务的统一句柄。本模块同时提供后端身份、能力契约
6//! 与生命周期管理(健康检查 / 关闭 / 连接池状态)。
7//!
8//! 后端身份与能力契约来自 `yang-db` 的单一事实源:
9//! [`yang_db::BackendKind`] 与 [`yang_db::BackendCapabilities`]。
10
11use 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/// 持有单个关系数据库连接池的运行时容器。
20///
21/// 使用 `#[non_exhaustive]`:内部后端集合随 feature 变化,调用方不得按结构体字面量
22/// 构造,必须通过 `AnyDatabase::mysql` / `AnyDatabase::postgres` 构造(按 feature 启用)。
23#[non_exhaustive]
24pub struct AnyDatabase {
25    inner: AnyDatabaseKind,
26}
27
28/// 内部后端分派;各变体按 feature 独占编译。
29///
30/// PG 变体因携带可选的 TLS 证书路径而明显大于 MySQL 变体,触发
31/// `clippy::large_enum_variant`。`AnyDatabase` 在 `Tools` 中通常只构造一次,
32/// 为省下这些栈空间把 PG 变体 Box 化反而多一次堆分配,收益不抵成本。
33#[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    /// 用 MySQL 连接池构造容器。
53    #[cfg(feature = "mysql")]
54    pub fn mysql(database: yang_db::mysql::Database) -> Self {
55        Self {
56            inner: AnyDatabaseKind::MySql(database),
57        }
58    }
59
60    /// 用 PostgreSQL 连接池构造容器。
61    #[cfg(feature = "postgres")]
62    pub fn postgres(database: yang_db::postgres::Database) -> Self {
63        Self {
64            inner: AnyDatabaseKind::PostgreSql(database),
65        }
66    }
67
68    /// 返回后端类型。
69    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    /// 返回后端静态能力契约。
79    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    /// 启动期能力门禁:校验后端是否支持全部 `required` 能力。
89    ///
90    /// 缺失任一能力时返回 [`BaseError::UnsupportedCapability`],错误消息包含后端
91    /// 类型与缺失能力名。调用方应在启动/初始化时一次性校验自己实际用到的能力集合,
92    /// 而不是把检查散落到每个查询上——这样配置错误在启动期就 fail-fast,而不是执行
93    /// 到方言专属语法时才暴露。
94    ///
95    /// # 示例
96    ///
97    /// ```rust,ignore
98    /// database.require_capabilities(&[
99    ///     BackendCapability::Select,
100    ///     BackendCapability::Savepoint,
101    /// ])?;
102    /// ```
103    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    /// 连接池是否已关闭。
117    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    /// 健康检查:执行 `SELECT 1` 验证连接可用。
127    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    /// 幂等关闭连接池。
137    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    /// 返回连接池状态快照。
147    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    /// 当容器持有 MySQL 后端时返回其连接池引用。
157    #[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    /// 当容器持有 PostgreSQL 后端时返回其连接池引用。
167    #[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    /// 返回与当前后端共享同一连接池的可克隆句柄。
177    ///
178    /// sqlx 连接池内部基于 `Arc`,克隆只是引用计数递增;本方法返回的 [`AnyPool`]
179    /// 可在请求作用域内自由复制,不会复制物理连接。
180    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    /// 在当前后端上开启事务。
192    ///
193    /// 返回的 [`AnyTransaction`] 可传入 `TableQuery` 的 `*_in_tx` 系列方法,也可通过
194    /// [`AnyTransaction::commit`] / [`AnyTransaction::rollback`] 显式结束。未显式结束时
195    /// 由 sqlx 在 drop 时尽力回滚。
196    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    /// 整事务重试:按次数与指数退避重跑 `operation`,只重试序列化失败与死锁。
210    ///
211    /// 仅 PostgreSQL 的 `40001`(序列化失败)与 `40P01`(死锁)会重试,判定复用
212    /// [`SqlErrorKind`] 的 SQLSTATE 归一,与 `yang-db` 的 `PgDatabase::retry_transaction`
213    /// 口径一致。其他错误立即原样返回——包括约束冲突(如 `23505`)、
214    /// [`DbError::ConnectionError`] 与 SQLSTATE `08`/`53` 类瞬时连接错误。提交阶段
215    /// 断连时事务是否已生效未知,重试可能重复执行副作用,因此不属于可重试范围。
216    ///
217    /// `operation` 每次被调用都应自行开启并结束一个事务(例如 `self.begin()` →
218    /// 业务语句 → `commit()`)。重试前 helper 按 `backoff * 2^(n-1)` 退避(最多放大
219    /// 32 倍);失败事务的回滚由被丢弃的事务句柄兜底。
220    ///
221    /// # 示例
222    ///
223    /// ```rust,ignore
224    /// let value = database
225    ///     .retry_transaction(3, Duration::from_millis(50), || async {
226    ///         let mut tx = database.begin().await?;
227    ///         // ... 业务语句 ...
228    ///         tx.commit().await?;
229    ///         Ok(())
230    ///     })
231    ///     .await?;
232    /// ```
233    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
261/// 整事务重试只接受序列化失败(40001)与死锁(40P01)。
262///
263/// SQLSTATE 归一复用 `yang-db` 的 [`SqlErrorKind`],与 `PgDatabase::retry_transaction`
264/// 保持一致。连接类(`08`/`53`)错误不在其列:提交阶段断连时事务结果不明,重试
265/// 可能重复执行已生效的副作用。
266fn 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/// 可克隆的连接池句柄,按运行时后端分派。
274///
275/// 由 [`AnyDatabase::pool`] 构造,供受保护查询层([`crate::table::TableQuery`])
276/// 在请求期共享连接池。变体在编译期按 feature 独占存在。
277#[derive(Clone)]
278pub enum AnyPool {
279    /// MySQL 连接池。
280    #[cfg(feature = "mysql")]
281    MySql(Arc<sqlx::MySqlPool>),
282    /// PostgreSQL 连接池。
283    #[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    /// 返回连接池所属后端。
298    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    /// 当持有 MySQL 连接池时返回其引用。
308    #[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    /// 当持有 PostgreSQL 连接池时返回其引用。
318    #[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
328/// 两种后端事务的统一句柄。
329///
330/// 由 [`AnyDatabase::begin`] 或 [`crate::action::ActionContext::begin_transaction`]
331/// 创建;`TableQuery` 的 `*_in_tx` 系列方法按变体分派到对应后端。
332pub enum AnyTransaction {
333    /// MySQL 事务。
334    #[cfg(feature = "mysql")]
335    MySql(yang_db::mysql::Transaction),
336    /// PostgreSQL 事务。
337    #[cfg(feature = "postgres")]
338    Postgres(yang_db::postgres::Transaction),
339}
340
341impl AnyTransaction {
342    /// 返回事务所属后端。
343    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    /// 当持有 MySQL 事务时返回其可变引用。
353    #[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    /// 当持有 PostgreSQL 事务时返回其可变引用。
363    #[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    /// 提交事务。
373    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    /// 在当前事务内创建保存点(与后端无关的封装)。
383    ///
384    /// PostgreSQL 走其后端原生 `SAVEPOINT`;MySQL 同样支持保存点语法,这里用
385    /// 校验过的标识符拼接控制语句。`name` 必须是 ASCII 标识符(字母/下划线开头,
386    /// 仅字母/数字/下划线),非法名称返回 [`DbError::InvalidArgument`]。
387    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    /// 回滚到指定保存点(`ROLLBACK TO SAVEPOINT`)。
400    ///
401    /// 只撤销保存点之后的工作;更早的保存点与外层事务不受影响。
402    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    /// 释放保存点(`RELEASE SAVEPOINT`)。
415    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    /// 回滚事务。
428    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/// 校验 MySQL 保存点名并拼出控制语句。
439///
440/// MySQL 的 `SAVEPOINT` 语法不接受绑定参数形式的标识符,故先按严格白名单
441/// (1..=128 字节,字母/下划线开头,仅字母/数字/下划线)校验,再拼接成 SQL,
442/// 从根上消除注入面。
443#[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/// 在 MySQL 事务上执行一条控制语句(保存点相关,无可绑定值)。
463#[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    /// 用惰性连接池构造 MySQL 容器:不建立真实网络连接,仅验证运行时抽象。
480    #[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    /// 用惰性连接池构造 PostgreSQL 容器:不建立真实网络连接,仅验证运行时抽象。
491    #[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    /// 同时启用两种后端时,`as_*` 必须对另一后端返回 `None`,避免静默误用。
540    #[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    /// [`AnyDatabase::pool`] 必须返回与容器后端一致的共享句柄,且两后端互斥。
554    #[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    /// [`AnyDatabase::pool`] 的 PostgreSQL 分支同样保持后端身份。
567    #[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    /// 能力门禁:缺失能力返回 `UnsupportedCapability`,且错误消息包含能力名。
580    #[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    /// 能力门禁:PostgreSQL 声明的保存点能力应通过校验。
600    #[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    /// 整事务重试:可重试错误按次数退避重试,成功后返回结果。
625    #[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    /// 整事务重试:不可重试错误立即返回,只执行一次。
649    #[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    /// 整事务重试:用尽次数后返回最后一次可重试错误。
667    #[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    /// 死锁(40P01)同样属于整事务可重试错误。
685    #[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    /// 唯一约束冲突(23505)是确定性错误,只执行一次。
709    #[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    /// 连接错误不在整事务重试范围(提交阶段断连结果不明),只执行一次。
727    #[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    /// SQLSTATE 08 类连接失败同样不参与整事务重试。
749    #[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    /// `max_attempts = 0` 维持既有语义:至少执行一次,不因参数为 0 而跳过。
767    #[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    /// 重试 helper 与后端无关;借一个惰性容器即可,不建立真实连接。
785    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    /// MySQL 保存点名白名单拒绝注入形态,合法名称原样拼入控制语句。
797    #[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}