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        }))
154    }
155}
156
157/// Incremental parser backed by arrow-csv's decoder.
158struct CsvRecordParser {
159    decoder: CsvDecoder,
160    /// Indices of Boolean columns, decoded as Utf8 and converted by
161    /// [`flush_batch`] to accept PostgreSQL's boolean spellings.
162    boolean_columns: Vec<usize>,
163}
164
165impl RecordParser for CsvRecordParser {
166    fn feed(&mut self, data: &[u8]) -> PgWireResult<Vec<ParsedRow>> {
167        let mut buf = data;
168        let mut rows = Vec::new();
169        while !buf.is_empty() {
170            let consumed = self.decoder.decode(buf).map_err(decode_error)?;
171            if consumed == 0 {
172                while let Some(batch) = self.decoder.flush().map_err(decode_error)? {
173                    rows.extend(self.flush_batch(&batch)?);
174                }
175            } else {
176                buf = &buf[consumed..];
177            }
178        }
179        Ok(rows)
180    }
181
182    fn finish(&mut self) -> PgWireResult<Vec<ParsedRow>> {
183        // An empty decode signals EOF, finalizing a trailing record that
184        // lacks its record separator.
185        self.decoder.decode(&[]).map_err(decode_error)?;
186        let mut rows = Vec::new();
187        while let Some(batch) = self.decoder.flush().map_err(decode_error)? {
188            rows.extend(self.flush_batch(&batch)?);
189        }
190        Ok(rows)
191    }
192}
193
194impl CsvRecordParser {
195    fn flush_batch(
196        &mut self,
197        batch: &arrow::record_batch::RecordBatch,
198    ) -> PgWireResult<Vec<ParsedRow>> {
199        let mut vectors = Helper::try_into_vectors(batch.columns())
200            .map_err(|e| bad_copy_data(format!("failed to convert decoded CSV batch: {e}")))?;
201        for &index in &self.boolean_columns {
202            let Some(vector) = vectors[index].as_any().downcast_ref::<StringVector>() else {
203                return Err(bad_copy_data(
204                    "expected boolean column to decode as a string vector",
205                ));
206            };
207            let mut values = Vec::with_capacity(batch.num_rows());
208            for row_index in 0..batch.num_rows() {
209                values.push(match vector.get(row_index) {
210                    datatypes::value::Value::Null => None,
211                    datatypes::value::Value::String(s) => Some(parse_pg_bool(s.as_utf8())?),
212                    other => {
213                        return Err(bad_copy_data(format!(
214                            "expected string values in a boolean column, got {other:?}"
215                        )));
216                    }
217                });
218            }
219            vectors[index] = Arc::new(BooleanVector::from(values));
220        }
221        Ok(vectors_to_rows(vectors.iter(), batch.num_rows()))
222    }
223}
224
225/// Parses PostgreSQL's boolean spellings: `true`/`false`, `t`/`f`,
226/// `yes`/`no`, `on`/`off` and `1`/`0`, case-insensitive with surrounding
227/// whitespace allowed (see the BOOLEAN type's input grammar). COPY OUT
228/// emits `t`/`f`, so accepting them keeps both COPY directions
229/// round-trippable.
230fn parse_pg_bool(input: &str) -> PgWireResult<bool> {
231    match input.trim().to_ascii_lowercase().as_str() {
232        "true" | "t" | "yes" | "y" | "on" | "1" => Ok(true),
233        "false" | "f" | "no" | "n" | "off" | "0" => Ok(false),
234        _ => Err(invalid_text_repr(format!(
235            "invalid input syntax for type boolean: \"{input}\""
236        ))),
237    }
238}
239
240fn decode_error(error: ArrowError) -> PgWireError {
241    match &error {
242        ArrowError::CsvError(message) => {
243            bad_copy_data(format!("failed to parse CSV data: {message}"))
244        }
245        ArrowError::ParseError(message) | ArrowError::CastError(message) => {
246            invalid_text_repr(format!("failed to parse CSV data: {message}"))
247        }
248        _ => bad_copy_data(format!("failed to parse CSV data: {error}")),
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use datatypes::schema::ColumnSchema;
255
256    use super::*;
257    use crate::postgres::copy_in::options::CopyOptionValue;
258
259    fn test_columns() -> Vec<ColumnSchema> {
260        vec![
261            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
262            ColumnSchema::new("val", ConcreteDataType::float64_datatype(), true),
263            ColumnSchema::new(
264                "ts",
265                ConcreteDataType::timestamp_millisecond_datatype(),
266                false,
267            ),
268        ]
269    }
270
271    fn build_codec(set: CopyOptionSet) -> CsvCodec {
272        match build_csv_codec(set).unwrap() {
273            CopyFormat::Csv(codec) => codec,
274            other => panic!("expected csv format, got {other:?}"),
275        }
276    }
277
278    fn parser() -> Box<dyn RecordParser + Send> {
279        build_codec(CopyOptionSet::default())
280            .create_parser(&test_columns(), "UTC")
281            .unwrap()
282    }
283
284    fn string_at(row: &ParsedRow, index: usize) -> Option<String> {
285        row.values[index].value_data.as_ref().map(|v| match v {
286            api::v1::value::ValueData::StringValue(s) => s.clone(),
287            other => panic!("expected string, got {other:?}"),
288        })
289    }
290
291    fn rows_with(mut set: CopyOptionSet) -> Box<dyn RecordParser + Send> {
292        set.take_format().unwrap();
293        build_codec(set)
294            .create_parser(&test_columns(), "UTC")
295            .unwrap()
296    }
297
298    /// Feeds chunks and then the EOF signal, returning all rows: with the
299    /// strict decoder protocol, feeds only emit full
300    /// `COPY_IN_FLUSH_ROWS` batches; a trailing partial batch surfaces at
301    /// `finish`.
302    fn feed_all(parser: &mut Box<dyn RecordParser + Send>, chunks: &[&[u8]]) -> Vec<ParsedRow> {
303        let mut rows = Vec::new();
304        for chunk in chunks {
305            rows.extend(parser.feed(chunk).unwrap());
306        }
307        rows.extend(parser.finish().unwrap());
308        rows
309    }
310
311    #[test]
312    fn test_build_defaults() {
313        let codec = build_codec(CopyOptionSet::default());
314        assert!(matches!(codec, CsvCodec { .. }));
315    }
316
317    #[test]
318    fn test_build_rejects_bad_options() {
319        let mut set = CopyOptionSet::default();
320        set.insert("delimiter".into(), CopyOptionValue::String("\"".into()))
321            .unwrap();
322        let err = build_csv_codec(set).unwrap_err();
323        assert!(
324            err.to_string()
325                .contains("DELIMITER must not be equal to QUOTE")
326        );
327
328        let mut set = CopyOptionSet::default();
329        set.insert("null".into(), CopyOptionValue::String("NULL".into()))
330            .unwrap();
331        assert!(
332            build_csv_codec(set)
333                .unwrap_err()
334                .to_string()
335                .contains("custom NULL string")
336        );
337
338        let mut set = CopyOptionSet::default();
339        set.take_format().unwrap();
340        set.insert("precision".into(), CopyOptionValue::Ident("ns".into()))
341            .unwrap();
342        assert!(
343            build_csv_codec(set)
344                .unwrap_err()
345                .to_string()
346                .contains("not supported by format csv")
347        );
348    }
349
350    #[test]
351    fn test_check_column_type() {
352        let codec = build_codec(CopyOptionSet::default());
353        assert!(
354            codec
355                .check_column_type(&ConcreteDataType::json_datatype())
356                .is_err()
357        );
358        assert!(
359            codec
360                .check_column_type(&ConcreteDataType::binary_datatype())
361                .is_err()
362        );
363        assert!(
364            codec
365                .check_column_type(&ConcreteDataType::string_datatype())
366                .is_ok()
367        );
368    }
369
370    #[test]
371    fn test_csv_parse_records() {
372        let mut parser = parser();
373        let rows = feed_all(
374            &mut parser,
375            &[b"host1,1.5,2023-11-14 22:13:20\n\
376                ,2.5,2023-11-14 22:13:21\n\
377                \"quoted, comma\",3.5,2023-11-14 22:13:22\n"],
378        );
379        assert_eq!(rows.len(), 3);
380        assert_eq!(string_at(&rows[0], 0), Some("host1".into()));
381        // An empty field is NULL.
382        assert_eq!(string_at(&rows[1], 0), None);
383        assert_eq!(string_at(&rows[2], 0), Some("quoted, comma".into()));
384    }
385
386    #[test]
387    fn test_csv_escaped_quotes() {
388        let mut parser = parser();
389        let rows = feed_all(
390            &mut parser,
391            &[b"\"say \"\"hi\"\"\",1.0,2023-11-14 22:13:20\n"],
392        );
393        assert_eq!(string_at(&rows[0], 0), Some("say \"hi\"".into()));
394    }
395
396    #[test]
397    fn test_csv_custom_escape() {
398        let mut set = CopyOptionSet::default();
399        set.insert("escape".into(), CopyOptionValue::String("\\".into()))
400            .unwrap();
401        let mut parser = rows_with(set);
402        let rows = feed_all(&mut parser, &[b"\"a\\\"b\",1.0,2023-11-14 22:13:20\n"]);
403        assert_eq!(string_at(&rows[0], 0), Some("a\"b".into()));
404    }
405
406    #[test]
407    fn test_csv_quoted_newline_and_chunk_boundaries() {
408        let mut parser = parser();
409        // Split inside a quoted field containing a newline, and a CRLF
410        // record separator split across chunks. No batch is full, so all
411        // feeds return nothing and both rows surface at the EOF signal.
412        assert!(parser.feed(b"\"multi").unwrap().is_empty());
413        assert!(
414            parser
415                .feed(b"line\nfield\",1.0,2023-11-14 22:13:20")
416                .unwrap()
417                .is_empty()
418        );
419        assert!(
420            parser
421                .feed(b"\r\nhost2,2.0,2023-11-14 22:13:21\n")
422                .unwrap()
423                .is_empty()
424        );
425        let rows = parser.finish().unwrap();
426        assert_eq!(rows.len(), 2);
427        assert_eq!(string_at(&rows[0], 0), Some("multiline\nfield".into()));
428        assert_eq!(string_at(&rows[1], 0), Some("host2".into()));
429    }
430
431    #[test]
432    fn test_csv_header() {
433        let mut set = CopyOptionSet::default();
434        set.insert("header".into(), CopyOptionValue::Flag).unwrap();
435        let mut parser = rows_with(set);
436        let rows = feed_all(
437            &mut parser,
438            &[b"host,val,ts\nhost1,1.0,2023-11-14 22:13:20\n"],
439        );
440        assert_eq!(rows.len(), 1);
441        assert_eq!(string_at(&rows[0], 0), Some("host1".into()));
442    }
443
444    #[test]
445    fn test_csv_trailing_record_without_newline() {
446        let mut parser = parser();
447        let fed = parser
448            .feed(b"host1,1.0,2023-11-14 22:13:20\nhost2,2.0,2023-11-14 22:13:21")
449            .unwrap();
450        // While the trailing record is pending, flush cannot emit the
451        // completed one either; both surface at the EOF signal.
452        assert!(fed.is_empty());
453        let rows = parser.finish().unwrap();
454        assert_eq!(rows.len(), 2);
455        assert_eq!(string_at(&rows[0], 0), Some("host1".into()));
456        assert_eq!(string_at(&rows[1], 0), Some("host2".into()));
457    }
458
459    #[test]
460    fn test_csv_finish_at_record_boundary() {
461        let mut parser = parser();
462        // The complete record stays buffered (no full batch); the feed
463        // emits nothing and `finish` surfaces it.
464        assert!(
465            parser
466                .feed(b"host1,1.0,2023-11-14 22:13:20\n")
467                .unwrap()
468                .is_empty()
469        );
470        let rows = parser.finish().unwrap();
471        assert_eq!(rows.len(), 1);
472        assert_eq!(string_at(&rows[0], 0), Some("host1".into()));
473    }
474
475    /// Regression test for chunk-boundary corruption: CopyData chunking is
476    /// arbitrary (records may split mid-field), and an earlier feed loop
477    /// flushed partial batches at record-boundary chunk ends, which
478    /// arrow-csv does not permit mid-stream — fields then parse
479    /// ("00001h,ost-001u,..."). Feed the same payload at many chunk sizes
480    /// and verify EVERY cell.
481    #[test]
482    fn test_csv_chunked_feeds_are_alignment_safe() {
483        // (int32 id, timestamp) rows of near-equal length.
484        let sweep_columns = vec![
485            ColumnSchema::new("i", ConcreteDataType::int32_datatype(), true),
486            ColumnSchema::new(
487                "ts",
488                ConcreteDataType::timestamp_millisecond_datatype(),
489                false,
490            ),
491        ];
492        // A payload wider than one decoder batch so batch-full flushes
493        // interleave with chunk boundaries too.
494        let total = 2 * COPY_IN_FLUSH_ROWS + 137;
495        let payload: Vec<u8> = (0..total)
496            .map(|i| {
497                format!(
498                    "{:06},2024-01-01 00:00:{:02}.{:03}\n",
499                    i,
500                    (i / 1000) % 60,
501                    i % 1000
502                )
503            })
504            .collect::<String>()
505            .into_bytes();
506
507        let check = |chunk: usize| {
508            let mut parser = build_codec(CopyOptionSet::default())
509                .create_parser(&sweep_columns, "UTC")
510                .unwrap();
511            let mut ids: Vec<i32> = Vec::new();
512            for c in payload.chunks(chunk) {
513                for row in parser.feed(c).unwrap() {
514                    ids.push(match row.values[0].value_data.as_ref().unwrap() {
515                        api::v1::value::ValueData::I32Value(v) => *v,
516                        other => panic!("expected i32, got {other:?}"),
517                    });
518                }
519            }
520            for row in parser.finish().unwrap() {
521                ids.push(match row.values[0].value_data.as_ref().unwrap() {
522                    api::v1::value::ValueData::I32Value(v) => *v,
523                    other => panic!("expected i32, got {other:?}"),
524                });
525            }
526            assert_eq!(ids.len(), total, "chunk={chunk}");
527            for (i, v) in ids.iter().enumerate() {
528                assert_eq!(*v, i as i32, "chunk={chunk} row {i} corrupted");
529            }
530        };
531
532        // Small chunk sizes hit every possible boundary alignment,
533        // including multiple decode calls per record.
534        for chunk in [1usize, 2, 3, 7, 8, 13, 31, 64, 97, 128, 1024] {
535            check(chunk);
536        }
537        // Client-natural sizes with a shifted start to vary where
538        // boundaries land relative to records.
539        for chunk in [4096usize, 8192, 65531] {
540            check(chunk);
541            let mut shifted = payload.clone();
542            shifted.drain(..37);
543            let mut parser = build_codec(CopyOptionSet::default())
544                .create_parser(&sweep_columns, "UTC")
545                .unwrap();
546            let mut count = 0usize;
547            for c in shifted.chunks(chunk) {
548                count += parser.feed(c).unwrap().len();
549            }
550            count += parser.finish().unwrap().len();
551            assert_eq!(count, total - 1, "chunk={chunk} shifted");
552        }
553    }
554
555    #[test]
556    fn test_csv_boolean_spellings() {
557        // PostgreSQL COPY OUT emits `t`/`f`; COPY IN accepts the full
558        // boolean input grammar.
559        let columns = vec![
560            ColumnSchema::new("flag", ConcreteDataType::boolean_datatype(), true),
561            ColumnSchema::new(
562                "ts",
563                ConcreteDataType::timestamp_millisecond_datatype(),
564                false,
565            ),
566        ];
567        let mut parser = build_codec(CopyOptionSet::default())
568            .create_parser(&columns, "UTC")
569            .unwrap();
570        let rows = feed_all(
571            &mut parser,
572            &[b"t,2024-01-01 00:00:00\n\
573                 f,2024-01-01 00:00:01\n\
574                 TRUE,2024-01-01 00:00:02\n\
575                 no,2024-01-01 00:00:03\n\
576                 on,2024-01-01 00:00:04\n\
577                 0,2024-01-01 00:00:05\n\
578                 ,2024-01-01 00:00:06\n"],
579        );
580        let expected = [
581            Some(true),
582            Some(false),
583            Some(true),
584            Some(false),
585            Some(true),
586            Some(false),
587            None,
588        ];
589        for (row, want) in rows.iter().zip(expected) {
590            assert_eq!(
591                row.values[0].value_data,
592                want.map(api::v1::value::ValueData::BoolValue),
593                "{:?}",
594                row.values[0].value_data
595            );
596        }
597    }
598
599    #[test]
600    fn test_csv_boolean_rejects_garbage() {
601        let columns = vec![
602            ColumnSchema::new("flag", ConcreteDataType::boolean_datatype(), true),
603            ColumnSchema::new(
604                "ts",
605                ConcreteDataType::timestamp_millisecond_datatype(),
606                false,
607            ),
608        ];
609        let mut parser = build_codec(CopyOptionSet::default())
610            .create_parser(&columns, "UTC")
611            .unwrap();
612        parser.feed(b"maybe,2024-01-01 00:00:00\n").unwrap();
613        let err = match parser.finish() {
614            Ok(_) => panic!("expected parse error"),
615            Err(e) => e,
616        };
617        assert!(
618            err.to_string()
619                .contains("invalid input syntax for type boolean"),
620            "{err}"
621        );
622    }
623
624    #[test]
625    fn test_csv_timestamp_session_timezone() {
626        // Offset-free timestamp strings must parse in the session
627        // timezone (parity with SQL INSERT); explicit offsets win.
628        let columns = vec![
629            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
630            ColumnSchema::new(
631                "ts",
632                ConcreteDataType::timestamp_millisecond_datatype(),
633                false,
634            ),
635        ];
636        let mut parser = build_codec(CopyOptionSet::default())
637            .create_parser(&columns, "Asia/Shanghai")
638            .unwrap();
639        let rows = feed_all(
640            &mut parser,
641            &[b"host1,2024-01-01 00:00:00\n\
642                host2,2024-01-01T00:00:00+08:00\n\
643                host3,2024-01-01T00:00:00Z\n"],
644        );
645        let millis = |row: &ParsedRow| match row.values[1].value_data.as_ref().unwrap() {
646            api::v1::value::ValueData::TimestampMillisecondValue(v) => *v,
647            other => panic!("expected ts, got {other:?}"),
648        };
649        // 2024-01-01T00:00:00+08:00 == 2023-12-31T16:00:00Z
650        assert_eq!(millis(&rows[0]), 1704038400000);
651        // Explicit +08:00 offset: same instant as the naive parse.
652        assert_eq!(millis(&rows[1]), 1704038400000);
653        // Explicit Z: parsed as UTC regardless of the session zone.
654        assert_eq!(millis(&rows[2]), 1704067200000);
655    }
656
657    #[test]
658    fn test_csv_errors() {
659        let mut p = parser();
660        let err = match p.feed(b"host1,1.0\n") {
661            Ok(_) => panic!("expected parse error"),
662            Err(e) => e,
663        };
664        assert!(
665            err.to_string().contains("incorrect number of fields"),
666            "{err}"
667        );
668
669        // Value conversion runs at flush time, so the bad double
670        // surfaces at the EOF signal, not at feed time.
671        let mut p = parser();
672        p.feed(b"host1,not_a_double,2023-11-14 22:13:20\n").unwrap();
673        let err = match p.finish() {
674            Ok(_) => panic!("expected parse error"),
675            Err(e) => e,
676        };
677        assert!(err.to_string().contains("failed to parse"), "{err}");
678    }
679}