connectorx/destinations/arrow/
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::typesystem::{Realize, TypeAssoc, TypeSystem};
15use anyhow::anyhow;
16use arrow::{datatypes::Schema, record_batch::RecordBatch};
17use arrow_assoc::ArrowAssoc;
18use fehler::{throw, throws};
19use funcs::{FFinishBuilder, FNewBuilder, FNewField};
20use itertools::Itertools;
21use std::{
22 any::Any,
23 sync::{Arc, Mutex},
24};
25
26#[cfg(feature = "dst_polars")]
27use {
28 arrow::ffi::to_ffi,
29 polars::prelude::{concat, Column, DataFrame, IntoLazy, PlSmallStr, Series, UnionArgs},
30 polars_arrow::ffi::{import_array_from_c, import_field_from_c},
31 std::mem::transmute,
32};
33
34type Builder = Box<dyn Any + Send>;
35type Builders = Vec<Builder>;
36
37pub struct ArrowDestination {
39 schema: Vec<ArrowTypeSystem>,
40 names: Vec<String>,
41 data: Arc<Mutex<Vec<RecordBatch>>>,
42 arrow_schema: Arc<Schema>,
43 batch_size: usize,
44}
45
46impl Default for ArrowDestination {
47 fn default() -> Self {
48 ArrowDestination {
49 schema: vec![],
50 names: vec![],
51 data: Arc::new(Mutex::new(vec![])),
52 arrow_schema: Arc::new(Schema::empty()),
53 batch_size: RECORD_BATCH_SIZE,
54 }
55 }
56}
57
58impl ArrowDestination {
59 pub fn new() -> Self {
61 Self::default()
62 }
63
64 pub fn new_with_batch_size(batch_size: usize) -> Self {
66 ArrowDestination {
67 schema: vec![],
68 names: vec![],
69 data: Arc::new(Mutex::new(vec![])),
70 arrow_schema: Arc::new(Schema::empty()),
71 batch_size,
72 }
73 }
74}
75
76impl Destination for ArrowDestination {
77 const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::ColumnMajor, DataOrder::RowMajor];
78 type TypeSystem = ArrowTypeSystem;
79 type Partition<'a> = ArrowPartitionWriter;
80 type Error = ArrowDestinationError;
81
82 fn needs_count(&self) -> bool {
83 false
84 }
85
86 #[throws(ArrowDestinationError)]
87 fn allocate<S: AsRef<str>>(
88 &mut self,
89 _nrow: usize,
90 names: &[S],
91 schema: &[ArrowTypeSystem],
92 data_order: DataOrder,
93 ) {
94 if !matches!(data_order, DataOrder::RowMajor) {
96 throw!(crate::errors::ConnectorXError::UnsupportedDataOrder(
97 data_order
98 ))
99 }
100
101 self.schema = schema.to_vec();
103 self.names = names.iter().map(|n| n.as_ref().to_string()).collect();
104 let fields = self
105 .schema
106 .iter()
107 .zip_eq(&self.names)
108 .map(|(&dt, h)| Ok(Realize::<FNewField>::realize(dt)?(h.as_str())))
109 .collect::<Result<Vec<_>>>()?;
110 self.arrow_schema = Arc::new(Schema::new(fields));
111 }
112
113 #[throws(ArrowDestinationError)]
114 fn partition(&mut self, counts: usize) -> Vec<Self::Partition<'_>> {
115 let mut partitions = vec![];
116 for _ in 0..counts {
117 partitions.push(ArrowPartitionWriter::new(
118 self.schema.clone(),
119 Arc::clone(&self.data),
120 Arc::clone(&self.arrow_schema),
121 self.batch_size,
122 )?);
123 }
124 partitions
125 }
126
127 fn schema(&self) -> &[ArrowTypeSystem] {
128 self.schema.as_slice()
129 }
130}
131
132impl ArrowDestination {
133 #[throws(ArrowDestinationError)]
135 pub fn arrow(self) -> Vec<RecordBatch> {
136 let lock = Arc::try_unwrap(self.data).map_err(|_| anyhow!("Partitions are not freed"))?;
137 lock.into_inner()
138 .map_err(|e| anyhow!("mutex poisoned {}", e))?
139 }
140
141 #[cfg(feature = "dst_polars")]
143 #[throws(ArrowDestinationError)]
144 pub fn polars(self) -> DataFrame {
145 let rbs = self.arrow()?;
147
148 let mut lf_vec = vec![];
150
151 for chunk in rbs.into_iter() {
152 let mut columns = Vec::with_capacity(chunk.num_columns());
154
155 for (i, col) in chunk.columns().iter().enumerate() {
157 let array = col.to_data();
159
160 let (out_array, out_schema) = to_ffi(&array).unwrap();
162
163 let field = unsafe {
165 import_field_from_c(transmute::<
166 &arrow::ffi::FFI_ArrowSchema,
167 &polars_arrow::ffi::ArrowSchema,
168 >(&out_schema))
169 }?;
170
171 let data = unsafe {
173 import_array_from_c(
174 transmute::<arrow::ffi::FFI_ArrowArray, polars_arrow::ffi::ArrowArray>(
175 out_array,
176 ),
177 field.dtype().clone(),
178 )
179 }?;
180
181 columns.push(Column::from(Series::from_arrow(
183 PlSmallStr::from(chunk.schema().field(i).name()),
184 data,
185 )?));
186 }
187
188 lf_vec.push(DataFrame::new(chunk.num_rows(), columns)?.lazy());
190 }
191
192 let union_args = UnionArgs::default();
194 concat(lf_vec, union_args)?.collect()?
195 }
196
197 #[throws(ArrowDestinationError)]
199 pub fn record_batch(&mut self) -> Option<RecordBatch> {
200 let mut guard = self
201 .data
202 .lock()
203 .map_err(|e| anyhow!("mutex poisoned {}", e))?;
204 (*guard).pop()
205 }
206
207 pub fn empty_batch(&self) -> RecordBatch {
209 RecordBatch::new_empty(self.arrow_schema.clone())
210 }
211
212 pub fn arrow_schema(&self) -> Arc<Schema> {
214 self.arrow_schema.clone()
215 }
216
217 pub fn names(&self) -> &[String] {
219 self.names.as_slice()
220 }
221}
222
223pub struct ArrowPartitionWriter {
225 schema: Vec<ArrowTypeSystem>,
226 builders: Option<Builders>,
227 current_row: usize,
228 current_col: usize,
229 data: Arc<Mutex<Vec<RecordBatch>>>,
230 arrow_schema: Arc<Schema>,
231 batch_size: usize,
232}
233
234impl ArrowPartitionWriter {
237 #[throws(ArrowDestinationError)]
238 fn new(
239 schema: Vec<ArrowTypeSystem>,
240 data: Arc<Mutex<Vec<RecordBatch>>>,
241 arrow_schema: Arc<Schema>,
242 batch_size: usize,
243 ) -> Self {
244 let mut pw = ArrowPartitionWriter {
245 schema,
246 builders: None,
247 current_row: 0,
248 current_col: 0,
249 data,
250 arrow_schema,
251 batch_size,
252 };
253 pw.allocate()?;
254 pw
255 }
256
257 #[throws(ArrowDestinationError)]
258 fn allocate(&mut self) {
259 let builders = self
260 .schema
261 .iter()
262 .map(|dt| Ok(Realize::<FNewBuilder>::realize(*dt)?(self.batch_size)))
263 .collect::<Result<Vec<_>>>()?;
264 self.builders.replace(builders);
265 }
266
267 #[throws(ArrowDestinationError)]
268 fn flush(&mut self) {
269 let builders = self
270 .builders
271 .take()
272 .unwrap_or_else(|| panic!("arrow builder is none when flush!"));
273 let columns = builders
274 .into_iter()
275 .zip(self.schema.iter())
276 .map(|(builder, &dt)| Realize::<FFinishBuilder>::realize(dt)?(builder))
277 .collect::<std::result::Result<Vec<_>, crate::errors::ConnectorXError>>()?;
278 let rb = RecordBatch::try_new(Arc::clone(&self.arrow_schema), columns)?;
279 {
280 let mut guard = self
281 .data
282 .lock()
283 .map_err(|e| anyhow!("mutex poisoned {}", e))?;
284 let inner_data = &mut *guard;
285 inner_data.push(rb);
286 }
287
288 self.current_row = 0;
289 self.current_col = 0;
290 }
291}
292
293impl<'a> DestinationPartition<'a> for ArrowPartitionWriter {
294 type TypeSystem = ArrowTypeSystem;
295 type Error = ArrowDestinationError;
296
297 #[throws(ArrowDestinationError)]
298 fn finalize(&mut self) {
299 if self.builders.is_some() {
300 self.flush()?;
301 }
302 }
303
304 #[throws(ArrowDestinationError)]
305 fn aquire_row(&mut self, _n: usize) -> usize {
306 self.current_row
307 }
308
309 fn ncols(&self) -> usize {
310 self.schema.len()
311 }
312}
313
314impl<'a, T> Consume<T> for ArrowPartitionWriter
315where
316 T: TypeAssoc<<Self as DestinationPartition<'a>>::TypeSystem> + ArrowAssoc + 'static,
317{
318 type Error = ArrowDestinationError;
319
320 #[throws(ArrowDestinationError)]
321 fn consume(&mut self, value: T) {
322 let col = self.current_col;
323 self.current_col = (self.current_col + 1) % self.ncols();
324 self.schema[col].check::<T>()?;
325
326 loop {
327 match &mut self.builders {
328 Some(builders) => {
329 <T as ArrowAssoc>::append(
330 builders[col]
331 .downcast_mut::<T::Builder>()
332 .ok_or_else(|| anyhow!("cannot cast arrow builder for append"))?,
333 value,
334 )?;
335 break;
336 }
337 None => self.allocate()?, }
339 }
340
341 if self.current_col == 0 {
343 self.current_row += 1;
344 if self.current_row >= self.batch_size {
345 self.flush()?;
346 self.allocate()?;
347 }
348 }
349 }
350}
351
352#[cfg(test)]
355#[allow(clippy::duplicate_mod)]
356#[path = "../destination_tests.rs"]
357mod tests;