#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DbError {
#[error("连接错误: {0}")]
ConnectionError(String),
#[error("查询错误: {0}")]
QueryError(String),
#[error("SQL 语法错误: {0}")]
SqlSyntaxError(String),
#[error("约束错误: {0}")]
ConstraintError(String),
#[error("类型转换错误: {0}")]
TypeConversionError(String),
#[error("序列化错误: {0}")]
SerializationError(String),
#[error("反序列化错误: {0}")]
DeserializationError(String),
#[error("事务错误: {0}")]
TransactionError(String),
#[error("表不存在: {0}")]
TableNotFound(String),
#[error("缺少 WHERE 条件,禁止全表操作")]
MissingWhereClause,
#[error("Redis 连接错误: {0}")]
RedisConnectionError(String),
#[error("Redis 命令错误: {0}")]
RedisCommandError(String),
#[error("Redis 连接池错误: {0}")]
RedisPoolError(String),
#[error("Redis 类型转换错误: {0}")]
RedisTypeConversionError(String),
#[error("Redis 超时错误: {0}")]
RedisTimeoutError(String),
#[error("Redis 错误: {0}")]
RedisError(RedisErrorInfo),
#[error("Redis 连接池已关闭")]
RedisPoolClosed,
#[error("HAVING 子句需要 GROUP BY 子句")]
MissingGroupByClause,
#[error("不支持的操作符: {0}")]
UnsupportedOperator(String),
#[error("参数非法: {0}")]
InvalidArgument(String),
#[error("未知错误: {0}")]
Unknown(String),
#[error("连接池已关闭")]
PoolClosed,
#[error("数据库错误 [{code}]: {message}", code = .0.code(), message = .0.message())]
DatabaseError(Box<SqlErrorInfo>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SqlErrorKind {
UniqueViolation,
ForeignKeyViolation,
NotNullViolation,
CheckViolation,
ExclusionViolation,
SerializationFailure,
DeadlockDetected,
QueryCanceled,
LockNotAvailable,
InFailedTransaction,
ConnectionFailure,
TooManyConnections,
UndefinedTable,
UndefinedColumn,
SyntaxError,
InvalidTextRepresentation,
StringDataRightTruncation,
NumericValueOutOfRange,
Other,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SqlErrorInfo {
code: String,
message: String,
constraint: Option<String>,
schema: Option<String>,
table: Option<String>,
column: Option<String>,
detail: Option<String>,
hint: Option<String>,
kind_hint: Option<SqlErrorKind>,
}
impl SqlErrorInfo {
pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
Self {
code: code.into(),
message: message.into(),
constraint: None,
schema: None,
table: None,
column: None,
detail: None,
hint: None,
kind_hint: None,
}
}
pub fn with_constraint(mut self, constraint: Option<String>) -> Self {
self.constraint = constraint;
self
}
pub fn with_schema(mut self, schema: Option<String>) -> Self {
self.schema = schema;
self
}
pub fn with_table(mut self, table: Option<String>) -> Self {
self.table = table;
self
}
pub fn with_column(mut self, column: Option<String>) -> Self {
self.column = column;
self
}
pub fn with_detail(mut self, detail: Option<String>) -> Self {
self.detail = detail;
self
}
pub fn with_hint(mut self, hint: Option<String>) -> Self {
self.hint = hint;
self
}
pub fn with_kind_hint(mut self, kind: SqlErrorKind) -> Self {
self.kind_hint = Some(kind);
self
}
pub fn code(&self) -> &str {
&self.code
}
pub fn message(&self) -> &str {
&self.message
}
pub fn constraint(&self) -> Option<&str> {
self.constraint.as_deref()
}
pub fn schema(&self) -> Option<&str> {
self.schema.as_deref()
}
pub fn table(&self) -> Option<&str> {
self.table.as_deref()
}
pub fn column(&self) -> Option<&str> {
self.column.as_deref()
}
pub fn detail(&self) -> Option<&str> {
self.detail.as_deref()
}
pub fn hint(&self) -> Option<&str> {
self.hint.as_deref()
}
pub fn class(&self) -> &str {
self.code.get(..2).unwrap_or(self.code.as_str())
}
pub fn kind(&self) -> SqlErrorKind {
if let Some(kind) = self.kind_hint {
return kind;
}
use SqlErrorKind as K;
match self.code.as_str() {
"23505" => K::UniqueViolation,
"23503" => K::ForeignKeyViolation,
"23502" => K::NotNullViolation,
"23514" => K::CheckViolation,
"23P01" => K::ExclusionViolation,
"40001" => K::SerializationFailure,
"40P01" => K::DeadlockDetected,
"57014" => K::QueryCanceled,
"55P03" => K::LockNotAvailable,
"25P02" => K::InFailedTransaction,
"08000" | "08001" | "08003" | "08004" | "08006" => K::ConnectionFailure,
"53300" => K::TooManyConnections,
"42P01" | "42S02" => K::UndefinedTable,
"42703" => K::UndefinedColumn,
"42601" | "42000" => K::SyntaxError,
"22P02" => K::InvalidTextRepresentation,
"22001" => K::StringDataRightTruncation,
"22003" => K::NumericValueOutOfRange,
_ => K::Other,
}
}
pub fn is_retryable(&self) -> bool {
matches!(self.code(), "40001" | "40P01") || matches!(self.class(), "08" | "53")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DbErrorCategory {
Client,
Conflict,
NotFound,
Transient,
Timeout,
Server,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RedisErrorKind {
Timeout,
Connection,
Io,
Type,
ExecAbort,
BusyLoading,
TryAgain,
NoScript,
Response,
Authentication,
Cluster,
Other,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RedisRetryMethod {
NoRetry,
RetryImmediately,
WaitAndRetry,
Reconnect,
}
#[derive(Debug, Clone)]
pub struct RedisErrorInfo {
pub kind: RedisErrorKind,
pub retry_method: RedisRetryMethod,
pub message: String,
}
impl RedisErrorInfo {
pub fn is_retryable(&self) -> bool {
!matches!(self.retry_method, RedisRetryMethod::NoRetry)
}
}
impl std::fmt::Display for RedisErrorInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"[{:?}/{:?}] {}",
self.kind, self.retry_method, self.message
)
}
}
impl DbError {
pub fn code(&self) -> u32 {
match self {
DbError::ConnectionError(_) => 800001,
DbError::QueryError(_) => 800002,
DbError::SqlSyntaxError(_) => 800003,
DbError::ConstraintError(_) => 800004,
DbError::TypeConversionError(_) => 800005,
DbError::SerializationError(_) => 800006,
DbError::DeserializationError(_) => 800007,
DbError::TransactionError(_) => 800008,
DbError::TableNotFound(_) => 800009,
DbError::MissingWhereClause => 800010,
DbError::RedisConnectionError(_) => 810001,
DbError::RedisCommandError(_) => 810002,
DbError::RedisPoolError(_) => 810003,
DbError::RedisTypeConversionError(_) => 810004,
DbError::RedisTimeoutError(_) => 810005,
DbError::RedisError(_) => 810006,
DbError::RedisPoolClosed => 810007,
DbError::MissingGroupByClause => 800011,
DbError::UnsupportedOperator(_) => 800012,
DbError::InvalidArgument(_) => 800013,
DbError::Unknown(_) => 899999,
DbError::PoolClosed => 800015,
DbError::DatabaseError(_) => 800014,
}
}
pub fn category(&self) -> DbErrorCategory {
use DbErrorCategory as C;
match self {
DbError::ConnectionError(_)
| DbError::RedisConnectionError(_)
| DbError::RedisPoolError(_)
| DbError::RedisTimeoutError(_) => C::Transient,
DbError::RedisError(info) if info.is_retryable() => C::Transient,
DbError::RedisError(_) | DbError::RedisPoolClosed => C::Server,
DbError::ConstraintError(_) => C::Conflict,
DbError::TableNotFound(_) => C::NotFound,
DbError::SqlSyntaxError(_)
| DbError::MissingWhereClause
| DbError::MissingGroupByClause
| DbError::UnsupportedOperator(_)
| DbError::InvalidArgument(_)
| DbError::SerializationError(_)
| DbError::DeserializationError(_)
| DbError::TypeConversionError(_)
| DbError::RedisTypeConversionError(_) => C::Client,
DbError::QueryError(_)
| DbError::TransactionError(_)
| DbError::RedisCommandError(_)
| DbError::Unknown(_)
| DbError::PoolClosed => C::Server,
DbError::DatabaseError(info) => match info.kind() {
SqlErrorKind::UniqueViolation
| SqlErrorKind::ForeignKeyViolation
| SqlErrorKind::NotNullViolation
| SqlErrorKind::CheckViolation
| SqlErrorKind::ExclusionViolation => C::Conflict,
SqlErrorKind::UndefinedTable => C::NotFound,
SqlErrorKind::SerializationFailure
| SqlErrorKind::DeadlockDetected
| SqlErrorKind::ConnectionFailure
| SqlErrorKind::TooManyConnections => C::Transient,
SqlErrorKind::QueryCanceled | SqlErrorKind::LockNotAvailable => C::Timeout,
SqlErrorKind::InFailedTransaction
| SqlErrorKind::UndefinedColumn
| SqlErrorKind::SyntaxError
| SqlErrorKind::InvalidTextRepresentation
| SqlErrorKind::StringDataRightTruncation
| SqlErrorKind::NumericValueOutOfRange => C::Client,
SqlErrorKind::Other => {
if info.is_retryable() {
C::Transient
} else if info.class() == "23" {
C::Conflict
} else if info.class() == "57" {
C::Timeout
} else {
C::Server
}
}
},
}
}
pub fn is_retryable(&self) -> bool {
self.category() == DbErrorCategory::Transient
}
pub fn is_constraint_violation(&self) -> bool {
match self {
DbError::ConstraintError(_) => true,
DbError::DatabaseError(info) => matches!(
info.kind(),
SqlErrorKind::UniqueViolation
| SqlErrorKind::ForeignKeyViolation
| SqlErrorKind::NotNullViolation
| SqlErrorKind::CheckViolation
| SqlErrorKind::ExclusionViolation
),
_ => false,
}
}
pub fn sql_error(&self) -> Option<&SqlErrorInfo> {
match self {
DbError::DatabaseError(info) => Some(info.as_ref()),
_ => None,
}
}
pub fn sqlstate(&self) -> Option<&str> {
self.sql_error().map(SqlErrorInfo::code)
}
pub fn constraint(&self) -> Option<&str> {
self.sql_error().and_then(SqlErrorInfo::constraint)
}
}
#[cfg_attr(not(any(feature = "mysql", feature = "postgres")), allow(dead_code))]
fn refine_mysql_integrity(info: SqlErrorInfo) -> SqlErrorInfo {
let message = info.message();
if message.contains("Duplicate entry") {
info.with_kind_hint(SqlErrorKind::UniqueViolation)
} else if message.contains("foreign key constraint") {
info.with_kind_hint(SqlErrorKind::ForeignKeyViolation)
} else if message.contains("cannot be null") {
info.with_kind_hint(SqlErrorKind::NotNullViolation)
} else if message.contains("Check constraint") {
info.with_kind_hint(SqlErrorKind::CheckViolation)
} else {
info
}
}
#[cfg(any(feature = "mysql", feature = "postgres"))]
impl From<sqlx::Error> for DbError {
fn from(err: sqlx::Error) -> Self {
match err {
sqlx::Error::Configuration(_) => DbError::ConnectionError(format!("配置错误: {}", err)),
sqlx::Error::Database(db_err) => {
let code = db_err
.code()
.map(|code| code.into_owned())
.unwrap_or_default();
let message = db_err.message().to_string();
let mut info = SqlErrorInfo::new(code, message)
.with_constraint(db_err.constraint().map(str::to_string))
.with_table(db_err.table().map(str::to_string));
#[cfg(feature = "postgres")]
if let Some(pg) = db_err.try_downcast_ref::<sqlx::postgres::PgDatabaseError>() {
let constraint = pg
.constraint()
.map(str::to_string)
.or_else(|| info.constraint().map(str::to_string));
let table = pg
.table()
.map(str::to_string)
.or_else(|| info.table().map(str::to_string));
let schema = pg.schema().map(str::to_string);
let column = pg.column().map(str::to_string);
let detail = pg.detail().map(str::to_string);
let hint = pg.hint().map(str::to_string);
info = info
.with_constraint(constraint)
.with_schema(schema)
.with_table(table)
.with_column(column)
.with_detail(detail)
.with_hint(hint);
}
if info.code().starts_with("23") && info.kind() == SqlErrorKind::Other {
info = refine_mysql_integrity(info);
}
DbError::DatabaseError(Box::new(info))
}
sqlx::Error::Io(_) => DbError::ConnectionError(format!("IO 错误: {}", err)),
sqlx::Error::Tls(_) => DbError::ConnectionError(format!("TLS 错误: {}", err)),
sqlx::Error::Protocol(_) => DbError::QueryError(format!("协议错误: {}", err)),
sqlx::Error::RowNotFound => DbError::QueryError("未找到记录".to_string()),
sqlx::Error::TypeNotFound { type_name } => {
DbError::TypeConversionError(format!("类型未找到: {}", type_name))
}
sqlx::Error::ColumnIndexOutOfBounds { index, len } => {
DbError::QueryError(format!("列索引越界: {} (总列数: {})", index, len))
}
sqlx::Error::ColumnNotFound(col) => DbError::QueryError(format!("列不存在: {}", col)),
sqlx::Error::ColumnDecode { index, source } => {
DbError::TypeConversionError(format!("列 {} 解码失败: {}", index, source))
}
sqlx::Error::Decode(source) => {
DbError::DeserializationError(format!("解码失败: {}", source))
}
sqlx::Error::PoolTimedOut => DbError::ConnectionError("连接池超时".to_string()),
sqlx::Error::PoolClosed => DbError::PoolClosed,
sqlx::Error::WorkerCrashed => DbError::ConnectionError("工作线程崩溃".to_string()),
_ => DbError::Unknown(format!("未知错误: {}", err)),
}
}
}
#[cfg(feature = "redis")]
pub fn map_redis_error_kind(kind: redis::ErrorKind) -> RedisErrorKind {
use redis::ErrorKind;
match kind {
ErrorKind::ResponseError => RedisErrorKind::Response,
ErrorKind::ParseError => RedisErrorKind::Other,
ErrorKind::AuthenticationFailed => RedisErrorKind::Authentication,
ErrorKind::TypeError => RedisErrorKind::Type,
ErrorKind::ExecAbortError => RedisErrorKind::ExecAbort,
ErrorKind::BusyLoadingError => RedisErrorKind::BusyLoading,
ErrorKind::NoScriptError => RedisErrorKind::NoScript,
ErrorKind::Moved
| ErrorKind::Ask
| ErrorKind::ClusterDown
| ErrorKind::CrossSlot
| ErrorKind::MasterDown
| ErrorKind::ClusterConnectionNotFound => RedisErrorKind::Cluster,
ErrorKind::TryAgain => RedisErrorKind::TryAgain,
ErrorKind::IoError => RedisErrorKind::Io,
_ => RedisErrorKind::Other,
}
}
#[cfg(feature = "redis")]
pub fn map_redis_retry_method(method: redis::RetryMethod) -> RedisRetryMethod {
use redis::RetryMethod;
match method {
RetryMethod::NoRetry => RedisRetryMethod::NoRetry,
RetryMethod::RetryImmediately => RedisRetryMethod::RetryImmediately,
RetryMethod::WaitAndRetry => RedisRetryMethod::WaitAndRetry,
RetryMethod::Reconnect
| RetryMethod::ReconnectFromInitialConnections
| RetryMethod::MovedRedirect
| RetryMethod::AskRedirect => RedisRetryMethod::Reconnect,
_ => RedisRetryMethod::NoRetry,
}
}
#[cfg(feature = "redis")]
impl From<redis::RedisError> for DbError {
fn from(err: redis::RedisError) -> Self {
use redis::ErrorKind;
if err.is_timeout() {
return DbError::RedisTimeoutError(format!("超时错误: {}", err));
}
if err.is_connection_dropped() || err.is_io_error() || err.is_connection_refusal() {
return DbError::RedisConnectionError(format!("连接错误: {}", err));
}
let kind = err.kind();
if matches!(kind, ErrorKind::TypeError) {
return DbError::RedisTypeConversionError(
"Redis 响应类型不匹配(原始响应已省略)".to_string(),
);
}
let info = RedisErrorInfo {
kind: map_redis_error_kind(kind),
retry_method: map_redis_retry_method(err.retry_method()),
message: err.to_string(),
};
match kind {
ErrorKind::ResponseError | ErrorKind::ExecAbortError | ErrorKind::ExtensionError => {
DbError::RedisCommandError(format!("Redis 错误: {}", err))
}
_ => DbError::RedisError(info),
}
}
}
#[cfg(feature = "redis")]
impl From<deadpool_redis::PoolError> for DbError {
fn from(err: deadpool_redis::PoolError) -> Self {
match err {
deadpool_redis::PoolError::Timeout(_) => {
DbError::RedisTimeoutError("连接池获取连接超时".to_string())
}
deadpool_redis::PoolError::Closed => DbError::RedisPoolClosed,
deadpool_redis::PoolError::NoRuntimeSpecified => {
DbError::RedisPoolError("未指定运行时".to_string())
}
deadpool_redis::PoolError::PostCreateHook(source) => {
DbError::RedisPoolError(format!("连接创建后钩子失败: {:?}", source))
}
deadpool_redis::PoolError::Backend(err) => DbError::from(err),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_error_display_chinese() {
let errors = vec![
DbError::ConnectionError("测试".to_string()),
DbError::QueryError("测试".to_string()),
DbError::SqlSyntaxError("测试".to_string()),
DbError::ConstraintError("测试".to_string()),
DbError::TypeConversionError("测试".to_string()),
DbError::SerializationError("测试".to_string()),
DbError::DeserializationError("测试".to_string()),
DbError::TransactionError("测试".to_string()),
DbError::TableNotFound("测试".to_string()),
DbError::MissingWhereClause,
DbError::RedisConnectionError("测试".to_string()),
DbError::RedisCommandError("测试".to_string()),
DbError::RedisPoolError("测试".to_string()),
DbError::RedisTypeConversionError("测试".to_string()),
DbError::RedisTimeoutError("测试".to_string()),
DbError::RedisError(RedisErrorInfo {
kind: RedisErrorKind::TryAgain,
retry_method: RedisRetryMethod::WaitAndRetry,
message: "测试".to_string(),
}),
DbError::RedisPoolClosed,
DbError::MissingGroupByClause,
DbError::UnsupportedOperator("测试".to_string()),
DbError::InvalidArgument("测试".to_string()),
DbError::Unknown("测试".to_string()),
DbError::PoolClosed,
DbError::DatabaseError(Box::new(SqlErrorInfo::new("23505", "duplicate key"))),
];
for error in errors {
let msg = format!("{}", error);
let has_chinese = msg.chars().any(|c| matches!(c, '\u{4e00}'..='\u{9fff}'));
assert!(has_chinese, "错误消息应该包含中文: {}", msg);
}
}
#[test]
fn test_connection_error() {
let err = DbError::ConnectionError("无法连接到数据库".to_string());
assert_eq!(format!("{}", err), "连接错误: 无法连接到数据库");
}
#[test]
fn test_query_error() {
let err = DbError::QueryError("查询超时".to_string());
assert_eq!(format!("{}", err), "查询错误: 查询超时");
}
#[test]
fn test_sql_syntax_error() {
let err = DbError::SqlSyntaxError("语法错误".to_string());
assert_eq!(format!("{}", err), "SQL 语法错误: 语法错误");
}
#[test]
fn test_constraint_error() {
let err = DbError::ConstraintError("主键冲突".to_string());
assert_eq!(format!("{}", err), "约束错误: 主键冲突");
}
#[test]
fn test_type_conversion_error() {
let err = DbError::TypeConversionError("无法转换类型".to_string());
assert_eq!(format!("{}", err), "类型转换错误: 无法转换类型");
}
#[test]
#[cfg(feature = "redis")]
fn test_redis_error_classification_distinguishes_type_and_command_errors() {
let type_error = redis::RedisError::from((redis::ErrorKind::TypeError, "返回值类型不匹配"));
let response_error =
redis::RedisError::from((redis::ErrorKind::ResponseError, "命令执行失败"));
assert!(matches!(
DbError::from(type_error),
DbError::RedisTypeConversionError(_)
));
assert!(matches!(
DbError::from(response_error),
DbError::RedisCommandError(_)
));
}
#[test]
fn test_serialization_error() {
let err = DbError::SerializationError("序列化失败".to_string());
assert_eq!(format!("{}", err), "序列化错误: 序列化失败");
}
#[test]
fn test_deserialization_error() {
let err = DbError::DeserializationError("反序列化失败".to_string());
assert_eq!(format!("{}", err), "反序列化错误: 反序列化失败");
}
#[test]
fn test_transaction_error() {
let err = DbError::TransactionError("事务已提交".to_string());
assert_eq!(format!("{}", err), "事务错误: 事务已提交");
}
#[test]
fn test_table_not_found() {
let err = DbError::TableNotFound("users".to_string());
assert_eq!(format!("{}", err), "表不存在: users");
}
#[test]
fn test_missing_where_clause() {
let err = DbError::MissingWhereClause;
assert_eq!(format!("{}", err), "缺少 WHERE 条件,禁止全表操作");
}
#[test]
fn test_unknown_error() {
let err = DbError::Unknown("未知问题".to_string());
assert_eq!(format!("{}", err), "未知错误: 未知问题");
}
#[test]
fn test_error_implements_std_error() {
let err = DbError::QueryError("测试".to_string());
let _: &dyn std::error::Error = &err;
}
#[test]
fn test_redis_connection_error() {
let err = DbError::RedisConnectionError("连接失败".to_string());
assert_eq!(format!("{}", err), "Redis 连接错误: 连接失败");
}
#[test]
fn test_redis_command_error() {
let err = DbError::RedisCommandError("命令执行失败".to_string());
assert_eq!(format!("{}", err), "Redis 命令错误: 命令执行失败");
}
#[test]
fn test_redis_pool_error() {
let err = DbError::RedisPoolError("连接池错误".to_string());
assert_eq!(format!("{}", err), "Redis 连接池错误: 连接池错误");
}
#[test]
fn test_redis_type_conversion_error() {
let err = DbError::RedisTypeConversionError("类型转换失败".to_string());
assert_eq!(format!("{}", err), "Redis 类型转换错误: 类型转换失败");
}
#[test]
fn test_redis_timeout_error() {
let err = DbError::RedisTimeoutError("操作超时".to_string());
assert_eq!(format!("{}", err), "Redis 超时错误: 操作超时");
}
#[test]
#[cfg(feature = "redis")]
fn test_pool_error_conversion() {
let pool_err = deadpool_redis::PoolError::Closed;
let db_err: DbError = pool_err.into();
assert!(matches!(db_err, DbError::RedisPoolClosed));
assert!(!db_err.is_retryable());
}
#[test]
fn test_unsupported_operator_error_message() {
let op = "BETWEEN";
let err = DbError::UnsupportedOperator(op.to_string());
assert_eq!(format!("{}", err), "不支持的操作符: BETWEEN");
}
#[test]
fn test_unsupported_operator_empty_string() {
let err = DbError::UnsupportedOperator(String::new());
assert_eq!(format!("{}", err), "不支持的操作符: ");
}
#[test]
fn test_unsupported_operator_special_chars() {
let err = DbError::UnsupportedOperator("<>".to_string());
assert_eq!(format!("{}", err), "不支持的操作符: <>");
}
#[test]
fn test_unsupported_operator_implements_std_error() {
let err = DbError::UnsupportedOperator("IN".to_string());
let _: &dyn std::error::Error = &err;
}
#[test]
fn test_unsupported_operator_message_contains_chinese() {
let err = DbError::UnsupportedOperator("XOR".to_string());
let msg = format!("{}", err);
let has_chinese = msg.chars().any(|c| matches!(c, '\u{4e00}'..='\u{9fff}'));
assert!(has_chinese, "错误消息应该包含中文: {}", msg);
}
#[test]
fn test_db_error_category_coverage() {
use super::DbErrorCategory as C;
assert_eq!(
DbError::ConnectionError("c".into()).category(),
C::Transient
);
assert_eq!(
DbError::RedisConnectionError("c".into()).category(),
C::Transient
);
assert_eq!(DbError::RedisPoolError("p".into()).category(), C::Transient);
assert_eq!(
DbError::RedisTimeoutError("t".into()).category(),
C::Transient
);
assert_eq!(
DbError::RedisError(RedisErrorInfo {
kind: RedisErrorKind::TryAgain,
retry_method: RedisRetryMethod::WaitAndRetry,
message: "t".into(),
})
.category(),
C::Transient
);
assert_eq!(
DbError::RedisError(RedisErrorInfo {
kind: RedisErrorKind::Response,
retry_method: RedisRetryMethod::NoRetry,
message: "r".into(),
})
.category(),
C::Server
);
assert_eq!(DbError::RedisPoolClosed.category(), C::Server);
assert!(!DbError::RedisPoolClosed.is_retryable());
assert_eq!(DbError::ConstraintError("c".into()).category(), C::Conflict);
assert_eq!(DbError::TableNotFound("t".into()).category(), C::NotFound);
assert_eq!(DbError::SqlSyntaxError("s".into()).category(), C::Client);
assert_eq!(DbError::MissingWhereClause.category(), C::Client);
assert_eq!(DbError::MissingGroupByClause.category(), C::Client);
assert_eq!(
DbError::UnsupportedOperator("o".into()).category(),
C::Client
);
assert_eq!(DbError::InvalidArgument("a".into()).category(), C::Client);
assert_eq!(
DbError::TypeConversionError("t".into()).category(),
C::Client
);
assert_eq!(
DbError::SerializationError("s".into()).category(),
C::Client
);
assert_eq!(
DbError::DeserializationError("d".into()).category(),
C::Client
);
assert_eq!(
DbError::RedisTypeConversionError("t".into()).category(),
C::Client
);
assert_eq!(DbError::QueryError("q".into()).category(), C::Server);
assert_eq!(DbError::TransactionError("t".into()).category(), C::Server);
assert_eq!(DbError::RedisCommandError("c".into()).category(), C::Server);
assert_eq!(DbError::Unknown("u".into()).category(), C::Server);
assert_eq!(DbError::PoolClosed.category(), C::Server);
assert_eq!(
DbError::DatabaseError(Box::new(SqlErrorInfo::new("23505", "dup"))).category(),
C::Conflict
);
assert_eq!(
DbError::DatabaseError(Box::new(SqlErrorInfo::new("40P01", "deadlock"))).category(),
C::Transient
);
assert_eq!(
DbError::DatabaseError(Box::new(SqlErrorInfo::new("57014", "canceled"))).category(),
C::Timeout
);
assert_eq!(
DbError::DatabaseError(Box::new(SqlErrorInfo::new("42P01", "missing"))).category(),
C::NotFound
);
}
#[test]
fn test_db_error_is_retryable() {
assert!(DbError::ConnectionError("c".into()).is_retryable());
assert!(DbError::RedisTimeoutError("t".into()).is_retryable());
assert!(!DbError::QueryError("q".into()).is_retryable());
assert!(!DbError::MissingWhereClause.is_retryable());
assert!(!DbError::ConstraintError("c".into()).is_retryable());
assert!(!DbError::PoolClosed.is_retryable());
assert!(
DbError::DatabaseError(Box::new(SqlErrorInfo::new("40001", "serialization")))
.is_retryable()
);
assert!(
DbError::DatabaseError(Box::new(SqlErrorInfo::new("40P01", "deadlock"))).is_retryable()
);
assert!(
!DbError::DatabaseError(Box::new(SqlErrorInfo::new("23505", "unique"))).is_retryable()
);
assert!(
!DbError::DatabaseError(Box::new(SqlErrorInfo::new("57014", "canceled")))
.is_retryable()
);
}
#[test]
fn retryable_sqlstates_are_exactly_postgres_transient_classes() {
use DbErrorCategory as C;
for code in [
"40001", "40P01", "08000", "08001", "08003", "08006",
"08007", "53300", "53200", "53100", ] {
let info = SqlErrorInfo::new(code, "transient");
assert!(info.is_retryable(), "{code} 应可重试");
let error = DbError::DatabaseError(Box::new(info));
assert_eq!(error.category(), C::Transient, "{code} 应归 Transient");
assert!(error.is_retryable(), "{code} 应可重试");
}
for code in [
"55P03", "57014", "25P02", "23505", "42P01", "42601", "22001", "22003", "40000", "XX000", ] {
let info = SqlErrorInfo::new(code, "non-transient");
assert!(!info.is_retryable(), "{code} 不应可重试");
assert_ne!(
DbError::DatabaseError(Box::new(info)).category(),
C::Transient,
"{code} 不应归 Transient"
);
}
for code in ["55P03", "57014", "57000"] {
assert_eq!(
DbError::DatabaseError(Box::new(SqlErrorInfo::new(code, "timeout"))).category(),
C::Timeout,
"{code} 应归 Timeout"
);
}
assert_eq!(
DbError::DatabaseError(Box::new(SqlErrorInfo::new("25P02", "aborted"))).category(),
C::Client
);
}
#[test]
fn structured_sqlstate_classification() {
let unique = SqlErrorInfo::new("23505", "duplicate key")
.with_constraint(Some("users_email_key".to_string()))
.with_table(Some("users".to_string()));
assert_eq!(unique.kind(), SqlErrorKind::UniqueViolation);
assert_eq!(unique.constraint(), Some("users_email_key"));
assert_eq!(unique.table(), Some("users"));
assert_eq!(unique.class(), "23");
let mysql_duplicate =
SqlErrorInfo::new("23000", "Duplicate entry 'x' for key 'users_email_key'");
assert_eq!(
refine_mysql_integrity(mysql_duplicate).kind(),
SqlErrorKind::UniqueViolation
);
let mysql_fk = SqlErrorInfo::new(
"23000",
"Cannot add or update a child row: a foreign key constraint fails",
);
assert_eq!(
refine_mysql_integrity(mysql_fk).kind(),
SqlErrorKind::ForeignKeyViolation
);
let not_null = SqlErrorInfo::new("23502", "null value in column");
assert_eq!(not_null.kind(), SqlErrorKind::NotNullViolation);
assert!(!not_null.is_retryable());
}
#[test]
fn test_db_error_code_unique() {
let codes: Vec<u32> = vec![
DbError::ConnectionError("".into()).code(),
DbError::QueryError("".into()).code(),
DbError::SqlSyntaxError("".into()).code(),
DbError::ConstraintError("".into()).code(),
DbError::TypeConversionError("".into()).code(),
DbError::SerializationError("".into()).code(),
DbError::DeserializationError("".into()).code(),
DbError::TransactionError("".into()).code(),
DbError::TableNotFound("".into()).code(),
DbError::MissingWhereClause.code(),
DbError::RedisConnectionError("".into()).code(),
DbError::RedisCommandError("".into()).code(),
DbError::RedisPoolError("".into()).code(),
DbError::RedisTypeConversionError("".into()).code(),
DbError::RedisTimeoutError("".into()).code(),
DbError::RedisError(RedisErrorInfo {
kind: RedisErrorKind::Other,
retry_method: RedisRetryMethod::NoRetry,
message: "".into(),
})
.code(),
DbError::RedisPoolClosed.code(),
DbError::MissingGroupByClause.code(),
DbError::UnsupportedOperator("".into()).code(),
DbError::InvalidArgument("".into()).code(),
DbError::Unknown("".into()).code(),
DbError::PoolClosed.code(),
DbError::DatabaseError(Box::new(SqlErrorInfo::new("23505", ""))).code(),
];
let mut sorted = codes.clone();
sorted.sort();
sorted.dedup();
assert_eq!(codes.len(), sorted.len(), "所有变体的 code 应全部唯一");
for &c in &codes {
assert!((800000..900000).contains(&c), "code {} 不在 8xxxxx 段", c);
}
}
}