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
use super::*;

// type DeserializeIter<'b, B, T> =
//     std::iter::Map<RowsIter<'b, B>, fn(RowInBlock<'b, B>) -> Result<T, DeError>>;

/// Trait to define a data `Block` to fetch records bulky.
///
/// If query performance is not your main concern, you can just use the deserialize method from result set.
pub trait BlockExt: Debug + Sized {
    /// A block should container number of rows.
    fn num_of_rows(&self) -> usize;

    /// Fields can be queried from a block.
    fn fields(&self) -> &[Field];

    /// Number of fields.
    fn field_count(&self) -> usize {
        self.fields().len()
    }

    fn precision(&self) -> Precision;

    fn is_null(&self, row: usize, col: usize) -> bool;

    /// Get field without column index check.
    ///
    /// # Safety
    ///
    /// This should not be called manually, please use [get_field](#method.get_field).
    unsafe fn get_field_unchecked(&self, col: usize) -> &Field {
        self.fields().get_unchecked(col)
    }

    /// Get field of one column.
    fn get_field(&self, col: usize) -> Option<&Field> {
        self.fields().get(col)
    }

    /// # Safety
    ///
    /// **DO NOT** call it directly.
    unsafe fn cell_unchecked(&self, row: usize, col: usize) -> (&Field, BorrowedValue);

    /// # Safety
    /// **DO NOT** call it directly.
    unsafe fn get_col_unchecked(&self, col: usize) -> &ColumnView;

    /// Query by rows.
    // fn iter_rows(&self) -> RowsIter<'_, Self> {
    //     RowsIter::new(self)
    // }

    /// Consume self into rows.
    // fn into_iter_rows(self) -> IntoRowsIter<Self> {
    //     IntoRowsIter::new(self)
    // }

    /// Columns iterator with borrowed data from block.
    fn columns_iter(&self) -> ColsIter<'_, Self> {
        ColsIter::new(self)
    }

    // fn to_records(&self) -> Vec<Vec<Value>> {
    //     self.iter_rows()
    //         .map(|row| row.into_iter().map(|(f, v)| v.into_value()).collect_vec())
    //         .collect_vec()
    // }

    // / Deserialize a row to a record type(primitive type or a struct).
    // /
    // / Any record could borrow data from the block, so that &[u8], &[str] could be used as record element (if valid).
    // fn deserialize<'b, T>(&'b self) -> DeserializeIter<'b, Self, T>
    // where
    //     T: serde::de::Deserialize<'b>,
    // {
    //     self.iter_rows().map(|row| {
    //         let de = de::RecordDeserializer::from(row);
    //         T::deserialize(de)
    //     })
    // }

    // / Deserialize a row to a record type(primitive type or a struct).
    // /
    // / Any record could borrow data from the block, so that &[u8], &[str] could be used as record element (if valid).
    // fn deserialize_into<T>(
    //     self,
    // ) -> std::iter::Map<IntoRowsIter<Self>, fn(QueryRowIter<Self>) -> Result<T, DeError>>
    // where
    //     T: serde::de::DeserializeOwned,
    // {
    //     self.into_iter_rows().map(|row| {
    //         let de = de::RecordDeserializer::from(&row);
    //         T::deserialize(de)
    //     })
    // }

    // / Shortcut version to `.deserialize_into.collect::<Vec<T>>()`
    //
    // fn deserialize_into_vec<T>(self) -> Vec<Result<T, DeError>>
    // where
    //     T: serde::de::DeserializeOwned,
    // {
    //     self.deserialize_into().collect()
    // }

    // #[cfg(feature = "async")]
    // /// Rows as [futures::stream::Stream].
    // fn rows_stream(&self) -> futures::stream::Iter<RowsIter<'_, Self>> {
    //     futures::stream::iter(Self::iter_rows(self))
    // }

    // #[cfg(feature = "async")]
    // /// Owned version to rows stream.
    // fn into_rows_stream(self) -> futures::stream::Iter<IntoRowsIter<Self>> {
    //     futures::stream::iter(Self::into_iter_rows(self))
    // }

    // #[cfg(feature = "async")]
    // /// Rows stream to deserialized record.
    // fn deserialize_stream<'b, T>(&'b self) -> futures::stream::Iter<DeserializeIter<'b, Self, T>>
    // where
    //     T: serde::de::Deserialize<'b>,
    // {
    //     futures::stream::iter(Self::deserialize(self))
    // }
}

