Skip to main content

diesel_async/run_query_dsl/
mod.rs

1mod utils;
2
3use crate::AsyncConnectionCore;
4#[cfg(any(feature = "mysql", feature = "mariadb"))]
5use crate::mysql_like::MysqlLikeAsyncBackend;
6use diesel::AsChangeset;
7use diesel::associations::HasTable;
8use diesel::query_builder::IntoUpdateTarget;
9use diesel::result::QueryResult;
10use futures_core::future::BoxFuture;
11#[cfg(any(
12    feature = "mysql",
13    feature = "mariadb",
14    feature = "postgres",
15    feature = "sqlite"
16))]
17use futures_util::FutureExt;
18use futures_util::{StreamExt, TryStreamExt, stream};
19use std::future::Future;
20
21/// The traits used by `QueryDsl`.
22///
23/// Each trait in this module represents exactly one method from [`RunQueryDsl`].
24/// Apps should general rely on [`RunQueryDsl`] directly, rather than these traits.
25/// However, generic code may need to include a where clause that references
26/// these traits.
27pub mod methods {
28    use super::*;
29    use diesel::backend::Backend;
30    use diesel::deserialize::FromSqlRow;
31    use diesel::expression::QueryMetadata;
32    use diesel::query_builder::{AsQuery, QueryFragment, QueryId};
33    use diesel::query_dsl::CompatibleType;
34    use futures_util::{Future, Stream};
35
36    /// The `execute` method
37    ///
38    /// This trait should not be relied on directly by most apps. Its behavior is
39    /// provided by [`RunQueryDsl`]. However, you may need a where clause on this trait
40    /// to call `execute` from generic code.
41    ///
42    /// [`RunQueryDsl`]: super::RunQueryDsl
43    pub trait ExecuteDsl<Conn, DB = <Conn as AsyncConnectionCore>::Backend>
44    where
45        Conn: AsyncConnectionCore<Backend = DB>,
46        DB: Backend,
47    {
48        /// Execute this command
49        fn execute<'conn, 'query>(
50            query: Self,
51            conn: &'conn mut Conn,
52        ) -> Conn::ExecuteFuture<'conn, 'query>
53        where
54            Self: 'query;
55    }
56
57    impl<Conn, DB, T> ExecuteDsl<Conn, DB> for T
58    where
59        Conn: AsyncConnectionCore<Backend = DB>,
60        DB: Backend,
61        T: QueryFragment<DB> + QueryId + Send,
62    {
63        fn execute<'conn, 'query>(
64            query: Self,
65            conn: &'conn mut Conn,
66        ) -> Conn::ExecuteFuture<'conn, 'query>
67        where
68            Self: 'query,
69        {
70            conn.execute_returning_count(query)
71        }
72    }
73
74    /// The `load` method
75    ///
76    /// This trait should not be relied on directly by most apps. Its behavior is
77    /// provided by [`RunQueryDsl`]. However, you may need a where clause on this trait
78    /// to call `load` from generic code.
79    ///
80    /// [`RunQueryDsl`]: super::RunQueryDsl
81    pub trait LoadQuery<'query, Conn: AsyncConnectionCore, U> {
82        /// The future returned by [`LoadQuery::internal_load`]
83        type LoadFuture<'conn>: Future<Output = QueryResult<Self::Stream<'conn>>> + Send
84        where
85            Conn: 'conn;
86
87        /// The inner stream returned by [`LoadQuery::internal_load`]
88        type Stream<'conn>: Stream<Item = QueryResult<U>> + Send
89        where
90            Conn: 'conn;
91
92        /// Load this query
93        fn internal_load(self, conn: &mut Conn) -> Self::LoadFuture<'_>;
94    }
95
96    impl<'query, Conn, DB, T, U, ST> LoadQuery<'query, Conn, U> for T
97    where
98        Conn: AsyncConnectionCore<Backend = DB>,
99        U: Send,
100        DB: Backend + 'static,
101        T: AsQuery + Send + 'query,
102        T::Query: QueryFragment<DB> + QueryId + Send + 'query,
103        T::SqlType: CompatibleType<U, DB, SqlType = ST>,
104        U: FromSqlRow<ST, DB> + Send + 'static,
105        DB: QueryMetadata<T::SqlType>,
106        ST: 'static,
107    {
108        type LoadFuture<'conn>
109            = utils::MapOk<Conn::LoadFuture<'conn, 'query>, Self::Stream<'conn>>
110        where
111            Conn: 'conn;
112
113        type Stream<'conn>
114            = stream::Map<
115            Conn::Stream<'conn, 'query>,
116            fn(QueryResult<Conn::Row<'conn, 'query>>) -> QueryResult<U>,
117        >
118        where
119            Conn: 'conn;
120
121        fn internal_load(self, conn: &mut Conn) -> Self::LoadFuture<'_> {
122            utils::MapOk::new(conn.load(self), |stream| {
123                stream.map(|row| {
124                    U::build_from_row(&row?).map_err(diesel::result::Error::DeserializationError)
125                })
126            })
127        }
128    }
129}
130
131/// The return types produced by the various [`RunQueryDsl`] methods
132///
133// We cannot box these types as this would require specifying a lifetime,
134// but concrete connection implementations might want to have control
135// about that so that they can support multiple simultaneous queries on
136// the same connection
137#[allow(type_alias_bounds)] // we need these bounds otherwise we cannot use GAT's
138pub mod return_futures {
139    use crate::run_query_dsl::utils;
140
141    use super::methods::LoadQuery;
142    use futures_util::stream;
143    use std::pin::Pin;
144
145    /// The future returned by [`RunQueryDsl::load`](super::RunQueryDsl::load)
146    /// and [`RunQueryDsl::get_results`](super::RunQueryDsl::get_results)
147    ///
148    /// This is essentially `impl Future<Output = QueryResult<Vec<U>>>`
149    pub type LoadFuture<'conn, 'query, Q: LoadQuery<'query, Conn, U>, Conn, U> =
150        utils::AndThen<Q::LoadFuture<'conn>, stream::TryCollect<Q::Stream<'conn>, Vec<U>>>;
151
152    /// The future returned by [`RunQueryDsl::get_result`](super::RunQueryDsl::get_result)
153    ///
154    /// This is essentially `impl Future<Output = QueryResult<U>>`
155    pub type GetResult<'conn, 'query, Q: LoadQuery<'query, Conn, U>, Conn, U> =
156        utils::AndThen<Q::LoadFuture<'conn>, utils::LoadNext<Pin<Box<Q::Stream<'conn>>>>>;
157}
158
159/// Methods used to execute queries.
160pub trait RunQueryDsl<Conn>: Sized {
161    /// Executes the given command, returning the number of rows affected.
162    ///
163    /// `execute` is usually used in conjunction with [`insert_into`](diesel::insert_into()),
164    /// [`update`](diesel::update()) and [`delete`](diesel::delete()) where the number of
165    /// affected rows is often enough information.
166    ///
167    /// When asking the database to return data from a query, [`load`](crate::run_query_dsl::RunQueryDsl::load()) should
168    /// probably be used instead.
169    ///
170    /// # Example
171    ///
172    /// ```rust
173    /// # include!("../doctest_setup.rs");
174    /// #
175    /// use diesel_async::RunQueryDsl;
176    ///
177    /// # #[tokio::main(flavor = "current_thread")]
178    /// # async fn main() {
179    /// #     run_test().await;
180    /// # }
181    /// #
182    /// # async fn run_test() -> QueryResult<()> {
183    /// #     use diesel::insert_into;
184    /// #     use schema::users::dsl::*;
185    /// #     let connection = &mut establish_connection().await;
186    /// let inserted_rows = insert_into(users)
187    ///     .values(name.eq("Ruby"))
188    ///     .execute(connection)
189    ///     .await?;
190    /// assert_eq!(1, inserted_rows);
191    ///
192    /// # #[cfg(not(feature = "sqlite"))]
193    /// let inserted_rows = insert_into(users)
194    ///     .values(&vec![name.eq("Jim"), name.eq("James")])
195    ///     .execute(connection)
196    ///     .await?;
197    /// # #[cfg(not(feature = "sqlite"))]
198    /// assert_eq!(2, inserted_rows);
199    /// #     Ok(())
200    /// # }
201    /// ```
202    fn execute<'conn, 'query>(self, conn: &'conn mut Conn) -> Conn::ExecuteFuture<'conn, 'query>
203    where
204        Conn: AsyncConnectionCore + Send,
205        Self: methods::ExecuteDsl<Conn> + 'query,
206    {
207        methods::ExecuteDsl::execute(self, conn)
208    }
209
210    /// Executes the given query, returning a [`Vec`] with the returned rows.
211    ///
212    /// When using the query builder, the return type can be
213    /// a tuple of the values, or a struct which implements [`Queryable`].
214    ///
215    /// When this method is called on [`sql_query`],
216    /// the return type can only be a struct which implements [`QueryableByName`]
217    ///
218    /// For insert, update, and delete operations where only a count of affected is needed,
219    /// [`execute`] should be used instead.
220    ///
221    /// [`Queryable`]: diesel::deserialize::Queryable
222    /// [`QueryableByName`]: diesel::deserialize::QueryableByName
223    /// [`execute`]: crate::run_query_dsl::RunQueryDsl::execute()
224    /// [`sql_query`]: diesel::sql_query()
225    ///
226    /// # Examples
227    ///
228    /// ## Returning a single field
229    ///
230    /// ```rust
231    /// # include!("../doctest_setup.rs");
232    /// #
233    /// use diesel_async::{RunQueryDsl, AsyncConnection};
234    ///
235    /// #
236    /// # #[tokio::main(flavor = "current_thread")]
237    /// # async fn main() {
238    /// #     run_test().await;
239    /// # }
240    /// #
241    /// # async fn run_test() -> QueryResult<()> {
242    /// #     use diesel::insert_into;
243    /// #     use schema::users::dsl::*;
244    /// #     let connection = &mut establish_connection().await;
245    /// let data = users.select(name)
246    ///     .load::<String>(connection)
247    ///     .await?;
248    /// assert_eq!(vec!["Sean", "Tess"], data);
249    /// #     Ok(())
250    /// # }
251    /// ```
252    ///
253    /// ## Returning a tuple
254    ///
255    /// ```rust
256    /// # include!("../doctest_setup.rs");
257    /// use diesel_async::RunQueryDsl;
258    ///
259    /// #
260    /// # #[tokio::main(flavor = "current_thread")]
261    /// # async fn main() {
262    /// #     run_test().await;
263    /// # }
264    /// #
265    /// # async fn run_test() -> QueryResult<()> {
266    /// #     use diesel::insert_into;
267    /// #     use schema::users::dsl::*;
268    /// #     let connection = &mut establish_connection().await;
269    /// let data = users
270    ///     .load::<(i32, String)>(connection)
271    ///     .await?;
272    /// let expected_data = vec![
273    ///     (1, String::from("Sean")),
274    ///     (2, String::from("Tess")),
275    /// ];
276    /// assert_eq!(expected_data, data);
277    /// #     Ok(())
278    /// # }
279    /// ```
280    ///
281    /// ## Returning a struct
282    ///
283    /// ```rust
284    /// # include!("../doctest_setup.rs");
285    /// use diesel_async::RunQueryDsl;
286    ///
287    /// #
288    /// #[derive(Queryable, PartialEq, Debug)]
289    /// struct User {
290    ///     id: i32,
291    ///     name: String,
292    /// }
293    ///
294    /// # #[tokio::main(flavor = "current_thread")]
295    /// # async fn main() {
296    /// #     run_test().await;
297    /// # }
298    /// #
299    /// # async fn run_test() -> QueryResult<()> {
300    /// #     use diesel::insert_into;
301    /// #     use schema::users::dsl::*;
302    /// #     let connection = &mut establish_connection().await;
303    /// let data = users
304    ///     .load::<User>(connection)
305    ///     .await?;
306    /// let expected_data = vec![
307    ///     User { id: 1, name: String::from("Sean") },
308    ///     User { id: 2, name: String::from("Tess") },
309    /// ];
310    /// assert_eq!(expected_data, data);
311    /// #     Ok(())
312    /// # }
313    /// ```
314    fn load<'query, 'conn, U>(
315        self,
316        conn: &'conn mut Conn,
317    ) -> return_futures::LoadFuture<'conn, 'query, Self, Conn, U>
318    where
319        U: Send,
320        Conn: AsyncConnectionCore,
321        Self: methods::LoadQuery<'query, Conn, U> + 'query,
322    {
323        utils::AndThen::new(self.internal_load(conn), |stream| stream.try_collect())
324    }
325
326    /// Executes the given query, returning a [`Stream`] with the returned rows.
327    ///
328    /// **You should normally prefer to use [`RunQueryDsl::load`] instead**. This method
329    /// is provided for situations where the result needs to be collected into a different
330    /// container than a [`Vec`]
331    ///
332    /// When using the query builder, the return type can be
333    /// a tuple of the values, or a struct which implements [`Queryable`].
334    ///
335    /// When this method is called on [`sql_query`],
336    /// the return type can only be a struct which implements [`QueryableByName`]
337    ///
338    /// For insert, update, and delete operations where only a count of affected is needed,
339    /// [`execute`] should be used instead.
340    ///
341    /// [`Queryable`]: diesel::deserialize::Queryable
342    /// [`QueryableByName`]: diesel::deserialize::QueryableByName
343    /// [`execute`]: crate::run_query_dsl::RunQueryDsl::execute()
344    /// [`sql_query`]: diesel::sql_query()
345    ///
346    /// # Examples
347    ///
348    /// ## Returning a single field
349    ///
350    /// ```rust
351    /// # include!("../doctest_setup.rs");
352    /// #
353    /// use diesel_async::RunQueryDsl;
354    ///
355    /// # #[tokio::main(flavor = "current_thread")]
356    /// # async fn main() {
357    /// #     run_test().await;
358    /// # }
359    /// #
360    /// # async fn run_test() -> QueryResult<()> {
361    /// #     use diesel::insert_into;
362    /// #     use schema::users::dsl::*;
363    /// #     use futures_util::stream::TryStreamExt;
364    /// #     let connection = &mut establish_connection().await;
365    /// let data = users.select(name)
366    ///     .load_stream::<String>(connection)
367    ///     .await?
368    ///     .try_fold(Vec::new(), |mut acc, item| {
369    ///          acc.push(item);
370    ///          std::future::ready(Ok(acc))
371    ///      })
372    ///     .await?;
373    /// assert_eq!(vec!["Sean", "Tess"], data);
374    /// #     Ok(())
375    /// # }
376    /// ```
377    ///
378    /// ## Returning a tuple
379    ///
380    /// ```rust
381    /// # include!("../doctest_setup.rs");
382    /// use diesel_async::RunQueryDsl;
383    /// #
384    /// # #[tokio::main(flavor = "current_thread")]
385    /// # async fn main() {
386    /// #     run_test().await;
387    /// # }
388    /// #
389    /// # async fn run_test() -> QueryResult<()> {
390    /// #     use diesel::insert_into;
391    /// #     use schema::users::dsl::*;
392    /// #     use futures_util::stream::TryStreamExt;
393    /// #     let connection = &mut establish_connection().await;
394    /// let data = users
395    ///     .load_stream::<(i32, String)>(connection)
396    ///     .await?
397    ///     .try_fold(Vec::new(), |mut acc, item| {
398    ///          acc.push(item);
399    ///          std::future::ready(Ok(acc))
400    ///      })
401    ///     .await?;
402    /// let expected_data = vec![
403    ///     (1, String::from("Sean")),
404    ///     (2, String::from("Tess")),
405    /// ];
406    /// assert_eq!(expected_data, data);
407    /// #     Ok(())
408    /// # }
409    /// ```
410    ///
411    /// ## Returning a struct
412    ///
413    /// ```rust
414    /// # include!("../doctest_setup.rs");
415    /// #
416    /// use diesel_async::RunQueryDsl;
417    ///
418    /// #[derive(Queryable, PartialEq, Debug)]
419    /// struct User {
420    ///     id: i32,
421    ///     name: String,
422    /// }
423    ///
424    /// # #[tokio::main(flavor = "current_thread")]
425    /// # async fn main() {
426    /// #     run_test().await;
427    /// # }
428    /// #
429    /// # async fn run_test() -> QueryResult<()> {
430    /// #     use diesel::insert_into;
431    /// #     use schema::users::dsl::*;
432    /// #     use futures_util::stream::TryStreamExt;
433    /// #     let connection = &mut establish_connection().await;
434    /// let data = users
435    ///     .load_stream::<User>(connection)
436    ///     .await?
437    ///     .try_fold(Vec::new(), |mut acc, item| {
438    ///          acc.push(item);
439    ///          std::future::ready(Ok(acc))
440    ///      })
441    ///     .await?;
442    /// let expected_data = vec![
443    ///     User { id: 1, name: String::from("Sean") },
444    ///     User { id: 2, name: String::from("Tess") },
445    /// ];
446    /// assert_eq!(expected_data, data);
447    /// #     Ok(())
448    /// # }
449    /// ```
450    fn load_stream<'conn, 'query, U>(self, conn: &'conn mut Conn) -> Self::LoadFuture<'conn>
451    where
452        Conn: AsyncConnectionCore,
453        U: 'conn,
454        Self: methods::LoadQuery<'query, Conn, U> + 'query,
455    {
456        self.internal_load(conn)
457    }
458
459    /// Runs the command, and returns the affected row.
460    ///
461    /// `Err(NotFound)` will be returned if the query affected 0 rows. You can
462    /// call `.optional()` on the result of this if the command was optional to
463    /// get back a `Result<Option<U>>`
464    ///
465    /// When this method is called on an insert, update, or delete statement,
466    /// it will implicitly add a `RETURNING *` to the query,
467    /// unless a returning clause was already specified.
468    ///
469    /// This method only returns the first row that was affected, even if more
470    /// rows are affected.
471    ///
472    /// # Example
473    ///
474    /// ```rust
475    /// # include!("../doctest_setup.rs");
476    /// use diesel_async::RunQueryDsl;
477    ///
478    /// #
479    /// # #[tokio::main(flavor = "current_thread")]
480    /// # async fn main() {
481    /// #     run_test().await;
482    /// # }
483    /// #
484    /// # #[cfg(feature = "postgres")]
485    /// # async fn run_test() -> QueryResult<()> {
486    /// #     use diesel::{insert_into, update};
487    /// #     use schema::users::dsl::*;
488    /// #     let connection = &mut establish_connection().await;
489    /// let inserted_row = insert_into(users)
490    ///     .values(name.eq("Ruby"))
491    ///     .get_result(connection)
492    ///     .await?;
493    /// assert_eq!((3, String::from("Ruby")), inserted_row);
494    ///
495    /// // This will return `NotFound`, as there is no user with ID 4
496    /// let update_result = update(users.find(4))
497    ///     .set(name.eq("Jim"))
498    ///     .get_result::<(i32, String)>(connection)
499    ///     .await;
500    /// assert_eq!(Err(diesel::NotFound), update_result);
501    /// #     Ok(())
502    /// # }
503    /// #
504    /// # #[cfg(not(feature = "postgres"))]
505    /// # async fn run_test() -> QueryResult<()> {
506    /// #     Ok(())
507    /// # }
508    /// ```
509    fn get_result<'query, 'conn, U>(
510        self,
511        conn: &'conn mut Conn,
512    ) -> return_futures::GetResult<'conn, 'query, Self, Conn, U>
513    where
514        U: Send + 'conn,
515        Conn: AsyncConnectionCore,
516        Self: methods::LoadQuery<'query, Conn, U> + 'query,
517    {
518        utils::AndThen::new(self.internal_load(conn), |stream| {
519            utils::LoadNext::new(Box::pin(stream))
520        })
521    }
522
523    /// Runs the command, returning an `Vec` with the affected rows.
524    ///
525    /// This method is an alias for [`load`], but with a name that makes more
526    /// sense for insert, update, and delete statements.
527    ///
528    /// [`load`]: crate::run_query_dsl::RunQueryDsl::load()
529    fn get_results<'query, 'conn, U>(
530        self,
531        conn: &'conn mut Conn,
532    ) -> return_futures::LoadFuture<'conn, 'query, Self, Conn, U>
533    where
534        U: Send,
535        Conn: AsyncConnectionCore,
536        Self: methods::LoadQuery<'query, Conn, U> + 'query,
537    {
538        self.load(conn)
539    }
540
541    /// Attempts to load a single record.
542    ///
543    /// This method is equivalent to `.limit(1).get_result()`
544    ///
545    /// Returns `Ok(record)` if found, and `Err(NotFound)` if no results are
546    /// returned. If the query truly is optional, you can call `.optional()` on
547    /// the result of this to get a `Result<Option<U>>`.
548    ///
549    /// # Example:
550    ///
551    /// ```rust
552    /// # include!("../doctest_setup.rs");
553    /// use diesel_async::RunQueryDsl;
554    ///
555    /// #
556    /// # #[tokio::main(flavor = "current_thread")]
557    /// # async fn main() {
558    /// #     run_test();
559    /// # }
560    /// #
561    /// # async fn run_test() -> QueryResult<()> {
562    /// #     use schema::users::dsl::*;
563    /// #     let connection = &mut establish_connection().await;
564    /// for n in &["Sean", "Pascal"] {
565    ///     diesel::insert_into(users)
566    ///         .values(name.eq(n))
567    ///         .execute(connection)
568    ///         .await?;
569    /// }
570    ///
571    /// let first_name = users.order(id)
572    ///     .select(name)
573    ///     .first(connection)
574    ///     .await;
575    /// assert_eq!(Ok(String::from("Sean")), first_name);
576    ///
577    /// let not_found = users
578    ///     .filter(name.eq("Foo"))
579    ///     .first::<(i32, String)>(connection)
580    ///     .await;
581    /// assert_eq!(Err(diesel::NotFound), not_found);
582    /// #     Ok(())
583    /// # }
584    /// ```
585    fn first<'query, 'conn, U>(
586        self,
587        conn: &'conn mut Conn,
588    ) -> return_futures::GetResult<'conn, 'query, diesel::dsl::Limit<Self>, Conn, U>
589    where
590        U: Send + 'conn,
591        Conn: AsyncConnectionCore,
592        Self: diesel::query_dsl::methods::LimitDsl,
593        diesel::dsl::Limit<Self>:
594            methods::LoadQuery<'query, Conn, U> + RunQueryDsl<Conn> + Send + 'query,
595    {
596        diesel::query_dsl::methods::LimitDsl::limit(self, 1).get_result(conn)
597    }
598}
599
600impl<T, Conn> RunQueryDsl<Conn> for T where T: diesel::query_dsl::RunQueryDslSupport {}
601
602/// Sugar for types which implement both `AsChangeset` and `Identifiable`
603///
604/// On backends which support the `RETURNING` keyword,
605/// `foo.save_changes(&conn)` is equivalent to
606/// `update(&foo).set(&foo).get_result(&conn)`.
607/// On other backends, two queries will be executed.
608///
609/// # Example
610///
611/// ```rust
612/// # include!("../doctest_setup.rs");
613/// # use schema::animals;
614/// #
615/// use diesel_async::{SaveChangesDsl, AsyncConnection};
616///
617/// #[derive(Queryable, Debug, PartialEq)]
618/// struct Animal {
619///    id: i32,
620///    species: String,
621///    legs: i32,
622///    name: Option<String>,
623/// }
624///
625/// #[derive(AsChangeset, Identifiable)]
626/// #[diesel(table_name = animals)]
627/// struct AnimalForm<'a> {
628///     id: i32,
629///     name: &'a str,
630/// }
631///
632/// # #[tokio::main(flavor = "current_thread")]
633/// # async fn main() {
634/// #     run_test().await.unwrap();
635/// # }
636/// #
637/// # async fn run_test() -> QueryResult<()> {
638/// #     use self::animals::dsl::*;
639/// #     let connection = &mut establish_connection().await;
640/// let form = AnimalForm { id: 2, name: "Super scary" };
641/// # #[cfg(not(feature = "sqlite"))]
642/// let changed_animal = form.save_changes(connection).await?;
643/// let expected_animal = Animal {
644///     id: 2,
645///     species: String::from("spider"),
646///     legs: 8,
647///     name: Some(String::from("Super scary")),
648/// };
649/// # #[cfg(not(feature = "sqlite"))]
650/// assert_eq!(expected_animal, changed_animal);
651/// #     Ok(())
652/// # }
653/// ```
654pub trait SaveChangesDsl<Conn> {
655    /// See the trait documentation
656    fn save_changes<'life0, 'async_trait, T>(
657        self,
658        connection: &'life0 mut Conn,
659    ) -> impl Future<Output = QueryResult<T>> + Send + 'async_trait
660    where
661        Self: Sized + diesel::prelude::Identifiable,
662        Conn: UpdateAndFetchResults<Self, T>,
663        T: 'async_trait,
664        'life0: 'async_trait,
665        Self: ::core::marker::Send + 'async_trait,
666    {
667        connection.update_and_fetch(self)
668    }
669}
670
671impl<T, Conn> SaveChangesDsl<Conn> for T where
672    T: Copy + AsChangeset<Target = <T as HasTable>::Table> + IntoUpdateTarget
673{
674}
675
676/// A trait defining how to update a record and fetch the updated entry
677/// on a certain backend.
678///
679/// The only case where it is required to work with this trait is while
680/// implementing a new connection type.
681/// Otherwise use [`SaveChangesDsl`]
682///
683/// For implementing this trait for a custom backend:
684/// * The `Changes` generic parameter represents the changeset that should be stored
685/// * The `Output` generic parameter represents the type of the response.
686pub trait UpdateAndFetchResults<Changes, Output>: AsyncConnectionCore
687where
688    Changes: diesel::prelude::Identifiable + HasTable,
689{
690    /// See the traits documentation.
691    fn update_and_fetch<'conn, 'changes>(
692        &'conn mut self,
693        changeset: Changes,
694    ) -> BoxFuture<'changes, QueryResult<Output>>
695    // cannot use impl future due to rustc bugs
696    // https://github.com/rust-lang/rust/issues/135619
697    //impl Future<Output = QueryResult<Output>> + Send + 'changes
698    where
699        Changes: 'changes,
700        'conn: 'changes,
701        Self: 'changes;
702}
703
704#[cfg(any(feature = "mysql", feature = "mariadb"))]
705impl<'b, Changes, Output, Tab, V, DB> UpdateAndFetchResults<Changes, Output>
706    for crate::mysql_like::AsyncMysqlLikeConnection<DB>
707where
708    Output: Send + 'static,
709    Changes:
710        Copy + AsChangeset<Target = Tab> + Send + diesel::associations::Identifiable<Table = Tab>,
711    Tab: diesel::Table + diesel::query_dsl::methods::FindDsl<Changes::Id> + 'b,
712    diesel::dsl::Find<Tab, Changes::Id>: IntoUpdateTarget<Table = Tab, WhereClause = V>,
713    diesel::query_builder::UpdateStatement<Tab, V, Changes::Changeset>:
714        diesel::query_builder::AsQuery,
715    diesel::dsl::Update<Changes, Changes>: methods::ExecuteDsl<Self>,
716    V: Send + 'b,
717    DB: MysqlLikeAsyncBackend,
718    Self: AsyncConnectionCore,
719    Changes::Changeset: Send + 'b,
720    Changes::Id: 'b,
721    Tab::FromClause: Send,
722    diesel::dsl::Find<Changes::Table, Changes::Id>: methods::LoadQuery<'b, crate::mysql_like::AsyncMysqlLikeConnection<DB>, Output>
723        + RunQueryDsl<crate::mysql_like::AsyncMysqlLikeConnection<DB>>
724        + Send,
725{
726    fn update_and_fetch<'conn, 'changes>(
727        &'conn mut self,
728        changeset: Changes,
729    ) -> BoxFuture<'changes, QueryResult<Output>>
730    where
731        Changes: 'changes,
732        Changes::Changeset: 'changes,
733        'conn: 'changes,
734        Self: 'changes,
735    {
736        async move {
737            diesel::update(changeset)
738                .set(changeset)
739                .execute(self)
740                .await?;
741            Changes::table().find(changeset.id()).get_result(self).await
742        }
743        .boxed()
744    }
745}
746
747#[cfg(feature = "postgres")]
748impl<'b, Changes, Output, Tab, V> UpdateAndFetchResults<Changes, Output>
749    for crate::AsyncPgConnection
750where
751    Output: Send + 'static,
752    Changes:
753        Copy + AsChangeset<Target = Tab> + Send + diesel::associations::Identifiable<Table = Tab>,
754    Tab: diesel::Table + diesel::query_dsl::methods::FindDsl<Changes::Id> + 'b,
755    diesel::dsl::Find<Tab, Changes::Id>: IntoUpdateTarget<Table = Tab, WhereClause = V>,
756    diesel::query_builder::UpdateStatement<Tab, V, Changes::Changeset>:
757        diesel::query_builder::AsQuery,
758    diesel::dsl::Update<Changes, Changes>: methods::LoadQuery<'b, Self, Output>,
759    V: Send + 'b,
760    Changes::Changeset: Send + 'b,
761    Tab::FromClause: Send,
762{
763    fn update_and_fetch<'conn, 'changes>(
764        &'conn mut self,
765        changeset: Changes,
766    ) -> BoxFuture<'changes, QueryResult<Output>>
767    where
768        Changes: 'changes,
769        Changes::Changeset: 'changes,
770        'conn: 'changes,
771        Self: 'changes,
772    {
773        async move {
774            diesel::update(changeset)
775                .set(changeset)
776                .get_result(self)
777                .await
778        }
779        .boxed()
780    }
781}
782
783#[cfg(feature = "sqlite")]
784impl<'b, Changes, Output, Tab, V, C, B> UpdateAndFetchResults<Changes, Output>
785    for crate::sync_connection_wrapper::SyncConnectionWrapper<C, B>
786where
787    crate::sync_connection_wrapper::SyncConnectionWrapper<C, B>: AsyncConnectionCore,
788    C: 'static,
789    B: 'static,
790    Output: Send + 'static,
791    Changes:
792        Copy + AsChangeset<Target = Tab> + Send + diesel::associations::Identifiable<Table = Tab>,
793    Tab: diesel::Table + diesel::query_dsl::methods::FindDsl<Changes::Id> + 'b,
794    diesel::dsl::Find<Tab, Changes::Id>: IntoUpdateTarget<Table = Tab, WhereClause = V>,
795    diesel::query_builder::UpdateStatement<Tab, V, Changes::Changeset>:
796        diesel::query_builder::AsQuery,
797    diesel::dsl::Update<Changes, Changes>: methods::LoadQuery<'b, Self, Output>,
798    V: Send + 'b,
799    Changes::Changeset: Send + 'b,
800    Tab::FromClause: Send,
801{
802    fn update_and_fetch<'conn, 'changes>(
803        &'conn mut self,
804        changeset: Changes,
805    ) -> BoxFuture<'changes, QueryResult<Output>>
806    where
807        Changes: 'changes,
808        Changes::Changeset: 'changes,
809        'conn: 'changes,
810        Self: 'changes,
811    {
812        async move {
813            diesel::update(changeset)
814                .set(changeset)
815                .get_result(self)
816                .await
817        }
818        .boxed()
819    }
820}