Skip to main content

toasty_core/error/
serialization_failure.rs

1use super::Error;
2
3/// Error when a transaction is aborted due to a serialization conflict.
4///
5/// Drivers should classify retryable transaction conflicts here:
6/// PostgreSQL SQLSTATE `40001`, MySQL error `1213`, and equivalents on
7/// other backends. The engine does not retry automatically — the error
8/// propagates to the caller, who decides whether to re-run the
9/// transaction.
10#[derive(Debug)]
11pub(super) struct SerializationFailure {
12    message: Box<str>,
13}
14
15impl std::error::Error for SerializationFailure {}
16
17impl core::fmt::Display for SerializationFailure {
18    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
19        write!(f, "transaction serialization failure: {}", self.message)
20    }
21}
22
23impl Error {
24    /// Creates a serialization failure error.
25    ///
26    /// Returned when the database aborts a transaction due to a serialization
27    /// conflict (e.g. PostgreSQL SQLSTATE 40001, MySQL error 1213).
28    ///
29    /// # Examples
30    ///
31    /// ```
32    /// use toasty_core::Error;
33    ///
34    /// let err = Error::serialization_failure("concurrent update conflict");
35    /// assert!(err.is_serialization_failure());
36    /// ```
37    pub fn serialization_failure(message: impl Into<String>) -> Error {
38        Error::from(super::ErrorKind::SerializationFailure(
39            SerializationFailure {
40                message: message.into().into(),
41            },
42        ))
43    }
44
45    /// Returns `true` if this error is a serialization failure.
46    pub fn is_serialization_failure(&self) -> bool {
47        matches!(self.kind(), super::ErrorKind::SerializationFailure(_))
48    }
49}