Skip to main content

crisol_core/data/
workbook.rs

1//! Spreadsheet connector through `calamine`.
2
3use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5
6use calamine::{Data, Reader};
7
8use super::column::{Column, DataValue};
9use super::dataset::Dataset;
10use super::source::{ColumnSchema, DataError, DataSource};
11
12/// Most cells one sheet may hold.
13const MAX_CELLS: usize = 50_000_000;
14
15/// One workbook with a dataset per sheet.
16/// # Example
17///
18/// ```
19/// use crisol_core::data::WorkbookSource;
20/// ```
21pub struct WorkbookSource {
22    path: PathBuf,
23    sheets: BTreeMap<String, Dataset>,
24    /// Sheet names in workbook order; the map sorts them alphabetically.
25    order: Vec<String>,
26    schema: Vec<ColumnSchema>,
27}
28
29impl WorkbookSource {
30    #[cfg(feature = "threads")]
31    /// Open a workbook and read every sheet.
32    ///
33    /// # Errors
34    /// When the workbook cannot be read.
35    pub fn open(path: impl AsRef<Path>) -> Result<Self, DataError> {
36        let path = path.as_ref().to_path_buf();
37        // The size check happens before calamine reads anything.
38        if std::fs::metadata(&path).is_ok_and(|metadata| metadata.len() > super::source::MAX_FILE_BYTES) {
39            return Err(DataError::Connector("the workbook is larger than 512 MiB".to_owned()));
40        }
41        let mut workbook =
42            calamine::open_workbook_auto(&path).map_err(|error| DataError::Connector(error.to_string()))?;
43        let names = workbook.sheet_names().to_vec();
44        let order = names.clone();
45        let mut sheets = BTreeMap::new();
46        for name in names {
47            let range = workbook
48                .worksheet_range(&name)
49                .map_err(|error| DataError::Connector(error.to_string()))?;
50            // A sheet is dense: one stray cell far from the origin makes millions of
51            // empty ones, and each becomes a column value below.
52            let (rows, columns) = range.get_size();
53            if rows.saturating_mul(columns) > MAX_CELLS {
54                return Err(DataError::Connector(format!(
55                    "sheet `{name}` has more than {MAX_CELLS} cells"
56                )));
57            }
58            sheets.insert(name, dataset_from_range(&range));
59        }
60        let schema = order
61            .first()
62            .and_then(|name| sheets.get(name))
63            .map(|data| data.columns().iter().map(ColumnSchema::from_column).collect())
64            .unwrap_or_default();
65        Ok(Self {
66            path,
67            sheets,
68            order,
69            schema,
70        })
71    }
72
73    /// The workbook path.
74    pub fn path(&self) -> &Path {
75        &self.path
76    }
77
78    /// The sheet names.
79    pub fn sheet_names(&self) -> impl Iterator<Item = &str> {
80        self.order.iter().map(String::as_str)
81    }
82
83    /// A sheet dataset.
84    pub fn sheet(&self, name: &str) -> Option<&Dataset> {
85        self.sheets.get(name)
86    }
87
88    /// The first sheet.
89    pub fn first(&self) -> Option<&Dataset> {
90        self.order.first().and_then(|name| self.sheets.get(name))
91    }
92}
93
94impl DataSource for WorkbookSource {
95    fn schema(&self) -> &[ColumnSchema] {
96        &self.schema
97    }
98
99    fn row_count(&self) -> usize {
100        self.first().map_or(0, Dataset::row_count)
101    }
102
103    fn read_range(&self, range: std::ops::Range<usize>) -> Result<Dataset, DataError> {
104        let data = self
105            .first()
106            .ok_or_else(|| DataError::Connector("the workbook has no sheets".to_owned()))?;
107        super::source::check_range(&range, data.row_count())?;
108        Ok(data.slice(range))
109    }
110}
111
112fn dataset_from_range(range: &calamine::Range<Data>) -> Dataset {
113    let mut rows = range.rows();
114    let Some(headers) = rows.next() else {
115        return Dataset::new();
116    };
117    let names: Vec<String> = headers
118        .iter()
119        .enumerate()
120        .map(|(index, value)| cell_text(value).unwrap_or_else(|| format!("column_{index}")))
121        .collect();
122    let values: Vec<Vec<DataValue>> = rows.map(|row| row.iter().map(cell_value).collect::<Vec<_>>()).collect();
123    let columns: Vec<Column> = names
124        .iter()
125        .enumerate()
126        .map(|(index, name)| {
127            column_from_values(
128                name,
129                &values
130                    .iter()
131                    .map(|row| row.get(index).cloned().unwrap_or(DataValue::Null))
132                    .collect::<Vec<_>>(),
133            )
134        })
135        .collect();
136    Dataset::from_columns(columns)
137}
138
139fn cell_value(value: &Data) -> DataValue {
140    match value {
141        Data::Empty => DataValue::Null,
142        Data::String(value) => DataValue::Text(value.clone()),
143        Data::Float(value) => DataValue::Float(*value),
144        Data::Int(value) => DataValue::Int(*value),
145        Data::Bool(value) => DataValue::Bool(*value),
146        Data::DateTime(value) => DataValue::Float(value.as_f64()),
147        Data::DateTimeIso(value) | Data::DurationIso(value) => DataValue::Text(value.clone()),
148        Data::Error(error) => DataValue::Text(format!("{error:?}")),
149    }
150}
151
152fn cell_text(value: &Data) -> Option<String> {
153    match cell_value(value) {
154        DataValue::Null => None,
155        DataValue::Text(value) => Some(value),
156        DataValue::Float(value) => Some(value.to_string()),
157        DataValue::Int(value) => Some(value.to_string()),
158        DataValue::Bool(value) => Some(value.to_string()),
159        DataValue::Date(value) | DataValue::Time(value) => Some(value.to_string()),
160    }
161}
162
163fn column_from_values(name: &str, values: &[DataValue]) -> Column {
164    let non_null: Vec<&DataValue> = values
165        .iter()
166        .filter(|value| !matches!(value, DataValue::Null))
167        .collect();
168    let all_int = !non_null.is_empty() && non_null.iter().all(|value| matches!(value, DataValue::Int(_)));
169    let all_float = !non_null.is_empty()
170        && non_null
171            .iter()
172            .all(|value| matches!(value, DataValue::Int(_) | DataValue::Float(_)));
173    let column = if all_int {
174        Column::ints(
175            name,
176            values
177                .iter()
178                .map(|value| if let DataValue::Int(value) = value { *value } else { 0 })
179                .collect::<Vec<_>>(),
180        )
181    } else if all_float {
182        Column::floats(
183            name,
184            values
185                .iter()
186                .map(|value| value.as_f64().unwrap_or(f64::NAN))
187                .collect::<Vec<_>>(),
188        )
189    } else {
190        Column::text(
191            name,
192            values
193                .iter()
194                // `{other:?}` printed `Int(5)` in a mixed column.
195                .map(DataValue::display_text)
196                .collect::<Vec<_>>(),
197        )
198    };
199    let valid: Vec<bool> = values.iter().map(|value| !matches!(value, DataValue::Null)).collect();
200    if valid.iter().all(|valid| *valid) {
201        column
202    } else {
203        column.with_validity(valid)
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210
211    #[cfg(feature = "threads")]
212    #[test]
213    fn the_fixture_workbook_has_sheets_and_rows() {
214        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/sales.xlsx");
215        let source = WorkbookSource::open(&path).expect("workbook");
216        assert!(source.sheet_names().next().is_some());
217        assert!(source.first().is_some_and(|sheet| sheet.row_count() > 0));
218        assert!(source.row_count() > 0);
219        assert!(source.read_range(0..1).is_ok());
220    }
221}