Skip to main content

crisol_core/data/
arrow_ipc.rs

1//! Arrow IPC connector.
2
3use arrow::array::{
4    Array, ArrayRef, BooleanArray, Date32Array, Float32Array, Float64Array, Int8Array, Int16Array, Int32Array,
5    Int64Array, StringArray, TimestampNanosecondArray, UInt8Array, UInt16Array, UInt32Array, UInt64Array,
6};
7use arrow::datatypes::DataType;
8use arrow::record_batch::RecordBatch;
9use std::path::Path;
10
11use super::column::Column;
12use super::dataset::Dataset;
13use super::source::{ColumnSchema, DataError, DataSource};
14
15/// Read an Arrow IPC file (the `.arrow`/`.feather` file format) into a dataset.
16///
17/// # Errors
18/// When the file is not a valid Arrow IPC file or a column type is unsupported.
19/// # Example
20///
21/// ```
22/// use crisol_core::data::read_arrow_ipc;
23/// ```
24pub fn read_arrow_ipc(bytes: &[u8]) -> Result<Dataset, DataError> {
25    let reader = arrow::ipc::reader::FileReader::try_new(std::io::Cursor::new(bytes), None)
26        .map_err(|error| DataError::Connector(error.to_string()))?;
27    let schema = reader.schema();
28    let batches: Vec<RecordBatch> = reader
29        .map(|batch| batch.map_err(|error| DataError::Connector(error.to_string())))
30        .collect::<Result<_, _>>()?;
31    if batches.is_empty() {
32        return Ok(Dataset::new());
33    }
34    let batch =
35        arrow::compute::concat_batches(&schema, &batches).map_err(|error| DataError::Connector(error.to_string()))?;
36    dataset_from_batch(&batch)
37}
38
39/// Convert an Arrow record batch into a typed dataset.
40///
41/// # Errors
42/// When a column type has no dataset representation.
43/// # Example
44///
45/// ```
46/// use crisol_core::data::dataset_from_batch;
47/// ```
48pub fn dataset_from_batch(batch: &RecordBatch) -> Result<Dataset, DataError> {
49    let mut columns = Vec::with_capacity(batch.num_columns());
50    for (index, field) in batch.schema().fields().iter().enumerate() {
51        let array = batch.column(index);
52        columns.push(column_from_array(field.name(), array)?);
53    }
54    Ok(Dataset::from_columns(columns))
55}
56
57pub(crate) fn column_from_array(name: &str, array: &ArrayRef) -> Result<Column, DataError> {
58    macro_rules! primitive {
59        ($array_ty:ty, $variant:ident) => {{
60            let values = array
61                .as_any()
62                .downcast_ref::<$array_ty>()
63                .ok_or_else(|| DataError::Unsupported(format!("column `{name}` is not {}", stringify!($array_ty))))?;
64            let data: Vec<_> = (0..values.len())
65                .map(|row| {
66                    if values.is_null(row) {
67                        None
68                    } else {
69                        Some(values.value(row))
70                    }
71                })
72                .collect();
73            let valid: Vec<bool> = data.iter().map(Option::is_some).collect();
74            let values: Vec<_> = data.into_iter().map(Option::unwrap_or_default).collect();
75            let column = Column::$variant(name, values);
76            Some(if valid.iter().all(|value| *value) {
77                column
78            } else {
79                column.with_validity(valid)
80            })
81        }};
82    }
83    let column = match array.data_type() {
84        DataType::Float64 => primitive!(Float64Array, floats),
85        DataType::Float32 => {
86            let values = array
87                .as_any()
88                .downcast_ref::<Float32Array>()
89                .ok_or_else(|| DataError::Unsupported(format!("column `{name}` is not Float32")))?;
90            Some(with_validity(
91                Column::floats(
92                    name,
93                    values
94                        .values()
95                        .iter()
96                        .map(|value| f64::from(*value))
97                        .collect::<Vec<_>>(),
98                ),
99                values,
100            ))
101        }
102        DataType::Int64 => primitive!(Int64Array, ints),
103        DataType::Int32 => {
104            let values = array
105                .as_any()
106                .downcast_ref::<Int32Array>()
107                .ok_or_else(|| DataError::Unsupported(format!("column `{name}` is not Int32")))?;
108            Some(with_validity(
109                Column::ints(
110                    name,
111                    values
112                        .values()
113                        .iter()
114                        .map(|value| i64::from(*value))
115                        .collect::<Vec<_>>(),
116                ),
117                values,
118            ))
119        }
120        DataType::Int16 => {
121            let values = array
122                .as_any()
123                .downcast_ref::<Int16Array>()
124                .ok_or_else(|| DataError::Unsupported(format!("column `{name}` is not Int16")))?;
125            Some(with_validity(
126                Column::ints(
127                    name,
128                    values
129                        .values()
130                        .iter()
131                        .map(|value| i64::from(*value))
132                        .collect::<Vec<_>>(),
133                ),
134                values,
135            ))
136        }
137        DataType::Int8 => {
138            let values = array
139                .as_any()
140                .downcast_ref::<Int8Array>()
141                .ok_or_else(|| DataError::Unsupported(format!("column `{name}` is not Int8")))?;
142            Some(with_validity(
143                Column::ints(
144                    name,
145                    values
146                        .values()
147                        .iter()
148                        .map(|value| i64::from(*value))
149                        .collect::<Vec<_>>(),
150                ),
151                values,
152            ))
153        }
154        DataType::UInt64 => {
155            let values = array
156                .as_any()
157                .downcast_ref::<UInt64Array>()
158                .ok_or_else(|| DataError::Unsupported(format!("column `{name}` is not UInt64")))?;
159            Some(with_validity(
160                Column::ints(
161                    name,
162                    values.values().iter().map(|value| *value as i64).collect::<Vec<_>>(),
163                ),
164                values,
165            ))
166        }
167        DataType::UInt32 => {
168            let values = array
169                .as_any()
170                .downcast_ref::<UInt32Array>()
171                .ok_or_else(|| DataError::Unsupported(format!("column `{name}` is not UInt32")))?;
172            Some(with_validity(
173                Column::ints(
174                    name,
175                    values
176                        .values()
177                        .iter()
178                        .map(|value| i64::from(*value))
179                        .collect::<Vec<_>>(),
180                ),
181                values,
182            ))
183        }
184        DataType::UInt16 => {
185            let values = array
186                .as_any()
187                .downcast_ref::<UInt16Array>()
188                .ok_or_else(|| DataError::Unsupported(format!("column `{name}` is not UInt16")))?;
189            Some(with_validity(
190                Column::ints(
191                    name,
192                    values
193                        .values()
194                        .iter()
195                        .map(|value| i64::from(*value))
196                        .collect::<Vec<_>>(),
197                ),
198                values,
199            ))
200        }
201        DataType::UInt8 => {
202            let values = array
203                .as_any()
204                .downcast_ref::<UInt8Array>()
205                .ok_or_else(|| DataError::Unsupported(format!("column `{name}` is not UInt8")))?;
206            Some(with_validity(
207                Column::ints(
208                    name,
209                    values
210                        .values()
211                        .iter()
212                        .map(|value| i64::from(*value))
213                        .collect::<Vec<_>>(),
214                ),
215                values,
216            ))
217        }
218        DataType::Boolean => primitive!(BooleanArray, bools),
219        DataType::Utf8 => {
220            let values = array
221                .as_any()
222                .downcast_ref::<StringArray>()
223                .ok_or_else(|| DataError::Unsupported(format!("column `{name}` is not Utf8")))?;
224            Some(with_validity(
225                Column::text(
226                    name,
227                    values
228                        .iter()
229                        .map(|value| value.unwrap_or_default().to_owned())
230                        .collect::<Vec<_>>(),
231                ),
232                values,
233            ))
234        }
235        DataType::Date32 => {
236            let values = array
237                .as_any()
238                .downcast_ref::<Date32Array>()
239                .ok_or_else(|| DataError::Unsupported(format!("column `{name}` is not Date32")))?;
240            Some(with_validity(
241                Column::dates(
242                    name,
243                    values
244                        .values()
245                        .iter()
246                        .map(|value| i64::from(*value))
247                        .collect::<Vec<_>>(),
248                ),
249                values,
250            ))
251        }
252        DataType::Timestamp(unit, _) => {
253            use arrow::array::{TimestampMicrosecondArray, TimestampMillisecondArray, TimestampSecondArray};
254            use arrow::datatypes::TimeUnit;
255            let unsupported = || DataError::Unsupported(format!("column `{name}` is not a timestamp"));
256            // Datasets store nanoseconds; scale the other units, saturating on overflow.
257            let (raw, factor): (Vec<i64>, i64) = match unit {
258                TimeUnit::Second => (
259                    array
260                        .as_any()
261                        .downcast_ref::<TimestampSecondArray>()
262                        .ok_or_else(unsupported)?
263                        .values()
264                        .to_vec(),
265                    1_000_000_000,
266                ),
267                TimeUnit::Millisecond => (
268                    array
269                        .as_any()
270                        .downcast_ref::<TimestampMillisecondArray>()
271                        .ok_or_else(unsupported)?
272                        .values()
273                        .to_vec(),
274                    1_000_000,
275                ),
276                TimeUnit::Microsecond => (
277                    array
278                        .as_any()
279                        .downcast_ref::<TimestampMicrosecondArray>()
280                        .ok_or_else(unsupported)?
281                        .values()
282                        .to_vec(),
283                    1_000,
284                ),
285                TimeUnit::Nanosecond => (
286                    array
287                        .as_any()
288                        .downcast_ref::<TimestampNanosecondArray>()
289                        .ok_or_else(unsupported)?
290                        .values()
291                        .to_vec(),
292                    1,
293                ),
294            };
295            let nanoseconds = raw
296                .into_iter()
297                .map(|value| value.saturating_mul(factor))
298                .collect::<Vec<_>>();
299            let validity: Vec<bool> = (0..array.len()).map(|row| !array.is_null(row)).collect();
300            let column = Column::times(name, nanoseconds);
301            Some(if validity.iter().all(|valid| *valid) {
302                column
303            } else {
304                column.with_validity(validity)
305            })
306        }
307        other => return Err(DataError::Unsupported(format!("unsupported Arrow type {other:?}"))),
308    };
309    column.ok_or_else(|| DataError::Unsupported(format!("column `{name}`")))
310}
311
312fn with_validity<A: Array>(column: Column, array: &A) -> Column {
313    let valid: Vec<bool> = (0..array.len()).map(|row| !array.is_null(row)).collect();
314    if valid.iter().all(|value| *value) {
315        column
316    } else {
317        column.with_validity(valid)
318    }
319}
320
321/// An Arrow IPC file exposed as a paged data source.
322/// # Example
323///
324/// ```
325/// use crisol_core::data::ArrowSource;
326/// ```
327pub struct ArrowSource {
328    name: String,
329    data: Dataset,
330    schema: Vec<ColumnSchema>,
331}
332
333impl ArrowSource {
334    /// Read an Arrow IPC file from disk.
335    ///
336    /// # Errors
337    /// When the file cannot be read or parsed.
338    #[cfg(feature = "threads")]
339    pub fn open(path: impl AsRef<Path>) -> Result<Self, DataError> {
340        let path = path.as_ref();
341        let bytes = super::source::read_limited(path)?;
342        Self::from_bytes(
343            path.file_name().and_then(|name| name.to_str()).unwrap_or("data.arrow"),
344            &bytes,
345        )
346    }
347
348    /// Read Arrow IPC bytes.
349    ///
350    /// # Errors
351    /// When the bytes are not a valid Arrow IPC file.
352    pub fn from_bytes(name: impl Into<String>, bytes: &[u8]) -> Result<Self, DataError> {
353        let data = read_arrow_ipc(bytes)?;
354        let schema = data.columns().iter().map(ColumnSchema::from_column).collect();
355        Ok(Self {
356            name: name.into(),
357            data,
358            schema,
359        })
360    }
361
362    /// The file name.
363    pub fn name(&self) -> &str {
364        &self.name
365    }
366
367    /// The parsed data.
368    pub fn data(&self) -> &Dataset {
369        &self.data
370    }
371}
372
373impl DataSource for ArrowSource {
374    fn schema(&self) -> &[ColumnSchema] {
375        &self.schema
376    }
377
378    fn row_count(&self) -> usize {
379        self.data.row_count()
380    }
381
382    fn read_range(&self, range: std::ops::Range<usize>) -> Result<Dataset, DataError> {
383        super::source::check_range(&range, self.row_count())?;
384        Ok(self.data.slice(range))
385    }
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391
392    use std::sync::Arc;
393
394    use crate::data::dataset_to_batch;
395    use arrow::array::{Float64Array, Int64Array, StringArray};
396    use arrow::datatypes::{DataType, Field, Schema};
397
398    fn batch() -> RecordBatch {
399        let schema = Arc::new(Schema::new(vec![
400            Field::new("n", DataType::Int64, false),
401            Field::new("v", DataType::Float64, false),
402            Field::new("name", DataType::Utf8, false),
403        ]));
404        RecordBatch::try_new(
405            schema,
406            vec![
407                Arc::new(Int64Array::from(vec![1, 2])),
408                Arc::new(Float64Array::from(vec![0.5, 1.5])),
409                Arc::new(StringArray::from(vec!["a", "b"])),
410            ],
411        )
412        .expect("batch")
413    }
414
415    #[test]
416    fn a_dataset_round_trips_through_a_batch() {
417        let data = Dataset::from_columns([
418            Column::floats("x", vec![1.0, f64::NAN]).with_validity([true, false]),
419            Column::ints("n", vec![1, 2]),
420            Column::text("label", ["a", "b"]),
421        ]);
422        let batch = dataset_to_batch(&data).expect("batch");
423        let restored = dataset_from_batch(&batch).expect("dataset");
424        assert_eq!(restored.row_count(), 2);
425        assert_eq!(restored.cell(1, 0), crate::data::CellValue::Null);
426        assert_eq!(restored.cell(1, 2), crate::data::CellValue::Text("b"));
427    }
428
429    #[test]
430    fn arrow_ipc_round_trips_through_a_dataset() {
431        let batch = batch();
432        let mut bytes = Vec::new();
433        {
434            let mut writer = arrow::ipc::writer::FileWriter::try_new(&mut bytes, &batch.schema()).expect("writer");
435            writer.write(&batch).expect("write");
436            writer.finish().expect("finish");
437        }
438        let dataset = read_arrow_ipc(&bytes).expect("read");
439        assert_eq!(dataset.row_count(), 2);
440        assert_eq!(dataset.cell(1, 0), crate::data::CellValue::Int(2));
441        assert_eq!(dataset.cell(0, 2), crate::data::CellValue::Text("a"));
442        let source = ArrowSource::from_bytes("test.arrow", &bytes).expect("source");
443        assert_eq!(source.schema().len(), 3);
444        assert_eq!(source.read_range(1..2).expect("page").row_count(), 1);
445    }
446}