diesel/
result.rs

1//! Errors, type aliases, and functions related to working with `Result`.
2
3use std::error::Error as StdError;
4use std::ffi::NulError;
5use std::fmt::{self, Display};
6
7#[derive(Debug)]
8#[allow(clippy::enum_variant_names)]
9/// Represents all the ways that a query can fail.
10///
11/// This type is not intended to be exhaustively matched, and new variants may
12/// be added in the future without a major version bump.
13#[non_exhaustive]
14pub enum Error {
15    /// The query contained a nul byte.
16    ///
17    /// This should never occur in normal usage.
18    InvalidCString(NulError),
19
20    /// The database returned an error.
21    ///
22    /// While Diesel prevents almost all sources of runtime errors at compile
23    /// time, it does not attempt to prevent 100% of them. Typically this error
24    /// will occur from insert or update statements due to a constraint
25    /// violation.
26    DatabaseError(
27        DatabaseErrorKind,
28        Box<dyn DatabaseErrorInformation + Send + Sync>,
29    ),
30
31    /// No rows were returned by a query expected to return at least one row.
32    ///
33    /// This variant is only returned by [`get_result`] and [`first`]. [`load`]
34    /// does not treat 0 rows as an error. If you would like to allow either 0
35    /// or 1 rows, call [`optional`] on the result.
36    ///
37    /// [`get_result`]: crate::query_dsl::RunQueryDsl::get_result()
38    /// [`first`]: crate::query_dsl::RunQueryDsl::first()
39    /// [`load`]: crate::query_dsl::RunQueryDsl::load()
40    /// [`optional`]: OptionalExtension::optional
41    NotFound,
42
43    /// The query could not be constructed
44    ///
45    /// An example of when this error could occur is if you are attempting to
46    /// construct an update statement with no changes (e.g. all fields on the
47    /// struct are `None`).
48    QueryBuilderError(Box<dyn StdError + Send + Sync>),
49
50    /// An error occurred deserializing the data being sent to the database.
51    ///
52    /// Typically this error means that the stated type of the query is
53    /// incorrect. An example of when this error might occur in normal usage is
54    /// attempting to deserialize an infinite date into chrono.
55    DeserializationError(Box<dyn StdError + Send + Sync>),
56
57    /// An error occurred serializing the data being sent to the database.
58    ///
59    /// An example of when this error would be returned is if you attempted to
60    /// serialize a `chrono::NaiveDate` earlier than the earliest date supported
61    /// by PostgreSQL.
62    SerializationError(Box<dyn StdError + Send + Sync>),
63
64    /// An error occurred when attempting rollback of a transaction subsequently to a failed
65    /// commit attempt.
66    ///
67    /// When a commit attempt fails and Diesel believes that it can attempt a rollback to return
68    /// the connection back in a usable state (out of that transaction), it attempts it then
69    /// returns the original error.
70    ///
71    /// If that fails, you get this.
72    RollbackErrorOnCommit {
73        /// The error that was encountered when attempting the rollback
74        rollback_error: Box<Error>,
75        /// The error that was encountered during the failed commit attempt
76        commit_error: Box<Error>,
77    },
78
79    /// Roll back the current transaction.
80    ///
81    /// You can return this variant inside of a transaction when you want to
82    /// roll it back, but have no actual error to return. Diesel will never
83    /// return this variant unless you gave it to us, and it can be safely
84    /// ignored in error handling.
85    RollbackTransaction,
86
87    /// Attempted to perform an operation that cannot be done inside a transaction
88    /// when a transaction was already open.
89    AlreadyInTransaction,
90
91    /// Attempted to perform an operation that can only be done inside a transaction
92    /// when no transaction was open
93    NotInTransaction,
94
95    /// Transaction manager broken, likely due to a broken connection. No other operations are possible.
96    BrokenTransactionManager,
97}
98
99#[derive(Debug, Clone, Copy)]
100/// The kind of database error that occurred.
101///
102/// This is not meant to exhaustively cover all possible errors, but is used to
103/// identify errors which are commonly recovered from programmatically. This enum
104/// is not intended to be exhaustively matched, and new variants may be added in
105/// the future without a major version bump.
106#[non_exhaustive]
107pub enum DatabaseErrorKind {
108    /// A unique constraint was violated.
109    UniqueViolation,
110
111    /// A foreign key constraint was violated.
112    ForeignKeyViolation,
113
114    /// The query could not be sent to the database due to a protocol violation.
115    ///
116    /// An example of a case where this would occur is if you attempted to send
117    /// a query with more than 65000 bind parameters using PostgreSQL.
118    UnableToSendCommand,
119
120    /// A serializable transaction failed to commit due to a read/write
121    /// dependency on a concurrent transaction.
122    ///
123    /// Corresponds to SQLSTATE code 40001
124    ///
125    /// This error is only detected for PostgreSQL, as we do not yet support
126    /// transaction isolation levels for other backends.
127    SerializationFailure,
128
129    /// The command could not be completed because the transaction was read
130    /// only.
131    ///
132    /// This error will also be returned for `SELECT` statements which attempted
133    /// to lock the rows.
134    ReadOnlyTransaction,
135
136    /// A not null constraint was violated.
137    NotNullViolation,
138
139    /// A check constraint was violated.
140    CheckViolation,
141
142    /// The connection to the server was unexpectedly closed.
143    ///
144    /// This error is only detected for PostgreSQL and is emitted on a best-effort basis
145    /// and may be missed.
146    ClosedConnection,
147
148    #[doc(hidden)]
149    Unknown, // Match against _ instead, more variants may be added in the future
150}
151
152/// Information about an error that was returned by the database.
153pub trait DatabaseErrorInformation {
154    /// The primary human-readable error message. Typically one line.
155    fn message(&self) -> &str;
156
157    /// An optional secondary error message providing more details about the
158    /// problem, if it was provided by the database. Might span multiple lines.
159    fn details(&self) -> Option<&str>;
160
161    /// An optional suggestion of what to do about the problem, if one was
162    /// provided by the database.
163    fn hint(&self) -> Option<&str>;
164
165    /// The name of the table the error was associated with, if the error was
166    /// associated with a specific table and the backend supports retrieving
167    /// that information.
168    ///
169    /// Currently this method will return `None` for all backends other than
170    /// PostgreSQL.
171    fn table_name(&self) -> Option<&str>;
172
173    /// The name of the column the error was associated with, if the error was
174    /// associated with a specific column and the backend supports retrieving
175    /// that information.
176    ///
177    /// Currently this method will return `None` for all backends other than
178    /// PostgreSQL.
179    fn column_name(&self) -> Option<&str>;
180
181    /// The constraint that was violated if this error is a constraint violation
182    /// and the backend supports retrieving that information.
183    ///
184    /// Currently this method will return `None` for all backends other than
185    /// PostgreSQL.
186    fn constraint_name(&self) -> Option<&str>;
187
188    /// An optional integer indicating an error cursor position as an index into
189    /// the original statement string.
190    fn statement_position(&self) -> Option<i32>;
191}
192
193impl fmt::Debug for dyn DatabaseErrorInformation + Send + Sync {
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        fmt::Debug::fmt(&self.message(), f)
196    }
197}
198
199impl DatabaseErrorInformation for String {
200    fn message(&self) -> &str {
201        self
202    }
203    fn details(&self) -> Option<&str> {
204        None
205    }
206    fn hint(&self) -> Option<&str> {
207        None
208    }
209    fn table_name(&self) -> Option<&str> {
210        None
211    }
212    fn column_name(&self) -> Option<&str> {
213        None
214    }
215    fn constraint_name(&self) -> Option<&str> {
216        None
217    }
218    fn statement_position(&self) -> Option<i32> {
219        None
220    }
221}
222
223/// Errors which can occur during [`Connection::establish`]
224///
225/// [`Connection::establish`]: crate::connection::Connection::establish
226#[derive(Debug, PartialEq)]
227#[non_exhaustive]
228pub enum ConnectionError {
229    /// The connection URL contained a `NUL` byte.
230    InvalidCString(NulError),
231    /// The database returned an error.
232    BadConnection(String),
233    /// The connection URL could not be parsed.
234    InvalidConnectionUrl(String),
235    /// Diesel could not configure the database connection.
236    ///
237    /// Diesel may try to automatically set session specific configuration
238    /// values, such as UTF8 encoding, or enabling the `||` operator on MySQL.
239    /// This variant is returned if an error occurred executing the query to set
240    /// those options. Diesel will never affect global configuration.
241    CouldntSetupConfiguration(Error),
242}
243
244/// A specialized result type for queries.
245///
246/// This type is exported by `diesel::prelude`, and is generally used by any
247/// code which is interacting with Diesel. This type exists to avoid writing out
248/// `diesel::result::Error`, and is otherwise a direct mapping to `Result`.
249pub type QueryResult<T> = Result<T, Error>;
250
251/// A specialized result type for establishing connections.
252///
253/// This type exists to avoid writing out `diesel::result::ConnectionError`, and
254/// is otherwise a direct mapping to `Result`.
255pub type ConnectionResult<T> = Result<T, ConnectionError>;
256
257/// See the [method documentation](OptionalExtension::optional).
258pub trait OptionalExtension<T> {
259    /// Converts a `QueryResult<T>` into a `QueryResult<Option<T>>`.
260    ///
261    /// By default, Diesel treats 0 rows being returned from a query that is expected to return 1
262    /// row as an error (e.g. the return value of [`get_result`] or [`first`]). This method will
263    /// handle that error, and give you back an `Option<T>` instead.
264    ///
265    /// [`get_result`]: crate::query_dsl::RunQueryDsl::get_result()
266    /// [`first`]: crate::query_dsl::RunQueryDsl::first()
267    ///
268    /// # Example
269    ///
270    /// ```rust
271    /// use diesel::{QueryResult, NotFound, OptionalExtension};
272    ///
273    /// let result: QueryResult<i32> = Ok(1);
274    /// assert_eq!(Ok(Some(1)), result.optional());
275    ///
276    /// let result: QueryResult<i32> = Err(NotFound);
277    /// assert_eq!(Ok(None), result.optional());
278    /// ```
279    fn optional(self) -> Result<Option<T>, Error>;
280}
281
282impl<T> OptionalExtension<T> for QueryResult<T> {
283    fn optional(self) -> Result<Option<T>, Error> {
284        match self {
285            Ok(value) => Ok(Some(value)),
286            Err(Error::NotFound) => Ok(None),
287            Err(e) => Err(e),
288        }
289    }
290}
291
292/// See the [method documentation](OptionalEmptyChangesetExtension::optional_empty_changeset).
293pub trait OptionalEmptyChangesetExtension<T> {
294    /// By default, Diesel treats an empty update as a `QueryBuilderError`. This method will
295    /// convert that error into `None`.
296    ///
297    /// # Example
298    ///
299    /// ```rust
300    /// use diesel::{QueryResult, OptionalEmptyChangesetExtension, result::Error::QueryBuilderError, result::EmptyChangeset};
301    /// let result: QueryResult<i32> = Err(QueryBuilderError(Box::new(EmptyChangeset)));
302    /// assert_eq!(Ok(None), result.optional_empty_changeset());
303    /// ```
304    fn optional_empty_changeset(self) -> Result<Option<T>, Error>;
305}
306
307impl<T> OptionalEmptyChangesetExtension<T> for QueryResult<T> {
308    fn optional_empty_changeset(self) -> Result<Option<T>, Error> {
309        match self {
310            Ok(value) => Ok(Some(value)),
311            Err(Error::QueryBuilderError(e)) if e.is::<EmptyChangeset>() => Ok(None),
312            Err(e) => Err(e),
313        }
314    }
315}
316
317impl From<NulError> for ConnectionError {
318    fn from(e: NulError) -> Self {
319        ConnectionError::InvalidCString(e)
320    }
321}
322
323impl From<NulError> for Error {
324    fn from(e: NulError) -> Self {
325        Error::InvalidCString(e)
326    }
327}
328
329impl Display for Error {
330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331        match *self {
332            Error::InvalidCString(ref nul_err) => write!(f, "{nul_err}"),
333            Error::DatabaseError(_, ref e) => write!(f, "{}", e.message()),
334            Error::NotFound => f.write_str("Record not found"),
335            Error::QueryBuilderError(ref e) => e.fmt(f),
336            Error::DeserializationError(ref e) => e.fmt(f),
337            Error::SerializationError(ref e) => e.fmt(f),
338            Error::RollbackErrorOnCommit {
339                ref rollback_error,
340                ref commit_error,
341            } => {
342                write!(
343                    f,
344                    "Transaction rollback failed: {} \
345                        (rollback attempted because of failure to commit: {})",
346                    &**rollback_error, &**commit_error
347                )?;
348                Ok(())
349            }
350            Error::RollbackTransaction => {
351                write!(f, "You have asked diesel to rollback the transaction")
352            }
353            Error::BrokenTransactionManager => write!(f, "The transaction manager is broken"),
354            Error::AlreadyInTransaction => write!(
355                f,
356                "Cannot perform this operation while a transaction is open",
357            ),
358            Error::NotInTransaction => {
359                write!(f, "Cannot perform this operation outside of a transaction",)
360            }
361        }
362    }
363}
364
365impl StdError for Error {
366    fn cause(&self) -> Option<&dyn StdError> {
367        match *self {
368            Error::InvalidCString(ref e) => Some(e),
369            Error::QueryBuilderError(ref e) => Some(&**e),
370            Error::DeserializationError(ref e) => Some(&**e),
371            Error::SerializationError(ref e) => Some(&**e),
372            _ => None,
373        }
374    }
375}
376
377impl Display for ConnectionError {
378    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
379        match *self {
380            ConnectionError::InvalidCString(ref nul_err) => nul_err.fmt(f),
381            ConnectionError::BadConnection(ref s) => write!(f, "{s}"),
382            ConnectionError::InvalidConnectionUrl(ref s) => write!(f, "{s}"),
383            ConnectionError::CouldntSetupConfiguration(ref e) => e.fmt(f),
384        }
385    }
386}
387
388impl StdError for ConnectionError {
389    fn cause(&self) -> Option<&dyn StdError> {
390        match *self {
391            ConnectionError::InvalidCString(ref e) => Some(e),
392            ConnectionError::CouldntSetupConfiguration(ref e) => Some(e),
393            _ => None,
394        }
395    }
396}
397
398impl PartialEq for Error {
399    fn eq(&self, other: &Error) -> bool {
400        match (self, other) {
401            (Error::InvalidCString(a), Error::InvalidCString(b)) => a == b,
402            (Error::DatabaseError(_, a), Error::DatabaseError(_, b)) => a.message() == b.message(),
403            (&Error::NotFound, &Error::NotFound) => true,
404            (&Error::RollbackTransaction, &Error::RollbackTransaction) => true,
405            (&Error::AlreadyInTransaction, &Error::AlreadyInTransaction) => true,
406            _ => false,
407        }
408    }
409}
410
411#[cfg(test)]
412#[allow(warnings)]
413fn error_impls_send() {
414    let err: Error = unimplemented!();
415    let x: &dyn Send = &err;
416}
417
418/// An unexpected `NULL` was encountered during deserialization
419#[derive(Debug, Clone, Copy)]
420pub struct UnexpectedNullError;
421
422impl fmt::Display for UnexpectedNullError {
423    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
424        write!(f, "Unexpected null for non-null column")
425    }
426}
427
428impl StdError for UnexpectedNullError {}
429
430/// Expected more fields then present in the current row while deserializing results
431#[derive(Debug, Clone, Copy)]
432pub struct UnexpectedEndOfRow;
433
434impl fmt::Display for UnexpectedEndOfRow {
435    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
436        write!(f, "Unexpected end of row")
437    }
438}
439
440impl StdError for UnexpectedEndOfRow {}
441
442/// Expected when an update has no changes to save.
443///
444/// When using `optional_empty_changeset`, this error is turned into `None`.
445#[derive(Debug, Clone, Copy)]
446pub struct EmptyChangeset;
447
448impl fmt::Display for EmptyChangeset {
449    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
450        write!(
451            f,
452            "There are no changes to save. This query cannot be built"
453        )
454    }
455}
456
457impl StdError for EmptyChangeset {}
458
459/// Expected when you try to execute an empty query
460#[derive(Debug, Clone, Copy)]
461pub struct EmptyQuery;
462
463impl fmt::Display for EmptyQuery {
464    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465        write!(
466            f,
467            "Detected an empty query. These are not supported by your database system"
468        )
469    }
470}
471
472impl StdError for EmptyQuery {}
473
474/// An error occurred while deserializing a field
475#[derive(Debug)]
476#[non_exhaustive]
477pub struct DeserializeFieldError {
478    /// The name of the field that failed to deserialize
479    pub field_name: Option<String>,
480    /// The error that occurred while deserializing the field
481    pub error: Box<dyn StdError + Send + Sync>,
482}
483
484impl DeserializeFieldError {
485    #[cold]
486    pub(crate) fn new<'a, F, DB>(field: F, error: Box<dyn std::error::Error + Send + Sync>) -> Self
487    where
488        DB: crate::backend::Backend,
489        F: crate::row::Field<'a, DB>,
490    {
491        DeserializeFieldError {
492            field_name: field.field_name().map(|s| s.to_string()),
493            error,
494        }
495    }
496}
497
498impl StdError for DeserializeFieldError {
499    fn source(&self) -> Option<&(dyn StdError + 'static)> {
500        Some(&*self.error)
501    }
502}
503
504impl fmt::Display for DeserializeFieldError {
505    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
506        if let Some(ref field_name) = self.field_name {
507            write!(
508                f,
509                "Error deserializing field '{}': {}",
510                field_name, self.error
511            )
512        } else {
513            write!(f, "Error deserializing field: {}", self.error)
514        }
515    }
516}