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