connectorx/destinations/arrowstream/
mod.rs1mod arrow_assoc;
4mod errors;
5mod funcs;
6pub 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
33type Message = OutResult<RecordBatch>;
35
36pub 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 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 pub fn new() -> Self {
65 Self::default()
66 }
67
68 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 if !matches!(data_order, DataOrder::RowMajor) {
102 throw!(crate::errors::ConnectorXError::UnsupportedDataOrder(
103 data_order
104 ))
105 }
106
107 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 }
134
135 fn schema(&self) -> &[ArrowTypeSystem] {
136 self.schema.as_slice()
137 }
138}
139
140impl ArrowDestination {
141 #[throws(ConnectorXOutError)]
143 pub fn arrow(self) -> Vec<RecordBatch> {
144 if self.sender.is_some() {
145 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 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 pub fn empty_batch(&self) -> RecordBatch {
174 RecordBatch::new_empty(self.arrow_schema.clone())
175 }
176
177 pub fn arrow_schema(&self) -> Arc<Schema> {
179 self.arrow_schema.clone()
180 }
181
182 pub fn names(&self) -> &[String] {
184 self.names.as_slice()
185 }
186}
187
188pub 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
199impl 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 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 pub fn send_error(&mut self, err: ConnectorXOutError) {
263 self.builders = None;
264 if let Some(sender) = self.sender.take() {
265 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 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()?, }
319 }
320
321 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#[cfg(test)]
335#[allow(clippy::duplicate_mod)]
336#[path = "../destination_tests.rs"]
337mod tests;