diesel/query_dsl/
load_dsl.rs

1use self::private::LoadIter;
2use super::RunQueryDsl;
3use crate::backend::Backend;
4use crate::connection::{Connection, DefaultLoadingMode, LoadConnection};
5use crate::deserialize::FromSqlRow;
6use crate::expression::QueryMetadata;
7use crate::query_builder::{AsQuery, QueryFragment, QueryId};
8use crate::result::QueryResult;
9
10#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
11pub use self::private::CompatibleType;
12
13#[cfg(not(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"))]
14pub(crate) use self::private::CompatibleType;
15
16/// The `load` method
17///
18/// This trait should not be relied on directly by most apps. Its behavior is
19/// provided by [`RunQueryDsl`]. However, you may need a where clause on this trait
20/// to call `load` from generic code.
21///
22/// [`RunQueryDsl`]: crate::RunQueryDsl
23pub trait LoadQuery<'query, Conn, U, B = DefaultLoadingMode>: RunQueryDsl<Conn> {
24    /// Return type of `LoadQuery::internal_load`
25    type RowIter<'conn>: Iterator<Item = QueryResult<U>>
26    where
27        Conn: 'conn;
28
29    /// Load this query
30    #[diesel_derives::__diesel_public_if(
31        feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
32    )]
33    fn internal_load(self, conn: &mut Conn) -> QueryResult<Self::RowIter<'_>>;
34}
35
36#[doc(hidden)]
37#[cfg(all(feature = "with-deprecated", not(feature = "without-deprecated")))]
38#[deprecated(note = "Use `LoadQuery::Iter` directly")]
39pub type LoadRet<'conn, 'query, Q, C, U, B = DefaultLoadingMode> =
40    <Q as LoadQuery<'query, C, U, B>>::RowIter<'conn>;
41
42impl<'query, Conn, T, U, DB, B> LoadQuery<'query, Conn, U, B> for T
43where
44    Conn: Connection<Backend = DB> + LoadConnection<B>,
45    T: AsQuery + RunQueryDsl<Conn>,
46    T::Query: QueryFragment<DB> + QueryId + 'query,
47    T::SqlType: CompatibleType<U, DB>,
48    DB: Backend + QueryMetadata<T::SqlType> + 'static,
49    U: FromSqlRow<<T::SqlType as CompatibleType<U, DB>>::SqlType, DB> + 'static,
50    <T::SqlType as CompatibleType<U, DB>>::SqlType: 'static,
51{
52    type RowIter<'conn>
53        = LoadIter<
54        U,
55        <Conn as LoadConnection<B>>::Cursor<'conn, 'query>,
56        <T::SqlType as CompatibleType<U, DB>>::SqlType,
57        DB,
58    >
59    where
60        Conn: 'conn;
61
62    fn internal_load(self, conn: &mut Conn) -> QueryResult<Self::RowIter<'_>> {
63        Ok(LoadIter {
64            cursor: conn.load(self.as_query())?,
65            _marker: Default::default(),
66        })
67    }
68}
69
70/// The `execute` method
71///
72/// This trait should not be relied on directly by most apps. Its behavior is
73/// provided by [`RunQueryDsl`]. However, you may need a where clause on this trait
74/// to call `execute` from generic code.
75///
76/// [`RunQueryDsl`]: crate::RunQueryDsl
77pub trait ExecuteDsl<Conn: Connection<Backend = DB>, DB: Backend = <Conn as Connection>::Backend>:
78    Sized
79{
80    /// Execute this command
81    fn execute(query: Self, conn: &mut Conn) -> QueryResult<usize>;
82}
83
84use crate::result::Error;
85
86impl<Conn, DB, T> ExecuteDsl<Conn, DB> for T
87where
88    Conn: Connection<Backend = DB>,
89    DB: Backend,
90    T: QueryFragment<DB> + QueryId,
91{
92    fn execute(query: T, conn: &mut Conn) -> Result<usize, Error> {
93        conn.execute_returning_count(&query)
94    }
95}
96
97// These types and traits are not part of the public API.
98//
99// * CompatibleType as we consider this as "sealed" trait. It shouldn't
100// be implemented by a third party
101// * LoadIter as it's an implementation detail
102mod private {
103    use crate::backend::Backend;
104    use crate::deserialize::FromSqlRow;
105    use crate::expression::select_by::SelectBy;
106    use crate::expression::{Expression, TypedExpressionType};
107    use crate::sql_types::{SqlType, Untyped};
108    use crate::{QueryResult, Selectable};
109
110    #[allow(missing_debug_implementations)]
111    pub struct LoadIter<U, C, ST, DB> {
112        pub(super) cursor: C,
113        pub(super) _marker: std::marker::PhantomData<(ST, U, DB)>,
114    }
115
116    impl<'a, C, U, ST, DB, R> LoadIter<U, C, ST, DB>
117    where
118        DB: Backend,
119        C: Iterator<Item = QueryResult<R>>,
120        R: crate::row::Row<'a, DB>,
121        U: FromSqlRow<ST, DB>,
122    {
123        pub(super) fn map_row(row: Option<QueryResult<R>>) -> Option<QueryResult<U>> {
124            match row? {
125                Ok(row) => Some(
126                    U::build_from_row(&row).map_err(crate::result::Error::DeserializationError),
127                ),
128                Err(e) => Some(Err(e)),
129            }
130        }
131    }
132
133    impl<'a, C, U, ST, DB, R> Iterator for LoadIter<U, C, ST, DB>
134    where
135        DB: Backend,
136        C: Iterator<Item = QueryResult<R>>,
137        R: crate::row::Row<'a, DB>,
138        U: FromSqlRow<ST, DB>,
139    {
140        type Item = QueryResult<U>;
141
142        fn next(&mut self) -> Option<Self::Item> {
143            Self::map_row(self.cursor.next())
144        }
145
146        fn size_hint(&self) -> (usize, Option<usize>) {
147            self.cursor.size_hint()
148        }
149
150        fn count(self) -> usize
151        where
152            Self: Sized,
153        {
154            self.cursor.count()
155        }
156
157        fn last(self) -> Option<Self::Item>
158        where
159            Self: Sized,
160        {
161            Self::map_row(self.cursor.last())
162        }
163
164        fn nth(&mut self, n: usize) -> Option<Self::Item> {
165            Self::map_row(self.cursor.nth(n))
166        }
167    }
168
169    impl<'a, C, U, ST, DB, R> ExactSizeIterator for LoadIter<U, C, ST, DB>
170    where
171        DB: Backend,
172        C: ExactSizeIterator + Iterator<Item = QueryResult<R>>,
173        R: crate::row::Row<'a, DB>,
174        U: FromSqlRow<ST, DB>,
175    {
176        fn len(&self) -> usize {
177            self.cursor.len()
178        }
179    }
180
181    #[cfg_attr(
182        docsrs,
183        doc(cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"))
184    )]
185    #[diagnostic::on_unimplemented(
186        note = "this is a mismatch between what your query returns and what your type expects the query to return",
187        note = "the fields in your struct need to match the fields returned by your query in count, order and type",
188        note = "consider using `#[diesel(check_for_backend({DB}))]` on either `#[derive(Selectable)]` or `#[derive(QueryableByName)]` \n\
189                on your struct `{U}` and in your query `.select({U}::as_select())` to get a better error message"
190    )]
191    pub trait CompatibleType<U, DB> {
192        type SqlType;
193    }
194
195    impl<ST, U, DB> CompatibleType<U, DB> for ST
196    where
197        DB: Backend,
198        ST: SqlType + crate::sql_types::SingleValue,
199        U: FromSqlRow<ST, DB>,
200    {
201        type SqlType = ST;
202    }
203
204    impl<U, DB> CompatibleType<U, DB> for Untyped
205    where
206        U: FromSqlRow<Untyped, DB>,
207        DB: Backend,
208    {
209        type SqlType = Untyped;
210    }
211
212    impl<U, DB, E, ST> CompatibleType<U, DB> for SelectBy<U, DB>
213    where
214        DB: Backend,
215        ST: SqlType + TypedExpressionType,
216        U: Selectable<DB, SelectExpression = E>,
217        E: Expression<SqlType = ST>,
218        U: FromSqlRow<ST, DB>,
219    {
220        type SqlType = ST;
221    }
222}