Skip to main content

diesel/mysql_like/connection/stmt/
iterator.rs

1#![allow(unsafe_code)] // module uses ffi
2use alloc::rc::Rc;
3use core::cell::{Ref, RefCell};
4use core::marker::PhantomData;
5
6use super::{OutputBinds, Statement, StatementMetadata, StatementUse};
7use crate::backend::Backend;
8use crate::connection::statement_cache::MaybeCached;
9use crate::mysql_like::{MysqlLikeBackend, MysqlType};
10use crate::result::Error::DeserializationError;
11use crate::result::QueryResult;
12use crate::row::*;
13
14#[allow(missing_debug_implementations)]
15pub struct StatementIterator<'a, DB: MysqlLikeBackend> {
16    stmt: StatementUse<'a, DB>,
17    last_row: Rc<RefCell<PrivateMysqlRow>>,
18    metadata: Rc<StatementMetadata>,
19    len: usize,
20}
21
22impl<'a, DB: MysqlLikeBackend> StatementIterator<'a, DB> {
23    pub fn from_stmt(
24        stmt: MaybeCached<'a, Statement<DB>>,
25        types: &[Option<MysqlType>],
26    ) -> QueryResult<Self> {
27        let mut stmt = if let Some(metadata) = stmt.metadata()? {
28            let mut output_binds =
29                OutputBinds::from_output_types(types, &metadata).map_err(DeserializationError)?;
30            /*
31                This may seem redundant but if we don't do this we will hit
32                a memory bug in `libmysqlclient`
33            */
34            stmt.execute_statement(&mut output_binds)?
35        } else {
36            //Sometimes we must execute the statement to get its metadata.
37            unsafe { stmt.execute()? }
38        };
39
40        let metadata = stmt.metadata()?;
41        let output_binds =
42            OutputBinds::from_output_types(types, &metadata).map_err(DeserializationError)?;
43
44        let size = unsafe { stmt.result_size() }?;
45
46        Ok(StatementIterator {
47            metadata: Rc::new(metadata),
48            last_row: Rc::new(RefCell::new(PrivateMysqlRow::Direct(output_binds))),
49            len: size,
50            stmt,
51        })
52    }
53}
54
55impl<DB: MysqlLikeBackend> Iterator for StatementIterator<'_, DB> {
56    type Item = QueryResult<MysqlRow<DB>>;
57
58    fn next(&mut self) -> Option<Self::Item> {
59        // check if we own the only instance of the bind buffer
60        // if that's the case we can reuse the underlying allocations
61        // if that's not the case, we need to copy the output bind buffers
62        // to somewhere else
63        let res = if let Some(binds) = Rc::get_mut(&mut self.last_row) {
64            if let PrivateMysqlRow::Direct(binds) = RefCell::get_mut(binds) {
65                self.stmt.populate_row_buffers(binds)
66            } else {
67                // any other state than `PrivateMysqlRow::Direct` is invalid here
68                // and should not happen. If this ever happens this is a logic error
69                // in the code above
70                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("You\'ve reached an impossible internal state. If you ever see this error message please open an issue at https://github.com/diesel-rs/diesel providing example code how to trigger this error.")));
}unreachable!(
71                    "You've reached an impossible internal state. \
72                     If you ever see this error message please open \
73                     an issue at https://github.com/diesel-rs/diesel \
74                     providing example code how to trigger this error."
75                )
76            }
77        } else {
78            // The shared bind buffer is in use by someone else,
79            // this means we copy out the values and replace the used reference
80            // by the copied values. After this we can advance the statement
81            // another step
82            let mut last_row = {
83                let mut last_row = match self.last_row.try_borrow_mut() {
84                    Ok(o) => o,
85                    Err(_e) => {
86                        return Some(Err(DeserializationError(
87                            "Failed to reborrow row. Try to release any `MysqlField` or `MysqlValue` \
88                             that exists at this point"
89                                .into(),
90                        )));
91                    }
92                };
93                let last_row = &mut *last_row;
94                let duplicated = last_row.duplicate();
95                core::mem::replace(last_row, duplicated)
96            };
97            let res = if let PrivateMysqlRow::Direct(ref mut binds) = last_row {
98                self.stmt.populate_row_buffers(binds)
99            } else {
100                // any other state than `PrivateMysqlRow::Direct` is invalid here
101                // and should not happen. If this ever happens this is a logic error
102                // in the code above
103                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("You\'ve reached an impossible internal state. If you ever see this error message please open an issue at https://github.com/diesel-rs/diesel providing example code how to trigger this error.")));
}unreachable!(
104                    "You've reached an impossible internal state. \
105                     If you ever see this error message please open \
106                     an issue at https://github.com/diesel-rs/diesel \
107                     providing example code how to trigger this error."
108                )
109            };
110            self.last_row = Rc::new(RefCell::new(last_row));
111            res
112        };
113
114        match res {
115            Ok(Some(())) => {
116                self.len = self.len.saturating_sub(1);
117                Some(Ok(MysqlRow {
118                    metadata: self.metadata.clone(),
119                    row: self.last_row.clone(),
120                    _phantom: PhantomData,
121                }))
122            }
123            Ok(None) => None,
124            Err(e) => {
125                self.len = self.len.saturating_sub(1);
126                Some(Err(e))
127            }
128        }
129    }
130
131    fn size_hint(&self) -> (usize, Option<usize>) {
132        (self.len(), Some(self.len()))
133    }
134
135    fn count(self) -> usize
136    where
137        Self: Sized,
138    {
139        self.len()
140    }
141}
142
143impl<DB: MysqlLikeBackend> ExactSizeIterator for StatementIterator<'_, DB> {
144    fn len(&self) -> usize {
145        self.len
146    }
147}
148
149#[derive(#[automatically_derived]
#[allow(missing_debug_implementations)]
impl<DB: ::core::clone::Clone + MysqlLikeBackend> ::core::clone::Clone for
    MysqlRow<DB> {
    #[inline]
    fn clone(&self) -> MysqlRow<DB> {
        MysqlRow {
            row: ::core::clone::Clone::clone(&self.row),
            metadata: ::core::clone::Clone::clone(&self.metadata),
            _phantom: ::core::clone::Clone::clone(&self._phantom),
        }
    }
}Clone)]
150#[allow(missing_debug_implementations)]
151pub struct MysqlRow<DB: MysqlLikeBackend> {
152    row: Rc<RefCell<PrivateMysqlRow>>,
153    metadata: Rc<StatementMetadata>,
154    _phantom: PhantomData<DB>,
155}
156
157enum PrivateMysqlRow {
158    Direct(OutputBinds),
159    Copied(OutputBinds),
160}
161
162impl PrivateMysqlRow {
163    fn duplicate(&self) -> Self {
164        match self {
165            Self::Copied(b) | Self::Direct(b) => Self::Copied(b.clone()),
166        }
167    }
168}
169
170impl<DB: MysqlLikeBackend> RowSealed for MysqlRow<DB> {}
171
172impl<'a, DB: MysqlLikeBackend> Row<'a, DB> for MysqlRow<DB> {
173    type Field<'f>
174        = MysqlLikeField<'f, DB>
175    where
176        'a: 'f,
177        Self: 'f;
178    type InnerPartialRow = Self;
179
180    fn field_count(&self) -> usize {
181        self.metadata.fields().len()
182    }
183
184    fn get<'b, I>(&'b self, idx: I) -> Option<Self::Field<'b>>
185    where
186        'a: 'b,
187        Self: RowIndex<I>,
188    {
189        let idx = self.idx(idx)?;
190        Some(MysqlLikeField {
191            binds: self.row.borrow(),
192            metadata: self.metadata.clone(),
193            idx,
194            _phantom: PhantomData,
195        })
196    }
197
198    fn partial_row(&self, range: core::ops::Range<usize>) -> PartialRow<'_, Self::InnerPartialRow> {
199        PartialRow::new::<DB>(self, range)
200    }
201}
202
203impl<DB: MysqlLikeBackend> RowIndex<usize> for MysqlRow<DB>
204where
205    MysqlRow<DB>: for<'a> Row<'a, DB>,
206{
207    fn idx(&self, idx: usize) -> Option<usize> {
208        if idx < self.field_count() {
209            Some(idx)
210        } else {
211            None
212        }
213    }
214}
215
216impl<'a, DB: MysqlLikeBackend> RowIndex<&'a str> for MysqlRow<DB> {
217    fn idx(&self, idx: &'a str) -> Option<usize> {
218        self.metadata
219            .fields()
220            .iter()
221            .enumerate()
222            .find(|(_, field_meta)| field_meta.field_name() == Some(idx))
223            .map(|(idx, _)| idx)
224    }
225}
226
227#[allow(missing_debug_implementations)]
228pub struct MysqlLikeField<'a, DB: MysqlLikeBackend> {
229    binds: Ref<'a, PrivateMysqlRow>,
230    metadata: Rc<StatementMetadata>,
231    idx: usize,
232    _phantom: PhantomData<DB>,
233}
234
235impl<'a, DB: MysqlLikeBackend> Field<'a, DB> for MysqlLikeField<'a, DB> {
236    fn field_name(&self) -> Option<&str> {
237        self.metadata.fields()[self.idx].field_name()
238    }
239
240    fn is_null(&self) -> bool {
241        match &*self.binds {
242            PrivateMysqlRow::Copied(b) | PrivateMysqlRow::Direct(b) => b[self.idx].is_null(),
243        }
244    }
245
246    fn value(&self) -> Option<<DB as Backend>::RawValue<'_>> {
247        match &*self.binds {
248            PrivateMysqlRow::Copied(b) | PrivateMysqlRow::Direct(b) => b[self.idx].value(),
249        }
250    }
251}
252
253#[cfg(all(test, any(feature = "mysql", feature = "mariadb")))]
254#[diesel_test_helper::test]
255#[allow(clippy::drop_non_drop)] // we want to explicitly extend lifetimes here
256fn fun_with_row_iters() {
257    crate::table! {
258        users(id) {
259            id -> Integer,
260            name -> Text,
261        }
262    }
263
264    use crate::connection::LoadConnection;
265    use crate::deserialize::{FromSql, FromSqlRow};
266    use crate::prelude::*;
267    use crate::row::{Field, Row};
268    use crate::sql_types;
269
270    #[cfg(feature = "mysql")]
271    type DB = crate::mysql::Mysql;
272    #[cfg(feature = "mariadb")]
273    type DB = crate::mariadb::Mariadb;
274
275    let conn = &mut crate::test_helpers::connection();
276
277    crate::sql_query(
278        "CREATE TEMPORARY TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, name TEXT NOT NULL);",
279    )
280    .execute(conn)
281    .unwrap();
282
283    crate::insert_into(users::table)
284        .values(vec![
285            (users::id.eq(1), users::name.eq("Sean")),
286            (users::id.eq(2), users::name.eq("Tess")),
287        ])
288        .execute(conn)
289        .unwrap();
290
291    let query = users::table.select((users::id, users::name));
292
293    let expected = vec![(1, String::from("Sean")), (2, String::from("Tess"))];
294
295    {
296        let row_iter = conn.load(query).unwrap();
297        for (row, expected) in row_iter.zip(&expected) {
298            let row = row.unwrap();
299
300            let deserialized = <(i32, String) as FromSqlRow<
301                (sql_types::Integer, sql_types::Text),
302                _,
303            >>::build_from_row(&row)
304            .unwrap();
305
306            assert_eq!(&deserialized, expected);
307        }
308    }
309
310    {
311        let collected_rows = conn.load(query).unwrap().collect::<Vec<_>>();
312        assert_eq!(collected_rows.len(), 2);
313        for (row, expected) in collected_rows.iter().zip(&expected) {
314            let deserialized = row
315                .as_ref()
316                .map(|row| {
317                    <(i32, String) as FromSqlRow<
318                            (sql_types::Integer, sql_types::Text),
319                        _,
320                        >>::build_from_row(row).unwrap()
321                })
322                .unwrap();
323            assert_eq!(&deserialized, expected);
324        }
325    }
326
327    let mut row_iter = conn.load(query).unwrap();
328
329    let first_row = row_iter.next().unwrap().unwrap();
330    let first_fields = (
331        Row::get(&first_row, 0).unwrap(),
332        Row::get(&first_row, 1).unwrap(),
333    );
334    let first_values = (first_fields.0.value(), first_fields.1.value());
335
336    assert!(row_iter.next().unwrap().is_err());
337    std::mem::drop(first_values);
338    assert!(row_iter.next().unwrap().is_err());
339    std::mem::drop(first_fields);
340
341    let second_row = row_iter.next().unwrap().unwrap();
342    let second_fields = (
343        Row::get(&second_row, 0).unwrap(),
344        Row::get(&second_row, 1).unwrap(),
345    );
346    let second_values = (second_fields.0.value(), second_fields.1.value());
347
348    assert!(row_iter.next().unwrap().is_err());
349    std::mem::drop(second_values);
350    assert!(row_iter.next().unwrap().is_err());
351    std::mem::drop(second_fields);
352
353    assert!(row_iter.next().is_none());
354
355    let first_fields = (
356        Row::get(&first_row, 0).unwrap(),
357        Row::get(&first_row, 1).unwrap(),
358    );
359    let second_fields = (
360        Row::get(&second_row, 0).unwrap(),
361        Row::get(&second_row, 1).unwrap(),
362    );
363
364    let first_values = (first_fields.0.value(), first_fields.1.value());
365    let second_values = (second_fields.0.value(), second_fields.1.value());
366
367    assert_eq!(
368        <i32 as FromSql<sql_types::Integer, DB>>::from_nullable_sql(first_values.0).unwrap(),
369        expected[0].0
370    );
371    assert_eq!(
372        <String as FromSql<sql_types::Text, DB>>::from_nullable_sql(first_values.1).unwrap(),
373        expected[0].1
374    );
375
376    assert_eq!(
377        <i32 as FromSql<sql_types::Integer, DB>>::from_nullable_sql(second_values.0).unwrap(),
378        expected[1].0
379    );
380    assert_eq!(
381        <String as FromSql<sql_types::Text, DB>>::from_nullable_sql(second_values.1).unwrap(),
382        expected[1].1
383    );
384
385    let first_fields = (
386        Row::get(&first_row, 0).unwrap(),
387        Row::get(&first_row, 1).unwrap(),
388    );
389    let first_values = (first_fields.0.value(), first_fields.1.value());
390
391    assert_eq!(
392        <i32 as FromSql<sql_types::Integer, DB>>::from_nullable_sql(first_values.0).unwrap(),
393        expected[0].0
394    );
395    assert_eq!(
396        <String as FromSql<sql_types::Text, DB>>::from_nullable_sql(first_values.1).unwrap(),
397        expected[0].1
398    );
399}