Skip to content

Commit

Permalink
Add From impls to convert other error types to diesel::r2d2::Error
Browse files Browse the repository at this point in the history
My concrete use-case is a transaction wrapper function I have, which
takes a
`FnOnce(..) -> Result<T, E> where E: From<diesel::result::Error>`.
Oftentimes, these closures will just directly return diesel Errors. The
wrapper does nothing more than setting up and committing the
transaction.

I now want to upgrade this to support r2d2. That means I have to change
the signature of the closure to accept r2d2 errors, too, because I will
have to take a connection from the pool (which could cause a
ConnectionError [1]), by changing the trait bound. Unfortunately, that
would make it impossible to ergonomically use any diesel functions
within the closure:

- If I return `Result<_, diesel::r2d2::Error>` from the closure, I
  cannot call query functions, because diesel::r2d2::Error does not
  implement `From<diesel::result::Error>`.

- I cannot return `Result<_, diesel::result::Error>` directly because
  `diesel::r2d2::Error` cannot be converted to `diesel::result::Error`.

With the conversions introduced in this commit, the wrapper becomes
feasible again.

   [1]: My wrapper converts the opaque `r2d2::Error` (a.k.a.
        `diesel::r2d2::PoolError`) type to
        `diesel::r2d2::Error(diesel::prelude::ConnectionError::BadConnecton(_))`.
  • Loading branch information
horazont committed Nov 30, 2024
1 parent 022f5ab commit 504f2b6
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions diesel/src/r2d2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,18 @@ impl fmt::Display for Error {

impl ::std::error::Error for Error {}

impl From<crate::result::Error> for Error {
fn from(other: crate::result::Error) -> Self {
Self::QueryError(other)
}
}

impl From<ConnectionError> for Error {
fn from(other: ConnectionError) -> Self {
Self::ConnectionError(other)
}
}

/// A trait indicating a connection could be used inside a r2d2 pool
pub trait R2D2Connection: Connection {
/// Check if a connection is still valid
Expand Down

0 comments on commit 504f2b6

Please sign in to comment.