sqlx_core_guts/
error.rs

1//! Types for working with errors produced by SQLx.
2
3use std::any::type_name;
4use std::borrow::Cow;
5use std::error::Error as StdError;
6use std::fmt::Display;
7use std::io;
8use std::result::Result as StdResult;
9
10use crate::database::Database;
11use crate::type_info::TypeInfo;
12use crate::types::Type;
13
14/// A specialized `Result` type for SQLx.
15pub type Result<T> = StdResult<T, Error>;
16
17// Convenience type alias for usage within SQLx.
18// Do not make this type public.
19pub type BoxDynError = Box<dyn StdError + 'static + Send + Sync>;
20
21/// An unexpected `NULL` was encountered during decoding.
22///
23/// Returned from [`Row::get`](crate::row::Row::get) if the value from the database is `NULL`,
24/// and you are not decoding into an `Option`.
25#[derive(thiserror::Error, Debug)]
26#[error("unexpected null; try decoding as an `Option`")]
27pub struct UnexpectedNullError;
28
29/// Represents all the ways a method can fail within SQLx.
30#[derive(Debug, thiserror::Error)]
31#[non_exhaustive]
32pub enum Error {
33    /// Error occurred while parsing a connection string.
34    #[error("error with configuration: {0}")]
35    Configuration(#[source] BoxDynError),
36
37    /// Error returned from the database.
38    #[error("error returned from database: {0}")]
39    Database(#[source] Box<dyn DatabaseError>),
40
41    /// Error communicating with the database backend.
42    #[error("error communicating with database: {0}")]
43    Io(#[from] io::Error),
44
45    /// Error occurred while attempting to establish a TLS connection.
46    #[error("error occurred while attempting to establish a TLS connection: {0}")]
47    Tls(#[source] BoxDynError),
48
49    /// Unexpected or invalid data encountered while communicating with the database.
50    ///
51    /// This should indicate there is a programming error in a SQLx driver or there
52    /// is something corrupted with the connection to the database itself.
53    #[error("encountered unexpected or invalid data: {0}")]
54    Protocol(String),
55
56    /// No rows returned by a query that expected to return at least one row.
57    #[error("no rows returned by a query that expected to return at least one row")]
58    RowNotFound,
59
60    /// Type in query doesn't exist. Likely due to typo or missing user type.
61    #[error("type named {type_name} not found")]
62    TypeNotFound { type_name: String },
63
64    /// Column index was out of bounds.
65    #[error("column index out of bounds: the len is {len}, but the index is {index}")]
66    ColumnIndexOutOfBounds { index: usize, len: usize },
67
68    /// No column found for the given name.
69    #[error("no column found for name: {0}")]
70    ColumnNotFound(String),
71
72    /// Error occurred while decoding a value from a specific column.
73    #[error("error occurred while decoding column {index}: {source}")]
74    ColumnDecode {
75        index: String,
76
77        #[source]
78        source: BoxDynError,
79    },
80
81    /// Error occurred while decoding a value.
82    #[error("error occurred while decoding: {0}")]
83    Decode(#[source] BoxDynError),
84
85    /// A [`Pool::acquire`] timed out due to connections not becoming available or
86    /// because another task encountered too many errors while trying to open a new connection.
87    ///
88    /// [`Pool::acquire`]: crate::pool::Pool::acquire
89    #[error("pool timed out while waiting for an open connection")]
90    PoolTimedOut,
91
92    /// [`Pool::close`] was called while we were waiting in [`Pool::acquire`].
93    ///
94    /// [`Pool::acquire`]: crate::pool::Pool::acquire
95    /// [`Pool::close`]: crate::pool::Pool::close
96    #[error("attempted to acquire a connection on a closed pool")]
97    PoolClosed,
98
99    /// A background worker has crashed.
100    #[error("attempted to communicate with a crashed background worker")]
101    WorkerCrashed,
102
103    #[cfg(feature = "migrate")]
104    #[error("{0}")]
105    Migrate(#[source] Box<crate::migrate::MigrateError>),
106}
107
108impl StdError for Box<dyn DatabaseError> {}
109
110impl Error {
111    pub fn into_database_error(self) -> Option<Box<dyn DatabaseError + 'static>> {
112        match self {
113            Error::Database(err) => Some(err),
114            _ => None,
115        }
116    }
117
118    pub fn as_database_error(&self) -> Option<&(dyn DatabaseError + 'static)> {
119        match self {
120            Error::Database(err) => Some(&**err),
121            _ => None,
122        }
123    }
124
125    #[allow(dead_code)]
126    #[inline]
127    pub(crate) fn protocol(err: impl Display) -> Self {
128        Error::Protocol(err.to_string())
129    }
130
131    #[allow(dead_code)]
132    #[inline]
133    pub(crate) fn config(err: impl StdError + Send + Sync + 'static) -> Self {
134        Error::Configuration(err.into())
135    }
136}
137
138pub(crate) fn mismatched_types<DB: Database, T: Type<DB>>(ty: &DB::TypeInfo) -> BoxDynError {
139    // TODO: `#name` only produces `TINYINT` but perhaps we want to show `TINYINT(1)`
140    format!(
141        "mismatched types; Rust type `{}` (as SQL type `{}`) is not compatible with SQL type `{}`",
142        type_name::<T>(),
143        T::type_info().name(),
144        ty.name()
145    )
146    .into()
147}
148
149/// An error that was returned from the database.
150pub trait DatabaseError: 'static + Send + Sync + StdError {
151    /// The primary, human-readable error message.
152    fn message(&self) -> &str;
153
154    /// The (SQLSTATE) code for the error.
155    fn code(&self) -> Option<Cow<'_, str>> {
156        None
157    }
158
159    #[doc(hidden)]
160    fn as_error(&self) -> &(dyn StdError + Send + Sync + 'static);
161
162    #[doc(hidden)]
163    fn as_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static);
164
165    #[doc(hidden)]
166    fn into_error(self: Box<Self>) -> Box<dyn StdError + Send + Sync + 'static>;
167
168    #[doc(hidden)]
169    fn is_transient_in_connect_phase(&self) -> bool {
170        false
171    }
172
173    /// Returns the name of the constraint that triggered the error, if applicable.
174    /// If the error was caused by a conflict of a unique index, this will be the index name.
175    ///
176    /// ### Note
177    /// Currently only populated by the Postgres driver.
178    fn constraint(&self) -> Option<&str> {
179        None
180    }
181}
182
183impl dyn DatabaseError {
184    /// Downcast a reference to this generic database error to a specific
185    /// database error type.
186    ///
187    /// # Panics
188    ///
189    /// Panics if the database error type is not `E`. This is a deliberate contrast from
190    /// `Error::downcast_ref` which returns `Option<&E>`. In normal usage, you should know the
191    /// specific error type. In other cases, use `try_downcast_ref`.
192    pub fn downcast_ref<E: DatabaseError>(&self) -> &E {
193        self.try_downcast_ref().unwrap_or_else(|| {
194            panic!(
195                "downcast to wrong DatabaseError type; original error: {}",
196                self
197            )
198        })
199    }
200
201    /// Downcast this generic database error to a specific database error type.
202    ///
203    /// # Panics
204    ///
205    /// Panics if the database error type is not `E`. This is a deliberate contrast from
206    /// `Error::downcast` which returns `Option<E>`. In normal usage, you should know the
207    /// specific error type. In other cases, use `try_downcast`.
208    pub fn downcast<E: DatabaseError>(self: Box<Self>) -> Box<E> {
209        self.try_downcast().unwrap_or_else(|e| {
210            panic!(
211                "downcast to wrong DatabaseError type; original error: {}",
212                e
213            )
214        })
215    }
216
217    /// Downcast a reference to this generic database error to a specific
218    /// database error type.
219    #[inline]
220    pub fn try_downcast_ref<E: DatabaseError>(&self) -> Option<&E> {
221        self.as_error().downcast_ref()
222    }
223
224    /// Downcast this generic database error to a specific database error type.
225    #[inline]
226    pub fn try_downcast<E: DatabaseError>(self: Box<Self>) -> StdResult<Box<E>, Box<Self>> {
227        if self.as_error().is::<E>() {
228            Ok(self.into_error().downcast().unwrap())
229        } else {
230            Err(self)
231        }
232    }
233}
234
235impl<E> From<E> for Error
236where
237    E: DatabaseError,
238{
239    #[inline]
240    fn from(error: E) -> Self {
241        Error::Database(Box::new(error))
242    }
243}
244
245#[cfg(feature = "migrate")]
246impl From<crate::migrate::MigrateError> for Error {
247    #[inline]
248    fn from(error: crate::migrate::MigrateError) -> Self {
249        Error::Migrate(Box::new(error))
250    }
251}
252
253#[cfg(feature = "_tls-native-tls")]
254impl From<sqlx_rt::native_tls::Error> for Error {
255    #[inline]
256    fn from(error: sqlx_rt::native_tls::Error) -> Self {
257        Error::Tls(Box::new(error))
258    }
259}
260
261// Format an error message as a `Protocol` error
262macro_rules! err_protocol {
263    ($expr:expr) => {
264        $crate::error::Error::Protocol($expr.into())
265    };
266
267    ($fmt:expr, $($arg:tt)*) => {
268        $crate::error::Error::Protocol(format!($fmt, $($arg)*))
269    };
270}