diesel_async/
async_connection_wrapper.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
//! This module contains an wrapper type
//! that provides a [`diesel::Connection`]
//! implementation for types that implement
//! [`crate::AsyncConnection`]. Using this type
//! might be useful for the following usecases:
//!
//! * Executing migrations on application startup
//! * Using a pure rust diesel connection implementation
//!   as replacement for the existing connection
//!   implementations provided by diesel

use futures_util::Future;
use futures_util::Stream;
use futures_util::StreamExt;
use std::pin::Pin;

/// This is a helper trait that allows to customize the
/// async runtime used to execute futures as part of the
/// [`AsyncConnectionWrapper`] type. By default a
/// tokio runtime is used.
pub trait BlockOn {
    /// This function should allow to execute a
    /// given future to get the result
    fn block_on<F>(&self, f: F) -> F::Output
    where
        F: Future;

    /// This function should be used to construct
    /// a new runtime instance
    fn get_runtime() -> Self;
}

/// A helper type that wraps an [`AsyncConnection`][crate::AsyncConnection] to
/// provide a sync [`diesel::Connection`] implementation.
///
/// Internally this wrapper type will use `block_on` to wait for
/// the execution of futures from the inner connection. This implies you
/// cannot use functions of this type in a scope with an already existing
/// tokio runtime. If you are in a situation where you want to use this
/// connection wrapper in the scope of an existing tokio runtime (for example
/// for running migrations via `diesel_migration`) you need to wrap
/// the relevant code block into a `tokio::task::spawn_blocking` task.
///
/// # Examples
///
/// ```rust,no_run
/// # include!("doctest_setup.rs");
/// use schema::users;
/// use diesel_async::async_connection_wrapper::AsyncConnectionWrapper;
/// #
/// # fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
/// use diesel::prelude::{RunQueryDsl, Connection};
/// # let database_url = database_url();
/// let mut conn = AsyncConnectionWrapper::<DbConnection>::establish(&database_url)?;
///
/// let all_users = users::table.load::<(i32, String)>(&mut conn)?;
/// # assert_eq!(all_users.len(), 0);
/// # Ok(())
/// # }
/// ```
///
/// If you are in the scope of an existing tokio runtime you need to use
/// `tokio::task::spawn_blocking` to encapsulate the blocking tasks
/// ```rust,no_run
/// # include!("doctest_setup.rs");
/// use schema::users;
/// use diesel_async::async_connection_wrapper::AsyncConnectionWrapper;
///
/// async fn some_async_fn() {
/// # let database_url = database_url();
///      // need to use `spawn_blocking` to execute
///      // a blocking task in the scope of an existing runtime
///      let res = tokio::task::spawn_blocking(move || {
///          use diesel::prelude::{RunQueryDsl, Connection};
///          let mut conn = AsyncConnectionWrapper::<DbConnection>::establish(&database_url)?;
///
///          let all_users = users::table.load::<(i32, String)>(&mut conn)?;
/// #         assert_eq!(all_users.len(), 0);
///          Ok::<_, Box<dyn std::error::Error + Send + Sync>>(())
///      }).await;
///
/// # res.unwrap().unwrap();
/// }
///
/// # #[tokio::main]
/// # async fn main() {
/// #    some_async_fn().await;
/// # }
/// ```
#[cfg(feature = "tokio")]
pub type AsyncConnectionWrapper<C, B = self::implementation::Tokio> =
    self::implementation::AsyncConnectionWrapper<C, B>;

/// A helper type that wraps an [`crate::AsyncConnectionWrapper`] to
/// provide a sync [`diesel::Connection`] implementation.
///
/// Internally this wrapper type will use `block_on` to wait for
/// the execution of futures from the inner connection.
#[cfg(not(feature = "tokio"))]
pub use self::implementation::AsyncConnectionWrapper;

mod implementation {
    use diesel::connection::{Instrumentation, SimpleConnection};
    use std::ops::{Deref, DerefMut};

    use super::*;

    pub struct AsyncConnectionWrapper<C, B> {
        inner: C,
        runtime: B,
    }

