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