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::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/// 持有单个关系数据库连接池的运行时容器。
21///
22/// 使用 `#[non_exhaustive]`:内部后端集合随 feature 变化,调用方不得按结构体字面量
23/// 构造,必须通过 `AnyDatabase::mysql` / `AnyDatabase::postgres` 构造(按 feature 启用)。
24#[derive(Clone)]
25#[non_exhaustive]
26pub struct AnyDatabase {
27    id: DatasourceId,
28    inner: AnyDatabaseKind,
29}
30
31/// 内部后端分派;各变体按 feature 独占编译。
32///
33/// PG 变体因携带可选的 TLS 证书路径而明显大于 MySQL 变体,触发
34/// `clippy::large_enum_variant`。`AnyDatabase` 在 `Tools` 中通常只构造一次,
35/// 为省下这些栈空间把 PG 变体 Box 化反而多一次堆分配,收益不抵成本。
36#[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    /// 用 MySQL 连接池构造容器(默认数据源)。
57    #[cfg(feature = "mysql")]
58    pub fn mysql(database: yang_db::mysql::Database) -> Self {
59        Self::mysql_on(DatasourceId::default_source(), database)
60    }
61
62    /// 用指定逻辑名与 MySQL 连接池构造容器。
63    #[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    /// 用 PostgreSQL 连接池构造容器(默认数据源)。
72    #[cfg(feature = "postgres")]
73    pub fn postgres(database: yang_db::postgres::Database) -> Self {
74        Self::postgres_on(DatasourceId::default_source(), database)
75    }
76
77    /// 用指定逻辑名与 PostgreSQL 连接池构造容器。
78    #[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    /// 返回逻辑数据源名。
87    pub fn id(&self) -> &DatasourceId {
88        &self.id
89    }
90
91    /// 覆盖逻辑数据源名(供注册表在构造时对齐键与容器身份)。
92    #[must_use]
93    pub(crate) fn with_id(mut self, id: DatasourceId) -> Self {
94        self.id = id;
95        self
96    }
97
98    /// 返回后端类型。
99    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    /// 返回后端静态能力契约。
109    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    /// 启动期能力门禁:校验后端是否支持全部 `required` 能力。
119    ///
120    /// 缺失任一能力时返回 [`BaseError::UnsupportedCapability`],错误消息包含后端
121    /// 类型与缺失能力名。调用方应在启动/初始化时一次性校验自己实际用到的能力集合,
122    /// 而不是把检查散落到每个查询上——这样配置错误在启动期就 fail-fast,而不是执行
123    /// 到方言专属语法时才暴露。
124    ///
125    /// # 示例
126    ///
127    /// ```rust,ignore
128    /// database.require_capabilities(&[
129    ///     BackendCapability::Select,
130    ///     BackendCapability::Savepoint,
131    /// ])?;
132    /// ```
133    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    /// 连接池是否已关闭。
147    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    /// 健康检查:执行 `SELECT 1` 验证连接可用。
157    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    /// 幂等关闭连接池。
167    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    /// 返回连接池状态快照。
177    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    /// 当容器持有 MySQL 后端时返回其连接池引用。
187    #[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    /// 当容器持有 PostgreSQL 后端时返回其连接池引用。
197    #[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    /// 返回与当前后端共享同一连接池的可克隆句柄。
207    ///
208    /// sqlx 连接池内部基于 `Arc`,克隆只是引用计数递增;本方法返回的 [`AnyPool`]
209    /// 可在请求作用域内自由复制,不会复制物理连接。
210    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    /// 返回带逻辑数据源身份的连接池句柄,供 `TableQuery` 做事务同源校验。
222    pub fn source_pool(&self) -> PoolHandle {
223        PoolHandle {
224            source: self.id.clone(),
225            pool: self.pool(),
226        }
227    }
228
229    /// 在当前后端上开启事务。
230    ///
231    /// 返回的 [`AnyTransaction`] 可传入 `TableQuery` 的 `*_in_tx` 系列方法,也可通过
232    /// [`AnyTransaction::commit`] / [`AnyTransaction::rollback`] 显式结束。未显式结束时
233    /// 由 sqlx 在 drop 时尽力回滚。
234    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    /// 整事务重试:按次数与指数退避重跑 `operation`,只重试序列化失败与死锁。
251    ///
252    /// 仅 PostgreSQL 的 `40001`(序列化失败)与 `40P01`(死锁)会重试,判定复用
253    /// [`SqlErrorKind`] 的 SQLSTATE 归一,与 `yang-db` 的 `PgDatabase::retry_transaction`
254    /// 口径一致。其他错误立即原样返回——包括约束冲突(如 `23505`)、
255    /// [`DbError::ConnectionError`] 与 SQLSTATE `08`/`53` 类瞬时连接错误。提交阶段
256    /// 断连时事务是否已生效未知,重试可能重复执行副作用,因此不属于可重试范围。
257    ///
258    /// `operation` 每次被调用都应自行开启并结束一个事务(例如 `self.begin()` →
259    /// 业务语句 → `commit()`)。重试前 helper 按 `backoff * 2^(n-1)` 退避(最多放大
260    /// 32 倍);失败事务的回滚由被丢弃的事务句柄兜底。
261    ///
262    /// # 示例
263    ///
264    /// ```rust,ignore
265    /// let value = database
266    ///     .retry_transaction(3, Duration::from_millis(50), || async {
267    ///         let mut tx = database.begin().await?;
268    ///         // ... 业务语句 ...
269    ///         tx.commit().await?;
270    ///         Ok(())
271    ///     })
272    ///     .await?;
273    /// ```
274    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
302/// 整事务重试只接受序列化失败(40001)与死锁(40P01)。
303///
304/// SQLSTATE 归一复用 `yang-db` 的 [`SqlErrorKind`],与 `PgDatabase::retry_transaction`
305/// 保持一致。连接类(`08`/`53`)错误不在其列:提交阶段断连时事务结果不明,重试
306/// 可能重复执行已生效的副作用。
307fn 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/// 可克隆的连接池句柄,按运行时后端分派。
315///
316/// 由 [`AnyDatabase::pool`] 构造,供受保护查询层([`crate::table::TableQuery`])
317/// 在请求期共享连接池。变体在编译期按 feature 独占存在。
318#[derive(Clone)]
319pub enum AnyPool {
320    /// MySQL 连接池。
321    #[cfg(feature = "mysql")]
322    MySql(Arc<sqlx::MySqlPool>),
323    /// PostgreSQL 连接池。
324    #[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    /// 返回连接池所属后端。
339    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    /// 当持有 MySQL 连接池时返回其引用。
349    #[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    /// 当持有 PostgreSQL 连接池时返回其引用。
359    #[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/// 带逻辑数据源身份的连接池句柄。
370///
371/// `TableQuery` 持有它;事务在 `*_in_tx` 中与它比较数据源,跨源直接拒绝。
372#[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    /// 用逻辑数据源名与连接池构造句柄。
390    pub(crate) fn new(source: DatasourceId, pool: AnyPool) -> Self {
391        Self { source, pool }
392    }
393
394    /// 返回逻辑数据源名。
395    pub fn source(&self) -> &DatasourceId {
396        &self.source
397    }
398
399    /// 返回底层连接池。
400    pub fn pool(&self) -> &AnyPool {
401        &self.pool
402    }
403
404    /// 返回物理后端。
405    pub fn backend(&self) -> BackendKind {
406        self.pool.backend()
407    }
408}
409
410/// 两种后端事务的统一句柄,并携带逻辑数据源身份。
411///
412/// 旧构造器 [`AnyTransaction::MySql`] / [`AnyTransaction::Postgres`] 保持调用语法,
413/// 但产生的事务没有数据源身份(`source() == None`);框架内部通过
414/// [`AnyDatabase::begin`] 创建时会自动标注默认/具名源。
415pub 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
430/// 内部后端事务分派;各变体按 feature 独占编译。
431pub(crate) enum AnyTransactionKind {
432    /// MySQL 事务。
433    #[cfg(feature = "mysql")]
434    MySql(yang_db::mysql::Transaction),
435    /// PostgreSQL 事务。
436    #[cfg(feature = "postgres")]
437    Postgres(yang_db::postgres::Transaction),
438}
439
440impl AnyTransaction {
441    /// 用 MySQL 事务构造未标注数据源的事务句柄(兼容入口)。
442    #[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    /// 用 PostgreSQL 事务构造未标注数据源的事务句柄(兼容入口)。
452    #[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    /// 标注事务所属逻辑数据源。
462    #[must_use]
463    pub(crate) fn with_source(mut self, source: DatasourceId) -> Self {
464        self.source = Some(source);
465        self
466    }
467
468    /// 返回事务所属逻辑数据源;旧构造器创建的事务为 `None`。
469    pub fn source(&self) -> Option<&DatasourceId> {
470        self.source.as_ref()
471    }
472
473    /// 返回事务所属后端。
474    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    /// 内部使用:按后端解构事务。
484    pub(crate) fn kind_mut(&mut self) -> &mut AnyTransactionKind {
485        &mut self.kind
486    }
487
488    /// 当持有 MySQL 事务时返回其可变引用。
489    #[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    /// 当持有 PostgreSQL 事务时返回其可变引用。
499    #[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    /// 提交事务。
509    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    /// 在当前事务内创建保存点(与后端无关的封装)。
519    ///
520    /// PostgreSQL 走其后端原生 `SAVEPOINT`;MySQL 同样支持保存点语法,这里用
521    /// 校验过的标识符拼接控制语句。`name` 必须是 ASCII 标识符(字母/下划线开头,
522    /// 仅字母/数字/下划线),非法名称返回 [`DbError::InvalidArgument`]。
523    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    /// 回滚到指定保存点(`ROLLBACK TO SAVEPOINT`)。
536    ///
537    /// 只撤销保存点之后的工作;更早的保存点与外层事务不受影响。
538    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    /// 释放保存点(`RELEASE SAVEPOINT`)。
551    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    /// 回滚事务。
564    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/// 校验 MySQL 保存点名并拼出控制语句。
575///
576/// MySQL 的 `SAVEPOINT` 语法不接受绑定参数形式的标识符,故先按严格白名单
577/// (1..=128 字节,字母/下划线开头,仅字母/数字/下划线)校验,再拼接成 SQL,
578/// 从根上消除注入面。
579#[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/// 在 MySQL 事务上执行一条控制语句(保存点相关,无可绑定值)。
599#[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    /// 用惰性连接池构造 MySQL 容器:不建立真实网络连接,仅验证运行时抽象。
616    #[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    /// 用惰性连接池构造 PostgreSQL 容器:不建立真实网络连接,仅验证运行时抽象。
627    #[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    /// 同时启用两种后端时,`as_*` 必须对另一后端返回 `None`,避免静默误用。
676    #[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    /// [`AnyDatabase::pool`] 必须返回与容器后端一致的共享句柄,且两后端互斥。
690    #[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    /// [`AnyDatabase::pool`] 的 PostgreSQL 分支同样保持后端身份。
703    #[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    /// 能力门禁:缺失能力返回 `UnsupportedCapability`,且错误消息包含能力名。
716    #[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    /// 能力门禁:PostgreSQL 声明的保存点能力应通过校验。
736    #[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    /// 整事务重试:可重试错误按次数退避重试,成功后返回结果。
761    #[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    /// 整事务重试:不可重试错误立即返回,只执行一次。
785    #[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    /// 整事务重试:用尽次数后返回最后一次可重试错误。
803    #[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    /// 死锁(40P01)同样属于整事务可重试错误。
821    #[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    /// 唯一约束冲突(23505)是确定性错误,只执行一次。
845    #[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    /// 连接错误不在整事务重试范围(提交阶段断连结果不明),只执行一次。
863    #[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    /// SQLSTATE 08 类连接失败同样不参与整事务重试。
885    #[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    /// `max_attempts = 0` 维持既有语义:至少执行一次,不因参数为 0 而跳过。
903    #[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    /// 重试 helper 与后端无关;借一个惰性容器即可,不建立真实连接。
921    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    /// MySQL 保存点名白名单拒绝注入形态,合法名称原样拼入控制语句。
933    #[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}