Skip to main content

connectorx/
arrow_batch_iter.rs

1use crate::errors::OutResult;
2use crate::prelude::*;
3use arrow::record_batch::RecordBatch;
4use itertools::Itertools;
5use log::debug;
6use rayon::prelude::*;
7use std::marker::PhantomData;
8
9/// Set the number of threads in rayon's global thread pool. Panics if the global pool was already built.
10pub fn set_global_num_thread(num: usize) {
11    rayon::ThreadPoolBuilder::new()
12        .num_threads(num)
13        .build_global()
14        .unwrap();
15}
16
17/// The iterator that returns arrow in `RecordBatch`
18pub struct ArrowBatchIter<S, TP>
19where
20    S: Source,
21    TP: Transport<
22        TSS = S::TypeSystem,
23        TSD = ArrowStreamTypeSystem,
24        S = S,
25        D = ArrowStreamDestination,
26    >,
27    <S as Source>::Partition: 'static,
28    <S as Source>::TypeSystem: 'static,
29    <TP as Transport>::Error: 'static,
30{
31    dst: ArrowStreamDestination,
32    dst_parts: Option<Vec<ArrowStreamPartitionWriter>>,
33    src_parts: Option<Vec<S::Partition>>,
34    dorder: DataOrder,
35    src_schema: Vec<S::TypeSystem>,
36    dst_schema: Vec<ArrowStreamTypeSystem>,
37    handle: Option<std::thread::JoinHandle<()>>,
38    _phantom: PhantomData<TP>,
39}
40
41impl<S, TP> ArrowBatchIter<S, TP>
42where
43    S: Source,
44    TP: Transport<
45        TSS = S::TypeSystem,
46        TSD = ArrowStreamTypeSystem,
47        S = S,
48        D = ArrowStreamDestination,
49    >,
50{
51    /// Prepare the dispatcher for `queries` and return an iterator that has not started fetching yet.
52    pub fn new(
53        src: S,
54        mut dst: ArrowStreamDestination,
55        origin_query: Option<String>,
56        queries: &[CXQuery<String>],
57    ) -> Result<Self, TP::Error> {
58        let dispatcher = Dispatcher::<_, _, TP>::new(src, &mut dst, queries, origin_query);
59        let (dorder, src_parts, dst_parts, src_schema, dst_schema) = dispatcher.prepare()?;
60
61        Ok(Self {
62            dst,
63            dst_parts: Some(dst_parts),
64            src_parts: Some(src_parts),
65            dorder,
66            src_schema,
67            dst_schema,
68            handle: None,
69            _phantom: PhantomData,
70        })
71    }
72
73    fn run(&mut self)
74    where
75        ConnectorXOutError: From<TP::Error>,
76    {
77        let src_schema = self.src_schema.clone();
78        let dst_schema = self.dst_schema.clone();
79        let src_partitions = self.src_parts.take().unwrap();
80        let dst_partitions = self.dst_parts.take().unwrap();
81        let dorder = self.dorder;
82
83        self.handle = Some(std::thread::spawn(move || {
84            let schemas: Vec<_> = src_schema
85                .iter()
86                .zip_eq(&dst_schema)
87                .map(|(&src_ty, &dst_ty)| (src_ty, dst_ty))
88                .collect();
89
90            debug!("Start writing");
91            // parse and write
92            //
93            // Each partition reports its own error through the record batch
94            // channel (see `ArrowPartitionWriter::send_error`), so the consumer
95            // learns about it without joining this thread. `Err(())` only tells
96            // rayon to stop scheduling the remaining partitions.
97            let _ = dst_partitions
98                .into_par_iter()
99                .zip_eq(src_partitions)
100                .enumerate()
101                .try_for_each(|(i, (mut dst, mut src))| -> Result<(), ()> {
102                    let mut parser = match src.parser() {
103                        Ok(parser) => parser,
104                        Err(e) => {
105                            dst.send_error(TP::Error::from(e).into());
106                            return Err(());
107                        }
108                    };
109
110                    let result = (|| -> Result<(), TP::Error> {
111                        match dorder {
112                            DataOrder::RowMajor => loop {
113                                let (n, is_last) = parser.fetch_next()?;
114                                dst.aquire_row(n)?;
115                                for _ in 0..n {
116                                    #[allow(clippy::needless_range_loop)]
117                                    for col in 0..dst.ncols() {
118                                        {
119                                            let (s1, s2) = schemas[col];
120                                            TP::process(s1, s2, &mut parser, &mut dst)?;
121                                        }
122                                    }
123                                }
124                                if is_last {
125                                    break;
126                                }
127                            },
128                            DataOrder::ColumnMajor => loop {
129                                let (n, is_last) = parser.fetch_next()?;
130                                dst.aquire_row(n)?;
131                                #[allow(clippy::needless_range_loop)]
132                                for col in 0..dst.ncols() {
133                                    for _ in 0..n {
134                                        {
135                                            let (s1, s2) = schemas[col];
136                                            TP::process(s1, s2, &mut parser, &mut dst)?;
137                                        }
138                                    }
139                                }
140                                if is_last {
141                                    break;
142                                }
143                            },
144                        }
145
146                        debug!("Finalize partition {}", i);
147                        dst.finalize()?;
148                        debug!("Partition {} finished", i);
149                        Ok(())
150                    })();
151
152                    match result {
153                        Ok(()) => Ok(()),
154                        Err(e) => {
155                            debug!("Partition {} failed: {:?}", i, e);
156                            // `parser` is still alive here on purpose; see
157                            // `ArrowPartitionWriter::send_error`.
158                            dst.send_error(e.into());
159                            Err(())
160                        }
161                    }
162                });
163
164            debug!("Writing finished");
165        }));
166    }
167}
168
169impl<S, TP> Iterator for ArrowBatchIter<S, TP>
170where
171    S: Source,
172    TP: Transport<
173        TSS = S::TypeSystem,
174        TSD = ArrowStreamTypeSystem,
175        S = S,
176        D = ArrowStreamDestination,
177    >,
178    ConnectorXOutError: From<TP::Error>,
179{
180    type Item = OutResult<RecordBatch>;
181
182    /// Yields the next batch, or the first error raised by a partition.
183    ///
184    /// The error is returned as soon as the failing partition reports it,
185    /// without waiting for the producer to shut down. Calling `next` again
186    /// after an error joins the producer and returns `None`. That call blocks
187    /// until the other partitions have stopped at their next batch boundary
188    /// and every source has been torn down, which for MySQL includes draining
189    /// the rest of the result set.
190    ///
191    /// NOTE: not thread safe
192    fn next(&mut self) -> Option<Self::Item> {
193        match self.dst.record_batch() {
194            Some(msg) => Some(msg),
195            None => {
196                // On stream end we must join the producer;
197                // a detached handle would swallow producer panics
198                if let Some(handle) = self.handle.take() {
199                    if let Err(payload) = handle.join() {
200                        std::panic::resume_unwind(payload);
201                    }
202                }
203                None
204            }
205        }
206    }
207}
208
209/// Object-safe interface over [`ArrowBatchIter`] for streaming Arrow record batches.
210pub trait RecordBatchIterator: Send {
211    /// Return an empty record batch carrying the result schema, together with the column names.
212    fn get_schema(&self) -> (RecordBatch, &[String]);
213    /// Start fetching and writing the partitions in the background.
214    fn prepare(&mut self);
215    /// See [`ArrowBatchIter::next`] for the error semantics.
216    fn next_batch(&mut self) -> Option<OutResult<RecordBatch>>;
217}
218
219impl<S, TP> RecordBatchIterator for ArrowBatchIter<S, TP>
220where
221    S: Source,
222    TP: Transport<
223            TSS = S::TypeSystem,
224            TSD = ArrowStreamTypeSystem,
225            S = S,
226            D = ArrowStreamDestination,
227        > + std::marker::Send,
228    ConnectorXOutError: From<TP::Error>,
229{
230    fn get_schema(&self) -> (RecordBatch, &[String]) {
231        (self.dst.empty_batch(), self.dst.names())
232    }
233
234    fn prepare(&mut self) {
235        self.run();
236    }
237
238    fn next_batch(&mut self) -> Option<OutResult<RecordBatch>> {
239        self.next()
240    }
241}
242
243#[cfg(all(test, feature = "src_dummy"))]
244mod tests {
245    use super::*;
246    use crate::sources::dummy::{DummySource, DummyTypeSystem};
247    use arrow::array::AsArray;
248    use arrow::datatypes::Int64Type;
249
250    // ArrowBatchIter needs `ConnectorXOutError: From<TP::Error>`; the library's
251    // dummy stream transport has its own error type, so define one here.
252    struct DummyStreamTransport;
253
254    impl_transport!(
255        name = DummyStreamTransport,
256        error = ConnectorXOutError,
257        systems = DummyTypeSystem => ArrowStreamTypeSystem,
258        route = DummySource => ArrowStreamDestination,
259        mappings = {
260            { I64[i64]       => Int64[i64]        | conversion auto }
261            { String[String] => LargeUtf8[String] | conversion auto }
262        }
263    );
264
265    fn iter(
266        nrows: &[usize],
267        batch_size: usize,
268    ) -> ArrowBatchIter<DummySource, DummyStreamTransport> {
269        let schema = [DummyTypeSystem::I64(false), DummyTypeSystem::String(true)];
270        let queries: Vec<CXQuery<String>> = nrows
271            .iter()
272            .map(|n| CXQuery::naked(format!("{n},2")))
273            .collect();
274        ArrowBatchIter::new(
275            DummySource::new(&["id", "name"], &schema),
276            ArrowStreamDestination::new_with_batch_size(batch_size),
277            None,
278            &queries,
279        )
280        .unwrap()
281    }
282
283    #[test]
284    fn schema_is_known_before_any_batch() {
285        let it = iter(&[3], 2);
286        let (empty, names) = it.get_schema();
287        assert_eq!(names, &["id".to_string(), "name".to_string()]);
288        assert_eq!(empty.num_rows(), 0);
289        assert_eq!(empty.num_columns(), 2);
290    }
291
292    #[test]
293    fn streams_all_rows_in_batches_through_the_trait() {
294        let mut it: Box<dyn RecordBatchIterator> = Box::new(iter(&[5, 3], 2));
295        it.prepare();
296        let mut sizes = vec![];
297        let mut ids = vec![];
298        while let Some(batch) = it.next_batch() {
299            let batch = batch.unwrap();
300            sizes.push(batch.num_rows());
301            ids.extend_from_slice(batch.column(0).as_primitive::<Int64Type>().values());
302        }
303        // Returns None again once exhausted (the producer is already joined).
304        assert!(it.next_batch().is_none());
305
306        sizes.sort();
307        assert_eq!(sizes, vec![1, 1, 2, 2, 2]);
308        ids.sort();
309        assert_eq!(ids, vec![0, 0, 1, 1, 2, 2, 3, 4]);
310    }
311
312    #[test]
313    fn iterator_impl_yields_the_same_rows() {
314        let mut it = iter(&[4], 10);
315        it.prepare();
316        let total: usize = it.by_ref().map(|b| b.unwrap().num_rows()).sum();
317        assert_eq!(total, 4);
318    }
319}