Skip to main content

connectorx/destinations/arrowstream/
mod.rs

1//! Destination implementation for Arrow and Polars.
2
3mod arrow_assoc;
4mod errors;
5mod funcs;
6/// Mapping between ConnectorX types and Arrow column types.
7pub mod typesystem;
8
9pub use self::errors::{ArrowDestinationError, Result};
10pub use self::typesystem::ArrowTypeSystem;
11use super::{Consume, Destination, DestinationPartition};
12use crate::constants::RECORD_BATCH_SIZE;
13use crate::data_order::DataOrder;
14use crate::errors::{ConnectorXOutError, OutResult};
15use crate::typesystem::{Realize, TypeAssoc, TypeSystem};
16use anyhow::anyhow;
17use arrow::{datatypes::Schema, record_batch::RecordBatch};
18use arrow_assoc::ArrowAssoc;
19use fehler::{throw, throws};
20use funcs::{FFinishBuilder, FNewBuilder, FNewField};
21use itertools::Itertools;
22use std::{
23    any::Any,
24    sync::{
25        mpsc::{channel, Receiver, Sender},
26        Arc,
27    },
28};
29
30type Builder = Box<dyn Any + Send>;
31type Builders = Vec<Builder>;
32
33/// A finished batch, or the error that stopped a partition.
34type Message = OutResult<RecordBatch>;
35
36/// Destination that sends Arrow record batches over a channel as partitions produce them.
37pub struct ArrowDestination {
38    schema: Vec<ArrowTypeSystem>,
39    names: Vec<String>,
40    arrow_schema: Arc<Schema>,
41    batch_size: usize,
42    sender: Option<Sender<Message>>,
43    /// `None` once an error has been received: the partition writers then fail
44    /// on their next send instead of buffering batches nobody will read.
45    receiver: Option<Receiver<Message>>,
46}
47
48impl Default for ArrowDestination {
49    fn default() -> Self {
50        let (tx, rx) = channel();
51        ArrowDestination {
52            schema: vec![],
53            names: vec![],
54            arrow_schema: Arc::new(Schema::empty()),
55            batch_size: RECORD_BATCH_SIZE,
56            sender: Some(tx),
57            receiver: Some(rx),
58        }
59    }
60}
61
62impl ArrowDestination {
63    /// Create an empty destination with the default batch size ([`RECORD_BATCH_SIZE`]).
64    pub fn new() -> Self {
65        Self::default()
66    }
67
68    /// Create an empty destination that sends batches of at most `batch_size` rows.
69    pub fn new_with_batch_size(batch_size: usize) -> Self {
70        let (tx, rx) = channel();
71        ArrowDestination {
72            schema: vec![],
73            names: vec![],
74            arrow_schema: Arc::new(Schema::empty()),
75            batch_size,
76            sender: Some(tx),
77            receiver: Some(rx),
78        }
79    }
80}
81
82impl Destination for ArrowDestination {
83    const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::ColumnMajor, DataOrder::RowMajor];
84    type TypeSystem = ArrowTypeSystem;
85    type Partition<'a> = ArrowPartitionWriter;
86    type Error = ArrowDestinationError;
87
88    fn needs_count(&self) -> bool {
89        false
90    }
91
92    #[throws(ArrowDestinationError)]
93    fn allocate<S: AsRef<str>>(
94        &mut self,
95        _nrow: usize,
96        names: &[S],
97        schema: &[ArrowTypeSystem],
98        data_order: DataOrder,
99    ) {
100        // todo: support colmajor
101        if !matches!(data_order, DataOrder::RowMajor) {
102            throw!(crate::errors::ConnectorXError::UnsupportedDataOrder(
103                data_order
104            ))
105        }
106
107        // parse the metadata
108        self.schema = schema.to_vec();
109        self.names = names.iter().map(|n| n.as_ref().to_string()).collect();
110        let fields = self
111            .schema
112            .iter()
113            .zip_eq(&self.names)
114            .map(|(&dt, h)| Ok(Realize::<FNewField>::realize(dt)?(h.as_str())))
115            .collect::<Result<Vec<_>>>()?;
116        self.arrow_schema = Arc::new(Schema::new(fields));
117    }
118
119    #[throws(ArrowDestinationError)]
120    fn partition(&mut self, counts: usize) -> Vec<Self::Partition<'_>> {
121        let mut partitions = vec![];
122        let sender = self.sender.take().unwrap();
123        for _ in 0..counts {
124            partitions.push(ArrowPartitionWriter::new(
125                self.schema.clone(),
126                Arc::clone(&self.arrow_schema),
127                self.batch_size,
128                sender.clone(),
129            )?);
130        }
131        partitions
132        // self.sender should be freed
133    }
134
135    fn schema(&self) -> &[ArrowTypeSystem] {
136        self.schema.as_slice()
137    }
138}
139
140impl ArrowDestination {
141    /// Consume the destination and collect every remaining record batch, returning the first error.
142    #[throws(ConnectorXOutError)]
143    pub fn arrow(self) -> Vec<RecordBatch> {
144        if self.sender.is_some() {
145            // should not happen since it is dropped after partition
146            // but need to make sure here otherwise recv will be blocked forever
147            std::mem::drop(self.sender);
148        }
149        let mut data = vec![];
150        if let Some(receiver) = self.receiver {
151            while let Ok(rb) = receiver.recv() {
152                data.push(rb?);
153            }
154        }
155        data
156    }
157
158    /// Blocks until the next record batch is available.
159    ///
160    /// Returns `None` once every partition writer is done, or `Some(Err(_))`
161    /// as soon as a partition fails. After an error the channel is closed, so
162    /// later calls return `None` and the other partitions stop at their next
163    /// batch boundary.
164    pub fn record_batch(&mut self) -> Option<Message> {
165        let msg = self.receiver.as_ref()?.recv().ok()?;
166        if msg.is_err() {
167            self.receiver = None;
168        }
169        Some(msg)
170    }
171
172    /// Return an empty record batch with the result schema.
173    pub fn empty_batch(&self) -> RecordBatch {
174        RecordBatch::new_empty(self.arrow_schema.clone())
175    }
176
177    /// Arrow schema of the result.
178    pub fn arrow_schema(&self) -> Arc<Schema> {
179        self.arrow_schema.clone()
180    }
181
182    /// Column names of the result.
183    pub fn names(&self) -> &[String] {
184        self.names.as_slice()
185    }
186}
187
188/// Writer for one partition of an [`ArrowDestination`].
189pub struct ArrowPartitionWriter {
190    schema: Vec<ArrowTypeSystem>,
191    builders: Option<Builders>,
192    current_row: usize,
193    current_col: usize,
194    arrow_schema: Arc<Schema>,
195    batch_size: usize,
196    sender: Option<Sender<Message>>,
197}
198
199// unsafe impl Sync for ArrowPartitionWriter {}
200
201impl ArrowPartitionWriter {
202    #[throws(ArrowDestinationError)]
203    fn new(
204        schema: Vec<ArrowTypeSystem>,
205        arrow_schema: Arc<Schema>,
206        batch_size: usize,
207        sender: Sender<Message>,
208    ) -> Self {
209        let mut pw = ArrowPartitionWriter {
210            schema,
211            builders: None,
212            current_row: 0,
213            current_col: 0,
214            arrow_schema,
215            batch_size,
216            sender: Some(sender),
217        };
218        pw.allocate()?;
219        pw
220    }
221
222    #[throws(ArrowDestinationError)]
223    fn allocate(&mut self) {
224        let builders = self
225            .schema
226            .iter()
227            .map(|dt| Ok(Realize::<FNewBuilder>::realize(*dt)?(self.batch_size)))
228            .collect::<Result<Vec<_>>>()?;
229        self.builders.replace(builders);
230    }
231
232    #[throws(ArrowDestinationError)]
233    fn flush(&mut self) {
234        let builders = self
235            .builders
236            .take()
237            .unwrap_or_else(|| panic!("arrow builder is none when flush!"));
238        let columns = builders
239            .into_iter()
240            .zip(self.schema.iter())
241            .map(|(builder, &dt)| Realize::<FFinishBuilder>::realize(dt)?(builder))
242            .collect::<std::result::Result<Vec<_>, crate::errors::ConnectorXError>>()?;
243        let rb = RecordBatch::try_new(Arc::clone(&self.arrow_schema), columns)?;
244        if let Some(sender) = &self.sender {
245            // The consumer is gone (dropped, or already got an error from
246            // another partition): stop instead of parsing the rest for nothing.
247            sender
248                .send(Ok(rb))
249                .map_err(|_| anyhow!("record batch receiver dropped"))?;
250        }
251
252        self.current_row = 0;
253        self.current_col = 0;
254    }
255
256    /// Reports `err` to the consumer and closes this partition's side of the
257    /// stream. Rows buffered since the last flush are discarded.
258    ///
259    /// Call this while the source's query is still alive: some drivers drain
260    /// the remaining result set when the query is dropped (MySQL does), and
261    /// the consumer should not have to wait for that.
262    pub fn send_error(&mut self, err: ConnectorXOutError) {
263        self.builders = None;
264        if let Some(sender) = self.sender.take() {
265            // The consumer may already be gone; nothing else to do then.
266            let _ = sender.send(Err(err));
267        }
268    }
269}
270
271impl<'a> DestinationPartition<'a> for ArrowPartitionWriter {
272    type TypeSystem = ArrowTypeSystem;
273    type Error = ArrowDestinationError;
274
275    #[throws(ArrowDestinationError)]
276    fn finalize(&mut self) {
277        if self.builders.is_some() {
278            self.flush()?;
279        }
280        // need to release the sender so receiver knows when the stream is exhasted
281        std::mem::drop(self.sender.take());
282    }
283
284    #[throws(ArrowDestinationError)]
285    fn aquire_row(&mut self, _n: usize) -> usize {
286        self.current_row
287    }
288
289    fn ncols(&self) -> usize {
290        self.schema.len()
291    }
292}
293
294impl<'a, T> Consume<T> for ArrowPartitionWriter
295where
296    T: TypeAssoc<<Self as DestinationPartition<'a>>::TypeSystem> + ArrowAssoc + 'static,
297{
298    type Error = ArrowDestinationError;
299
300    #[throws(ArrowDestinationError)]
301    fn consume(&mut self, value: T) {
302        let col = self.current_col;
303        self.current_col = (self.current_col + 1) % self.ncols();
304        self.schema[col].check::<T>()?;
305
306        loop {
307            match &mut self.builders {
308                Some(builders) => {
309                    <T as ArrowAssoc>::append(
310                        builders[col]
311                            .downcast_mut::<T::Builder>()
312                            .ok_or_else(|| anyhow!("cannot cast arrow builder for append"))?,
313                        value,
314                    )?;
315                    break;
316                }
317                None => self.allocate()?, // allocate if builders are not initialized
318            }
319        }
320
321        // flush if exceed batch_size
322        if self.current_col == 0 {
323            self.current_row += 1;
324            if self.current_row >= self.batch_size {
325                self.flush()?;
326                self.allocate()?;
327            }
328        }
329    }
330}
331
332// The arrow and arrowstream versions of this module share one API, so they
333// share their tests: both include the same file.
334#[cfg(test)]
335#[allow(clippy::duplicate_mod)]
336#[path = "../destination_tests.rs"]
337mod tests;