sqlx_core_guts/mysql/
error.rs

1use std::error::Error;
2use std::fmt::{self, Debug, Display, Formatter};
3
4use crate::error::DatabaseError;
5use crate::mysql::protocol::response::ErrPacket;
6use smallvec::alloc::borrow::Cow;
7
8/// An error returned from the MySQL database.
9pub struct MySqlDatabaseError(pub(super) ErrPacket);
10
11impl MySqlDatabaseError {
12    /// The [SQLSTATE](https://dev.mysql.com/doc/refman/8.0/en/server-error-reference.html) code for this error.
13    pub fn code(&self) -> Option<&str> {
14        self.0.sql_state.as_deref()
15    }
16
17    /// The [number](https://dev.mysql.com/doc/refman/8.0/en/server-error-reference.html)
18    /// for this error.
19    ///
20    /// MySQL tends to use SQLSTATE as a general error category, and the error number as a more
21    /// granular indication of the error.
22    pub fn number(&self) -> u16 {
23        self.0.error_code
24    }
25
26    /// The human-readable error message.
27    pub fn message(&self) -> &str {
28        &self.0.error_message
29    }
30}
31
32impl Debug for MySqlDatabaseError {
33    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
34        f.debug_struct("MySqlDatabaseError")
35            .field("code", &self.code())
36            .field("number", &self.number())
37            .field("message", &self.message())
38            .finish()
39    }
40}
41
42impl Display for MySqlDatabaseError {
43    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
44        if let Some(code) = &self.code() {
45            write!(f, "{} ({}): {}", self.number(), code, self.message())
46        } else {
47            write!(f, "{}: {}", self.number(), self.message())
48        }
49    }
50}
51
52impl Error for MySqlDatabaseError {}
53
54impl DatabaseError for MySqlDatabaseError {
55    #[inline]
56    fn message(&self) -> &str {
57        self.message()
58    }
59
60    #[inline]
61    fn code(&self) -> Option<Cow<'_, str>> {
62        self.code().map(Cow::Borrowed)
63    }
64
65    #[doc(hidden)]
66    fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {
67        self
68    }
69
70    #[doc(hidden)]
71    fn as_error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {
72        self
73    }
74
75    #[doc(hidden)]
76    fn into_error(self: Box<Self>) -> Box<dyn Error + Send + Sync + 'static> {
77        self
78    }
79}