From fc09bb39d68115c9d1b7e3144ae785b579dada57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Sch=C3=A4fer?= Date: Sat, 30 Nov 2024 14:05:34 +0100 Subject: [PATCH] Add From impls to convert other error types to diesel::r2d2::Error My concrete use-case is a transaction wrapper function I have, which takes a `FnOnce(..) -> Result where E: From`. 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`. - 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(_))`. --- diesel/src/r2d2.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/diesel/src/r2d2.rs b/diesel/src/r2d2.rs index 0b95aa986f29..4771277f4df0 100644 --- a/diesel/src/r2d2.rs +++ b/diesel/src/r2d2.rs @@ -248,6 +248,18 @@ impl fmt::Display for Error { impl ::std::error::Error for Error {} +impl From for Error { + fn from(other: crate::result::Error) -> Self { + Self::QueryError(other) + } +} + +impl From 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