Skip to main content

diesel/
result.rs

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