    impl<C, B> From<C> for AsyncConnectionWrapper<C, B>
    where
        C: crate::AsyncConnection,
        B: BlockOn + Send,
    {
        fn from(inner: C) -> Self {
            Self {
                inner,
                runtime: B::get_runtime(),
            }
        }
    }

    impl<C, B> Deref for AsyncConnectionWrapper<C, B> {
        type Target = C;

        fn deref(&self) -> &Self::Target {
            &self.inner
        }
    }

    impl<C, B> DerefMut for AsyncConnectionWrapper<C, B> {
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.inner
        }
    }

    impl<C, B> diesel::connection::SimpleConnection for AsyncConnectionWrapper<C, B>
    where
        C: crate::SimpleAsyncConnection,
        B: BlockOn,
    {
        fn batch_execute(&mut self, query: &str) -> diesel::QueryResult<()> {
            let f = self.inner.batch_execute(query);
            self.runtime.block_on(f)
        }
    }

    impl<C, B> diesel::connection::ConnectionSealed for AsyncConnectionWrapper<C, B> {}

    impl<C, B> diesel::connection::Connection for AsyncConnectionWrapper<C, B>
    where
        C: crate::AsyncConnection,
        B: BlockOn + Send,
    {
        type Backend = C::Backend;

        type TransactionManager = AsyncConnectionWrapperTransactionManagerWrapper;

        fn establish(database_url: &str) -> diesel::ConnectionResult<Self> {
            let runtime = B::get_runtime();
            let f = C::establish(database_url);
            let inner = runtime.block_on(f)?;
            Ok(Self { inner, runtime })
        }

        fn execute_returning_count<T>(&mut self, source: &T) -> diesel::QueryResult<usize>
        where
            T: diesel::query_builder::QueryFragment<Self::Backend> + diesel::query_builder::QueryId,
        {
            let f = self.inner.execute_returning_count(source);
            self.runtime.block_on(f)
        }

        fn transaction_state(
            &mut self,
        ) -> &mut <Self::TransactionManager as diesel::connection::TransactionManager<Self>>::TransactionStateData{
            self.inner.transaction_state()
        }

        fn instrumentation(&mut self) -> &mut dyn Instrumentation {
            self.inner.instrumentation()
        }

        fn set_instrumentation(&mut self, instrumentation: impl Instrumentation) {
            self.inner.set_instrumentation(instrumentation);
        }
    }

    impl<C, B> diesel::connection::LoadConnection for AsyncConnectionWrapper<C, B>
    where
        C: crate::AsyncConnection,
        B: BlockOn + Send,
    {
        type Cursor<'conn, 'query> = AsyncCursorWrapper<'conn, C::Stream<'conn, 'query>, B>
    where
        Self: 'conn;

        type Row<'conn, 'query> = C::Row<'conn, 'query>
    where
        Self: 'conn;

        fn load<'conn, 'query, T>(
            &'conn mut self,
            source: T,
        ) -> diesel::QueryResult<Self::Cursor<'conn, 'query>>
        where
            T: diesel::query_builder::Query
                + diesel::query_builder::QueryFragment<Self::Backend>
                + diesel::query_builder::QueryId
                + 'query,
            Self::Backend: diesel::expression::QueryMetadata<T::SqlType>,
        {
            let f = self.inner.load(source);
            let stream = self.runtime.block_on(f)?;

            Ok(AsyncCursorWrapper {
                stream: Box::pin(stream),
                runtime: &self.runtime,
            })
        }
    }

    pub struct AsyncCursorWrapper<'a, S, B> {
        stream: Pin<Box<S>>,
        runtime: &'a B,
    }

    impl<'a, S, B> Iterator for AsyncCursorWrapper<'a, S, B>
    where
        S: Stream,
        B: BlockOn,
    {
        type Item = S::Item;

        fn next(&mut self) -> Option<Self::Item> {
            let f = self.stream.next();
            self.runtime.block_on(f)
        }
    }

    pub struct AsyncConnectionWrapperTransactionManagerWrapper;

    impl<C, B> diesel::connection::TransactionManager<AsyncConnectionWrapper<C, B>>
        for AsyncConnectionWrapperTransactionManagerWrapper
    where
        C: crate::AsyncConnection,
        B: BlockOn + Send,
    {
        type TransactionStateData =
            <C::TransactionManager as crate::TransactionManager<C>>::TransactionStateData;

        fn begin_transaction(conn: &mut AsyncConnectionWrapper<C, B>) -> diesel::QueryResult<()> {
            let f = <C::TransactionManager as crate::TransactionManager<_>>::begin_transaction(
                &mut conn.inner,
            );
            conn.runtime.block_on(f)
        }

        fn rollback_transaction(
            conn: &mut AsyncConnectionWrapper<C, B>,
        ) -> diesel::QueryResult<()> {
            let f = <C::TransactionManager as crate::TransactionManager<_>>::rollback_transaction(
                &mut conn.inner,
            );
            conn.runtime.block_on(f)
        }

        fn commit_transaction(conn: &mut AsyncConnectionWrapper<C, B>) -> diesel::QueryResult<()> {
            let f = <C::TransactionManager as crate::TransactionManager<_>>::commit_transaction(
                &mut conn.inner,
            );
            conn.runtime.block_on(f)
        }

        fn transaction_manager_status_mut(
            conn: &mut AsyncConnectionWrapper<C, B>,
        ) -> &mut diesel::connection::TransactionManagerStatus {
            <C::TransactionManager as crate::TransactionManager<_>>::transaction_manager_status_mut(
                &mut conn.inner,
            )
        }

        fn is_broken_transaction_manager(conn: &mut AsyncConnectionWrapper<C, B>) -> bool {
            <C::TransactionManager as crate::TransactionManager<_>>::is_broken_transaction_manager(
                &mut conn.inner,
            )
        }
    }

    #[cfg(feature = "r2d2")]
    impl<C, B> diesel::r2d2::R2D2Connection for AsyncConnectionWrapper<C, B>
    where
        B: BlockOn,
        Self: diesel::Connection,
        C: crate::AsyncConnection<Backend = <Self as diesel::Connection>::Backend>
            + crate::pooled_connection::PoolableConnection
            + 'static,
        diesel::dsl::select<diesel::dsl::AsExprOf<i32, diesel::sql_types::Integer>>:
            crate::methods::ExecuteDsl<C>,
        diesel::query_builder::SqlQuery: crate::methods::ExecuteDsl<C>,
    {
        fn ping(&mut self) -> diesel::QueryResult<()> {
            let fut = crate::pooled_connection::PoolableConnection::ping(
                &mut self.inner,
                &crate::pooled_connection::RecyclingMethod::Verified,
            );
            self.runtime.block_on(fut)
        }

        fn is_broken(&mut self) -> bool {
            crate::pooled_connection::PoolableConnection::is_broken(&mut self.inner)
        }
    }

    impl<C, B> diesel::migration::MigrationConnection for AsyncConnectionWrapper<C, B>
    where
        B: BlockOn,
        Self: diesel::Connection,
    {
        fn setup(&mut self) -> diesel::QueryResult<usize> {
            self.batch_execute(diesel::migration::CREATE_MIGRATIONS_TABLE)
                .map(|()| 0)
        }
    }

    #[cfg(feature = "tokio")]
    pub struct Tokio {
        handle: Option<tokio::runtime::Handle>,
        runtime: Option<tokio::runtime::Runtime>,
    }

    #[cfg(feature = "tokio")]
    impl BlockOn for Tokio {
        fn block_on<F>(&self, f: F) -> F::Output
        where
            F: Future,
        {
            if let Some(handle) = &self.handle {
                handle.block_on(f)
            } else if let Some(runtime) = &self.runtime {
                runtime.block_on(f)
            } else {
                unreachable!()
            }
        }

        fn get_runtime() -> Self {
            if let Ok(handle) = tokio::runtime::Handle::try_current() {
                Self {
                    handle: Some(handle),
                    runtime: None,
                }
            } else {
                let runtime = tokio::runtime::Builder::new_current_thread()
                    .enable_io()
                    .build()
                    .unwrap();
                Self {
                    handle: None,
                    runtime: Some(runtime),
                }
            }
        }
    }
}