Skip to main content

connectorx/transports/
csv_arrow.rs

1//! Transport from CSV Source to Arrow Destination.
2
3use crate::destinations::arrow::{
4    typesystem::{ArrowTypeSystem, DateTimeWrapperMicro},
5    ArrowDestination, ArrowDestinationError,
6};
7use crate::sources::csv::{CSVSource, CSVSourceError, CSVTypeSystem};
8use crate::typesystem::TypeConversion;
9use chrono::{DateTime, Utc};
10use thiserror::Error;
11
12/// Convert CSV data types to Arrow data types.
13pub struct CSVArrowTransport;
14
15#[derive(Error, Debug)]
16pub enum CSVArrowTransportError {
17    #[error(transparent)]
18    Source(#[from] CSVSourceError),
19
20    #[error(transparent)]
21    Destination(#[from] ArrowDestinationError),
22
23    #[error(transparent)]
24    ConnectorX(#[from] crate::errors::ConnectorXError),
25}
26
27impl_transport!(
28    name = CSVArrowTransport,
29    error = CSVArrowTransportError,
30    systems = CSVTypeSystem => ArrowTypeSystem,
31    route = CSVSource => ArrowDestination,
32    mappings = {
33        { F64[f64]                => Float64[f64]              | conversion auto}
34        { I64[i64]                => Int64[i64]                | conversion auto}
35        { Bool[bool]              => Boolean[bool]             | conversion auto}
36        { String[String]          => LargeUtf8[String]         | conversion auto}
37        { DateTime[DateTime<Utc>] => DateTimeTzMicro[DateTimeWrapperMicro] | conversion option}
38    }
39);
40
41impl TypeConversion<DateTime<Utc>, DateTimeWrapperMicro> for CSVArrowTransport {
42    fn convert(val: DateTime<Utc>) -> DateTimeWrapperMicro {
43        DateTimeWrapperMicro(val)
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50    use crate::data_order::DataOrder;
51    use crate::dispatcher::Dispatcher;
52    use crate::sources::Source;
53    use crate::sql::CXQuery;
54    use arrow::array::{Array, AsArray};
55    use arrow::datatypes::{DataType, Float64Type, Int64Type, TimestampMicrosecondType};
56    use arrow::record_batch::RecordBatch;
57    use std::path::PathBuf;
58
59    /// A CSV file in the temp directory that is removed when the test ends.
60    struct TempCsv(PathBuf);
61
62    impl TempCsv {
63        fn new(name: &str, contents: &str) -> Self {
64            let path = std::env::temp_dir().join(format!(
65                "connectorx_csv_arrow_{}_{}.csv",
66                name,
67                std::process::id()
68            ));
69            std::fs::write(&path, contents).unwrap();
70            TempCsv(path)
71        }
72
73        fn query(&self) -> CXQuery {
74            CXQuery::naked(self.0.display().to_string())
75        }
76    }
77
78    impl Drop for TempCsv {
79        fn drop(&mut self) {
80            let _ = std::fs::remove_file(&self.0);
81        }
82    }
83
84    fn run(
85        schema: &[CSVTypeSystem],
86        files: &[&TempCsv],
87    ) -> Result<RecordBatch, CSVArrowTransportError> {
88        let mut dst = ArrowDestination::new();
89        let queries: Vec<CXQuery> = files.iter().map(|f| f.query()).collect();
90        Dispatcher::<_, _, CSVArrowTransport>::new(
91            CSVSource::new(schema),
92            &mut dst,
93            &queries,
94            None,
95        )
96        .run()?;
97        let batches = dst.arrow().unwrap();
98        Ok(arrow::compute::concat_batches(&batches[0].schema(), &batches).unwrap())
99    }
100
101    const HEADER: &str = "i,f,b,s,t,ni,nf,nb,ns,nt\n";
102
103    fn every_type() -> Vec<CSVTypeSystem> {
104        use CSVTypeSystem::*;
105        vec![
106            I64(false),
107            F64(false),
108            Bool(false),
109            String(false),
110            DateTime(false),
111            I64(true),
112            F64(true),
113            Bool(true),
114            String(true),
115            DateTime(true),
116        ]
117    }
118
119    #[test]
120    fn reads_every_type_from_several_files() {
121        let a = TempCsv::new(
122            "a",
123            &format!(
124                "{HEADER}1,1.5,true,x,2020-01-02T03:04:05Z,-7,0.25,false,y,1970-01-01T00:00:00Z\n"
125            ),
126        );
127        let b = TempCsv::new(
128            "b",
129            &format!("{HEADER}2,-2.5,false,,2021-06-30T12:00:00.5Z,,,,,\n"),
130        );
131        let rb = run(&every_type(), &[&a, &b]).unwrap();
132
133        assert_eq!(rb.num_rows(), 2);
134        let types: Vec<_> = rb
135            .schema()
136            .fields()
137            .iter()
138            .map(|f| f.data_type().clone())
139            .collect();
140        assert_eq!(
141            &types[..4],
142            &[
143                DataType::Int64,
144                DataType::Float64,
145                DataType::Boolean,
146                DataType::Utf8
147            ]
148        );
149        assert!(matches!(types[4], DataType::Timestamp(_, Some(_))));
150        let nullable: Vec<_> = rb
151            .schema()
152            .fields()
153            .iter()
154            .map(|f| f.is_nullable())
155            .collect();
156        assert_eq!(
157            nullable,
158            [false, false, false, false, false, true, true, true, true, true]
159        );
160
161        // Files are read in partition order, but the destination may finish
162        // them in any order, so look the rows up by the `i` column.
163        let i: Vec<i64> = rb.column(0).as_primitive::<Int64Type>().values().to_vec();
164        let (r1, r2) = (
165            i.iter().position(|v| *v == 1).unwrap(),
166            i.iter().position(|v| *v == 2).unwrap(),
167        );
168        let f = rb.column(1).as_primitive::<Float64Type>();
169        assert_eq!((f.value(r1), f.value(r2)), (1.5, -2.5));
170        let b = rb.column(2).as_boolean();
171        assert_eq!((b.value(r1), b.value(r2)), (true, false));
172        let s = rb.column(3).as_string::<i32>();
173        assert_eq!((s.value(r1), s.value(r2)), ("x", ""));
174        let t = rb.column(4).as_primitive::<TimestampMicrosecondType>();
175        assert_eq!(t.value(r1), 1_577_934_245_000_000);
176        assert_eq!(t.value(r2), 1_625_054_400_500_000);
177
178        // Empty fields are NULL in the nullable columns of the second file...
179        assert_eq!(rb.column(5).as_primitive::<Int64Type>().value(r1), -7);
180        assert_eq!(rb.column(6).as_primitive::<Float64Type>().value(r1), 0.25);
181        assert!(!rb.column(7).as_boolean().value(r1));
182        assert_eq!(
183            rb.column(9)
184                .as_primitive::<TimestampMicrosecondType>()
185                .value(r1),
186            0
187        );
188        for c in [5, 6, 7, 9] {
189            assert!(rb.column(c).is_null(r2), "column {c}");
190        }
191        // ...except strings: the CSV source cannot tell an empty string from
192        // a missing one, so it always produces "".
193        let ns = rb.column(8).as_string::<i32>();
194        assert_eq!(
195            (ns.value(r1), ns.is_null(r2), ns.value(r2)),
196            ("y", false, "")
197        );
198    }
199
200    #[test]
201    fn values_that_do_not_parse_are_errors() {
202        use CSVTypeSystem::*;
203        for (ty, value) in [
204            (I64(false), "1.5"),
205            (I64(true), "x"),
206            (F64(false), "one"),
207            (F64(true), "1,5"),
208            (Bool(false), "yes"),
209            (Bool(true), "1"),
210            (DateTime(false), "2020-01-02"),
211            (DateTime(true), "noon"),
212        ] {
213            let file = TempCsv::new("bad", &format!("x\n\"{value}\"\n"));
214            let err = run(&[ty], &[&file]).expect_err(&format!("{ty:?} = {value:?}"));
215            assert!(err.to_string().contains(value), "{err}");
216        }
217    }
218
219    #[test]
220    fn missing_file_is_an_error() {
221        let mut source = CSVSource::new(&[CSVTypeSystem::I64(false)]);
222        source.set_queries(&[CXQuery::naked("/no/such/dir/connectorx.csv")]);
223        assert!(source.fetch_metadata().is_err());
224        assert!(source.partition().is_err());
225    }
226
227    #[test]
228    fn only_row_major_is_supported() {
229        let mut source = CSVSource::new(&[]);
230        assert!(source.set_data_order(DataOrder::RowMajor).is_ok());
231        assert!(source.set_data_order(DataOrder::ColumnMajor).is_err());
232        assert_eq!(source.result_rows().unwrap(), None);
233    }
234}