Skip to main content

servers/postgres/copy_in/
csv.rs

1// Copyright 2023 Greptime Team
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
15//! The `csv` format — currently the only implemented COPY FROM STDIN
16//! format.
17//!
18//! Parsing and typed conversion both reuse arrow-csv's incremental
19//! [`Decoder`](arrow::csv::reader::Decoder) — the same engine backing
20//! GreptimeDB's file-based `COPY ... FROM 'file.csv'` (see
21//! `common-datasource`'s `csv` file format) — so both COPY routes accept
22//! identical data. The decoder splits records (quoting, escaped quotes,
23//! custom delimiters, `\n`/`\r\n` separators, optional headers) and
24//! converts fields against the targeted columns' schema in one pass.
25//!
26//! Consequences of sharing the engine: JSON and Binary columns are
27//! rejected, timestamps must be date/time strings (offset-free ones
28//! parse in the session timezone), and an empty field — quoted or not —
29//! is NULL, exactly like file-based COPY.
30
31use std::sync::Arc;
32
33use api::helper::vectors_to_rows;
34use arrow::csv::ReaderBuilder;
35use arrow::csv::reader::Decoder as CsvDecoder;
36use arrow_schema::{ArrowError, DataType as ArrowDataType, Field, Schema as ArrowSchema};
37use datatypes::prelude::ConcreteDataType;
38use datatypes::schema::{ColumnSchema, Schema as GreptimeSchema};
39use datatypes::vectors::{BooleanVector, Helper, StringVector, Vector};
40use pgwire::error::{PgWireError, PgWireResult};
41
42use crate::postgres::copy_in::codec::{
43    CopyFormat, ParsedRow, RecordParser, TableBoundCodec, check_arrow_column_type,
44};
45use crate::postgres::copy_in::options::CopyOptionSet;
46use crate::postgres::copy_in::{COPY_IN_FLUSH_ROWS, bad_copy_data, invalid_text_repr, unsupported};
47
48/// The validated `csv` format configuration.
49#[derive(Debug, Clone)]
50pub(super) struct CsvCodec {
51    delimiter: u8,
52    quote: u8,
53    escape: u8,
54    header: bool,
55}
56
57/// Builds the CSV codec from the parsed options.
58pub(super) fn build_csv_codec(mut options: CopyOptionSet) -> PgWireResult<CopyFormat> {
59    let delimiter = options.take_single_byte("DELIMITER")?.unwrap_or(b',');
60    let quote = options.take_single_byte("QUOTE")?.unwrap_or(b'"');
61    // In PostgreSQL the default escape character for CSV is the quote
62    // character itself (doubled quotes inside quoted fields).
63    let escape = options.take_single_byte("ESCAPE")?.unwrap_or(quote);
64    // An empty string is the default NULL marker (an empty field is NULL);
65    // a custom NULL string is not supported because arrow-csv's null
66    // matching does not distinguish quoted from unquoted fields.
67    if let Some(null) = options.take_string("NULL")?
68        && !null.is_empty()
69    {
70        return Err(unsupported(
71            "custom NULL string is not supported by format csv; an empty field is NULL",
72        ));
73    }
74    let header = options.take_flag("HEADER")?.unwrap_or(false);
75    options.reject_leftovers("csv")?;
76    if delimiter == quote {
77        return Err(bad_copy_data("DELIMITER must not be equal to QUOTE"));
78    }
79    Ok(CopyFormat::Csv(CsvCodec {
80        delimiter,
81        quote,
82        escape,
83        header,
84    }))
85}
86
87impl TableBoundCodec for CsvCodec {
88    fn name(&self) -> &'static str {
89        "csv"
90    }
91
92    fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()> {
93        check_arrow_column_type(data_type, "csv")
94    }
95
96    fn create_parser(
97        &self,
98        columns: &[ColumnSchema],
99        timezone: &str,
100    ) -> PgWireResult<Box<dyn RecordParser + Send>> {
101        // Decode schema: the greptime schema's arrow projection, except
102        // Boolean columns decode as Utf8 — arrow-csv only accepts
103        // `true`/`false`, while PostgreSQL COPY IN accepts its full set
104        // of boolean spellings (`t`, `f`, `yes`, `on`, ...), which COPY
105        // OUT emits — and Timestamp fields carry the SESSION timezone so
106        // offset-free strings parse like SQL INSERT does instead of as
107        // UTC. The substitutions are applied in `flush_batch` and by the
108        // decoder's tz-aware parsing respectively; explicit offsets in
109        // the input always win.
110        let boolean_columns: Vec<usize> = columns
111            .iter()
112            .enumerate()
113            .filter(|(_, c)| matches!(c.data_type, ConcreteDataType::Boolean(_)))
114            .map(|(i, _)| i)
115            .collect();
116        let arrow_schema = GreptimeSchema::try_new(columns.to_vec())
117            .map_err(|e| unsupported(format!("invalid columns for format csv: {e}")))?
118            .arrow_schema()
119            .clone();
120        let timezone = timezone.to_string();
121        let fields = arrow_schema
122            .fields()
123            .iter()
124            .zip(columns)
125            .map(|(field, column)| match &column.data_type {
126                ConcreteDataType::Boolean(_) => {
127                    Field::new(field.name(), ArrowDataType::Utf8, field.is_nullable())
128                }
129                ConcreteDataType::Timestamp(_) => match field.data_type() {
130                    ArrowDataType::Timestamp(unit, None) => Field::new(
131                        field.name(),
132                        ArrowDataType::Timestamp(*unit, Some(Arc::from(timezone.as_str()))),
133                        field.is_nullable(),
134                    ),
135                    _ => field.as_ref().clone(),
136                },
137                _ => field.as_ref().clone(),
138            })
139            .collect::<Vec<_>>();
140        let mut builder = ReaderBuilder::new(Arc::new(ArrowSchema::new(fields)))
141            .with_header(self.header)
142            .with_delimiter(self.delimiter)
143            .with_quote(self.quote)
144            .with_batch_size(COPY_IN_FLUSH_ROWS);
145        // An escape character equal to the quote is the doubled-quote
146        // default; csv-core handles that through quoting alone.
147        if self.escape != self.quote {
148            builder = builder.with_escape(self.escape);
149        }
150        Ok(Box::new(CsvRecordParser {
151            decoder: builder.build_decoder(),
152            boolean_columns,
153            format: self.clone(),
154            position: CsvPosition::StartOfFile,
155        }))
156    }
157}
158
159/// Incremental parser backed by arrow-csv's decoder.
160struct CsvRecordParser {
161    decoder: CsvDecoder,
162    format: CsvCodec,
163    position: CsvPosition,
164    /// Indices of Boolean columns, decoded as Utf8 and converted by
165    /// [`flush_batch`] to accept PostgreSQL's boolean spellings.
166    boolean_columns: Vec<usize>,
167}
168
169/// Tracks just enough csv-core syntax to recognize CR/LF *between* records.
170/// The first terminator after a field is charged conservatively, as are empty
171/// fields and all bytes inside quotes. Arrow remains responsible for parsing.
172#[derive(Clone, Copy)]
173enum CsvPosition {
174    StartOfFile,
175    RecordStart,
176    FieldStart,
177    Unquoted,
178    Quoted,
179    AfterQuote,
180    Escaped,
181}
182
183impl CsvPosition {
184    fn prefix(&mut self, data: &[u8], budget: usize, format: &CsvCodec) -> (usize, usize) {
185        let mut start = 0;
186        if matches!(self, Self::StartOfFile) {
187            *self = Self::RecordStart;
188            // csv-core strips a BOM only if present in full on its first read.
189            if budget >= 3 && data.starts_with(b"\xef\xbb\xbf") {
190                start = 3;
191            }
192        }
193        let mut charged = start;
194        for (i, &byte) in data.iter().enumerate().skip(start) {
195            let newline = matches!(byte, b'\r' | b'\n');
196            if matches!(self, Self::RecordStart) && newline {
197                continue;
198            }
199            if charged == budget {
200                return (i, charged);
201            }
202            charged += 1;
203            *self = match *self {
204                Self::Quoted if byte == format.quote => Self::AfterQuote,
205                Self::Quoted if byte == format.escape => Self::Escaped,
206                Self::Quoted | Self::Escaped => Self::Quoted,
207                Self::RecordStart | Self::FieldStart | Self::AfterQuote if byte == format.quote => {
208                    Self::Quoted
209                }
210                _ if byte == format.delimiter => Self::FieldStart,
211                _ if newline => Self::RecordStart,
212                _ => Self::Unquoted,
213            };
214        }
215        (data.len(), charged)
216    }
217}
218
219impl RecordParser for CsvRecordParser {
220    fn plan_input(&self, data: &[u8], budget: usize) -> (usize, usize) {
221        let mut preview = self.position;
222        preview.prefix(data, budget, &self.format)
223    }
224
225    fn decode(&mut self, data: &[u8]) -> PgWireResult<(usize, usize)> {
226        let consumed = self.decoder.decode(data).map_err(decode_error)?;
227        Ok(self
228            .position
229            .prefix(&data[..consumed], usize::MAX, &self.format))
230    }
231
232    fn is_full(&self) -> bool {
233        self.decoder.capacity() == 0
234    }
235
236    fn flush(&mut self) -> PgWireResult<Vec<ParsedRow>> {
237        match self.decoder.flush().map_err(decode_error)? {
238            Some(batch) => self.flush_batch(&batch),
239            None => Ok(Vec::new()),
240        }
241    }
242}
243
244impl CsvRecordParser {
245    fn flush_batch(
246        &mut self,
247        batch: &arrow::record_batch::RecordBatch,
248    ) -> PgWireResult<Vec<ParsedRow>> {
249        let mut vectors = Helper::try_into_vectors(batch.columns())
250            .map_err(|e| bad_copy_data(format!("failed to convert decoded CSV batch: {e}")))?;
251        for &index in &self.boolean_columns {
252            let Some(vector) = vectors[index].as_any().downcast_ref::<StringVector>() else {
253                return Err(bad_copy_data(
254                    "expected boolean column to decode as a string vector",
255                ));
256            };
257            let mut values = Vec::with_capacity(batch.num_rows());
258            for row_index in 0..batch.num_rows() {
259                values.push(match vector.get(row_index) {
260                    datatypes::value::Value::Null => None,
261                    datatypes::value::Value::String(s) => Some(parse_pg_bool(s.as_utf8())?),
262                    other => {
263                        return Err(bad_copy_data(format!(
264                            "expected string values in a boolean column, got {other:?}"
265                        )));
266                    }
267                });
268            }
269            vectors[index] = Arc::new(BooleanVector::from(values));
270        }
271        Ok(vectors_to_rows(vectors.iter(), batch.num_rows()))
272    }
273}
274
275/// Parses PostgreSQL's boolean spellings: `true`/`false`, `t`/`f`,
276/// `yes`/`no`, `on`/`off` and `1`/`0`, case-insensitive with surrounding
277/// whitespace allowed (see the BOOLEAN type's input grammar). COPY OUT
278/// emits `t`/`f`, so accepting them keeps both COPY directions
279/// round-trippable.
280fn parse_pg_bool(input: &str) -> PgWireResult<bool> {
281    match input.trim().to_ascii_lowercase().as_str() {
282        "true" | "t" | "yes" | "y" | "on" | "1" => Ok(true),
283        "false" | "f" | "no" | "n" | "off" | "0" => Ok(false),
284        _ => Err(invalid_text_repr(format!(
285            "invalid input syntax for type boolean: \"{input}\""
286        ))),
287    }
288}
289
290fn decode_error(error: ArrowError) -> PgWireError {
291    match &error {
292        ArrowError::CsvError(message) => {
293            bad_copy_data(format!("failed to parse CSV data: {message}"))
294        }
295        ArrowError::ParseError(message) | ArrowError::CastError(message) => {
296            invalid_text_repr(format!("failed to parse CSV data: {message}"))
297        }
298        _ => bad_copy_data(format!("failed to parse CSV data: {error}")),
299    }
300}
301
302#[cfg(test)]
303mod tests {
304    use datatypes::schema::ColumnSchema;
305
306    use super::*;
307    use crate::postgres::copy_in::options::CopyOptionValue;
308
309    fn test_columns() -> Vec<ColumnSchema> {
310        vec![
311            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
312            ColumnSchema::new("val", ConcreteDataType::float64_datatype(), true),
313            ColumnSchema::new(
314                "ts",
315                ConcreteDataType::timestamp_millisecond_datatype(),
316                false,
317            ),
318        ]
319    }
320
321    fn build_codec(set: CopyOptionSet) -> CsvCodec {
322        match build_csv_codec(set).unwrap() {
323            CopyFormat::Csv(codec) => codec,
324            other => panic!("expected csv format, got {other:?}"),
325        }
326    }
327
328    fn parser() -> Box<dyn RecordParser + Send> {
329        build_codec(CopyOptionSet::default())
330            .create_parser(&test_columns(), "UTC")
331            .unwrap()
332    }
333
334    fn string_at(row: &ParsedRow, index: usize) -> Option<String> {
335        row.values[index].value_data.as_ref().map(|v| match v {
336            api::v1::value::ValueData::StringValue(s) => s.clone(),
337            other => panic!("expected string, got {other:?}"),
338        })
339    }
340
341    fn rows_with(mut set: CopyOptionSet) -> Box<dyn RecordParser + Send> {
342        set.take_format().unwrap();
343        build_codec(set)
344            .create_parser(&test_columns(), "UTC")
345            .unwrap()
346    }
347
348    /// Feeds chunks and then the EOF signal, returning all rows: with the
349    /// strict decoder protocol, feeds only emit full
350    /// `COPY_IN_FLUSH_ROWS` batches; a trailing partial batch surfaces at
351    /// `finish`.
352    fn feed_all(parser: &mut Box<dyn RecordParser + Send>, chunks: &[&[u8]]) -> Vec<ParsedRow> {
353        let mut rows = Vec::new();
354        for chunk in chunks {
355            rows.extend(parser.feed(chunk).unwrap());
356        }
357        rows.extend(parser.finish().unwrap());
358        rows
359    }
360
361    #[test]
362    fn test_csv_blank_lines_and_quoted_newlines_accounting() {
363        let codec = CsvCodec {
364            delimiter: b'|',
365            quote: b'\'',
366            escape: b'\\',
367            header: false,
368        };
369        let columns = ["a", "b"]
370            .map(|name| ColumnSchema::new(name, ConcreteDataType::string_datatype(), true));
371        // Escaped and doubled quotes do not end a field. A quote in an
372        // unquoted field does not start one. An empty field is not a blank line.
373        let record = b"|'a\\'\n\r\n''b'\r";
374        let empty = b"un'quoted|\n";
375        let blanks = b"\n\r\n\n";
376        let data = [blanks.as_slice(), record, blanks, empty, blanks].concat();
377        for chunk_size in 1..=data.len() {
378            let mut parser = codec.create_parser(&columns, "UTC").unwrap();
379            let mut total = 0;
380            for mut chunk in data.chunks(chunk_size) {
381                while !chunk.is_empty() {
382                    let (len, charge) = parser.plan_input(chunk, 3);
383                    assert!(len > 0 && charge <= 3);
384                    assert_eq!(parser.decode(&chunk[..len]).unwrap(), (len, charge));
385                    total += charge;
386                    chunk = &chunk[len..];
387                }
388            }
389            assert_eq!(total, record.len() + empty.len());
390            let rows = parser.finish().unwrap();
391            assert_eq!(rows.len(), 2);
392            assert_eq!(string_at(&rows[0], 1).as_deref(), Some("a'\n\r\n'b"));
393        }
394    }
395
396    #[test]
397    fn test_build_defaults() {
398        let codec = build_codec(CopyOptionSet::default());
399        assert!(matches!(codec, CsvCodec { .. }));
400    }
401
402    #[test]
403    fn test_build_rejects_bad_options() {
404        let mut set = CopyOptionSet::default();
405        set.insert("delimiter".into(), CopyOptionValue::String("\"".into()))
406            .unwrap();
407        let err = build_csv_codec(set).unwrap_err();
408        assert!(
409            err.to_string()
410                .contains("DELIMITER must not be equal to QUOTE")
411        );
412
413        let mut set = CopyOptionSet::default();
414        set.insert("null".into(), CopyOptionValue::String("NULL".into()))
415            .unwrap();
416        assert!(
417            build_csv_codec(set)
418                .unwrap_err()
419                .to_string()
420                .contains("custom NULL string")
421        );
422
423        let mut set = CopyOptionSet::default();
424        set.take_format().unwrap();
425        set.insert("precision".into(), CopyOptionValue::Ident("ns".into()))
426            .unwrap();
427        assert!(
428            build_csv_codec(set)
429                .unwrap_err()
430                .to_string()
431                .contains("not supported by format csv")
432        );
433    }
434
435    #[test]
436    fn test_check_column_type() {
437        let codec = build_codec(CopyOptionSet::default());
438        assert!(
439            codec
440                .check_column_type(&ConcreteDataType::json_datatype())
441                .is_err()
442        );
443        assert!(
444            codec
445                .check_column_type(&ConcreteDataType::binary_datatype())
446                .is_err()
447        );
448        assert!(
449            codec
450                .check_column_type(&ConcreteDataType::string_datatype())
451                .is_ok()
452        );
453    }
454
455    #[test]
456    fn test_csv_parse_records() {
457        let mut parser = parser();
458        let rows = feed_all(
459            &mut parser,
460            &[b"host1,1.5,2023-11-14 22:13:20\n\
461                ,2.5,2023-11-14 22:13:21\n\
462                \"quoted, comma\",3.5,2023-11-14 22:13:22\n"],
463        );
464        assert_eq!(rows.len(), 3);
465        assert_eq!(string_at(&rows[0], 0), Some("host1".into()));
466        // An empty field is NULL.
467        assert_eq!(string_at(&rows[1], 0), None);
468        assert_eq!(string_at(&rows[2], 0), Some("quoted, comma".into()));
469    }
470
471    #[test]
472    fn test_csv_escaped_quotes() {
473        let mut parser = parser();
474        let rows = feed_all(
475            &mut parser,
476            &[b"\"say \"\"hi\"\"\",1.0,2023-11-14 22:13:20\n"],
477        );
478        assert_eq!(string_at(&rows[0], 0), Some("say \"hi\"".into()));
479    }
480
481    #[test]
482    fn test_csv_custom_escape() {
483        let mut set = CopyOptionSet::default();
484        set.insert("escape".into(), CopyOptionValue::String("\\".into()))
485            .unwrap();
486        let mut parser = rows_with(set);
487        let rows = feed_all(&mut parser, &[b"\"a\\\"b\",1.0,2023-11-14 22:13:20\n"]);
488        assert_eq!(string_at(&rows[0], 0), Some("a\"b".into()));
489    }
490
491    #[test]
492    fn test_csv_quoted_newline_and_chunk_boundaries() {
493        let mut parser = parser();
494        // Split inside a quoted field containing a newline, and a CRLF
495        // record separator split across chunks. No batch is full, so all
496        // feeds return nothing and both rows surface at the EOF signal.
497        assert!(parser.feed(b"\"multi").unwrap().is_empty());
498        assert!(
499            parser
500                .feed(b"line\nfield\",1.0,2023-11-14 22:13:20")
501                .unwrap()
502                .is_empty()
503        );
504        assert!(
505            parser
506                .feed(b"\r\nhost2,2.0,2023-11-14 22:13:21\n")
507                .unwrap()
508                .is_empty()
509        );
510        let rows = parser.finish().unwrap();
511        assert_eq!(rows.len(), 2);
512        assert_eq!(string_at(&rows[0], 0), Some("multiline\nfield".into()));
513        assert_eq!(string_at(&rows[1], 0), Some("host2".into()));
514    }
515
516    #[test]
517    fn test_csv_header() {
518        let mut set = CopyOptionSet::default();
519        set.insert("header".into(), CopyOptionValue::Flag).unwrap();
520        let mut parser = rows_with(set);
521        let rows = feed_all(
522            &mut parser,
523            &[b"host,val,ts\nhost1,1.0,2023-11-14 22:13:20\n"],
524        );
525        assert_eq!(rows.len(), 1);
526        assert_eq!(string_at(&rows[0], 0), Some("host1".into()));
527    }
528
529    #[test]
530    fn test_csv_trailing_record_without_newline() {
531        let mut parser = parser();
532        let fed = parser
533            .feed(b"host1,1.0,2023-11-14 22:13:20\nhost2,2.0,2023-11-14 22:13:21")
534            .unwrap();
535        // While the trailing record is pending, flush cannot emit the
536        // completed one either; both surface at the EOF signal.
537        assert!(fed.is_empty());
538        let rows = parser.finish().unwrap();
539        assert_eq!(rows.len(), 2);
540        assert_eq!(string_at(&rows[0], 0), Some("host1".into()));
541        assert_eq!(string_at(&rows[1], 0), Some("host2".into()));
542    }
543
544    #[test]
545    fn test_csv_finish_at_record_boundary() {
546        let mut parser = parser();
547        // The complete record stays buffered (no full batch); the feed
548        // emits nothing and `finish` surfaces it.
549        assert!(
550            parser
551                .feed(b"host1,1.0,2023-11-14 22:13:20\n")
552                .unwrap()
553                .is_empty()
554        );
555        let rows = parser.finish().unwrap();
556        assert_eq!(rows.len(), 1);
557        assert_eq!(string_at(&rows[0], 0), Some("host1".into()));
558    }
559
560    /// Regression test for chunk-boundary corruption: CopyData chunking is
561    /// arbitrary (records may split mid-field), and an earlier feed loop
562    /// flushed partial batches at record-boundary chunk ends, which
563    /// arrow-csv does not permit mid-stream — fields then parse
564    /// ("00001h,ost-001u,..."). Feed the same payload at many chunk sizes
565    /// and verify EVERY cell.
566    #[test]
567    fn test_csv_chunked_feeds_are_alignment_safe() {
568        // (int32 id, timestamp) rows of near-equal length.
569        let sweep_columns = vec![
570            ColumnSchema::new("i", ConcreteDataType::int32_datatype(), true),
571            ColumnSchema::new(
572                "ts",
573                ConcreteDataType::timestamp_millisecond_datatype(),
574                false,
575            ),
576        ];
577        // A payload wider than one decoder batch so batch-full flushes
578        // interleave with chunk boundaries too.
579        let total = 2 * COPY_IN_FLUSH_ROWS + 137;
580        let payload: Vec<u8> = (0..total)
581            .map(|i| {
582                format!(
583                    "{:06},2024-01-01 00:00:{:02}.{:03}\n",
584                    i,
585                    (i / 1000) % 60,
586                    i % 1000
587                )
588            })
589            .collect::<String>()
590            .into_bytes();
591
592        let check = |chunk: usize| {
593            let mut parser = build_codec(CopyOptionSet::default())
594                .create_parser(&sweep_columns, "UTC")
595                .unwrap();
596            let mut ids: Vec<i32> = Vec::new();
597            for c in payload.chunks(chunk) {
598                for row in parser.feed(c).unwrap() {
599                    ids.push(match row.values[0].value_data.as_ref().unwrap() {
600                        api::v1::value::ValueData::I32Value(v) => *v,
601                        other => panic!("expected i32, got {other:?}"),
602                    });
603                }
604            }
605            for row in parser.finish().unwrap() {
606                ids.push(match row.values[0].value_data.as_ref().unwrap() {
607                    api::v1::value::ValueData::I32Value(v) => *v,
608                    other => panic!("expected i32, got {other:?}"),
609                });
610            }
611            assert_eq!(ids.len(), total, "chunk={chunk}");
612            for (i, v) in ids.iter().enumerate() {
613                assert_eq!(*v, i as i32, "chunk={chunk} row {i} corrupted");
614            }
615        };
616
617        // Small chunk sizes hit every possible boundary alignment,
618        // including multiple decode calls per record.
619        for chunk in [1usize, 2, 3, 7, 8, 13, 31, 64, 97, 128, 1024] {
620            check(chunk);
621        }
622        // Client-natural sizes with a shifted start to vary where
623        // boundaries land relative to records.
624        for chunk in [4096usize, 8192, 65531] {
625            check(chunk);
626            let mut shifted = payload.clone();
627            shifted.drain(..37);
628            let mut parser = build_codec(CopyOptionSet::default())
629                .create_parser(&sweep_columns, "UTC")
630                .unwrap();
631            let mut count = 0usize;
632            for c in shifted.chunks(chunk) {
633                count += parser.feed(c).unwrap().len();
634            }
635            count += parser.finish().unwrap().len();
636            assert_eq!(count, total - 1, "chunk={chunk} shifted");
637        }
638    }
639
640    #[test]
641    fn test_csv_boolean_spellings() {
642        // PostgreSQL COPY OUT emits `t`/`f`; COPY IN accepts the full
643        // boolean input grammar.
644        let columns = vec![
645            ColumnSchema::new("flag", ConcreteDataType::boolean_datatype(), true),
646            ColumnSchema::new(
647                "ts",
648                ConcreteDataType::timestamp_millisecond_datatype(),
649                false,
650            ),
651        ];
652        let mut parser = build_codec(CopyOptionSet::default())
653            .create_parser(&columns, "UTC")
654            .unwrap();
655        let rows = feed_all(
656            &mut parser,
657            &[b"t,2024-01-01 00:00:00\n\
658                 f,2024-01-01 00:00:01\n\
659                 TRUE,2024-01-01 00:00:02\n\
660                 no,2024-01-01 00:00:03\n\
661                 on,2024-01-01 00:00:04\n\
662                 0,2024-01-01 00:00:05\n\
663                 ,2024-01-01 00:00:06\n"],
664        );
665        let expected = [
666            Some(true),
667            Some(false),
668            Some(true),
669            Some(false),
670            Some(true),
671            Some(false),
672            None,
673        ];
674        for (row, want) in rows.iter().zip(expected) {
675            assert_eq!(
676                row.values[0].value_data,
677                want.map(api::v1::value::ValueData::BoolValue),
678                "{:?}",
679                row.values[0].value_data
680            );
681        }
682    }
683
684    #[test]
685    fn test_csv_boolean_rejects_garbage() {
686        let columns = vec![
687            ColumnSchema::new("flag", ConcreteDataType::boolean_datatype(), true),
688            ColumnSchema::new(
689                "ts",
690                ConcreteDataType::timestamp_millisecond_datatype(),
691                false,
692            ),
693        ];
694        let mut parser = build_codec(CopyOptionSet::default())
695            .create_parser(&columns, "UTC")
696            .unwrap();
697        parser.feed(b"maybe,2024-01-01 00:00:00\n").unwrap();
698        let err = match parser.finish() {
699            Ok(_) => panic!("expected parse error"),
700            Err(e) => e,
701        };
702        assert!(
703            err.to_string()
704                .contains("invalid input syntax for type boolean"),
705            "{err}"
706        );
707    }
708
709    #[test]
710    fn test_csv_timestamp_session_timezone() {
711        // Offset-free timestamp strings must parse in the session
712        // timezone (parity with SQL INSERT); explicit offsets win.
713        let columns = vec![
714            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
715            ColumnSchema::new(
716                "ts",
717                ConcreteDataType::timestamp_millisecond_datatype(),
718                false,
719            ),
720        ];
721        let mut parser = build_codec(CopyOptionSet::default())
722            .create_parser(&columns, "Asia/Shanghai")
723            .unwrap();
724        let rows = feed_all(
725            &mut parser,
726            &[b"host1,2024-01-01 00:00:00\n\
727                host2,2024-01-01T00:00:00+08:00\n\
728                host3,2024-01-01T00:00:00Z\n"],
729        );
730        let millis = |row: &ParsedRow| match row.values[1].value_data.as_ref().unwrap() {
731            api::v1::value::ValueData::TimestampMillisecondValue(v) => *v,
732            other => panic!("expected ts, got {other:?}"),
733        };
734        // 2024-01-01T00:00:00+08:00 == 2023-12-31T16:00:00Z
735        assert_eq!(millis(&rows[0]), 1704038400000);
736        // Explicit +08:00 offset: same instant as the naive parse.
737        assert_eq!(millis(&rows[1]), 1704038400000);
738        // Explicit Z: parsed as UTC regardless of the session zone.
739        assert_eq!(millis(&rows[2]), 1704067200000);
740    }
741
742    #[test]
743    fn test_csv_errors() {
744        let mut p = parser();
745        let err = match p.feed(b"host1,1.0\n") {
746            Ok(_) => panic!("expected parse error"),
747            Err(e) => e,
748        };
749        assert!(
750            err.to_string().contains("incorrect number of fields"),
751            "{err}"
752        );
753
754        // Value conversion runs at flush time, so the bad double
755        // surfaces at the EOF signal, not at feed time.
756        let mut p = parser();
757        p.feed(b"host1,not_a_double,2023-11-14 22:13:20\n").unwrap();
758        let err = match p.finish() {
759            Ok(_) => panic!("expected parse error"),
760            Err(e) => e,
761        };
762        assert!(err.to_string().contains("failed to parse"), "{err}");
763    }
764}