Skip to main content

mz_pgcopy/
copy.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::borrow::Cow;
11use std::io;
12
13use bytes::BytesMut;
14use itertools::Itertools;
15use mz_pgrepr::TextEncodeSettings;
16use mz_repr::{
17    Datum, RelationDesc, Row, RowArena, RowRef, SharedRow, SqlColumnType, SqlRelationType,
18    SqlScalarType,
19};
20use proptest::prelude::{Arbitrary, any};
21use proptest::strategy::{BoxedStrategy, Strategy};
22use serde::{Deserialize, Serialize};
23
24static END_OF_COPY_MARKER: &[u8] = b"\\.";
25
26fn encode_copy_row_binary(
27    row: &RowRef,
28    typ: &SqlRelationType,
29    out: &mut Vec<u8>,
30) -> Result<(), io::Error> {
31    const NULL_BYTES: [u8; 4] = (-1i32).to_be_bytes();
32
33    // 16-bit int of number of tuples.
34    let count = i16::try_from(typ.column_types.len()).map_err(|_| {
35        io::Error::new(
36            io::ErrorKind::InvalidData,
37            "column count does not fit into an i16",
38        )
39    })?;
40
41    out.extend(count.to_be_bytes());
42    let mut buf = BytesMut::new();
43    for (field, typ) in row
44        .iter()
45        .zip_eq(&typ.column_types)
46        .map(|(datum, typ)| (mz_pgrepr::Value::from_datum(datum, &typ.scalar_type), typ))
47    {
48        match field {
49            None => out.extend(NULL_BYTES),
50            Some(field) => {
51                buf.clear();
52                field.encode_binary(&mz_pgrepr::Type::from(&typ.scalar_type), &mut buf)?;
53                out.extend(
54                    i32::try_from(buf.len())
55                        .map_err(|_| {
56                            io::Error::new(
57                                io::ErrorKind::InvalidData,
58                                "field length does not fit into an i32",
59                            )
60                        })?
61                        .to_be_bytes(),
62                );
63                out.extend(&buf);
64            }
65        }
66    }
67    Ok(())
68}
69
70fn encode_copy_row_text(
71    CopyTextFormatParams { null, delimiter }: &CopyTextFormatParams,
72    row: &RowRef,
73    typ: &SqlRelationType,
74    out: &mut Vec<u8>,
75    settings: TextEncodeSettings,
76) -> Result<(), io::Error> {
77    let null = null.as_bytes();
78    let mut buf = BytesMut::new();
79    for (idx, field) in mz_pgrepr::values_from_row(row, typ).into_iter().enumerate() {
80        if idx > 0 {
81            out.push(*delimiter);
82        }
83        match field {
84            None => out.extend(null),
85            Some(field) => {
86                buf.clear();
87                field.encode_text(&mut buf, settings);
88                for b in &buf {
89                    match b {
90                        b'\\' => out.extend(b"\\\\"),
91                        b'\n' => out.extend(b"\\n"),
92                        b'\r' => out.extend(b"\\r"),
93                        b'\t' => out.extend(b"\\t"),
94                        _ => out.push(*b),
95                    }
96                }
97            }
98        }
99    }
100    out.push(b'\n');
101    Ok(())
102}
103
104fn encode_copy_row_csv(
105    CopyCsvFormatParams {
106        delimiter: delim,
107        quote,
108        escape,
109        header: _,
110        null,
111    }: &CopyCsvFormatParams,
112    row: &RowRef,
113    typ: &SqlRelationType,
114    out: &mut Vec<u8>,
115    settings: TextEncodeSettings,
116) -> Result<(), io::Error> {
117    let null = null.as_bytes();
118    let is_special = |c: &u8| *c == *delim || *c == *quote || *c == b'\r' || *c == b'\n';
119    let mut buf = BytesMut::new();
120    for (idx, field) in mz_pgrepr::values_from_row(row, typ).into_iter().enumerate() {
121        if idx > 0 {
122            out.push(*delim);
123        }
124        match field {
125            None => out.extend(null),
126            Some(field) => {
127                buf.clear();
128                field.encode_text(&mut buf, settings);
129                // A field needs quoting if:
130                //   * It is the only field and the value is exactly the end
131                //     of copy marker.
132                //   * The field contains a special character.
133                //   * The field is exactly the NULL sentinel.
134                if (typ.column_types.len() == 1 && buf == END_OF_COPY_MARKER)
135                    || buf.iter().any(is_special)
136                    || &*buf == null
137                {
138                    // Quote the value by wrapping it in the quote character and
139                    // emitting the escape character before any quote or escape
140                    // characters within.
141                    out.push(*quote);
142                    for b in &buf {
143                        if *b == *quote || *b == *escape {
144                            out.push(*escape);
145                        }
146                        out.push(*b);
147                    }
148                    out.push(*quote);
149                } else {
150                    // The value does not need quoting and can be emitted
151                    // directly.
152                    out.extend(&buf);
153                }
154            }
155        }
156    }
157    out.push(b'\n');
158    Ok(())
159}
160
161pub struct CopyTextFormatParser<'a> {
162    data: &'a [u8],
163    position: usize,
164    column_delimiter: u8,
165    null_string: &'a str,
166    buffer: Vec<u8>,
167}
168
169impl<'a> CopyTextFormatParser<'a> {
170    pub fn new(data: &'a [u8], column_delimiter: u8, null_string: &'a str) -> Self {
171        Self {
172            data,
173            position: 0,
174            column_delimiter,
175            null_string,
176            buffer: Vec::new(),
177        }
178    }
179
180    fn peek(&self) -> Option<u8> {
181        if self.position < self.data.len() {
182            Some(self.data[self.position])
183        } else {
184            None
185        }
186    }
187
188    fn consume_n(&mut self, n: usize) {
189        self.position = std::cmp::min(self.position + n, self.data.len());
190    }
191
192    pub fn is_eof(&self) -> bool {
193        self.peek().is_none() || self.is_end_of_copy_marker()
194    }
195
196    pub fn is_end_of_copy_marker(&self) -> bool {
197        self.check_bytes(END_OF_COPY_MARKER)
198    }
199
200    fn is_end_of_line(&self) -> bool {
201        match self.peek() {
202            Some(b'\n') | None => true,
203            _ => false,
204        }
205    }
206
207    pub fn expect_end_of_line(&mut self) -> Result<(), io::Error> {
208        if self.is_end_of_line() {
209            self.consume_n(1);
210            Ok(())
211        } else {
212            Err(io::Error::new(
213                io::ErrorKind::InvalidData,
214                "extra data after last expected column",
215            ))
216        }
217    }
218
219    fn is_column_delimiter(&self) -> bool {
220        self.check_bytes(&[self.column_delimiter])
221    }
222
223    pub fn expect_column_delimiter(&mut self) -> Result<(), io::Error> {
224        if self.consume_bytes(&[self.column_delimiter]) {
225            Ok(())
226        } else {
227            Err(io::Error::new(
228                io::ErrorKind::InvalidData,
229                "missing data for column",
230            ))
231        }
232    }
233
234    fn check_bytes(&self, bytes: &[u8]) -> bool {
235        self.data
236            .get(self.position..self.position + bytes.len())
237            .map_or(false, |d| d == bytes)
238    }
239
240    fn consume_bytes(&mut self, bytes: &[u8]) -> bool {
241        if self.check_bytes(bytes) {
242            self.consume_n(bytes.len());
243            true
244        } else {
245            false
246        }
247    }
248
249    fn consume_null_string(&mut self) -> bool {
250        if self.null_string.is_empty() {
251            // An empty NULL marker is supported. Look ahead to ensure that is followed by
252            // a column delimiter, an end of line or it is at the end of the data.
253            self.is_column_delimiter()
254                || self.is_end_of_line()
255                || self.is_end_of_copy_marker()
256                || self.is_eof()
257        } else {
258            self.consume_bytes(self.null_string.as_bytes())
259        }
260    }
261
262    pub fn consume_raw_value(&mut self) -> Result<Option<&[u8]>, io::Error> {
263        if self.consume_null_string() {
264            return Ok(None);
265        }
266
267        let mut start = self.position;
268
269        // buffer where unescaped data is accumulated
270        self.buffer.clear();
271
272        while !self.is_eof() && !self.is_end_of_copy_marker() {
273            if self.is_end_of_line() || self.is_column_delimiter() {
274                break;
275            }
276            match self.peek() {
277                Some(b'\\') => {
278                    // Add non-escaped data parsed so far
279                    self.buffer.extend(&self.data[start..self.position]);
280
281                    self.consume_n(1);
282                    match self.peek() {
283                        Some(b'b') => {
284                            self.consume_n(1);
285                            self.buffer.push(8);
286                        }
287                        Some(b'f') => {
288                            self.consume_n(1);
289                            self.buffer.push(12);
290                        }
291                        Some(b'n') => {
292                            self.consume_n(1);
293                            self.buffer.push(b'\n');
294                        }
295                        Some(b'r') => {
296                            self.consume_n(1);
297                            self.buffer.push(b'\r');
298                        }
299                        Some(b't') => {
300                            self.consume_n(1);
301                            self.buffer.push(b'\t');
302                        }
303                        Some(b'v') => {
304                            self.consume_n(1);
305                            self.buffer.push(11);
306                        }
307                        Some(b'x') => {
308                            self.consume_n(1);
309                            match self.peek() {
310                                Some(_c @ b'0'..=b'9')
311                                | Some(_c @ b'A'..=b'F')
312                                | Some(_c @ b'a'..=b'f') => {
313                                    let mut value: u8 = 0;
314                                    let decode_nibble = |b| match b {
315                                        Some(c @ b'a'..=b'f') => Some(c - b'a' + 10),
316                                        Some(c @ b'A'..=b'F') => Some(c - b'A' + 10),
317                                        Some(c @ b'0'..=b'9') => Some(c - b'0'),
318                                        _ => None,
319                                    };
320                                    for _ in 0..2 {
321                                        match decode_nibble(self.peek()) {
322                                            Some(c) => {
323                                                self.consume_n(1);
324                                                value = (value << 4) | c;
325                                            }
326                                            _ => break,
327                                        }
328                                    }
329                                    self.buffer.push(value);
330                                }
331                                _ => {
332                                    self.buffer.push(b'x');
333                                }
334                            }
335                        }
336                        Some(_c @ b'0'..=b'7') => {
337                            let mut value: u8 = 0;
338                            for _ in 0..3 {
339                                match self.peek() {
340                                    Some(c @ b'0'..=b'7') => {
341                                        self.consume_n(1);
342                                        value = (value << 3) | (c - b'0');
343                                    }
344                                    _ => break,
345                                }
346                            }
347                            self.buffer.push(value);
348                        }
349                        Some(c) => {
350                            self.consume_n(1);
351                            self.buffer.push(c);
352                        }
353                        None => {
354                            self.buffer.push(b'\\');
355                        }
356                    }
357
358                    start = self.position;
359                }
360                Some(_) => {
361                    self.consume_n(1);
362                }
363                None => {}
364            }
365        }
366
367        // Return a slice of the original buffer if no escaped characters where processed
368        if self.buffer.is_empty() {
369            Ok(Some(&self.data[start..self.position]))
370        } else {
371            // ... otherwise, add the remaining non-escaped data to the decoding buffer
372            // and return a pointer to it
373            self.buffer.extend(&self.data[start..self.position]);
374            Ok(Some(&self.buffer[..]))
375        }
376    }
377
378    /// Error if more than `num_columns` values in `parser`.
379    pub fn iter_raw(self, num_columns: usize) -> RawIterator<'a> {
380        RawIterator {
381            parser: self,
382            current_column: 0,
383            num_columns,
384            truncate: false,
385        }
386    }
387
388    /// Return no more than `num_columns` values from `parser`.
389    pub fn iter_raw_truncating(self, num_columns: usize) -> RawIterator<'a> {
390        RawIterator {
391            parser: self,
392            current_column: 0,
393            num_columns,
394            truncate: true,
395        }
396    }
397}
398
399pub struct RawIterator<'a> {
400    parser: CopyTextFormatParser<'a>,
401    current_column: usize,
402    num_columns: usize,
403    truncate: bool,
404}
405
406impl<'a> RawIterator<'a> {
407    pub fn next(&mut self) -> Option<Result<Option<&[u8]>, io::Error>> {
408        if self.current_column > self.num_columns {
409            return None;
410        }
411
412        if self.current_column == self.num_columns {
413            if !self.truncate {
414                if let Some(err) = self.parser.expect_end_of_line().err() {
415                    return Some(Err(err));
416                }
417            }
418
419            return None;
420        }
421
422        if self.current_column > 0 {
423            if let Some(err) = self.parser.expect_column_delimiter().err() {
424                return Some(Err(err));
425            }
426        }
427
428        self.current_column += 1;
429        Some(self.parser.consume_raw_value())
430    }
431}
432
433#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
434pub enum CopyFormatParams<'a> {
435    Text(CopyTextFormatParams<'a>),
436    Csv(CopyCsvFormatParams<'a>),
437    Binary,
438    Parquet,
439}
440
441impl CopyFormatParams<'static> {
442    pub fn file_extension(&self) -> &str {
443        match self {
444            &CopyFormatParams::Text(_) => "txt",
445            &CopyFormatParams::Csv(_) => "csv",
446            &CopyFormatParams::Binary => "bin",
447            &CopyFormatParams::Parquet => "parquet",
448        }
449    }
450
451    pub fn requires_header(&self) -> bool {
452        match self {
453            CopyFormatParams::Text(_) => false,
454            CopyFormatParams::Csv(params) => params.header,
455            CopyFormatParams::Binary => false,
456            CopyFormatParams::Parquet => false,
457        }
458    }
459}
460
461/// Decodes the given bytes into `Row`-s based on the given `CopyFormatParams`.
462pub fn decode_copy_format<'a>(
463    data: &[u8],
464    column_types: &[mz_pgrepr::Type],
465    params: CopyFormatParams<'a>,
466) -> Result<Vec<Row>, io::Error> {
467    match params {
468        CopyFormatParams::Text(params) => decode_copy_format_text(data, column_types, params),
469        CopyFormatParams::Csv(params) => decode_copy_format_csv(data, column_types, params),
470        CopyFormatParams::Binary => Err(io::Error::new(
471            io::ErrorKind::Unsupported,
472            "cannot decode as binary format",
473        )),
474        CopyFormatParams::Parquet => {
475            // TODO(cf2): Support Parquet over STDIN.
476            Err(io::Error::new(io::ErrorKind::Unsupported, "parquet format"))
477        }
478    }
479}
480
481/// Encodes the given `Row` into bytes based on the given `CopyFormatParams`.
482///
483/// `settings` affects only the text and CSV formats. Callers that do not encode
484/// on behalf of a session, such as `COPY TO <external destination>`, which is
485/// executed in the dataflow layer, must pass [`TextEncodeSettings::STABLE`].
486pub fn encode_copy_format<'a>(
487    params: &CopyFormatParams<'a>,
488    row: &RowRef,
489    typ: &SqlRelationType,
490    out: &mut Vec<u8>,
491    settings: TextEncodeSettings,
492) -> Result<(), io::Error> {
493    match params {
494        CopyFormatParams::Text(params) => encode_copy_row_text(params, row, typ, out, settings),
495        CopyFormatParams::Csv(params) => encode_copy_row_csv(params, row, typ, out, settings),
496        CopyFormatParams::Binary => encode_copy_row_binary(row, typ, out),
497        CopyFormatParams::Parquet => {
498            // TODO(cf2): Support Parquet over STDIN.
499            Err(io::Error::new(io::ErrorKind::Unsupported, "parquet format"))
500        }
501    }
502}
503
504pub fn encode_copy_format_header<'a>(
505    params: &CopyFormatParams<'a>,
506    desc: &RelationDesc,
507    out: &mut Vec<u8>,
508) -> Result<(), io::Error> {
509    match params {
510        CopyFormatParams::Text(_) => Ok(()),
511        CopyFormatParams::Binary => Ok(()),
512        CopyFormatParams::Csv(params) => {
513            let mut header_row = Row::with_capacity(desc.arity());
514            header_row
515                .packer()
516                .extend(desc.iter_names().map(|s| Datum::from(s.as_str())));
517            let typ = SqlRelationType::new(vec![
518                SqlColumnType {
519                    scalar_type: SqlScalarType::String,
520                    nullable: false,
521                };
522                desc.arity()
523            ]);
524            encode_copy_row_csv(params, &header_row, &typ, out, TextEncodeSettings::STABLE)
525        }
526        CopyFormatParams::Parquet => {
527            // TODO(cf2): Support Parquet over STDIN.
528            Err(io::Error::new(io::ErrorKind::Unsupported, "parquet format"))
529        }
530    }
531}
532
533#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
534pub struct CopyTextFormatParams<'a> {
535    pub null: Cow<'a, str>,
536    pub delimiter: u8,
537}
538
539impl<'a> Default for CopyTextFormatParams<'a> {
540    fn default() -> Self {
541        CopyTextFormatParams {
542            delimiter: b'\t',
543            null: Cow::from("\\N"),
544        }
545    }
546}
547
548pub fn decode_copy_format_text(
549    data: &[u8],
550    column_types: &[mz_pgrepr::Type],
551    CopyTextFormatParams { null, delimiter }: CopyTextFormatParams,
552) -> Result<Vec<Row>, io::Error> {
553    let mut rows = Vec::new();
554
555    // TODO: pass the `CopyTextFormatParams` to the `new` method
556    let mut parser = CopyTextFormatParser::new(data, delimiter, &null);
557    while !parser.is_eof() && !parser.is_end_of_copy_marker() {
558        let mut row = Vec::new();
559        let buf = RowArena::new();
560        for (col, typ) in column_types.iter().enumerate() {
561            if col > 0 {
562                parser.expect_column_delimiter()?;
563            }
564            let raw_value = parser.consume_raw_value()?;
565            if let Some(raw_value) = raw_value {
566                match mz_pgrepr::Value::decode_text(typ, raw_value) {
567                    Ok(value) => {
568                        row.push(
569                            value
570                                .into_datum_decode_error(&buf, typ, "column")
571                                .map_err(|msg| io::Error::new(io::ErrorKind::InvalidData, msg))?,
572                        );
573                    }
574                    Err(err) => {
575                        let msg = format!("unable to decode column: {}", err);
576                        return Err(io::Error::new(io::ErrorKind::InvalidData, msg));
577                    }
578                }
579            } else {
580                row.push(Datum::Null);
581            }
582        }
583        parser.expect_end_of_line()?;
584        rows.push(Row::pack(row));
585    }
586    // Note that if there is any junk data after the end of copy marker, we drop
587    // it on the floor as PG does.
588    Ok(rows)
589}
590
591#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
592pub struct CopyCsvFormatParams<'a> {
593    pub delimiter: u8,
594    pub quote: u8,
595    pub escape: u8,
596    pub header: bool,
597    pub null: Cow<'a, str>,
598}
599
600impl<'a> CopyCsvFormatParams<'a> {
601    pub fn to_owned(&self) -> CopyCsvFormatParams<'static> {
602        CopyCsvFormatParams {
603            delimiter: self.delimiter,
604            quote: self.quote,
605            escape: self.escape,
606            header: self.header,
607            null: Cow::Owned(self.null.to_string()),
608        }
609    }
610}
611
612impl Arbitrary for CopyCsvFormatParams<'static> {
613    type Parameters = ();
614    type Strategy = BoxedStrategy<Self>;
615
616    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
617        (
618            any::<u8>(),
619            any::<u8>(),
620            any::<u8>(),
621            any::<bool>(),
622            any::<String>(),
623        )
624            .prop_map(|(delimiter, diff, escape, header, null)| {
625                // Delimiter and Quote need to be different.
626                let diff = diff.saturating_sub(1).max(1);
627                let quote = delimiter.wrapping_add(diff);
628
629                Self::try_new(
630                    Some(delimiter),
631                    Some(quote),
632                    Some(escape),
633                    Some(header),
634                    Some(null),
635                )
636                .expect("delimiter and quote should be different")
637            })
638            .boxed()
639    }
640}
641
642impl<'a> Default for CopyCsvFormatParams<'a> {
643    fn default() -> Self {
644        CopyCsvFormatParams {
645            delimiter: b',',
646            quote: b'"',
647            escape: b'"',
648            header: false,
649            null: Cow::from(""),
650        }
651    }
652}
653
654impl<'a> CopyCsvFormatParams<'a> {
655    pub fn try_new(
656        delimiter: Option<u8>,
657        quote: Option<u8>,
658        escape: Option<u8>,
659        header: Option<bool>,
660        null: Option<String>,
661    ) -> Result<CopyCsvFormatParams<'a>, String> {
662        let mut params = CopyCsvFormatParams::default();
663
664        if let Some(delimiter) = delimiter {
665            params.delimiter = delimiter;
666        }
667        if let Some(quote) = quote {
668            params.quote = quote;
669            // escape defaults to the value provided for quote
670            params.escape = quote;
671        }
672        if let Some(escape) = escape {
673            params.escape = escape;
674        }
675        if let Some(header) = header {
676            params.header = header;
677        }
678        if let Some(null) = null {
679            params.null = Cow::from(null);
680        }
681
682        if params.quote == params.delimiter {
683            return Err("COPY delimiter and quote must be different".to_string());
684        }
685        Ok(params)
686    }
687
688    /// Returns a reader for these options that never strips a BOM.
689    pub fn reader(&self) -> csv_core::Reader {
690        let double_quote = self.quote == self.escape;
691        let mut reader = csv_core::ReaderBuilder::new()
692            .delimiter(self.delimiter)
693            .quote(self.quote)
694            .escape((!double_quote).then_some(self.escape))
695            .double_quote(double_quote)
696            .build();
697        // csv-core strips a BOM from the first input it reads. A chunk past
698        // the first starts mid-stream, where those bytes are data.
699        reader.read_field(b"\n", &mut [0]);
700        reader
701    }
702}
703
704/// Returns whether a blank line in CSV `COPY FROM STDIN` input is a record
705/// when `column_count` columns are copied.
706///
707/// A blank line is one unquoted empty field. For one column that is a full
708/// row, and how `COPY TO` writes a NULL under the default NULL marker. For no
709/// columns it is the only way to write a row.
710///
711/// NOTE: For several columns PostgreSQL fails a blank line with `missing data
712/// for column`. We skip it there, so that files with a stray blank line keep
713/// loading: COPY skipped every blank line before one could be a record. With
714/// `HEADER`, the header is then the first line that is not blank.
715pub fn csv_blank_line_is_record(column_count: usize) -> bool {
716    column_count <= 1
717}
718
719/// One field decoded out of a CSV record by [`decode_copy_format_csv`]:
720/// `start..end` indexes into the per-record `output` buffer (csv-core
721/// unquotes/unescapes into that buffer), and `quoted` records whether the
722/// field's first input byte was the quote character. The quote flag is what
723/// distinguishes a literal `""` (quoted empty string) from an unquoted empty
724/// field (the default NULL marker), and a quoted `"\."` data row from the bare
725/// `\.` end-of-copy marker.
726struct DecodedField {
727    start: usize,
728    end: usize,
729    quoted: bool,
730}
731
732/// Decodes one chunk of CSV `COPY FROM STDIN` data into rows.
733///
734/// The caller cuts the stream into chunks, and must uphold:
735///
736/// * `data` does not start with the stream's BOM. It would decode as data.
737/// * `data` does not start between the CR and the LF of a line ending. The LF
738///   would decode as a blank line.
739/// * `params.quote` is neither CR nor LF. A record that starts with a quoted
740///   field would decode as a blank line.
741pub fn decode_copy_format_csv(
742    data: &[u8],
743    column_types: &[mz_pgrepr::Type],
744    params: CopyCsvFormatParams,
745) -> Result<Vec<Row>, io::Error> {
746    let mut rdr = params.reader();
747    let null_as_bytes = params.null.as_bytes();
748    let mut rows = Vec::new();
749    // We use csv-core (rather than the higher-level csv crate) so we can
750    // recover per-field "was this field quoted?" information by inspecting the
751    // first byte of each field's input. csv unquotes during parsing, which
752    // makes a quoted empty string indistinguishable from an unquoted empty
753    // field — and PostgreSQL COPY ... FORMAT CSV semantics need that
754    // distinction to honor the NULL marker.
755    let mut input = data;
756    let mut output = vec![0u8; data.len().max(1024)];
757    let mut out_pos = 0;
758    let mut fields: Vec<DecodedField> = Vec::new();
759    let mut field_start = 0;
760    let mut field_quoted: Option<bool> = None;
761    let mut skip_header = params.header;
762    let blank_line_is_record = csv_blank_line_is_record(column_types.len());
763
764    loop {
765        // csv-core skips blank lines without reporting them, so they are
766        // handled here.
767        let empty_line = fields.is_empty()
768            && field_quoted.is_none()
769            && matches!(input.first(), Some(b'\r' | b'\n'));
770        if empty_line && !blank_line_is_record {
771            input = &input[1..];
772            continue;
773        }
774        if field_quoted.is_none() {
775            field_quoted = Some(input.first() == Some(&params.quote));
776            field_start = out_pos;
777        }
778        let (result, nin, nout) = if empty_line {
779            (csv_core::ReadFieldResult::Field { record_end: true }, 1, 0)
780        } else {
781            rdr.read_field(input, &mut output[out_pos..])
782        };
783        let ends_in_cr = input[..nin].ends_with(b"\r");
784        input = &input[nin..];
785        out_pos += nout;
786
787        match result {
788            csv_core::ReadFieldResult::Field { record_end } => {
789                let quoted = field_quoted.take().unwrap();
790                if !empty_line || !column_types.is_empty() {
791                    fields.push(DecodedField {
792                        start: field_start,
793                        end: out_pos,
794                        quoted,
795                    });
796                }
797                if record_end {
798                    if ends_in_cr && input.starts_with(b"\n") {
799                        input = &input[1..];
800                    }
801                    if skip_header {
802                        skip_header = false;
803                    } else if let [
804                        DecodedField {
805                            start,
806                            end,
807                            quoted: false,
808                        },
809                    ] = fields[..]
810                        && &output[start..end] == END_OF_COPY_MARKER
811                    {
812                        // Bare `\.` on its own line: end-of-copy marker. A
813                        // quoted `"\."` also decodes to `\.` but is data, so
814                        // only an unquoted match terminates the import.
815                        return Ok(rows);
816                    } else {
817                        match fields.len().cmp(&column_types.len()) {
818                            std::cmp::Ordering::Less => {
819                                return Err(io::Error::new(
820                                    io::ErrorKind::InvalidData,
821                                    "missing data for column",
822                                ));
823                            }
824                            std::cmp::Ordering::Greater => {
825                                return Err(io::Error::new(
826                                    io::ErrorKind::InvalidData,
827                                    "extra data after last expected column",
828                                ));
829                            }
830                            std::cmp::Ordering::Equal => {}
831                        }
832
833                        let mut row_builder = SharedRow::get();
834                        let mut row_packer = row_builder.packer();
835                        for (typ, field) in column_types.iter().zip_eq(fields.iter()) {
836                            let raw_value = &output[field.start..field.end];
837                            if !field.quoted && raw_value == null_as_bytes {
838                                row_packer.push(Datum::Null);
839                            } else {
840                                let s = match std::str::from_utf8(raw_value) {
841                                    Ok(s) => s,
842                                    Err(err) => {
843                                        let msg = format!("invalid utf8 data in column: {}", err);
844                                        return Err(io::Error::new(
845                                            io::ErrorKind::InvalidData,
846                                            msg,
847                                        ));
848                                    }
849                                };
850                                if let Err(err) =
851                                    mz_pgrepr::Value::decode_text_into_row(typ, s, &mut row_packer)
852                                {
853                                    let msg = format!("unable to decode column: {}", err);
854                                    return Err(io::Error::new(io::ErrorKind::InvalidData, msg));
855                                }
856                            }
857                        }
858                        rows.push(row_builder.clone());
859                    }
860                    fields.clear();
861                    out_pos = 0;
862                }
863            }
864            csv_core::ReadFieldResult::OutputFull => {
865                let new_len = output.len().saturating_mul(2).max(out_pos + 1);
866                output.resize(new_len, 0);
867            }
868            csv_core::ReadFieldResult::InputEmpty => {
869                // InputEmpty means csv-core consumed all our input mid-field
870                // and wants more. We have no more to give, so the next
871                // iteration calls it with the now-empty slice; per its
872                // documented termination protocol, that yields the partial
873                // field (if any) as a final `Field`, then `End`.
874            }
875            csv_core::ReadFieldResult::End => return Ok(rows),
876        }
877    }
878}
879
880#[cfg(test)]
881mod tests {
882    use mz_ore::collections::CollectionExt;
883    use mz_repr::SqlColumnType;
884    use proptest::prelude::*;
885
886    use super::*;
887
888    #[mz_ore::test]
889    fn test_copy_format_text_parser() {
890        let text = "\t\\nt e\t\\N\t\n\\x60\\xA\\x7D\\x4a\n\\44\\044\\123".as_bytes();
891        let mut parser = CopyTextFormatParser::new(text, b'\t', "\\N");
892        assert!(parser.is_column_delimiter());
893        parser
894            .expect_column_delimiter()
895            .expect("expected column delimiter");
896        assert_eq!(
897            parser
898                .consume_raw_value()
899                .expect("unexpected error")
900                .expect("unexpected empty result"),
901            "\nt e".as_bytes()
902        );
903        parser
904            .expect_column_delimiter()
905            .expect("expected column delimiter");
906        // null value
907        assert!(
908            parser
909                .consume_raw_value()
910                .expect("unexpected error")
911                .is_none()
912        );
913        parser
914            .expect_column_delimiter()
915            .expect("expected column delimiter");
916        assert!(parser.is_end_of_line());
917        parser.expect_end_of_line().expect("expected eol");
918        // hex value
919        assert_eq!(
920            parser
921                .consume_raw_value()
922                .expect("unexpected error")
923                .expect("unexpected empty result"),
924            "`\n}J".as_bytes()
925        );
926        parser.expect_end_of_line().expect("expected eol");
927        // octal value
928        assert_eq!(
929            parser
930                .consume_raw_value()
931                .expect("unexpected error")
932                .expect("unexpected empty result"),
933            "$$S".as_bytes()
934        );
935        assert!(parser.is_eof());
936    }
937
938    #[mz_ore::test]
939    fn test_copy_format_text_empty_null_string() {
940        let text = "\t\n10\t20\n30\t\n40\t".as_bytes();
941        let expect = vec![
942            vec![None, None],
943            vec![Some("10"), Some("20")],
944            vec![Some("30"), None],
945            vec![Some("40"), None],
946        ];
947        let mut parser = CopyTextFormatParser::new(text, b'\t', "");
948        for line in expect {
949            for (i, value) in line.iter().enumerate() {
950                if i > 0 {
951                    parser
952                        .expect_column_delimiter()
953                        .expect("expected column delimiter");
954                }
955                match value {
956                    Some(s) => {
957                        assert!(!parser.consume_null_string());
958                        assert_eq!(
959                            parser
960                                .consume_raw_value()
961                                .expect("unexpected error")
962                                .expect("unexpected empty result"),
963                            s.as_bytes()
964                        );
965                    }
966                    None => {
967                        assert!(parser.consume_null_string());
968                    }
969                }
970            }
971            parser.expect_end_of_line().expect("expected eol");
972        }
973    }
974
975    #[mz_ore::test]
976    fn test_copy_format_text_parser_escapes() {
977        struct TestCase {
978            input: &'static str,
979            expect: &'static [u8],
980        }
981        let tests = vec![
982            TestCase {
983                input: "simple",
984                expect: b"simple",
985            },
986            TestCase {
987                input: r#"new\nline"#,
988                expect: b"new\nline",
989            },
990            TestCase {
991                input: r#"\b\f\n\r\t\v\\"#,
992                expect: b"\x08\x0c\n\r\t\x0b\\",
993            },
994            TestCase {
995                input: r#"\0\12\123"#,
996                expect: &[0, 0o12, 0o123],
997            },
998            TestCase {
999                input: r#"\x1\xaf"#,
1000                expect: &[0x01, 0xaf],
1001            },
1002            TestCase {
1003                input: r#"T\n\07\xEV\x0fA\xb2C\1"#,
1004                expect: b"T\n\x07\x0eV\x0fA\xb2C\x01",
1005            },
1006            TestCase {
1007                input: r#"\\\""#,
1008                expect: b"\\\"",
1009            },
1010            TestCase {
1011                input: r#"\x"#,
1012                expect: b"x",
1013            },
1014            TestCase {
1015                input: r#"\xg"#,
1016                expect: b"xg",
1017            },
1018            TestCase {
1019                input: r#"\"#,
1020                expect: b"\\",
1021            },
1022            TestCase {
1023                input: r#"\8"#,
1024                expect: b"8",
1025            },
1026            TestCase {
1027                input: r#"\a"#,
1028                expect: b"a",
1029            },
1030            TestCase {
1031                input: r#"\x\xg\8\xH\x32\s\"#,
1032                expect: b"xxg8xH2s\\",
1033            },
1034        ];
1035
1036        for test in tests {
1037            let mut parser = CopyTextFormatParser::new(test.input.as_bytes(), b'\t', "\\N");
1038            assert_eq!(
1039                parser
1040                    .consume_raw_value()
1041                    .expect("unexpected error")
1042                    .expect("unexpected empty result"),
1043                test.expect,
1044                "input: {}, expect: {:?}",
1045                test.input,
1046                std::str::from_utf8(test.expect),
1047            );
1048            assert!(parser.is_eof());
1049        }
1050    }
1051
1052    #[mz_ore::test]
1053    fn test_copy_csv_format_params() {
1054        assert_eq!(
1055            CopyCsvFormatParams::try_new(Some(b't'), Some(b'q'), None, None, None),
1056            Ok(CopyCsvFormatParams {
1057                delimiter: b't',
1058                quote: b'q',
1059                escape: b'q',
1060                header: false,
1061                null: Cow::from(""),
1062            })
1063        );
1064
1065        assert_eq!(
1066            CopyCsvFormatParams::try_new(
1067                Some(b't'),
1068                Some(b'q'),
1069                Some(b'e'),
1070                Some(true),
1071                Some("null".to_string())
1072            ),
1073            Ok(CopyCsvFormatParams {
1074                delimiter: b't',
1075                quote: b'q',
1076                escape: b'e',
1077                header: true,
1078                null: Cow::from("null"),
1079            })
1080        );
1081
1082        assert_eq!(
1083            CopyCsvFormatParams::try_new(
1084                None,
1085                Some(b','),
1086                Some(b'e'),
1087                Some(true),
1088                Some("null".to_string())
1089            ),
1090            Err("COPY delimiter and quote must be different".to_string())
1091        );
1092    }
1093
1094    #[mz_ore::test]
1095    fn test_copy_csv_row() -> Result<(), io::Error> {
1096        let mut row = Row::default();
1097        let mut packer = row.packer();
1098        packer.push(Datum::from("1,2,\"3\""));
1099        packer.push(Datum::Null);
1100        packer.push(Datum::from(1000u64));
1101        packer.push(Datum::from("qe")); // overridden quote and escape character in test below
1102        packer.push(Datum::from(""));
1103
1104        let typ: SqlRelationType = SqlRelationType::new(vec![
1105            SqlColumnType {
1106                scalar_type: mz_repr::SqlScalarType::String,
1107                nullable: false,
1108            },
1109            SqlColumnType {
1110                scalar_type: mz_repr::SqlScalarType::String,
1111                nullable: true,
1112            },
1113            SqlColumnType {
1114                scalar_type: mz_repr::SqlScalarType::UInt64,
1115                nullable: false,
1116            },
1117            SqlColumnType {
1118                scalar_type: mz_repr::SqlScalarType::String,
1119                nullable: false,
1120            },
1121            SqlColumnType {
1122                scalar_type: mz_repr::SqlScalarType::String,
1123                nullable: false,
1124            },
1125        ]);
1126
1127        let mut out = Vec::new();
1128
1129        struct TestCase<'a> {
1130            params: CopyCsvFormatParams<'a>,
1131            expected: &'static [u8],
1132        }
1133
1134        let tests = [
1135            TestCase {
1136                params: CopyCsvFormatParams::default(),
1137                expected: b"\"1,2,\"\"3\"\"\",,1000,qe,\"\"\n",
1138            },
1139            TestCase {
1140                params: CopyCsvFormatParams {
1141                    null: Cow::from("NULL"),
1142                    quote: b'q',
1143                    escape: b'e',
1144                    ..Default::default()
1145                },
1146                expected: b"q1,2,\"3\"q,NULL,1000,qeqeeq,\n",
1147            },
1148        ];
1149
1150        for TestCase { params, expected } in tests {
1151            out.clear();
1152            let params = CopyFormatParams::Csv(params);
1153            let _ = encode_copy_format(&params, &row, &typ, &mut out, TextEncodeSettings::STABLE);
1154            let output = std::str::from_utf8(&out);
1155            assert_eq!(output, std::str::from_utf8(expected));
1156        }
1157
1158        Ok(())
1159    }
1160
1161    #[mz_ore::test]
1162    fn test_decode_copy_format_csv_empty_line() {
1163        use mz_pgrepr::Type::Text;
1164        let decode = |types: &[mz_pgrepr::Type]| {
1165            decode_copy_format_csv(b"\n\r\n\r", types, Default::default())
1166        };
1167        assert_eq!(decode(&[Text]).unwrap(), vec![Row::pack([Datum::Null]); 3]);
1168        assert_eq!(decode(&[]).unwrap(), vec![Row::default(); 3]);
1169        assert_eq!(decode(&[Text, Text]).unwrap(), vec![]);
1170    }
1171
1172    #[mz_ore::test]
1173    fn test_decode_copy_format_csv_skipped_blank_lines() {
1174        use mz_pgrepr::Type::Text;
1175        let strings = |a, b| Row::pack([Datum::String(a), Datum::String(b)]);
1176        let decode = |data: &[u8], header| {
1177            let params = CopyCsvFormatParams {
1178                header,
1179                ..Default::default()
1180            };
1181            decode_copy_format_csv(data, &[Text, Text], params).unwrap()
1182        };
1183        assert_eq!(
1184            decode(b"\na,b\r\n\r\n\"\",d\r\r", false),
1185            vec![strings("a", "b"), strings("", "d")],
1186            "a quoted field after skipped lines stays quoted"
1187        );
1188        assert_eq!(
1189            decode(b"\r\n\nh,h\n\na,b\n\n", true),
1190            vec![strings("a", "b")],
1191            "the header is the first line that is not blank"
1192        );
1193        assert_eq!(
1194            decode(b"a,b\n\n\\.\nc,d\n", false),
1195            vec![strings("a", "b")],
1196            "the end marker ends the chunk after skipped lines"
1197        );
1198    }
1199
1200    #[mz_ore::test]
1201    fn test_decode_copy_format_csv_blank_header() {
1202        let params = CopyCsvFormatParams {
1203            header: true,
1204            ..Default::default()
1205        };
1206        let rows = decode_copy_format_csv(b"\nh\n", &[mz_pgrepr::Type::Text], params).unwrap();
1207        assert_eq!(rows, [Row::pack([Datum::String("h")])]);
1208    }
1209
1210    #[mz_ore::test]
1211    fn test_csv_record_start() {
1212        for (header, data) in [(false, "\u{feff}\\.\n"), (true, "\n\u{feff}\\.\n")] {
1213            let params = CopyCsvFormatParams {
1214                header,
1215                ..Default::default()
1216            };
1217            let rows =
1218                decode_copy_format_csv(data.as_bytes(), &[mz_pgrepr::Type::Text], params).unwrap();
1219            assert_eq!(rows, [Row::pack([Datum::String("\u{feff}\\.")])]);
1220        }
1221    }
1222
1223    #[mz_ore::test]
1224    fn test_decode_copy_format_csv_end_marker() {
1225        // Bare `\.` on its own line terminates the COPY. A quoted `"\."`
1226        // decodes to the same bytes but must be treated as data. This must
1227        // hold for every line ending (LF, CRLF, CR): csv-core places a CRLF
1228        // record boundary between `\r` and `\n`, so a naive raw-byte check is
1229        // fooled by the orphaned terminator bytes on CRLF/CR input.
1230        let column_types = vec![mz_pgrepr::Type::from(&mz_repr::SqlScalarType::String)];
1231
1232        let decode_strings = |input: &[u8]| -> Vec<String> {
1233            decode_copy_format_csv(input, &column_types, CopyCsvFormatParams::default())
1234                .expect("decode should succeed")
1235                .iter()
1236                .map(|r| match r.iter().next().unwrap() {
1237                    Datum::String(s) => s.to_owned(),
1238                    d => panic!("unexpected datum: {:?}", d),
1239                })
1240                .collect()
1241        };
1242
1243        for eol in [&b"\n"[..], b"\r\n", b"\r"] {
1244            let join = |lines: &[&str]| -> Vec<u8> {
1245                let mut out = Vec::new();
1246                for line in lines {
1247                    out.extend_from_slice(line.as_bytes());
1248                    out.extend_from_slice(eol);
1249                }
1250                out
1251            };
1252
1253            // Quoted "\." is data — all three rows are imported.
1254            assert_eq!(
1255                decode_strings(&join(&["before", "\"\\.\"", "after"])),
1256                vec!["before", "\\.", "after"],
1257                "quoted marker, eol={eol:?}"
1258            );
1259
1260            // Bare `\.` terminates the COPY; rows after it are dropped.
1261            assert_eq!(
1262                decode_strings(&join(&["first", "\\.", "ignored"])),
1263                vec!["first"],
1264                "bare marker, eol={eol:?}"
1265            );
1266        }
1267    }
1268
1269    #[mz_ore::test]
1270    fn test_decode_copy_format_csv_quoted_null() {
1271        // PG COPY ... FORMAT CSV distinguishes quoted vs unquoted NULL
1272        // markers: unquoted → SQL NULL, quoted → the literal string.
1273        let column_types = vec![
1274            mz_pgrepr::Type::from(&mz_repr::SqlScalarType::String),
1275            mz_pgrepr::Type::from(&mz_repr::SqlScalarType::String),
1276        ];
1277
1278        // Lines as (col_a, col_b) literals, joined per-eol below. The quoted
1279        // vs unquoted distinction must survive CRLF/CR line endings, where
1280        // csv-core leaves an orphaned terminator byte at the start of every
1281        // non-first record.
1282        let cases: &[(CopyCsvFormatParams, &[(&str, &str)], &[[Option<&str>; 2]])] = &[
1283            // Default params: NULL marker is empty string.
1284            (
1285                CopyCsvFormatParams::default(),
1286                &[("a", ""), ("b", "\"\""), ("\"\"", "c")],
1287                &[
1288                    [Some("a"), None],
1289                    [Some("b"), Some("")],
1290                    [Some(""), Some("c")],
1291                ],
1292            ),
1293            // Custom NULL marker "NULL".
1294            (
1295                CopyCsvFormatParams {
1296                    null: Cow::from("NULL"),
1297                    ..Default::default()
1298                },
1299                &[("a", "NULL"), ("b", "\"NULL\""), ("NULL", "c")],
1300                &[
1301                    [Some("a"), None],
1302                    [Some("b"), Some("NULL")],
1303                    [None, Some("c")],
1304                ],
1305            ),
1306        ];
1307
1308        for eol in [&b"\n"[..], b"\r\n", b"\r"] {
1309            for (params, lines, expected) in cases {
1310                let mut input = Vec::new();
1311                for (a, b) in *lines {
1312                    input.extend_from_slice(a.as_bytes());
1313                    input.push(b',');
1314                    input.extend_from_slice(b.as_bytes());
1315                    input.extend_from_slice(eol);
1316                }
1317                let rows = decode_copy_format_csv(&input, &column_types, params.clone())
1318                    .expect("decode should succeed");
1319                assert_eq!(rows.len(), expected.len(), "eol={eol:?}");
1320                for (row, want) in rows.iter().zip_eq(expected.iter()) {
1321                    let got: Vec<Datum> = row.iter().collect();
1322                    assert_eq!(got.len(), 2);
1323                    for (g, w) in got.iter().zip_eq(want.iter()) {
1324                        match (g, w) {
1325                            (Datum::Null, None) => {}
1326                            (Datum::String(s), Some(w)) => assert_eq!(s, w, "eol={eol:?}"),
1327                            _ => panic!("mismatch: got {g:?}, want {w:?}, eol={eol:?}"),
1328                        }
1329                    }
1330                }
1331            }
1332        }
1333    }
1334
1335    proptest! {
1336        #[mz_ore::test]
1337        #[cfg_attr(miri, ignore)]
1338        fn proptest_csv_roundtrips(copy_csv_params: CopyCsvFormatParams)  {
1339            prop_assume!(!matches!(copy_csv_params.quote, b'\r' | b'\n'));
1340            // Given a SqlScalarType and Datum roundtrips it through the CSV COPY format.
1341            let try_roundtrip_datum = |scalar_type: &SqlScalarType, datum| {
1342                let row = Row::pack_slice(&[datum]);
1343                let typ = SqlRelationType::new(vec![
1344                    SqlColumnType {
1345                        scalar_type: scalar_type.clone(),
1346                        nullable: true,
1347                    }
1348                ]);
1349
1350                let mut buf = Vec::new();
1351                let mut csv_params = copy_csv_params.clone();
1352                // TODO: Encoding never writes a header.
1353                csv_params.header = false;
1354                let params = CopyFormatParams::Csv(csv_params);
1355
1356                // Roundtrip the Row through our CSV format.
1357                encode_copy_format(&params, &row, &typ, &mut buf, TextEncodeSettings::STABLE)?;
1358                let column_types = typ
1359                    .column_types
1360                    .iter()
1361                    .map(|x| &x.scalar_type)
1362                    .map(mz_pgrepr::Type::from)
1363                    .collect::<Vec<mz_pgrepr::Type>>();
1364                let result = decode_copy_format(&buf, &column_types, params);
1365
1366                match result {
1367                    Ok(rows) => {
1368                        let out_str = std::str::from_utf8(&buf[..]);
1369
1370                        prop_assert_eq!(
1371                            rows.len(),
1372                            1,
1373                            "unexpected number of rows! {:?}, csv string: {:?}", rows, out_str
1374                        );
1375                        let output = rows.into_element();
1376
1377                        prop_assert_eq!(
1378                            row,
1379                            output,
1380                            "csv string: {:?}, scalar_type: {:?}", out_str, scalar_type
1381                        );
1382                    }
1383                    _ => {
1384                        // ignoring decoding failures
1385                    }
1386                }
1387
1388                Ok(())
1389            };
1390
1391            // Try roundtripping all of our interesting Datums.
1392            for scalar_type in SqlScalarType::enumerate() {
1393                for datum in scalar_type.interesting_datums() {
1394                    // TODO: The decoder cannot differentiate between empty string and null.
1395                    if let Some(value) = mz_pgrepr::Value::from_datum(datum, scalar_type) {
1396                        let mut buf = bytes::BytesMut::new();
1397                        value.encode_text(&mut buf, TextEncodeSettings::STABLE);
1398
1399                        if let Ok(datum_str) = std::str::from_utf8(&buf[..]) {
1400                            if datum_str == copy_csv_params.null {
1401                                continue;
1402                            }
1403                        }
1404                    }
1405
1406                    let updated_datum = match datum {
1407                        // TODO: Fix roundtrip decoding of these types.
1408                        Datum::Timestamp(_) | Datum::TimestampTz(_) | Datum::Null => {
1409                            continue;
1410                        }
1411                        // Text carries no sign for NaN, so `-NaN` decodes as
1412                        // `NaN`, and `Row` equality compares the encoded bytes,
1413                        // which differ. The positive NaN of the interesting set
1414                        // covers the roundtrip itself.
1415                        Datum::Float32(f) if f.is_nan() && f.is_sign_negative() => {
1416                            continue;
1417                        }
1418                        Datum::Float64(f) if f.is_nan() && f.is_sign_negative() => {
1419                            continue;
1420                        }
1421                        Datum::String(s) => {
1422                            // TODO: The decoder cannot differentiate between empty string and null.
1423                            if s.trim() == copy_csv_params.null || s.trim().is_empty() {
1424                                continue;
1425                            } else {
1426                                Datum::String(s)
1427                            }
1428                        }
1429                        other => other,
1430                    };
1431
1432                    let result = try_roundtrip_datum(scalar_type, updated_datum);
1433                    prop_assert!(result.is_ok(), "failure: {result:?}");
1434                }
1435            }
1436        }
1437    }
1438}