Skip to main content

diesel_async/pooled_connection/
mod.rs

1//! This module contains support using diesel-async with
2//! various async rust connection pooling solutions
3//!
4//! See the concrete pool implementations for examples:
5//! * [deadpool](self::deadpool)
6//! * [bb8](self::bb8)
7//! * [mobc](self::mobc)
8use crate::{AsyncConnection, TransactionManager};
9use diesel::QueryResult;
10use futures_core::future::BoxFuture;
11use futures_util::FutureExt;
12use std::borrow::Cow;
13use std::fmt;
14use std::future::Future;
15
16#[cfg(feature = "bb8")]
17pub mod bb8;
18#[cfg(feature = "deadpool")]
19pub mod deadpool;
20#[cfg(feature = "mobc")]
21pub mod mobc;
22
23/// The error used when managing connections with `deadpool`.
24#[derive(Debug)]
25pub enum PoolError {
26    /// An error occurred establishing the connection
27    ConnectionError(diesel::result::ConnectionError),
28
29    /// An error occurred pinging the database
30    QueryError(diesel::result::Error),
31}
32
33impl fmt::Display for PoolError {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match *self {
36            PoolError::ConnectionError(ref e) => e.fmt(f),
37            PoolError::QueryError(ref e) => e.fmt(f),
38        }
39    }
40}
41
42impl std::error::Error for PoolError {
43    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
44        match self {
45            PoolError::ConnectionError(connection_error) => Some(connection_error),
46            PoolError::QueryError(error) => Some(error),
47        }
48    }
49}
50
51impl From<diesel::result::ConnectionError> for PoolError {
52    fn from(value: diesel::result::ConnectionError) -> Self {
53        PoolError::ConnectionError(value)
54    }
55}
56
57impl From<diesel::result::Error> for PoolError {
58    fn from(value: diesel::result::Error) -> Self {
59        PoolError::QueryError(value)
60    }
61}
62
63/// Type of the custom setup closure passed to [`ManagerConfig::custom_setup`]
64pub type SetupCallback<C> =
65    Box<dyn Fn(&str) -> BoxFuture<diesel::ConnectionResult<C>> + Send + Sync>;
66
67/// Type of the recycle check callback for the [`RecyclingMethod::CustomFunction`] variant
68pub type RecycleCheckCallback<C> = dyn Fn(&mut C) -> BoxFuture<QueryResult<()>> + Send + Sync;
69
70/// Possible methods of how a connection is recycled.
71#[derive(Default)]
72pub enum RecyclingMethod<C> {
73    /// Only check for open transactions when recycling existing connections
74    /// Unless you have special needs this is a safe choice.
75    ///
76    /// If the database connection is closed you will receive an error on the first place
77    /// you actually try to use the connection
78    Fast,
79    /// In addition to checking for open transactions a test query is executed
80    ///
81    /// This is slower, but guarantees that the database connection is ready to be used.
82    #[default]
83    Verified,
84    /// Like `Verified` but with a custom query
85    CustomQuery(Cow<'static, str>),
86    /// Like `Verified` but with a custom callback that allows to perform more checks
87    ///
88    /// The connection is only recycled if the callback returns `Ok(())`
89    CustomFunction(Box<RecycleCheckCallback<C>>),
90}
91
92impl<C: fmt::Debug> fmt::Debug for RecyclingMethod<C> {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        match self {
95            Self::Fast => write!(f, "Fast"),
96            Self::Verified => write!(f, "Verified"),
97            Self::CustomQuery(arg0) => f.debug_tuple("CustomQuery").field(arg0).finish(),
98            Self::CustomFunction(_) => f.debug_tuple("CustomFunction").finish(),
99        }
100    }
101}
102
103/// Configuration object for a Manager.
104///
105/// This makes it possible to specify which [`RecyclingMethod`]
106/// should be used when retrieving existing objects from the `Pool`
107/// and it allows to provide a custom setup function.
108#[non_exhaustive]
109pub struct ManagerConfig<C> {
110    /// Method of how a connection is recycled. See [RecyclingMethod].
111    pub recycling_method: RecyclingMethod<C>,
112    /// Construct a new connection manger
113    /// with a custom setup procedure
114    ///
115    /// This can be used to for example establish a SSL secured
116    /// postgres connection
117    pub custom_setup: SetupCallback<C>,
118}
119
120impl<C> Default for ManagerConfig<C>
121where
122    C: AsyncConnection + 'static,
123{
124    fn default() -> Self {
125        Self {
126            recycling_method: Default::default(),
127            custom_setup: Box::new(|url| C::establish(url).boxed()),
128        }
129    }
130}
131
132/// An connection manager for use with diesel-async.
133///
134/// See the concrete pool implementations for examples:
135/// * [deadpool](self::deadpool)
136/// * [bb8](self::bb8)
137/// * [mobc](self::mobc)
138#[allow(dead_code)]
139pub struct AsyncDieselConnectionManager<C> {
140    connection_url: String,
141    manager_config: ManagerConfig<C>,
142}
143
144impl<C> fmt::Debug for AsyncDieselConnectionManager<C> {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        write!(
147            f,
148            "AsyncDieselConnectionManager<{}>",
149            std::any::type_name::<C>()
150        )
151    }
152}
153
154impl<C> AsyncDieselConnectionManager<C>
155where
156    C: AsyncConnection + 'static,
157{
158    /// Returns a new connection manager,
159    /// which establishes connections to the given database URL.
160    #[must_use]
161    pub fn new(connection_url: impl Into<String>) -> Self
162    where
163        C: AsyncConnection + 'static,
164    {
165        Self::new_with_config(connection_url, Default::default())
166    }
167
168    /// Returns a new connection manager,
169    /// which establishes connections with the given database URL
170    /// and that uses the specified configuration
171    #[must_use]
172    pub fn new_with_config(
173        connection_url: impl Into<String>,
174        manager_config: ManagerConfig<C>,
175    ) -> Self {
176        Self {
177            connection_url: connection_url.into(),
178            manager_config,
179        }
180    }
181}
182
183#[doc(hidden)]
184pub trait PoolableConnection: AsyncConnection {
185    /// Check if a connection is still valid
186    ///
187    /// The default implementation will perform a check based on the provided
188    /// recycling method variant
189    fn ping(
190        &mut self,
191        config: &RecyclingMethod<Self>,
192    ) -> impl Future<Output = diesel::QueryResult<()>> + Send
193    where
194        for<'a> Self: 'a,
195        for<'a> diesel::dsl::select<diesel::dsl::AsExprOf<i32, diesel::sql_types::Integer>>:
196            crate::methods::LoadQuery<'a, Self, i32>,
197        diesel::query_builder::SqlQuery: crate::methods::ExecuteDsl<Self>,
198    {
199        use crate::run_query_dsl::RunQueryDsl;
200        use diesel::IntoSql;
201
202        async move {
203            match config {
204                RecyclingMethod::Fast => Ok(()),
205                RecyclingMethod::Verified => {
206                    diesel::select(1_i32.into_sql::<diesel::sql_types::Integer>())
207                        .get_result::<i32>(self)
208                        .await
209                        .map(|_| ())
210                }
211                RecyclingMethod::CustomQuery(query) => diesel::sql_query(query.as_ref())
212                    .execute(self)
213                    .await
214                    .map(|_| ()),
215                RecyclingMethod::CustomFunction(c) => c(self).await,
216            }
217        }
218    }
219
220    /// Checks if the connection is broken and should not be reused
221    ///
222    /// This method should return only contain a fast non-blocking check
223    /// if the connection is considered to be broken or not. See
224    /// [ManageConnection::has_broken] for details.
225    ///
226    /// The default implementation uses
227    /// [TransactionManager::is_broken_transaction_manager].
228    fn is_broken(&mut self) -> bool {
229        Self::TransactionManager::is_broken_transaction_manager(self)
230    }
231}