pub struct CellIter<'b, T: BlockExt> {
    block: &'b T,
    row: usize,
    col: usize,
}

impl<'b, T: BlockExt> Iterator for CellIter<'b, T> {
    type Item = (&'b Field, BorrowedValue<'b>);

    fn next(&mut self) -> Option<Self::Item> {
        let col = self.col;
        if col < self.block.field_count() {
            self.col += 1;
            Some(unsafe { self.block.cell_unchecked(self.row, col) })
        } else {
            None
        }
    }
}

#[derive(Debug)]
pub struct RowInBlock<'b, T: BlockExt> {
    block: &'b T,
    row: usize,
}

impl<'b, T> IntoIterator for RowInBlock<'b, T>
where
    T: BlockExt,
{
    type Item = (&'b Field, BorrowedValue<'b>);

    type IntoIter = CellIter<'b, T>;

    fn into_iter(self) -> Self::IntoIter {
        CellIter {
            block: self.block,
            row: self.row,
            col: 0,
        }
    }
}

#[derive(Debug)]
pub struct RowsIter<'b, T: BlockExt> {
    block: &'b T,
    row: usize,
}

// impl<'b, T> RowsIter<'b, T>
// where
//     T: BlockExt,
// {
//     pub(crate) fn new(block: &'b T) -> Self {
//         Self { block, row: 0 }
//     }
// }

impl<'b, T> Iterator for RowsIter<'b, T>
where
    T: BlockExt,
{
    type Item = RowInBlock<'b, T>;

    fn next(&mut self) -> Option<Self::Item> {
        let row = self.row;

        if row < self.block.num_of_rows() {
            self.row += 1;
            Some(RowInBlock {
                block: self.block,
                row,
            })
        } else {
            None
        }
    }
}

#[derive(Debug)]
pub struct IntoRowsIter<T: BlockExt> {
    block: Rc<T>,
    row: usize,
}

// impl<T> IntoRowsIter<T>
// where
//     T: BlockExt,
// {
//     pub(crate) fn new(block: T) -> Self {
//         Self {
//             block: Rc::new(block),
//             row: 0,
//         }
//     }
// }

pub struct QueryRowIter<T: BlockExt> {
    block: Rc<T>,
    row: usize,
}

impl<'b, T> IntoIterator for &'b QueryRowIter<T>
where
    T: BlockExt,
{
    type Item = (&'b Field, BorrowedValue<'b>);

    type IntoIter = CellIter<'b, T>;

    fn into_iter(self) -> Self::IntoIter {
        CellIter {
            block: &self.block,
            row: self.row,
            col: 0,
        }
    }
}

impl<T> Iterator for IntoRowsIter<T>
where
    T: BlockExt,
{
    type Item = QueryRowIter<T>;

    fn next(&mut self) -> Option<Self::Item> {
        let row = self.row;

        if row < self.block.num_of_rows() {
            self.row += 1;
            Some(QueryRowIter {
                block: self.block.clone(),
                row,
            })
        } else {
            None
        }
    }
}

pub struct ColsIter<'b, T: BlockExt> {
    block: &'b T,
    col: usize,
}
impl<'b, T> ColsIter<'b, T>
where
    T: BlockExt,
{
    pub(crate) fn new(block: &'b T) -> Self {
        Self { block, col: 0 }
    }
}

impl<'b, T> Iterator for ColsIter<'b, T>
where
    T: BlockExt,
{
    type Item = &'b ColumnView;

    fn next(&mut self) -> Option<Self::Item> {
        if self.col >= self.block.field_count() {
            return None;
        }

        let v = unsafe { self.block.get_col_unchecked(self.col) };
        self.col += 1;
        Some(v)
    }
}