Skip to main content

risingwave_connector/parser/
csv_parser.rs

1// Copyright 2023 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use risingwave_common::cast::str_to_bool;
16use risingwave_common::types::{DataType, Date, Decimal, ScalarImpl, Time, Timestamp, Timestamptz};
17
18use super::unified::{AccessError, AccessResult};
19use super::{ByteStreamSourceParser, CsvProperties};
20use crate::error::ConnectorResult;
21use crate::only_parse_payload;
22use crate::parser::{ParserFormat, SourceStreamChunkRowWriter};
23use crate::source::{SourceColumnDesc, SourceContext, SourceContextRef};
24
25macro_rules! parse {
26    ($v:ident, $t:ty) => {
27        $v.parse::<$t>().map_err(|_| AccessError::TypeError {
28            expected: stringify!($t).to_owned(),
29            got: "string".to_owned(),
30            value: $v.to_string(),
31        })
32    };
33}
34
35/// Parser for CSV format
36#[derive(Debug)]
37pub struct CsvParser {
38    rw_columns: Vec<SourceColumnDesc>,
39    source_ctx: SourceContextRef,
40    headers: Option<Vec<String>>,
41    delimiter: u8,
42}
43
44impl CsvParser {
45    pub fn new(
46        rw_columns: Vec<SourceColumnDesc>,
47        csv_props: CsvProperties,
48        source_ctx: SourceContextRef,
49    ) -> ConnectorResult<Self> {
50        let CsvProperties {
51            delimiter,
52            has_header,
53        } = csv_props;
54
55        Ok(Self {
56            rw_columns,
57            delimiter,
58            headers: if has_header { Some(Vec::new()) } else { None },
59            source_ctx,
60        })
61    }
62
63    fn read_row(&self, buf: &[u8]) -> ConnectorResult<Vec<String>> {
64        let mut reader_builder = csv::ReaderBuilder::default();
65        reader_builder.delimiter(self.delimiter).has_headers(false);
66        let record = reader_builder
67            .from_reader(buf)
68            .records()
69            .next()
70            .transpose()?;
71        Ok(record
72            .map(|record| record.iter().map(|field| field.to_owned()).collect())
73            .unwrap_or_default())
74    }
75
76    #[inline]
77    fn parse_string(dtype: &DataType, v: String) -> AccessResult {
78        let v = match dtype {
79            // mysql use tinyint to represent boolean
80            DataType::Boolean => {
81                str_to_bool(&v)
82                    .map(ScalarImpl::Bool)
83                    .map_err(|_| AccessError::TypeError {
84                        expected: "boolean".to_owned(),
85                        got: "string".to_owned(),
86                        value: v,
87                    })?
88            }
89            DataType::Int16 => parse!(v, i16)?.into(),
90            DataType::Int32 => parse!(v, i32)?.into(),
91            DataType::Int64 => parse!(v, i64)?.into(),
92            DataType::Float32 => parse!(v, f32)?.into(),
93            DataType::Float64 => parse!(v, f64)?.into(),
94            DataType::Decimal => parse!(v, Decimal)?.into(),
95            DataType::Varchar => v.into(),
96            DataType::Date => parse!(v, Date)?.into(),
97            DataType::Time => parse!(v, Time)?.into(),
98            DataType::Timestamp => parse!(v, Timestamp)?.into(),
99            DataType::Timestamptz => parse!(v, Timestamptz)?.into(),
100            _ => {
101                return Err(AccessError::UnsupportedType {
102                    ty: dtype.to_string(),
103                });
104            }
105        };
106        Ok(Some(v))
107    }
108
109    #[expect(clippy::unused_async)]
110    pub async fn parse_inner(
111        &mut self,
112        payload: Vec<u8>,
113        mut writer: SourceStreamChunkRowWriter<'_>,
114    ) -> ConnectorResult<()> {
115        let mut fields = self.read_row(&payload)?;
116
117        if let Some(headers) = &mut self.headers {
118            if headers.is_empty() {
119                *headers = fields;
120                // The header row does not output a row, so we return early.
121                return Ok(());
122            }
123            writer.do_insert(|desc| {
124                if let Some(i) = headers.iter().position(|name| name == &desc.name) {
125                    let value = fields.get_mut(i).map(std::mem::take).unwrap_or_default();
126                    if value.is_empty() {
127                        return Ok(None);
128                    }
129                    Self::parse_string(&desc.data_type, value)
130                } else {
131                    Ok(None)
132                }
133            })?;
134        } else {
135            fields.reverse();
136            writer.do_insert(|desc| {
137                if let Some(value) = fields.pop() {
138                    if value.is_empty() {
139                        return Ok(None);
140                    }
141                    Self::parse_string(&desc.data_type, value)
142                } else {
143                    Ok(None)
144                }
145            })?;
146        }
147
148        Ok(())
149    }
150}
151
152impl ByteStreamSourceParser for CsvParser {
153    fn columns(&self) -> &[SourceColumnDesc] {
154        &self.rw_columns
155    }
156
157    fn source_ctx(&self) -> &SourceContext {
158        &self.source_ctx
159    }
160
161    fn parser_format(&self) -> ParserFormat {
162        ParserFormat::Csv
163    }
164
165    async fn parse_one<'a>(
166        &'a mut self,
167        _key: Option<Vec<u8>>,
168        payload: Option<Vec<u8>>,
169        writer: SourceStreamChunkRowWriter<'a>,
170    ) -> ConnectorResult<()> {
171        only_parse_payload!(self, payload, writer)
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use risingwave_common::array::Op;
178    use risingwave_common::row::Row;
179    use risingwave_common::types::{DataType, ToOwnedDatum};
180
181    use super::*;
182    use crate::parser::SourceStreamChunkBuilder;
183    use crate::source::SourceCtrlOpts;
184
185    #[tokio::test]
186    async fn test_csv_without_headers() {
187        let data = vec![
188            r#"1,a,2"#,
189            r#""15541","a,1,1,",4"#,
190            r#"0,"""0",0"#,
191            r#"0,0,0,0,0,0,0,0,0,0,0,0,0,"#,
192            r#",,,,"#,
193        ];
194        let descs = vec![
195            SourceColumnDesc::simple("a", DataType::Int32, 0.into()),
196            SourceColumnDesc::simple("b", DataType::Varchar, 1.into()),
197            SourceColumnDesc::simple("c", DataType::Int32, 2.into()),
198        ];
199        let mut parser = CsvParser::new(
200            Vec::new(),
201            CsvProperties {
202                delimiter: b',',
203                has_header: false,
204            },
205            SourceContext::dummy().into(),
206        )
207        .unwrap();
208        let mut builder = SourceStreamChunkBuilder::new(descs, SourceCtrlOpts::for_test());
209        for item in data {
210            parser
211                .parse_inner(item.as_bytes().to_vec(), builder.row_writer())
212                .await
213                .unwrap();
214        }
215        builder.finish_current_chunk();
216        let chunk = builder.consume_ready_chunks().next().unwrap();
217        let mut rows = chunk.rows();
218        {
219            let (op, row) = rows.next().unwrap();
220            assert_eq!(op, Op::Insert);
221            assert_eq!(
222                row.datum_at(0).to_owned_datum(),
223                (Some(ScalarImpl::Int32(1)))
224            );
225            assert_eq!(
226                row.datum_at(1).to_owned_datum(),
227                (Some(ScalarImpl::Utf8("a".into())))
228            );
229            assert_eq!(
230                row.datum_at(2).to_owned_datum(),
231                (Some(ScalarImpl::Int32(2)))
232            );
233        }
234        {
235            let (op, row) = rows.next().unwrap();
236            assert_eq!(op, Op::Insert);
237            assert_eq!(
238                row.datum_at(0).to_owned_datum(),
239                (Some(ScalarImpl::Int32(15541)))
240            );
241            assert_eq!(
242                row.datum_at(1).to_owned_datum(),
243                (Some(ScalarImpl::Utf8("a,1,1,".into())))
244            );
245            assert_eq!(
246                row.datum_at(2).to_owned_datum(),
247                (Some(ScalarImpl::Int32(4)))
248            );
249        }
250
251        {
252            let (op, row) = rows.next().unwrap();
253            assert_eq!(op, Op::Insert);
254            assert_eq!(
255                row.datum_at(0).to_owned_datum(),
256                (Some(ScalarImpl::Int32(0)))
257            );
258            assert_eq!(
259                row.datum_at(1).to_owned_datum(),
260                (Some(ScalarImpl::Utf8("\"0".into())))
261            );
262            assert_eq!(
263                row.datum_at(2).to_owned_datum(),
264                (Some(ScalarImpl::Int32(0)))
265            );
266        }
267
268        {
269            let (op, row) = rows.next().unwrap();
270            assert_eq!(op, Op::Insert);
271            assert_eq!(
272                row.datum_at(0).to_owned_datum(),
273                (Some(ScalarImpl::Int32(0)))
274            );
275            assert_eq!(
276                row.datum_at(1).to_owned_datum(),
277                (Some(ScalarImpl::Utf8("0".into())))
278            );
279            assert_eq!(
280                row.datum_at(2).to_owned_datum(),
281                (Some(ScalarImpl::Int32(0)))
282            );
283        }
284
285        {
286            let (op, row) = rows.next().unwrap();
287            assert_eq!(op, Op::Insert);
288            assert_eq!(row.datum_at(0), None);
289            assert_eq!(row.datum_at(1), None);
290            assert_eq!(row.datum_at(2), None);
291        }
292    }
293    #[tokio::test]
294    async fn test_csv_with_headers() {
295        let data = [
296            r#"c,b,a"#,
297            r#"1,a,2"#,
298            r#""15541","a,1,1,",4"#,
299            r#"0,"""0",0"#,
300            r#"0,0,0,0,0,0,0,0,0,0,0,0,0,"#,
301        ];
302        let descs = vec![
303            SourceColumnDesc::simple("a", DataType::Int32, 0.into()),
304            SourceColumnDesc::simple("b", DataType::Varchar, 1.into()),
305            SourceColumnDesc::simple("c", DataType::Int32, 2.into()),
306        ];
307        let mut parser = CsvParser::new(
308            Vec::new(),
309            CsvProperties {
310                delimiter: b',',
311                has_header: true,
312            },
313            SourceContext::dummy().into(),
314        )
315        .unwrap();
316        let mut builder = SourceStreamChunkBuilder::new(descs, SourceCtrlOpts::for_test());
317        for item in data {
318            let _ = parser
319                .parse_inner(item.as_bytes().to_vec(), builder.row_writer())
320                .await;
321        }
322        builder.finish_current_chunk();
323        let chunk = builder.consume_ready_chunks().next().unwrap();
324        let mut rows = chunk.rows();
325        {
326            let (op, row) = rows.next().unwrap();
327            assert_eq!(op, Op::Insert);
328            assert_eq!(
329                row.datum_at(2).to_owned_datum(),
330                (Some(ScalarImpl::Int32(1)))
331            );
332            assert_eq!(
333                row.datum_at(1).to_owned_datum(),
334                (Some(ScalarImpl::Utf8("a".into())))
335            );
336            assert_eq!(
337                row.datum_at(0).to_owned_datum(),
338                (Some(ScalarImpl::Int32(2)))
339            );
340        }
341        {
342            let (op, row) = rows.next().unwrap();
343            assert_eq!(op, Op::Insert);
344            assert_eq!(
345                row.datum_at(2).to_owned_datum(),
346                (Some(ScalarImpl::Int32(15541)))
347            );
348            assert_eq!(
349                row.datum_at(1).to_owned_datum(),
350                (Some(ScalarImpl::Utf8("a,1,1,".into())))
351            );
352            assert_eq!(
353                row.datum_at(0).to_owned_datum(),
354                (Some(ScalarImpl::Int32(4)))
355            );
356        }
357
358        {
359            let (op, row) = rows.next().unwrap();
360            assert_eq!(op, Op::Insert);
361            assert_eq!(
362                row.datum_at(2).to_owned_datum(),
363                (Some(ScalarImpl::Int32(0)))
364            );
365            assert_eq!(
366                row.datum_at(1).to_owned_datum(),
367                (Some(ScalarImpl::Utf8("\"0".into())))
368            );
369            assert_eq!(
370                row.datum_at(0).to_owned_datum(),
371                (Some(ScalarImpl::Int32(0)))
372            );
373        }
374
375        {
376            let (op, row) = rows.next().unwrap();
377            assert_eq!(op, Op::Insert);
378            assert_eq!(
379                row.datum_at(2).to_owned_datum(),
380                (Some(ScalarImpl::Int32(0)))
381            );
382            assert_eq!(
383                row.datum_at(1).to_owned_datum(),
384                (Some(ScalarImpl::Utf8("0".into())))
385            );
386            assert_eq!(
387                row.datum_at(0).to_owned_datum(),
388                (Some(ScalarImpl::Int32(0)))
389            );
390        }
391    }
392
393    #[test]
394    fn test_parse_boolean() {
395        assert_eq!(
396            CsvParser::parse_string(&DataType::Boolean, "1".to_owned()).unwrap(),
397            Some(true.into())
398        );
399        assert_eq!(
400            CsvParser::parse_string(&DataType::Boolean, "t".to_owned()).unwrap(),
401            Some(true.into())
402        );
403        assert_eq!(
404            CsvParser::parse_string(&DataType::Boolean, "T".to_owned()).unwrap(),
405            Some(true.into())
406        );
407        assert_eq!(
408            CsvParser::parse_string(&DataType::Boolean, "true".to_owned()).unwrap(),
409            Some(true.into())
410        );
411        assert_eq!(
412            CsvParser::parse_string(&DataType::Boolean, "TRUE".to_owned()).unwrap(),
413            Some(true.into())
414        );
415        assert_eq!(
416            CsvParser::parse_string(&DataType::Boolean, "True".to_owned()).unwrap(),
417            Some(true.into())
418        );
419
420        assert_eq!(
421            CsvParser::parse_string(&DataType::Boolean, "0".to_owned()).unwrap(),
422            Some(false.into())
423        );
424        assert_eq!(
425            CsvParser::parse_string(&DataType::Boolean, "f".to_owned()).unwrap(),
426            Some(false.into())
427        );
428        assert_eq!(
429            CsvParser::parse_string(&DataType::Boolean, "F".to_owned()).unwrap(),
430            Some(false.into())
431        );
432        assert_eq!(
433            CsvParser::parse_string(&DataType::Boolean, "false".to_owned()).unwrap(),
434            Some(false.into())
435        );
436        assert_eq!(
437            CsvParser::parse_string(&DataType::Boolean, "FALSE".to_owned()).unwrap(),
438            Some(false.into())
439        );
440        assert_eq!(
441            CsvParser::parse_string(&DataType::Boolean, "False".to_owned()).unwrap(),
442            Some(false.into())
443        );
444
445        assert!(CsvParser::parse_string(&DataType::Boolean, "2".to_owned()).is_err());
446        assert!(CsvParser::parse_string(&DataType::Boolean, "t1".to_owned()).is_err());
447        assert!(CsvParser::parse_string(&DataType::Boolean, "f1".to_owned()).is_err());
448        assert!(CsvParser::parse_string(&DataType::Boolean, "false1".to_owned()).is_err());
449        assert!(CsvParser::parse_string(&DataType::Boolean, "TRUE1".to_owned()).is_err());
450    }
451}