1#[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 #[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 #[error("Redis 错误: {0}")]
57 RedisError(RedisErrorInfo),
58
59 #[error("Redis 连接池已关闭")]
61 RedisPoolClosed,
62
63 #[error("HAVING 子句需要 GROUP BY 子句")]
64 MissingGroupByClause,
65
66 #[error("不支持的操作符: {0}")]
68 UnsupportedOperator(String),
69
70 #[error("参数非法: {0}")]
75 InvalidArgument(String),
76
77 #[error("未知错误: {0}")]
78 Unknown(String),
79
80 #[error("连接池已关闭")]
82 PoolClosed,
83
84 #[error("数据库错误 [{code}]: {message}", code = .0.code(), message = .0.message())]
90 DatabaseError(Box<SqlErrorInfo>),
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98#[non_exhaustive]
99pub enum SqlErrorKind {
100 UniqueViolation,
102 ForeignKeyViolation,
104 NotNullViolation,
106 CheckViolation,
108 ExclusionViolation,
110 SerializationFailure,
112 DeadlockDetected,
114 QueryCanceled,
116 LockNotAvailable,
118 InFailedTransaction,
120 ConnectionFailure,
122 TooManyConnections,
124 UndefinedTable,
126 UndefinedColumn,
128 SyntaxError,
130 InvalidTextRepresentation,
132 StringDataRightTruncation,
134 NumericValueOutOfRange,
136 Other,
138}
139
140#[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 kind_hint: Option<SqlErrorKind>,
154}
155
156impl SqlErrorInfo {
157 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 pub fn with_constraint(mut self, constraint: Option<String>) -> Self {
174 self.constraint = constraint;
175 self
176 }
177
178 pub fn with_schema(mut self, schema: Option<String>) -> Self {
180 self.schema = schema;
181 self
182 }
183
184 pub fn with_table(mut self, table: Option<String>) -> Self {
186 self.table = table;
187 self
188 }
189
190 pub fn with_column(mut self, column: Option<String>) -> Self {
192 self.column = column;
193 self
194 }
195
196 pub fn with_detail(mut self, detail: Option<String>) -> Self {
198 self.detail = detail;
199 self
200 }
201
202 pub fn with_hint(mut self, hint: Option<String>) -> Self {
204 self.hint = hint;
205 self
206 }
207
208 pub fn with_kind_hint(mut self, kind: SqlErrorKind) -> Self {
210 self.kind_hint = Some(kind);
211 self
212 }
213
214 pub fn code(&self) -> &str {
216 &self.code
217 }
218
219 pub fn message(&self) -> &str {
221 &self.message
222 }
223
224 pub fn constraint(&self) -> Option<&str> {
226 self.constraint.as_deref()
227 }
228
229 pub fn schema(&self) -> Option<&str> {
231 self.schema.as_deref()
232 }
233
234 pub fn table(&self) -> Option<&str> {
236 self.table.as_deref()
237 }
238
239 pub fn column(&self) -> Option<&str> {
241 self.column.as_deref()
242 }
243
244 pub fn detail(&self) -> Option<&str> {
246 self.detail.as_deref()
247 }
248
249 pub fn hint(&self) -> Option<&str> {
251 self.hint.as_deref()
252 }
253
254 pub fn class(&self) -> &str {
256 self.code.get(..2).unwrap_or(self.code.as_str())
257 }
258
259 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 pub fn is_retryable(&self) -> bool {
299 matches!(self.code(), "40001" | "40P01") || matches!(self.class(), "08" | "53")
300 }
301}
302
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308#[non_exhaustive]
309pub enum DbErrorCategory {
310 Client,
312 Conflict,
314 NotFound,
316 Transient,
318 Timeout,
320 Server,
322}
323
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326#[non_exhaustive]
327pub enum RedisErrorKind {
328 Timeout,
330 Connection,
332 Io,
334 Type,
336 ExecAbort,
338 BusyLoading,
340 TryAgain,
342 NoScript,
344 Response,
346 Authentication,
348 Cluster,
350 Other,
352}
353
354#[derive(Debug, Clone, Copy, PartialEq, Eq)]
356#[non_exhaustive]
357pub enum RedisRetryMethod {
358 NoRetry,
360 RetryImmediately,
362 WaitAndRetry,
364 Reconnect,
366}
367
368#[derive(Debug, Clone)]
370pub struct RedisErrorInfo {
371 pub kind: RedisErrorKind,
373 pub retry_method: RedisRetryMethod,
375 pub message: String,
377}
378
379impl RedisErrorInfo {
380 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 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 pub fn category(&self) -> DbErrorCategory {
430 use DbErrorCategory as C;
431 match self {
432 DbError::ConnectionError(_)
434 | DbError::RedisConnectionError(_)
435 | DbError::RedisPoolError(_)
436 | DbError::RedisTimeoutError(_) => C::Transient,
437 DbError::RedisError(info) if info.is_retryable() => C::Transient,
439 DbError::RedisError(_) | DbError::RedisPoolClosed => C::Server,
440 DbError::ConstraintError(_) => C::Conflict,
442 DbError::TableNotFound(_) => C::NotFound,
444 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 DbError::QueryError(_)
456 | DbError::TransactionError(_)
457 | DbError::RedisCommandError(_)
458 | DbError::Unknown(_)
459 | DbError::PoolClosed => C::Server,
460 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 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 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 pub fn is_retryable(&self) -> bool {
499 self.category() == DbErrorCategory::Transient
500 }
501
502 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 pub fn sql_error(&self) -> Option<&SqlErrorInfo> {
520 match self {
521 DbError::DatabaseError(info) => Some(info.as_ref()),
522 _ => None,
523 }
524 }
525
526 pub fn sqlstate(&self) -> Option<&str> {
528 self.sql_error().map(SqlErrorInfo::code)
529 }
530
531 pub fn constraint(&self) -> Option<&str> {
533 self.sql_error().and_then(SqlErrorInfo::constraint)
534 }
535}
536
537#[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#[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 #[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 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#[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#[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 _ => RedisRetryMethod::NoRetry,
669 }
670}
671
672#[cfg(feature = "redis")]
674impl From<redis::RedisError> for DbError {
675 fn from(err: redis::RedisError) -> Self {
676 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 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 ErrorKind::ResponseError | ErrorKind::ExecAbortError | ErrorKind::ExtensionError => {
705 DbError::RedisCommandError(format!("Redis 错误: {}", err))
706 }
707 _ => DbError::RedisError(info),
708 }
709 }
710}
711
712#[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 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 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 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 #[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 let err = DbError::QueryError("测试".to_string());
866 let _: &dyn std::error::Error = &err;
867 }
868
869 #[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 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 #[test]
912 fn test_unsupported_operator_error_message() {
913 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 let err = DbError::UnsupportedOperator(String::new());
923 assert_eq!(format!("{}", err), "不支持的操作符: ");
924 }
925
926 #[test]
927 fn test_unsupported_operator_special_chars() {
928 let err = DbError::UnsupportedOperator("<>".to_string());
930 assert_eq!(format!("{}", err), "不支持的操作符: <>");
931 }
932
933 #[test]
934 fn test_unsupported_operator_implements_std_error() {
935 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 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 #[test]
951 fn test_db_error_category_coverage() {
952 use super::DbErrorCategory as C;
953 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 assert_eq!(DbError::ConstraintError("c".into()).category(), C::Conflict);
989 assert_eq!(DbError::TableNotFound("t".into()).category(), C::NotFound);
991 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 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 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 #[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 #[test]
1071 fn retryable_sqlstates_are_exactly_postgres_transient_classes() {
1072 use DbErrorCategory as C;
1073
1074 for code in [
1075 "40001", "40P01", "08000", "08001", "08003", "08006",
1077 "08007", "53300", "53200", "53100", ] {
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", "57014", "25P02", "23505", "42P01", "42601", "22001", "22003", "40000", "XX000", ] {
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 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 #[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 #[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 for &c in &codes {
1189 assert!((800000..900000).contains(&c), "code {} 不在 8xxxxx 段", c);
1190 }
1191 }
1192}