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