Skip to main content

connectorx/sources/csv/
mod.rs

1//! Source implementation for CSV files.
2
3mod errors;
4mod typesystem;
5
6pub use self::errors::CSVSourceError;
7pub use self::typesystem::CSVTypeSystem;
8use super::{PartitionParser, Produce, Source, SourcePartition};
9use crate::{data_order::DataOrder, errors::ConnectorXError, sql::CXQuery};
10use anyhow::anyhow;
11use chrono::{DateTime, Utc};
12use fehler::{throw, throws};
13#[cfg(feature = "src_csv")]
14use regex::{Regex, RegexBuilder};
15use std::collections::HashSet;
16use std::fs::File;
17
18/// Source that reads CSV files. Each "query" is a file path.
19pub struct CSVSource {
20    schema: Vec<CSVTypeSystem>,
21    files: Vec<CXQuery<String>>,
22    names: Vec<String>,
23}
24
25impl CSVSource {
26    /// Create a source with the given column types.
27    pub fn new(schema: &[CSVTypeSystem]) -> Self {
28        CSVSource {
29            schema: schema.to_vec(),
30            files: vec![],
31            names: vec![],
32        }
33    }
34
35    /// Guess the column types from the values in the files.
36    #[throws(CSVSourceError)]
37    pub fn infer_schema(&mut self) -> Vec<CSVTypeSystem> {
38        // regular expressions for infer CSVTypeSystem from string
39        let decimal_re: Regex = Regex::new(r"^-?(\d+\.\d+)$")?;
40        let integer_re: Regex = Regex::new(r"^-?(\d+)$")?;
41        let boolean_re: Regex = RegexBuilder::new(r"^(true)$|^(false)$")
42            .case_insensitive(true)
43            .build()?;
44        let datetime_re: Regex = Regex::new(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d$")?;
45
46        // read max_records rows to infer possible CSVTypeSystems for each field
47        let mut reader = csv::ReaderBuilder::new()
48            .has_headers(true)
49            .from_reader(File::open(self.files[0].as_str())?);
50
51        let max_records_to_read = 50;
52        let num_cols = self.names.len();
53
54        let mut column_types: Vec<HashSet<CSVTypeSystem>> = vec![HashSet::new(); num_cols];
55        let mut nulls: Vec<bool> = vec![false; num_cols];
56
57        let mut record = csv::StringRecord::new();
58
59        for _record_counter in 0..max_records_to_read {
60            if !reader.read_record(&mut record)? {
61                break;
62            }
63            for field_counter in 0..num_cols {
64                if let Some(string) = record.get(field_counter) {
65                    if string.is_empty() {
66                        nulls[field_counter] = true;
67                    } else {
68                        let dt: CSVTypeSystem = if string.starts_with('"') {
69                            CSVTypeSystem::String(false)
70                        } else if boolean_re.is_match(string) {
71                            CSVTypeSystem::Bool(false)
72                        } else if decimal_re.is_match(string) {
73                            CSVTypeSystem::F64(false)
74                        } else if integer_re.is_match(string) {
75                            CSVTypeSystem::I64(false)
76                        } else if datetime_re.is_match(string) {
77                            CSVTypeSystem::DateTime(false)
78                        } else {
79                            CSVTypeSystem::String(false)
80                        };
81                        column_types[field_counter].insert(dt);
82                    }
83                }
84            }
85        }
86
87        // determine CSVTypeSystem based on possible candidates
88        let mut schema = vec![];
89
90        for field_counter in 0..num_cols {
91            let possibilities = &column_types[field_counter];
92            let has_nulls = nulls[field_counter];
93
94            match possibilities.len() {
95                1 => {
96                    for dt in possibilities.iter() {
97                        match *dt {
98                            CSVTypeSystem::I64(false) => {
99                                schema.push(CSVTypeSystem::I64(has_nulls));
100                            }
101                            CSVTypeSystem::F64(false) => {
102                                schema.push(CSVTypeSystem::F64(has_nulls));
103                            }
104                            CSVTypeSystem::Bool(false) => {
105                                schema.push(CSVTypeSystem::Bool(has_nulls));
106                            }
107                            CSVTypeSystem::String(false) => {
108                                schema.push(CSVTypeSystem::String(has_nulls));
109                            }
110                            CSVTypeSystem::DateTime(false) => {
111                                schema.push(CSVTypeSystem::DateTime(has_nulls));
112                            }
113                            _ => {}
114                        }
115                    }
116                }
117                2 if possibilities.contains(&CSVTypeSystem::I64(false))
118                    && possibilities.contains(&CSVTypeSystem::F64(false)) =>
119                {
120                    // Integer && Float -> Float
121                    schema.push(CSVTypeSystem::F64(has_nulls));
122                }
123                _ => {
124                    // Conflicting CSVTypeSystems -> String
125                    schema.push(CSVTypeSystem::String(has_nulls));
126                }
127            }
128        }
129        schema
130    }
131}
132
133impl Source for CSVSource {
134    const DATA_ORDERS: &'static [DataOrder] = &[DataOrder::RowMajor];
135    type Partition = CSVSourcePartition;
136    type TypeSystem = CSVTypeSystem;
137    type Error = CSVSourceError;
138
139    #[throws(CSVSourceError)]
140    fn set_data_order(&mut self, data_order: DataOrder) {
141        if !matches!(data_order, DataOrder::RowMajor) {
142            throw!(ConnectorXError::UnsupportedDataOrder(data_order))
143        }
144    }
145
146    fn set_queries<Q: ToString>(&mut self, queries: &[CXQuery<Q>]) {
147        self.files = queries.iter().map(|q| q.map(Q::to_string)).collect();
148    }
149
150    fn set_origin_query(&mut self, _query: Option<String>) {}
151
152    #[throws(CSVSourceError)]
153    fn fetch_metadata(&mut self) {
154        let mut reader = csv::ReaderBuilder::new()
155            .has_headers(true)
156            .from_reader(File::open(self.files[0].as_str())?);
157        let header = reader.headers()?;
158
159        self.names = header.iter().map(|s| s.to_string()).collect();
160
161        if self.schema.is_empty() {
162            self.schema = self.infer_schema()?;
163        }
164
165        assert_eq!(header.len(), self.schema.len());
166    }
167
168    #[throws(CSVSourceError)]
169    fn result_rows(&mut self) -> Option<usize> {
170        None
171    }
172
173    fn names(&self) -> Vec<String> {
174        self.names.clone()
175    }
176
177    fn schema(&self) -> Vec<Self::TypeSystem> {
178        self.schema.clone()
179    }
180
181    #[throws(CSVSourceError)]
182    fn partition(self) -> Vec<Self::Partition> {
183        let mut partitions = vec![];
184        for file in self.files {
185            partitions.push(CSVSourcePartition::new(file)?);
186        }
187        partitions
188    }
189}
190
191/// One CSV file of a [`CSVSource`].
192pub struct CSVSourcePartition {
193    records: Vec<csv::StringRecord>,
194    counter: usize,
195    nrows: usize,
196    ncols: usize,
197}
198
199impl CSVSourcePartition {
200    /// Open the file `fname`.
201    #[throws(CSVSourceError)]
202    pub fn new(fname: CXQuery<String>) -> Self {
203        let reader = csv::ReaderBuilder::new()
204            .has_headers(true)
205            .from_reader(File::open(fname.as_str())?);
206        let mut records = vec![];
207        reader
208            .into_records()
209            .try_for_each(|v| -> Result<(), CSVSourceError> {
210                records.push(v.map_err(|e| anyhow!(e))?);
211                Ok(())
212            })?;
213
214        let nrows = records.len();
215        let ncols = if nrows > 0 { records[0].len() } else { 0 };
216
217        Self {
218            records,
219            counter: 0,
220            nrows,
221            ncols,
222        }
223    }
224}
225
226impl SourcePartition for CSVSourcePartition {
227    type TypeSystem = CSVTypeSystem;
228    type Parser<'a> = CSVSourcePartitionParser<'a>;
229    type Error = CSVSourceError;
230
231    /// The parameter `query` is the path of the csv file
232    #[throws(CSVSourceError)]
233    fn result_rows(&mut self) {}
234
235    fn nrows(&self) -> usize {
236        self.nrows
237    }
238
239    fn ncols(&self) -> usize {
240        self.ncols
241    }
242
243    #[throws(CSVSourceError)]
244    fn parser(&mut self) -> Self::Parser<'_> {
245        CSVSourcePartitionParser {
246            records: &mut self.records,
247            counter: &mut self.counter,
248            ncols: self.ncols,
249        }
250    }
251}
252
253/// Value parser for a CSV file.
254pub struct CSVSourcePartitionParser<'a> {
255    records: &'a mut [csv::StringRecord],
256    counter: &'a mut usize,
257    ncols: usize,
258}
259
260impl<'a> CSVSourcePartitionParser<'a> {
261    fn next_val(&mut self) -> &str {
262        let v: &str = self.records[*self.counter / self.ncols][*self.counter % self.ncols].as_ref();
263        *self.counter += 1;
264
265        v
266    }
267}
268
269impl<'a> PartitionParser<'a> for CSVSourcePartitionParser<'a> {
270    type TypeSystem = CSVTypeSystem;
271    type Error = CSVSourceError;
272
273    #[throws(CSVSourceError)]
274    fn fetch_next(&mut self) -> (usize, bool) {
275        (self.records.len(), true)
276    }
277}
278
279impl<'r, 'a> Produce<'r, i64> for CSVSourcePartitionParser<'a> {
280    type Error = CSVSourceError;
281
282    #[throws(CSVSourceError)]
283    fn produce(&mut self) -> i64 {
284        let v = self.next_val();
285        v.parse()
286            .map_err(|_| ConnectorXError::cannot_produce::<i64>(Some(v.into())))?
287    }
288}
289
290impl<'r, 'a> Produce<'r, Option<i64>> for CSVSourcePartitionParser<'a> {
291    type Error = CSVSourceError;
292
293    #[throws(CSVSourceError)]
294    fn produce(&mut self) -> Option<i64> {
295        let v = self.next_val();
296        if v.is_empty() {
297            return None;
298        }
299        let v = v
300            .parse()
301            .map_err(|_| ConnectorXError::cannot_produce::<Option<i64>>(Some(v.into())))?;
302
303        Some(v)
304    }
305}
306
307impl<'r, 'a> Produce<'r, f64> for CSVSourcePartitionParser<'a> {
308    type Error = CSVSourceError;
309
310    #[throws(CSVSourceError)]
311    fn produce(&mut self) -> f64 {
312        let v = self.next_val();
313        v.parse()
314            .map_err(|_| ConnectorXError::cannot_produce::<f64>(Some(v.into())))?
315    }
316}
317
318impl<'r, 'a> Produce<'r, Option<f64>> for CSVSourcePartitionParser<'a> {
319    type Error = CSVSourceError;
320
321    #[throws(CSVSourceError)]
322    fn produce(&mut self) -> Option<f64> {
323        let v = self.next_val();
324        if v.is_empty() {
325            return None;
326        }
327        let v = v
328            .parse()
329            .map_err(|_| ConnectorXError::cannot_produce::<Option<f64>>(Some(v.into())))?;
330
331        Some(v)
332    }
333}
334
335impl<'r, 'a> Produce<'r, bool> for CSVSourcePartitionParser<'a> {
336    type Error = CSVSourceError;
337
338    #[throws(CSVSourceError)]
339    fn produce(&mut self) -> bool {
340        let v = self.next_val();
341        v.parse()
342            .map_err(|_| ConnectorXError::cannot_produce::<bool>(Some(v.into())))?
343    }
344}
345
346impl<'r, 'a> Produce<'r, Option<bool>> for CSVSourcePartitionParser<'a> {
347    type Error = CSVSourceError;
348
349    #[throws(CSVSourceError)]
350    fn produce(&mut self) -> Option<bool> {
351        let v = self.next_val();
352        if v.is_empty() {
353            return None;
354        }
355        let v = v
356            .parse()
357            .map_err(|_| ConnectorXError::cannot_produce::<Option<bool>>(Some(v.into())))?;
358
359        Some(v)
360    }
361}
362
363impl<'r, 'a> Produce<'r, String> for CSVSourcePartitionParser<'a> {
364    type Error = CSVSourceError;
365
366    #[throws(CSVSourceError)]
367    fn produce(&mut self) -> String {
368        let v = self.next_val();
369        String::from(v)
370    }
371}
372
373impl<'a, 'r> Produce<'r, Option<String>> for CSVSourcePartitionParser<'a> {
374    type Error = CSVSourceError;
375
376    #[throws(CSVSourceError)]
377    fn produce(&'r mut self) -> Option<String> {
378        let v = self.next_val();
379
380        Some(String::from(v))
381    }
382}
383
384impl<'r, 'a> Produce<'r, DateTime<Utc>> for CSVSourcePartitionParser<'a> {
385    type Error = CSVSourceError;
386
387    #[throws(CSVSourceError)]
388    fn produce(&mut self) -> DateTime<Utc> {
389        let v = self.next_val();
390        v.parse()
391            .map_err(|_| ConnectorXError::cannot_produce::<DateTime<Utc>>(Some(v.into())))?
392    }
393}
394
395impl<'r, 'a> Produce<'r, Option<DateTime<Utc>>> for CSVSourcePartitionParser<'a> {
396    type Error = CSVSourceError;
397
398    #[throws(CSVSourceError)]
399    fn produce(&mut self) -> Option<DateTime<Utc>> {
400        let v = self.next_val();
401        if v.is_empty() {
402            return None;
403        }
404        let v = v
405            .parse()
406            .map_err(|_| ConnectorXError::cannot_produce::<DateTime<Utc>>(Some(v.into())))?;
407        Some(v)
408    }
409}
410
411#[cfg(test)]
412mod tests {
413    use super::{CSVSource, CSVTypeSystem};
414    use crate::{sources::Source, sql::CXQuery};
415    use std::{fs, path::PathBuf};
416
417    #[test]
418    fn infers_schema_from_numeric_boolean_datetime_and_string_values() {
419        let path: PathBuf =
420            std::env::temp_dir().join(format!("connectorx-csv-infer-{}.csv", std::process::id()));
421        fs::write(
422            &path,
423            "integer,float,mixed,boolean,datetime,string,empty\n\
424             1,1.5,1,true,2020-01-02T03:04:05,hello,\n\
425             ,2.5,2.5,,2020-01-02T03:04:05,world,\n",
426        )
427        .unwrap();
428
429        let mut source = CSVSource::new(&[]);
430        source.set_queries(&[CXQuery::naked(path.to_string_lossy())]);
431        source.fetch_metadata().unwrap();
432
433        assert_eq!(
434            source.schema(),
435            vec![
436                CSVTypeSystem::I64(true),
437                CSVTypeSystem::F64(false),
438                CSVTypeSystem::F64(false),
439                CSVTypeSystem::Bool(true),
440                CSVTypeSystem::DateTime(false),
441                CSVTypeSystem::String(false),
442                CSVTypeSystem::String(true),
443            ]
444        );
445        assert_eq!(
446            source.names(),
447            vec![
448                "integer".to_owned(),
449                "float".to_owned(),
450                "mixed".to_owned(),
451                "boolean".to_owned(),
452                "datetime".to_owned(),
453                "string".to_owned(),
454                "empty".to_owned(),
455            ]
456        );
457
458        fs::remove_file(path).unwrap();
459    }
460}