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