Skip to main content

yang_db/
error.rs

1/// 数据库错误类型
2///
3/// 标注 `#[non_exhaustive]`:未来新增变体不构成跨 crate 破坏性变更(下游 match 需
4/// 带 `_` 臂)。同 crate 内的穷举 match 不受影响。
5#[derive(Debug, thiserror::Error)]
6#[non_exhaustive]
7pub enum DbError {
8    #[error("连接错误: {0}")]
9    ConnectionError(String),
10
11    #[error("查询错误: {0}")]
12    QueryError(String),
13
14    #[error("SQL 语法错误: {0}")]
15    SqlSyntaxError(String),
16
17    #[error("约束错误: {0}")]
18    ConstraintError(String),
19
20    #[error("类型转换错误: {0}")]
21    TypeConversionError(String),
22
23    #[error("序列化错误: {0}")]
24    SerializationError(String),
25
26    #[error("反序列化错误: {0}")]
27    DeserializationError(String),
28
29    #[error("事务错误: {0}")]
30    TransactionError(String),
31
32    #[error("表不存在: {0}")]
33    TableNotFound(String),
34
35    #[error("缺少 WHERE 条件,禁止全表操作")]
36    MissingWhereClause,
37
38    // Redis 相关错误
39    #[error("Redis 连接错误: {0}")]
40    RedisConnectionError(String),
41
42    #[error("Redis 命令错误: {0}")]
43    RedisCommandError(String),
44
45    #[error("Redis 连接池错误: {0}")]
46    RedisPoolError(String),
47
48    #[error("Redis 类型转换错误: {0}")]
49    RedisTypeConversionError(String),
50
51    #[error("Redis 超时错误: {0}")]
52    RedisTimeoutError(String),
53
54    /// 结构化 Redis 错误:保留协议层 `ErrorKind` 与重试建议,避免把
55    /// `LOADING`/`TRYAGAIN`/`NOSCRIPT` 等可重试错误压成不可重试的字符串。
56    #[error("Redis 错误: {0}")]
57    RedisError(RedisErrorInfo),
58
59    /// Redis 连接池已关闭(不可重试)。
60    #[error("Redis 连接池已关闭")]
61    RedisPoolClosed,
62
63    #[error("HAVING 子句需要 GROUP BY 子句")]
64    MissingGroupByClause,
65
66    /// 不支持的操作符错误,当传入的操作符不在支持集合中时返回
67    #[error("不支持的操作符: {0}")]
68    UnsupportedOperator(String),
69
70    /// 参数非法(调用方过错):批量数据列集不一致、空数据、batch_size 为 0 等。
71    ///
72    /// 与 [`DbError::SerializationError`] 区分——后者专表「(反)序列化失败」,
73    /// 此变体专表「入参本身不合法」,便于调用方按变体精确分流(DB-14)。
74    #[error("参数非法: {0}")]
75    InvalidArgument(String),
76
77    #[error("未知错误: {0}")]
78    Unknown(String),
79
80    /// 连接池已关闭(非瞬时错误,不应重试)。
81    #[error("连接池已关闭")]
82    PoolClosed,
83
84    /// 携带 SQLSTATE 与约束元数据的结构化数据库错误。
85    ///
86    /// `sqlx::Error::Database` 一律映射到本变体,便于下游按
87    /// [`SqlErrorInfo::kind`] / [`SqlErrorInfo::code`] 精确分流,
88    /// 而不是解析本地化报文。旧的字符串变体保留用于手工构造与向后兼容。
89    #[error("数据库错误 [{code}]: {message}", code = .0.code(), message = .0.message())]
90    DatabaseError(Box<SqlErrorInfo>),
91}
92
93/// SQLSTATE 归一后的错误类别。
94///
95/// 覆盖 PostgreSQL 与 MySQL 的常见完整性/并发/连接错误;未识别码落到
96/// [`SqlErrorKind::Other`],调用方仍可通过 [`SqlErrorInfo::code`] 读原始码。
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98#[non_exhaustive]
99pub enum SqlErrorKind {
100    /// 唯一约束冲突(SQLSTATE 23505 / MySQL 23000 且报文可判定)。
101    UniqueViolation,
102    /// 外键约束冲突(23503)。
103    ForeignKeyViolation,
104    /// 非空约束冲突(23502)。
105    NotNullViolation,
106    /// CHECK 约束冲突(23514)。
107    CheckViolation,
108    /// 排他约束冲突(23P01)。
109    ExclusionViolation,
110    /// 序列化失败,可整事务重试(40001)。
111    SerializationFailure,
112    /// 死锁检测,可整事务重试(40P01)。
113    DeadlockDetected,
114    /// 查询被取消(57014)。
115    QueryCanceled,
116    /// 锁不可用(55P03)。
117    LockNotAvailable,
118    /// 事务已中止,必须先 ROLLBACK(25P02)。
119    InFailedTransaction,
120    /// 连接失败/断开(08000/08003/08006 等)。
121    ConnectionFailure,
122    /// 连接数超限(53300)。
123    TooManyConnections,
124    /// 表不存在(42P01 / MySQL 42S02)。
125    UndefinedTable,
126    /// 列不存在(42703)。
127    UndefinedColumn,
128    /// SQL 语法错误(42601 / 42000)。
129    SyntaxError,
130    /// 文本表示的输入非法(22P02)。
131    InvalidTextRepresentation,
132    /// 字符串超长(22001)。
133    StringDataRightTruncation,
134    /// 数值超出范围(22003)。
135    NumericValueOutOfRange,
136    /// 未归一的 SQLSTATE。
137    Other,
138}
139
140/// 结构化数据库错误信息(SQLSTATE + 常用诊断字段)。
141#[derive(Debug, Clone, PartialEq, Eq)]
142#[non_exhaustive]
143pub struct SqlErrorInfo {
144    code: String,
145    message: String,
146    constraint: Option<String>,
147    schema: Option<String>,
148    table: Option<String>,
149    column: Option<String>,
150    detail: Option<String>,
151    hint: Option<String>,
152    /// 当 SQLSTATE 不足以区分时(MySQL 的 23000)由驱动报文补充的类别。
153    kind_hint: Option<SqlErrorKind>,
154}
155
156impl SqlErrorInfo {
157    /// 创建仅含 SQLSTATE 与报文的错误信息。
158    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
159        Self {
160            code: code.into(),
161            message: message.into(),
162            constraint: None,
163            schema: None,
164            table: None,
165            column: None,
166            detail: None,
167            hint: None,
168            kind_hint: None,
169        }
170    }
171
172    /// 设置约束名。
173    pub fn with_constraint(mut self, constraint: Option<String>) -> Self {
174        self.constraint = constraint;
175        self
176    }
177
178    /// 设置 schema 名。
179    pub fn with_schema(mut self, schema: Option<String>) -> Self {
180        self.schema = schema;
181        self
182    }
183
184    /// 设置表名。
185    pub fn with_table(mut self, table: Option<String>) -> Self {
186        self.table = table;
187        self
188    }
189
190    /// 设置列名。
191    pub fn with_column(mut self, column: Option<String>) -> Self {
192        self.column = column;
193        self
194    }
195
196    /// 设置 DETAIL 诊断信息。
197    pub fn with_detail(mut self, detail: Option<String>) -> Self {
198        self.detail = detail;
199        self
200    }
201
202    /// 设置 HINT 诊断信息。
203    pub fn with_hint(mut self, hint: Option<String>) -> Self {
204        self.hint = hint;
205        self
206    }
207
208    /// 在 SQLSTATE 不足以区分时补充错误类别(如 MySQL 23000)。
209    pub fn with_kind_hint(mut self, kind: SqlErrorKind) -> Self {
210        self.kind_hint = Some(kind);
211        self
212    }
213
214    /// 原始 SQLSTATE 五字符码(MySQL 可能返回更短的类码)。
215    pub fn code(&self) -> &str {
216        &self.code
217    }
218
219    /// 数据库返回的报文。
220    pub fn message(&self) -> &str {
221        &self.message
222    }
223
224    /// 触发错误的约束名(如唯一索引名)。
225    pub fn constraint(&self) -> Option<&str> {
226        self.constraint.as_deref()
227    }
228
229    /// 相关 schema。
230    pub fn schema(&self) -> Option<&str> {
231        self.schema.as_deref()
232    }
233
234    /// 相关表。
235    pub fn table(&self) -> Option<&str> {
236        self.table.as_deref()
237    }
238
239    /// 相关列。
240    pub fn column(&self) -> Option<&str> {
241        self.column.as_deref()
242    }
243
244    /// DETAIL 诊断信息。
245    pub fn detail(&self) -> Option<&str> {
246        self.detail.as_deref()
247    }
248
249    /// HINT 诊断信息。
250    pub fn hint(&self) -> Option<&str> {
251        self.hint.as_deref()
252    }
253
254    /// SQLSTATE 类别(前两位),如 `23`、`40`、`42`。
255    pub fn class(&self) -> &str {
256        self.code.get(..2).unwrap_or(self.code.as_str())
257    }
258
259    /// 归一后的错误类别。
260    pub fn kind(&self) -> SqlErrorKind {
261        if let Some(kind) = self.kind_hint {
262            return kind;
263        }
264        use SqlErrorKind as K;
265        match self.code.as_str() {
266            "23505" => K::UniqueViolation,
267            "23503" => K::ForeignKeyViolation,
268            "23502" => K::NotNullViolation,
269            "23514" => K::CheckViolation,
270            "23P01" => K::ExclusionViolation,
271            "40001" => K::SerializationFailure,
272            "40P01" => K::DeadlockDetected,
273            "57014" => K::QueryCanceled,
274            "55P03" => K::LockNotAvailable,
275            "25P02" => K::InFailedTransaction,
276            "08000" | "08001" | "08003" | "08004" | "08006" => K::ConnectionFailure,
277            "53300" => K::TooManyConnections,
278            "42P01" | "42S02" => K::UndefinedTable,
279            "42703" => K::UndefinedColumn,
280            "42601" | "42000" => K::SyntaxError,
281            "22P02" => K::InvalidTextRepresentation,
282            "22001" => K::StringDataRightTruncation,
283            "22003" => K::NumericValueOutOfRange,
284            _ => K::Other,
285        }
286    }
287
288    /// 是否为可安全重试的瞬时错误。
289    ///
290    /// 仅 PostgreSQL 的 `40001`(序列化失败)、`40P01`(死锁)、`08` 类
291    /// (连接失败/断开)与 `53` 类(资源不足,如连接数超限)返回 `true`。
292    /// 其余 SQLSTATE 一律不可重试,尤其是:
293    ///
294    /// - `55P03` 锁不可用(锁等待超时):属于 [`DbErrorCategory::Timeout`],
295    ///   是否重试由调用方决定;
296    /// - `57014` 语句被取消:同样归 [`DbErrorCategory::Timeout`],不是瞬时故障;
297    /// - `25P02` 事务已中止:必须先 `ROLLBACK`,重试只会在中止事务上继续失败。
298    pub fn is_retryable(&self) -> bool {
299        matches!(self.code(), "40001" | "40P01") || matches!(self.class(), "08" | "53")
300    }
301}
302
303/// 数据库错误的引擎级分类(与具体 HTTP/传输层无关)。
304///
305/// 用于下游统一适配(弹性重试、错误上报分桶)。`Transient` 表示瞬时故障、可重试;
306/// 其余为确定性错误,重试无益。
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308#[non_exhaustive]
309pub enum DbErrorCategory {
310    /// 调用方过错(SQL 语法、缺 WHERE/GROUP BY、不支持的操作符、参数非法、(反)序列化)
311    Client,
312    /// 约束冲突(唯一键/外键/非空/检查)
313    Conflict,
314    /// 资源不存在(表不存在)
315    NotFound,
316    /// 瞬时故障(连接/超时/连接池),可重试
317    Transient,
318    /// 操作被取消或锁等待超时(57014 / 55P03),是否重试由调用方决定
319    Timeout,
320    /// 服务端/未知错误
321    Server,
322}
323
324/// Redis 协议层错误类别(与 `redis::ErrorKind` 对齐,但不暴露上游类型)。
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326#[non_exhaustive]
327pub enum RedisErrorKind {
328    /// 超时
329    Timeout,
330    /// 连接断开 / 连接拒绝
331    Connection,
332    /// IO 错误
333    Io,
334    /// 类型不匹配
335    Type,
336    /// 事务因先前错误被丢弃
337    ExecAbort,
338    /// 服务端正在加载数据
339    BusyLoading,
340    /// 服务端要求重试
341    TryAgain,
342    /// 脚本不存在
343    NoScript,
344    /// 其他服务端响应错误
345    Response,
346    /// 认证失败
347    Authentication,
348    /// Cluster 拓扑错误(MOVED/ASK/CLUSTERDOWN 等)
349    Cluster,
350    /// 其他
351    Other,
352}
353
354/// Redis 建议的重试方式(与 `redis::RetryMethod` 对齐)。
355#[derive(Debug, Clone, Copy, PartialEq, Eq)]
356#[non_exhaustive]
357pub enum RedisRetryMethod {
358    /// 不重试(永久错误)
359    NoRetry,
360    /// 立即重试
361    RetryImmediately,
362    /// 延迟后重试
363    WaitAndRetry,
364    /// 重新建立连接后重试
365    Reconnect,
366}
367
368/// 结构化 Redis 错误信息。
369#[derive(Debug, Clone)]
370pub struct RedisErrorInfo {
371    /// 协议层错误类别
372    pub kind: RedisErrorKind,
373    /// 建议的重试方式
374    pub retry_method: RedisRetryMethod,
375    /// 错误消息(不含命令参数与 key)
376    pub message: String,
377}
378
379impl RedisErrorInfo {
380    /// 是否为可重试错误。
381    pub fn is_retryable(&self) -> bool {
382        !matches!(self.retry_method, RedisRetryMethod::NoRetry)
383    }
384}
385
386impl std::fmt::Display for RedisErrorInfo {
387    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
388        write!(
389            f,
390            "[{:?}/{:?}] {}",
391            self.kind, self.retry_method, self.message
392        )
393    }
394}
395
396impl DbError {
397    /// 稳定错误码(8xxxxx 段,独立于 yang-base 的 BaseError 码命名空间)。
398    ///
399    /// 与 [`DbError::category`] 同源维护;新增变体需同步补码。
400    pub fn code(&self) -> u32 {
401        match self {
402            DbError::ConnectionError(_) => 800001,
403            DbError::QueryError(_) => 800002,
404            DbError::SqlSyntaxError(_) => 800003,
405            DbError::ConstraintError(_) => 800004,
406            DbError::TypeConversionError(_) => 800005,
407            DbError::SerializationError(_) => 800006,
408            DbError::DeserializationError(_) => 800007,
409            DbError::TransactionError(_) => 800008,
410            DbError::TableNotFound(_) => 800009,
411            DbError::MissingWhereClause => 800010,
412            DbError::RedisConnectionError(_) => 810001,
413            DbError::RedisCommandError(_) => 810002,
414            DbError::RedisPoolError(_) => 810003,
415            DbError::RedisTypeConversionError(_) => 810004,
416            DbError::RedisTimeoutError(_) => 810005,
417            DbError::RedisError(_) => 810006,
418            DbError::RedisPoolClosed => 810007,
419            DbError::MissingGroupByClause => 800011,
420            DbError::UnsupportedOperator(_) => 800012,
421            DbError::InvalidArgument(_) => 800013,
422            DbError::Unknown(_) => 899999,
423            DbError::PoolClosed => 800015,
424            DbError::DatabaseError(_) => 800014,
425        }
426    }
427
428    /// 引擎级分类。是 [`DbError::is_retryable`] 的单一事实源。
429    pub fn category(&self) -> DbErrorCategory {
430        use DbErrorCategory as C;
431        match self {
432            // 瞬时:连接/超时/连接池 —— 可重试
433            DbError::ConnectionError(_)
434            | DbError::RedisConnectionError(_)
435            | DbError::RedisPoolError(_)
436            | DbError::RedisTimeoutError(_) => C::Transient,
437            // 结构化 Redis 错误:按协议层建议的重试方式分类
438            DbError::RedisError(info) if info.is_retryable() => C::Transient,
439            DbError::RedisError(_) | DbError::RedisPoolClosed => C::Server,
440            // 约束冲突
441            DbError::ConstraintError(_) => C::Conflict,
442            // 不存在
443            DbError::TableNotFound(_) => C::NotFound,
444            // 调用方过错:语法/缺子句/不支持操作符/(反)序列化/类型转换
445            DbError::SqlSyntaxError(_)
446            | DbError::MissingWhereClause
447            | DbError::MissingGroupByClause
448            | DbError::UnsupportedOperator(_)
449            | DbError::InvalidArgument(_)
450            | DbError::SerializationError(_)
451            | DbError::DeserializationError(_)
452            | DbError::TypeConversionError(_)
453            | DbError::RedisTypeConversionError(_) => C::Client,
454            // 服务端/未知:查询错误、Redis 命令错误、未知
455            DbError::QueryError(_)
456            | DbError::TransactionError(_)
457            | DbError::RedisCommandError(_)
458            | DbError::Unknown(_)
459            | DbError::PoolClosed => C::Server,
460            // 结构化 SQLSTATE 按错误类别分流
461            DbError::DatabaseError(info) => match info.kind() {
462                SqlErrorKind::UniqueViolation
463                | SqlErrorKind::ForeignKeyViolation
464                | SqlErrorKind::NotNullViolation
465                | SqlErrorKind::CheckViolation
466                | SqlErrorKind::ExclusionViolation => C::Conflict,
467                SqlErrorKind::UndefinedTable => C::NotFound,
468                SqlErrorKind::SerializationFailure
469                | SqlErrorKind::DeadlockDetected
470                | SqlErrorKind::ConnectionFailure
471                | SqlErrorKind::TooManyConnections => C::Transient,
472                // 57014 语句取消与 55P03 锁等待超时不是瞬时故障:
473                // 前者通常由调用方超时/取消主动触发,后者需由调用方决定是否重试。
474                SqlErrorKind::QueryCanceled | SqlErrorKind::LockNotAvailable => C::Timeout,
475                SqlErrorKind::InFailedTransaction
476                | SqlErrorKind::UndefinedColumn
477                | SqlErrorKind::SyntaxError
478                | SqlErrorKind::InvalidTextRepresentation
479                | SqlErrorKind::StringDataRightTruncation
480                | SqlErrorKind::NumericValueOutOfRange => C::Client,
481                SqlErrorKind::Other => {
482                    if info.is_retryable() {
483                        // 08xxx/53xxx 与 40001/40P01 之外的 40 类不重试。
484                        C::Transient
485                    } else if info.class() == "23" {
486                        C::Conflict
487                    } else if info.class() == "57" {
488                        C::Timeout
489                    } else {
490                        C::Server
491                    }
492                }
493            },
494        }
495    }
496
497    /// 是否为可重试的瞬时错误(等价 `category() == Transient`)。
498    pub fn is_retryable(&self) -> bool {
499        self.category() == DbErrorCategory::Transient
500    }
501
502    /// 是否为约束冲突(手工构造的旧变体或结构化 SQLSTATE 的 23 类)。
503    pub fn is_constraint_violation(&self) -> bool {
504        match self {
505            DbError::ConstraintError(_) => true,
506            DbError::DatabaseError(info) => matches!(
507                info.kind(),
508                SqlErrorKind::UniqueViolation
509                    | SqlErrorKind::ForeignKeyViolation
510                    | SqlErrorKind::NotNullViolation
511                    | SqlErrorKind::CheckViolation
512                    | SqlErrorKind::ExclusionViolation
513            ),
514            _ => false,
515        }
516    }
517
518    /// 结构化 SQLSTATE 错误信息(仅 [`DbError::DatabaseError`] 有值)。
519    pub fn sql_error(&self) -> Option<&SqlErrorInfo> {
520        match self {
521            DbError::DatabaseError(info) => Some(info.as_ref()),
522            _ => None,
523        }
524    }
525
526    /// 原始 SQLSTATE 码。
527    pub fn sqlstate(&self) -> Option<&str> {
528        self.sql_error().map(SqlErrorInfo::code)
529    }
530
531    /// 触发错误的约束名。
532    pub fn constraint(&self) -> Option<&str> {
533        self.sql_error().and_then(SqlErrorInfo::constraint)
534    }
535}
536
537/// MySQL 把唯一/外键/非空/CHECK 统一报为 SQLSTATE 23000,这里按驱动报文细分。
538///
539/// 仅在结构化字段(`constraint()`)不足以判定时使用;它是对 MySQL 协议限制的
540/// 兜底,不是主要分流路径。
541#[cfg_attr(not(any(feature = "mysql", feature = "postgres")), allow(dead_code))]
542fn refine_mysql_integrity(info: SqlErrorInfo) -> SqlErrorInfo {
543    let message = info.message();
544    if message.contains("Duplicate entry") {
545        info.with_kind_hint(SqlErrorKind::UniqueViolation)
546    } else if message.contains("foreign key constraint") {
547        info.with_kind_hint(SqlErrorKind::ForeignKeyViolation)
548    } else if message.contains("cannot be null") {
549        info.with_kind_hint(SqlErrorKind::NotNullViolation)
550    } else if message.contains("Check constraint") {
551        info.with_kind_hint(SqlErrorKind::CheckViolation)
552    } else {
553        info
554    }
555}
556
557/// 从 sqlx::Error 转换为 DbError
558#[cfg(any(feature = "mysql", feature = "postgres"))]
559impl From<sqlx::Error> for DbError {
560    fn from(err: sqlx::Error) -> Self {
561        match err {
562            sqlx::Error::Configuration(_) => DbError::ConnectionError(format!("配置错误: {}", err)),
563            sqlx::Error::Database(db_err) => {
564                let code = db_err
565                    .code()
566                    .map(|code| code.into_owned())
567                    .unwrap_or_default();
568                let message = db_err.message().to_string();
569
570                let mut info = SqlErrorInfo::new(code, message)
571                    .with_constraint(db_err.constraint().map(str::to_string))
572                    .with_table(db_err.table().map(str::to_string));
573
574                // PostgreSQL 驱动额外携带 schema/column/DETAIL/HINT 诊断字段。
575                #[cfg(feature = "postgres")]
576                if let Some(pg) = db_err.try_downcast_ref::<sqlx::postgres::PgDatabaseError>() {
577                    let constraint = pg
578                        .constraint()
579                        .map(str::to_string)
580                        .or_else(|| info.constraint().map(str::to_string));
581                    let table = pg
582                        .table()
583                        .map(str::to_string)
584                        .or_else(|| info.table().map(str::to_string));
585                    let schema = pg.schema().map(str::to_string);
586                    let column = pg.column().map(str::to_string);
587                    let detail = pg.detail().map(str::to_string);
588                    let hint = pg.hint().map(str::to_string);
589                    info = info
590                        .with_constraint(constraint)
591                        .with_schema(schema)
592                        .with_table(table)
593                        .with_column(column)
594                        .with_detail(detail)
595                        .with_hint(hint);
596                }
597
598                // MySQL 的完整性错误统一报 23000,需要按报文细分唯一/外键/非空/CHECK,
599                // 否则下游无法区分「可归因的输入冲突」与真正的数据完整性故障。
600                if info.code().starts_with("23") && info.kind() == SqlErrorKind::Other {
601                    info = refine_mysql_integrity(info);
602                }
603
604                DbError::DatabaseError(Box::new(info))
605            }
606            sqlx::Error::Io(_) => DbError::ConnectionError(format!("IO 错误: {}", err)),
607            sqlx::Error::Tls(_) => DbError::ConnectionError(format!("TLS 错误: {}", err)),
608            sqlx::Error::Protocol(_) => DbError::QueryError(format!("协议错误: {}", err)),
609            sqlx::Error::RowNotFound => DbError::QueryError("未找到记录".to_string()),
610            sqlx::Error::TypeNotFound { type_name } => {
611                DbError::TypeConversionError(format!("类型未找到: {}", type_name))
612            }
613            sqlx::Error::ColumnIndexOutOfBounds { index, len } => {
614                DbError::QueryError(format!("列索引越界: {} (总列数: {})", index, len))
615            }
616            sqlx::Error::ColumnNotFound(col) => DbError::QueryError(format!("列不存在: {}", col)),
617            sqlx::Error::ColumnDecode { index, source } => {
618                DbError::TypeConversionError(format!("列 {} 解码失败: {}", index, source))
619            }
620            sqlx::Error::Decode(source) => {
621                DbError::DeserializationError(format!("解码失败: {}", source))
622            }
623            sqlx::Error::PoolTimedOut => DbError::ConnectionError("连接池超时".to_string()),
624            sqlx::Error::PoolClosed => DbError::PoolClosed,
625            sqlx::Error::WorkerCrashed => DbError::ConnectionError("工作线程崩溃".to_string()),
626            _ => DbError::Unknown(format!("未知错误: {}", err)),
627        }
628    }
629}
630
631/// 将 redis 协议层的 `ErrorKind` 映射为稳定的 [`RedisErrorKind`]。
632#[cfg(feature = "redis")]
633pub fn map_redis_error_kind(kind: redis::ErrorKind) -> RedisErrorKind {
634    use redis::ErrorKind;
635    match kind {
636        ErrorKind::ResponseError => RedisErrorKind::Response,
637        ErrorKind::ParseError => RedisErrorKind::Other,
638        ErrorKind::AuthenticationFailed => RedisErrorKind::Authentication,
639        ErrorKind::TypeError => RedisErrorKind::Type,
640        ErrorKind::ExecAbortError => RedisErrorKind::ExecAbort,
641        ErrorKind::BusyLoadingError => RedisErrorKind::BusyLoading,
642        ErrorKind::NoScriptError => RedisErrorKind::NoScript,
643        ErrorKind::Moved
644        | ErrorKind::Ask
645        | ErrorKind::ClusterDown
646        | ErrorKind::CrossSlot
647        | ErrorKind::MasterDown
648        | ErrorKind::ClusterConnectionNotFound => RedisErrorKind::Cluster,
649        ErrorKind::TryAgain => RedisErrorKind::TryAgain,
650        ErrorKind::IoError => RedisErrorKind::Io,
651        _ => RedisErrorKind::Other,
652    }
653}
654
655/// 将 redis 协议层的 `RetryMethod` 映射为稳定的 [`RedisRetryMethod`]。
656#[cfg(feature = "redis")]
657pub fn map_redis_retry_method(method: redis::RetryMethod) -> RedisRetryMethod {
658    use redis::RetryMethod;
659    match method {
660        RetryMethod::NoRetry => RedisRetryMethod::NoRetry,
661        RetryMethod::RetryImmediately => RedisRetryMethod::RetryImmediately,
662        RetryMethod::WaitAndRetry => RedisRetryMethod::WaitAndRetry,
663        RetryMethod::Reconnect
664        | RetryMethod::ReconnectFromInitialConnections
665        | RetryMethod::MovedRedirect
666        | RetryMethod::AskRedirect => RedisRetryMethod::Reconnect,
667        // RetryMethod 是 non_exhaustive:未知策略按不可重试处理,避免误重试。
668        _ => RedisRetryMethod::NoRetry,
669    }
670}
671
672/// 从 redis::RedisError 转换为 DbError
673#[cfg(feature = "redis")]
674impl From<redis::RedisError> for DbError {
675    fn from(err: redis::RedisError) -> Self {
676        // 用协议层稳定 API 分类,而非脆弱的 Display 子串匹配:
677        // - 超时优先(is_timeout 涵盖连接超时与响应超时)
678        // - 连接断开 / IO / 连接拒绝 → 连接错误
679        // - 类型不匹配(TypeError)→ 类型转换错误
680        // - 服务端明确要求重试(LOADING/TRYAGAIN/MOVED 等)→ 结构化可重试错误
681        // - 其余响应错误 → 命令错误(不可重试兜底)
682        use redis::ErrorKind;
683        if err.is_timeout() {
684            return DbError::RedisTimeoutError(format!("超时错误: {}", err));
685        }
686        if err.is_connection_dropped() || err.is_io_error() || err.is_connection_refusal() {
687            return DbError::RedisConnectionError(format!("连接错误: {}", err));
688        }
689        let kind = err.kind();
690        if matches!(kind, ErrorKind::TypeError) {
691            // redis-rs 的 Display 会附带 `(response was <Value>)`,可能包含缓存值/
692            // token。类型错误只返回固定文案,绝不拼接原始响应。
693            return DbError::RedisTypeConversionError(
694                "Redis 响应类型不匹配(原始响应已省略)".to_string(),
695            );
696        }
697        let info = RedisErrorInfo {
698            kind: map_redis_error_kind(kind),
699            retry_method: map_redis_retry_method(err.retry_method()),
700            message: err.to_string(),
701        };
702        match kind {
703            // 保留历史变体:普通响应错误与事务中止仍归为命令错误。
704            ErrorKind::ResponseError | ErrorKind::ExecAbortError | ErrorKind::ExtensionError => {
705                DbError::RedisCommandError(format!("Redis 错误: {}", err))
706            }
707            _ => DbError::RedisError(info),
708        }
709    }
710}
711
712/// 从 deadpool_redis::PoolError 转换为 DbError
713#[cfg(feature = "redis")]
714impl From<deadpool_redis::PoolError> for DbError {
715    fn from(err: deadpool_redis::PoolError) -> Self {
716        match err {
717            deadpool_redis::PoolError::Timeout(_) => {
718                DbError::RedisTimeoutError("连接池获取连接超时".to_string())
719            }
720            // 关闭是确定性状态,不能归入「可重试的瞬时错误」。
721            deadpool_redis::PoolError::Closed => DbError::RedisPoolClosed,
722            deadpool_redis::PoolError::NoRuntimeSpecified => {
723                DbError::RedisPoolError("未指定运行时".to_string())
724            }
725            deadpool_redis::PoolError::PostCreateHook(source) => {
726                DbError::RedisPoolError(format!("连接创建后钩子失败: {:?}", source))
727            }
728            deadpool_redis::PoolError::Backend(err) => DbError::from(err),
729        }
730    }
731}
732
733#[cfg(test)]
734mod tests {
735    use super::*;
736
737    #[test]
738    fn test_error_display_chinese() {
739        // 测试所有 19 个错误变体的中文消息
740        let errors = vec![
741            DbError::ConnectionError("测试".to_string()),
742            DbError::QueryError("测试".to_string()),
743            DbError::SqlSyntaxError("测试".to_string()),
744            DbError::ConstraintError("测试".to_string()),
745            DbError::TypeConversionError("测试".to_string()),
746            DbError::SerializationError("测试".to_string()),
747            DbError::DeserializationError("测试".to_string()),
748            DbError::TransactionError("测试".to_string()),
749            DbError::TableNotFound("测试".to_string()),
750            DbError::MissingWhereClause,
751            DbError::RedisConnectionError("测试".to_string()),
752            DbError::RedisCommandError("测试".to_string()),
753            DbError::RedisPoolError("测试".to_string()),
754            DbError::RedisTypeConversionError("测试".to_string()),
755            DbError::RedisTimeoutError("测试".to_string()),
756            DbError::RedisError(RedisErrorInfo {
757                kind: RedisErrorKind::TryAgain,
758                retry_method: RedisRetryMethod::WaitAndRetry,
759                message: "测试".to_string(),
760            }),
761            DbError::RedisPoolClosed,
762            DbError::MissingGroupByClause,
763            DbError::UnsupportedOperator("测试".to_string()),
764            DbError::InvalidArgument("测试".to_string()),
765            DbError::Unknown("测试".to_string()),
766            DbError::PoolClosed,
767            DbError::DatabaseError(Box::new(SqlErrorInfo::new("23505", "duplicate key"))),
768        ];
769
770        for error in errors {
771            let msg = format!("{}", error);
772            // 验证错误消息包含中文字符
773            let has_chinese = msg.chars().any(|c| matches!(c, '\u{4e00}'..='\u{9fff}'));
774            assert!(has_chinese, "错误消息应该包含中文: {}", msg);
775        }
776    }
777
778    #[test]
779    fn test_connection_error() {
780        let err = DbError::ConnectionError("无法连接到数据库".to_string());
781        assert_eq!(format!("{}", err), "连接错误: 无法连接到数据库");
782    }
783
784    #[test]
785    fn test_query_error() {
786        let err = DbError::QueryError("查询超时".to_string());
787        assert_eq!(format!("{}", err), "查询错误: 查询超时");
788    }
789
790    #[test]
791    fn test_sql_syntax_error() {
792        let err = DbError::SqlSyntaxError("语法错误".to_string());
793        assert_eq!(format!("{}", err), "SQL 语法错误: 语法错误");
794    }
795
796    #[test]
797    fn test_constraint_error() {
798        let err = DbError::ConstraintError("主键冲突".to_string());
799        assert_eq!(format!("{}", err), "约束错误: 主键冲突");
800    }
801
802    #[test]
803    fn test_type_conversion_error() {
804        let err = DbError::TypeConversionError("无法转换类型".to_string());
805        assert_eq!(format!("{}", err), "类型转换错误: 无法转换类型");
806    }
807
808    /// 对抗性验证:Redis 类型错误必须精确归类,普通响应错误不能混入类型转换错误。
809    #[test]
810    #[cfg(feature = "redis")]
811    fn test_redis_error_classification_distinguishes_type_and_command_errors() {
812        let type_error = redis::RedisError::from((redis::ErrorKind::TypeError, "返回值类型不匹配"));
813        let response_error =
814            redis::RedisError::from((redis::ErrorKind::ResponseError, "命令执行失败"));
815
816        assert!(matches!(
817            DbError::from(type_error),
818            DbError::RedisTypeConversionError(_)
819        ));
820        assert!(matches!(
821            DbError::from(response_error),
822            DbError::RedisCommandError(_)
823        ));
824    }
825
826    #[test]
827    fn test_serialization_error() {
828        let err = DbError::SerializationError("序列化失败".to_string());
829        assert_eq!(format!("{}", err), "序列化错误: 序列化失败");
830    }
831
832    #[test]
833    fn test_deserialization_error() {
834        let err = DbError::DeserializationError("反序列化失败".to_string());
835        assert_eq!(format!("{}", err), "反序列化错误: 反序列化失败");
836    }
837
838    #[test]
839    fn test_transaction_error() {
840        let err = DbError::TransactionError("事务已提交".to_string());
841        assert_eq!(format!("{}", err), "事务错误: 事务已提交");
842    }
843
844    #[test]
845    fn test_table_not_found() {
846        let err = DbError::TableNotFound("users".to_string());
847        assert_eq!(format!("{}", err), "表不存在: users");
848    }
849
850    #[test]
851    fn test_missing_where_clause() {
852        let err = DbError::MissingWhereClause;
853        assert_eq!(format!("{}", err), "缺少 WHERE 条件,禁止全表操作");
854    }
855
856    #[test]
857    fn test_unknown_error() {
858        let err = DbError::Unknown("未知问题".to_string());
859        assert_eq!(format!("{}", err), "未知错误: 未知问题");
860    }
861
862    #[test]
863    fn test_error_implements_std_error() {
864        // 验证 DbError 实现了 std::error::Error trait
865        let err = DbError::QueryError("测试".to_string());
866        let _: &dyn std::error::Error = &err;
867    }
868
869    // Redis 错误测试
870    #[test]
871    fn test_redis_connection_error() {
872        let err = DbError::RedisConnectionError("连接失败".to_string());
873        assert_eq!(format!("{}", err), "Redis 连接错误: 连接失败");
874    }
875
876    #[test]
877    fn test_redis_command_error() {
878        let err = DbError::RedisCommandError("命令执行失败".to_string());
879        assert_eq!(format!("{}", err), "Redis 命令错误: 命令执行失败");
880    }
881
882    #[test]
883    fn test_redis_pool_error() {
884        let err = DbError::RedisPoolError("连接池错误".to_string());
885        assert_eq!(format!("{}", err), "Redis 连接池错误: 连接池错误");
886    }
887
888    #[test]
889    fn test_redis_type_conversion_error() {
890        let err = DbError::RedisTypeConversionError("类型转换失败".to_string());
891        assert_eq!(format!("{}", err), "Redis 类型转换错误: 类型转换失败");
892    }
893
894    #[test]
895    fn test_redis_timeout_error() {
896        let err = DbError::RedisTimeoutError("操作超时".to_string());
897        assert_eq!(format!("{}", err), "Redis 超时错误: 操作超时");
898    }
899
900    #[test]
901    #[cfg(feature = "redis")]
902    fn test_pool_error_conversion() {
903        // 测试 deadpool_redis::PoolError 转换
904        let pool_err = deadpool_redis::PoolError::Closed;
905        let db_err: DbError = pool_err.into();
906        assert!(matches!(db_err, DbError::RedisPoolClosed));
907        assert!(!db_err.is_retryable());
908    }
909
910    // 验证需求: 4.4 — UnsupportedOperator 变体错误消息格式测试
911    #[test]
912    fn test_unsupported_operator_error_message() {
913        // 验证错误消息格式为 "不支持的操作符: {op}"
914        let op = "BETWEEN";
915        let err = DbError::UnsupportedOperator(op.to_string());
916        assert_eq!(format!("{}", err), "不支持的操作符: BETWEEN");
917    }
918
919    #[test]
920    fn test_unsupported_operator_empty_string() {
921        // 验证空字符串操作符的错误消息格式
922        let err = DbError::UnsupportedOperator(String::new());
923        assert_eq!(format!("{}", err), "不支持的操作符: ");
924    }
925
926    #[test]
927    fn test_unsupported_operator_special_chars() {
928        // 验证包含特殊字符的操作符错误消息格式
929        let err = DbError::UnsupportedOperator("<>".to_string());
930        assert_eq!(format!("{}", err), "不支持的操作符: <>");
931    }
932
933    #[test]
934    fn test_unsupported_operator_implements_std_error() {
935        // 验证 UnsupportedOperator 变体实现了 std::error::Error trait
936        let err = DbError::UnsupportedOperator("IN".to_string());
937        let _: &dyn std::error::Error = &err;
938    }
939
940    #[test]
941    fn test_unsupported_operator_message_contains_chinese() {
942        // 验证错误消息包含中文字符("不支持的操作符")
943        let err = DbError::UnsupportedOperator("XOR".to_string());
944        let msg = format!("{}", err);
945        let has_chinese = msg.chars().any(|c| matches!(c, '\u{4e00}'..='\u{9fff}'));
946        assert!(has_chinese, "错误消息应该包含中文: {}", msg);
947    }
948
949    /// DB-7:category() 覆盖全部 19 个变体
950    #[test]
951    fn test_db_error_category_coverage() {
952        use super::DbErrorCategory as C;
953        // Transient:连接/超时/连接池
954        assert_eq!(
955            DbError::ConnectionError("c".into()).category(),
956            C::Transient
957        );
958        assert_eq!(
959            DbError::RedisConnectionError("c".into()).category(),
960            C::Transient
961        );
962        assert_eq!(DbError::RedisPoolError("p".into()).category(), C::Transient);
963        assert_eq!(
964            DbError::RedisTimeoutError("t".into()).category(),
965            C::Transient
966        );
967        assert_eq!(
968            DbError::RedisError(RedisErrorInfo {
969                kind: RedisErrorKind::TryAgain,
970                retry_method: RedisRetryMethod::WaitAndRetry,
971                message: "t".into(),
972            })
973            .category(),
974            C::Transient
975        );
976        assert_eq!(
977            DbError::RedisError(RedisErrorInfo {
978                kind: RedisErrorKind::Response,
979                retry_method: RedisRetryMethod::NoRetry,
980                message: "r".into(),
981            })
982            .category(),
983            C::Server
984        );
985        assert_eq!(DbError::RedisPoolClosed.category(), C::Server);
986        assert!(!DbError::RedisPoolClosed.is_retryable());
987        // Conflict:约束冲突
988        assert_eq!(DbError::ConstraintError("c".into()).category(), C::Conflict);
989        // NotFound:表不存在
990        assert_eq!(DbError::TableNotFound("t".into()).category(), C::NotFound);
991        // Client:语法/缺子句/不支持操作符/参数非法/类型转换/(反)序列化/Redis类型转换
992        assert_eq!(DbError::SqlSyntaxError("s".into()).category(), C::Client);
993        assert_eq!(DbError::MissingWhereClause.category(), C::Client);
994        assert_eq!(DbError::MissingGroupByClause.category(), C::Client);
995        assert_eq!(
996            DbError::UnsupportedOperator("o".into()).category(),
997            C::Client
998        );
999        assert_eq!(DbError::InvalidArgument("a".into()).category(), C::Client);
1000        assert_eq!(
1001            DbError::TypeConversionError("t".into()).category(),
1002            C::Client
1003        );
1004        assert_eq!(
1005            DbError::SerializationError("s".into()).category(),
1006            C::Client
1007        );
1008        assert_eq!(
1009            DbError::DeserializationError("d".into()).category(),
1010            C::Client
1011        );
1012        assert_eq!(
1013            DbError::RedisTypeConversionError("t".into()).category(),
1014            C::Client
1015        );
1016        // Server:查询错误/事务错误/Redis命令错误/未知
1017        assert_eq!(DbError::QueryError("q".into()).category(), C::Server);
1018        assert_eq!(DbError::TransactionError("t".into()).category(), C::Server);
1019        assert_eq!(DbError::RedisCommandError("c".into()).category(), C::Server);
1020        assert_eq!(DbError::Unknown("u".into()).category(), C::Server);
1021        assert_eq!(DbError::PoolClosed.category(), C::Server);
1022        // DatabaseError:按 SQLSTATE 分流
1023        assert_eq!(
1024            DbError::DatabaseError(Box::new(SqlErrorInfo::new("23505", "dup"))).category(),
1025            C::Conflict
1026        );
1027        assert_eq!(
1028            DbError::DatabaseError(Box::new(SqlErrorInfo::new("40P01", "deadlock"))).category(),
1029            C::Transient
1030        );
1031        assert_eq!(
1032            DbError::DatabaseError(Box::new(SqlErrorInfo::new("57014", "canceled"))).category(),
1033            C::Timeout
1034        );
1035        assert_eq!(
1036            DbError::DatabaseError(Box::new(SqlErrorInfo::new("42P01", "missing"))).category(),
1037            C::NotFound
1038        );
1039    }
1040
1041    /// DB-7:is_retryable = (category == Transient)
1042    #[test]
1043    fn test_db_error_is_retryable() {
1044        assert!(DbError::ConnectionError("c".into()).is_retryable());
1045        assert!(DbError::RedisTimeoutError("t".into()).is_retryable());
1046        assert!(!DbError::QueryError("q".into()).is_retryable());
1047        assert!(!DbError::MissingWhereClause.is_retryable());
1048        assert!(!DbError::ConstraintError("c".into()).is_retryable());
1049        assert!(!DbError::PoolClosed.is_retryable());
1050        assert!(
1051            DbError::DatabaseError(Box::new(SqlErrorInfo::new("40001", "serialization")))
1052                .is_retryable()
1053        );
1054        assert!(
1055            DbError::DatabaseError(Box::new(SqlErrorInfo::new("40P01", "deadlock"))).is_retryable()
1056        );
1057        assert!(
1058            !DbError::DatabaseError(Box::new(SqlErrorInfo::new("23505", "unique"))).is_retryable()
1059        );
1060        assert!(
1061            !DbError::DatabaseError(Box::new(SqlErrorInfo::new("57014", "canceled")))
1062                .is_retryable()
1063        );
1064    }
1065
1066    /// P0-2:逐 SQLSTATE 校验可重试分类。
1067    ///
1068    /// 只有 40001/40P01 与 08xxx、53xxx 是瞬时错误;55P03、57014 归 Timeout
1069    /// 且不可重试;25P02 必须先 ROLLBACK,重试无效。
1070    #[test]
1071    fn retryable_sqlstates_are_exactly_postgres_transient_classes() {
1072        use DbErrorCategory as C;
1073
1074        for code in [
1075            "40001", "40P01", // 序列化失败 / 死锁
1076            "08000", "08001", "08003", "08006",
1077            "08007", // 连接失败/断开(08 类全类)
1078            "53300", "53200", "53100", // 资源不足(53 类全类)
1079        ] {
1080            let info = SqlErrorInfo::new(code, "transient");
1081            assert!(info.is_retryable(), "{code} 应可重试");
1082            let error = DbError::DatabaseError(Box::new(info));
1083            assert_eq!(error.category(), C::Transient, "{code} 应归 Transient");
1084            assert!(error.is_retryable(), "{code} 应可重试");
1085        }
1086
1087        for code in [
1088            "55P03", // lock_timeout:锁不可用,交由调用方决定
1089            "57014", // statement_timeout / 主动取消
1090            "25P02", // 事务已中止
1091            "23505", "42P01", "42601", "22001", "22003", // 确定性错误
1092            "40000", // 40 类中非 40001/40P01 的码不得重试
1093            "XX000", // 内部错误
1094        ] {
1095            let info = SqlErrorInfo::new(code, "non-transient");
1096            assert!(!info.is_retryable(), "{code} 不应可重试");
1097            assert_ne!(
1098                DbError::DatabaseError(Box::new(info)).category(),
1099                C::Transient,
1100                "{code} 不应归 Transient"
1101            );
1102        }
1103
1104        // 超时类显式归 Timeout,而非 Transient。
1105        for code in ["55P03", "57014", "57000"] {
1106            assert_eq!(
1107                DbError::DatabaseError(Box::new(SqlErrorInfo::new(code, "timeout"))).category(),
1108                C::Timeout,
1109                "{code} 应归 Timeout"
1110            );
1111        }
1112        assert_eq!(
1113            DbError::DatabaseError(Box::new(SqlErrorInfo::new("25P02", "aborted"))).category(),
1114            C::Client
1115        );
1116    }
1117
1118    /// SQLSTATE 归一、约束元数据与 MySQL 23000 细分。
1119    #[test]
1120    fn structured_sqlstate_classification() {
1121        let unique = SqlErrorInfo::new("23505", "duplicate key")
1122            .with_constraint(Some("users_email_key".to_string()))
1123            .with_table(Some("users".to_string()));
1124        assert_eq!(unique.kind(), SqlErrorKind::UniqueViolation);
1125        assert_eq!(unique.constraint(), Some("users_email_key"));
1126        assert_eq!(unique.table(), Some("users"));
1127        assert_eq!(unique.class(), "23");
1128
1129        let mysql_duplicate =
1130            SqlErrorInfo::new("23000", "Duplicate entry 'x' for key 'users_email_key'");
1131        assert_eq!(
1132            refine_mysql_integrity(mysql_duplicate).kind(),
1133            SqlErrorKind::UniqueViolation
1134        );
1135
1136        let mysql_fk = SqlErrorInfo::new(
1137            "23000",
1138            "Cannot add or update a child row: a foreign key constraint fails",
1139        );
1140        assert_eq!(
1141            refine_mysql_integrity(mysql_fk).kind(),
1142            SqlErrorKind::ForeignKeyViolation
1143        );
1144
1145        let not_null = SqlErrorInfo::new("23502", "null value in column");
1146        assert_eq!(not_null.kind(), SqlErrorKind::NotNullViolation);
1147        assert!(!not_null.is_retryable());
1148    }
1149
1150    /// DB-7:code() 唯一性(19 个变体均为独立码段)
1151    #[test]
1152    fn test_db_error_code_unique() {
1153        let codes: Vec<u32> = vec![
1154            DbError::ConnectionError("".into()).code(),
1155            DbError::QueryError("".into()).code(),
1156            DbError::SqlSyntaxError("".into()).code(),
1157            DbError::ConstraintError("".into()).code(),
1158            DbError::TypeConversionError("".into()).code(),
1159            DbError::SerializationError("".into()).code(),
1160            DbError::DeserializationError("".into()).code(),
1161            DbError::TransactionError("".into()).code(),
1162            DbError::TableNotFound("".into()).code(),
1163            DbError::MissingWhereClause.code(),
1164            DbError::RedisConnectionError("".into()).code(),
1165            DbError::RedisCommandError("".into()).code(),
1166            DbError::RedisPoolError("".into()).code(),
1167            DbError::RedisTypeConversionError("".into()).code(),
1168            DbError::RedisTimeoutError("".into()).code(),
1169            DbError::RedisError(RedisErrorInfo {
1170                kind: RedisErrorKind::Other,
1171                retry_method: RedisRetryMethod::NoRetry,
1172                message: "".into(),
1173            })
1174            .code(),
1175            DbError::RedisPoolClosed.code(),
1176            DbError::MissingGroupByClause.code(),
1177            DbError::UnsupportedOperator("".into()).code(),
1178            DbError::InvalidArgument("".into()).code(),
1179            DbError::Unknown("".into()).code(),
1180            DbError::PoolClosed.code(),
1181            DbError::DatabaseError(Box::new(SqlErrorInfo::new("23505", ""))).code(),
1182        ];
1183        let mut sorted = codes.clone();
1184        sorted.sort();
1185        sorted.dedup();
1186        assert_eq!(codes.len(), sorted.len(), "所有变体的 code 应全部唯一");
1187        // 所有码在 8xxxxx 段
1188        for &c in &codes {
1189            assert!((800000..900000).contains(&c), "code {} 不在 8xxxxx 段", c);
1190        }
1191    }
1192}