Skip to main content

servers/postgres/copy_in/
jsonl.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 `jsonl` format: newline-delimited JSON objects, one per record.
16//!
17//! Parsing and typed conversion both reuse arrow-json's incremental
18//! [`Decoder`](arrow::json::reader::Decoder) — the engine behind
19//! GreptimeDB's file-based `COPY ... FROM 'file.json'` (see
20//! `common-datasource`'s `json` file format) — so both COPY routes
21//! accept identical data. The decoder splits records (objects may span
22//! chunk boundaries; pretty-printed multi-line objects and concatenated
23//! `{...}{...}` streams are accepted too) and converts fields against
24//! the targeted columns' schema in one pass; a record is one JSON
25//! object whose keys address the columns **by name** (the COPY column
26//! list fixes the target order, as with csv).
27//!
28//! What the engine actually accepts, so the rules match the behavior
29//! rather than a strict reading of the column types:
30//!
31//! - Numeric columns take JSON numbers **or numeric strings**
32//!   (`"val": 1.5` and `"val": "1.5"` both decode); booleans must be
33//!   JSON booleans (`"b": "true"` is rejected).
34//! - Timestamps are date-time strings (RFC 3339; offset-free ones parse
35//!   in the session timezone, like SQL INSERT) **or numbers**, taken as
36//!   the column's time unit verbatim: `"ts": 1704067200000` is an epoch
37//!   in milliseconds for a millisecond column — there is no unit
38//!   conversion, and `"ts": 1704067200` means 1970-01-20 in that column.
39//!   A quoted number is parsed as a date-time string and so fails.
40//! - Keys outside the column list are ignored, so a misspelled key
41//!   (`"hots"`) yields NULL in its column instead of an error, and
42//!   records may carry more keys than a column subset selects.
43//!   (arrow-json's strict mode would change the first half of that but
44//!   also reject the second, so it stays off.)
45//! - Absent keys become NULL; a NULL in a non-nullable column (such as
46//!   the time index) is rejected with a message naming the column.
47//! - Column types arrow-json cannot decode (JSON, Binary) are rejected
48//!   up front.
49//!
50//! The format is table-bound like `csv` and takes no options; the
51//! file-based json format's layout options are writer-side only, and
52//! arrow-json's reader parses date-time strings natively (RFC 3339,
53//! with the schema's timezone for offset-free strings). `json` is an
54//! alias for `jsonl`, matching the file-based format's name; it still
55//! means newline-delimited objects — a top-level JSON array `[{...}]`
56//! is rejected with a specific hint.
57
58use std::sync::Arc;
59
60use api::helper::vectors_to_rows;
61use arrow::json::reader::{Decoder as JsonDecoder, ReaderBuilder};
62use arrow::record_batch::RecordBatch;
63use arrow_schema::{ArrowError, DataType as ArrowDataType, Field, Schema as ArrowSchema};
64use datatypes::prelude::ConcreteDataType;
65use datatypes::schema::{ColumnSchema, Schema as GreptimeSchema};
66use datatypes::vectors::Helper;
67use pgwire::error::{PgWireError, PgWireResult};
68
69use crate::postgres::copy_in::codec::{
70    CopyFormat, ParsedRow, RecordParser, TableBoundCodec, check_arrow_column_type,
71};
72use crate::postgres::copy_in::options::CopyOptionSet;
73use crate::postgres::copy_in::{COPY_IN_FLUSH_ROWS, bad_copy_data, invalid_text_repr, unsupported};
74
75/// The validated `jsonl` format configuration.
76#[derive(Debug, Clone, Default)]
77pub(super) struct JsonlCodec;
78
79/// Builds the codec from the parsed options.
80pub(super) fn build_jsonl_codec(options: CopyOptionSet) -> PgWireResult<CopyFormat> {
81    options.reject_leftovers("jsonl")?;
82    Ok(CopyFormat::Jsonl(JsonlCodec))
83}
84
85impl TableBoundCodec for JsonlCodec {
86    fn name(&self) -> &'static str {
87        "jsonl"
88    }
89
90    fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()> {
91        check_arrow_column_type(data_type, "jsonl")
92    }
93
94    fn create_parser(
95        &self,
96        columns: &[ColumnSchema],
97        timezone: &str,
98    ) -> PgWireResult<Box<dyn RecordParser + Send>> {
99        // Decode schema: the greptime schema's arrow projection, with
100        // Timestamp fields carrying the SESSION timezone so offset-free
101        // strings parse like SQL INSERT does instead of as UTC (the same
102        // substitution the csv codec makes; explicit offsets in the
103        // input always win). Every field is made nullable: a missing or
104        // null value in a non-nullable column then surfaces as a NULL
105        // that `flush_batch` reports by column name, instead of
106        // arrow-json's generic "unmasked nulls in non-nullable
107        // StructArray child" error.
108        let arrow_schema = GreptimeSchema::try_new(columns.to_vec())
109            .map_err(|e| unsupported(format!("invalid columns for format jsonl: {e}")))?
110            .arrow_schema()
111            .clone();
112        let timezone = timezone.to_string();
113        let fields = arrow_schema
114            .fields()
115            .iter()
116            .zip(columns)
117            .map(|(field, column)| {
118                let data_type = match &column.data_type {
119                    ConcreteDataType::Timestamp(_) => match field.data_type() {
120                        ArrowDataType::Timestamp(unit, None) => {
121                            ArrowDataType::Timestamp(*unit, Some(Arc::from(timezone.as_str())))
122                        }
123                        _ => field.data_type().clone(),
124                    },
125                    _ => field.data_type().clone(),
126                };
127                Field::new(field.name(), data_type, true)
128            })
129            .collect::<Vec<_>>();
130        let builder = ReaderBuilder::new(Arc::new(ArrowSchema::new(fields)))
131            .with_batch_size(COPY_IN_FLUSH_ROWS);
132        Ok(Box::new(JsonlRecordParser {
133            decoder: builder.build_decoder().map_err(decode_error)?,
134            required: columns
135                .iter()
136                .enumerate()
137                .filter(|(_, column)| !column.is_nullable())
138                .map(|(index, column)| (index, column.name.clone()))
139                .collect(),
140            started: false,
141            string_state: JsonStringState::default(),
142        }))
143    }
144}
145
146/// Incremental parser backed by arrow-json's decoder. Unlike
147/// arrow-csv, a record finalizes as soon as its closing `}` is parsed,
148/// and a single `flush` drains and clears the buffered tape — so there
149/// is no EOF signal to send at `CopyDone`.
150struct JsonlRecordParser {
151    decoder: JsonDecoder,
152    /// The non-nullable target columns (position and name), checked per
153    /// decoded batch because the decode schema marks every field
154    /// nullable (see [`TableBoundCodec::create_parser`]).
155    required: Vec<(usize, String)>,
156    /// Whether the first non-whitespace byte of the stream has been
157    /// seen; only that byte can be a top-level array's `[`.
158    started: bool,
159    string_state: JsonStringState,
160}
161
162/// Only distinguishes string content from discarded JSON whitespace. Syntax
163/// validation and record boundaries remain entirely arrow-json's job.
164#[derive(Clone, Copy, Default)]
165struct JsonStringState {
166    quoted: bool,
167    escaped: bool,
168}
169
170impl JsonStringState {
171    fn prefix(&mut self, data: &[u8], budget: usize) -> (usize, usize) {
172        let mut charged = 0;
173        for (i, &byte) in data.iter().enumerate() {
174            if !self.quoted && is_json_whitespace(byte) {
175                continue;
176            }
177            if charged == budget {
178                return (i, charged);
179            }
180            charged += 1;
181            if self.escaped {
182                self.escaped = false;
183            } else if byte == b'"' {
184                self.quoted = !self.quoted;
185            } else if self.quoted && byte == b'\\' {
186                self.escaped = true;
187            }
188        }
189        (data.len(), charged)
190    }
191}
192
193const TOP_LEVEL_ARRAY_HINT: &str = "format jsonl expects newline-delimited JSON objects, one \
194     per record; a top-level JSON array is not supported, write one object per line instead";
195
196/// arrow-json's whitespace set, which `Decoder::decode` skips freely.
197fn is_json_whitespace(byte: u8) -> bool {
198    matches!(byte, b' ' | b'\t' | b'\n' | b'\r')
199}
200
201impl RecordParser for JsonlRecordParser {
202    fn plan_input(&self, data: &[u8], budget: usize) -> (usize, usize) {
203        let mut preview = self.string_state;
204        preview.prefix(data, budget)
205    }
206
207    fn decode(&mut self, data: &[u8]) -> PgWireResult<(usize, usize)> {
208        if !self.started {
209            // Report the most likely misuse of the `json` alias — a
210            // top-level array — specifically; arrow-json would only say
211            // `expected { got [...]`.
212            if let Some(first) = data.iter().copied().find(|&byte| !is_json_whitespace(byte)) {
213                self.started = true;
214                if first == b'[' {
215                    return Err(bad_copy_data(TOP_LEVEL_ARRAY_HINT));
216                }
217            }
218        }
219        let consumed = self.decoder.decode(data).map_err(decode_error)?;
220        // The decoder may stop at a full batch partway through the preview.
221        Ok(self.string_state.prefix(&data[..consumed], usize::MAX))
222    }
223
224    fn is_full(&self) -> bool {
225        self.decoder.len() == COPY_IN_FLUSH_ROWS && !self.decoder.has_partial_record()
226    }
227
228    fn flush(&mut self) -> PgWireResult<Vec<ParsedRow>> {
229        match self.decoder.flush().map_err(decode_error)? {
230            Some(batch) => self.flush_batch(&batch),
231            None => Ok(Vec::new()),
232        }
233    }
234}
235
236impl JsonlRecordParser {
237    /// Converts one decoded arrow batch into insertable rows with the
238    /// shared [`vectors_to_rows`] helper, after checking the
239    /// non-nullable columns.
240    fn flush_batch(&self, batch: &RecordBatch) -> PgWireResult<Vec<ParsedRow>> {
241        for (index, name) in &self.required {
242            if batch.column(*index).null_count() > 0 {
243                return Err(bad_copy_data(format!(
244                    "null value in non-nullable column \"{name}\"; every jsonl record must set it"
245                )));
246            }
247        }
248        let vectors = Helper::try_into_vectors(batch.columns())
249            .map_err(|e| bad_copy_data(format!("failed to convert decoded JSON batch: {e}")))?;
250        Ok(vectors_to_rows(vectors.iter(), batch.num_rows()))
251    }
252}
253
254/// Maps arrow-json errors to PostgreSQL's COPY error classes, the
255/// way `csv.rs` does. A field value that does not decode against its
256/// column type is an invalid text representation (22P02): arrow-json
257/// wraps those as `JsonError("whilst decoding field '<name>': …")` (see
258/// its `struct_array.rs`), since it has no separate `ParseError` for
259/// them. JSON syntax errors (truncated records, unexpected tokens) and
260/// anything else is bad copy data (22P04) — never an internal `XX000`.
261fn decode_error(error: ArrowError) -> PgWireError {
262    const FIELD_PREFIX: &str = "whilst decoding field '";
263    match &error {
264        ArrowError::ParseError(message) | ArrowError::CastError(message) => {
265            invalid_text_repr(format!("failed to parse JSON data: {message}"))
266        }
267        ArrowError::JsonError(message) if message.starts_with(FIELD_PREFIX) => {
268            invalid_text_repr(format!("failed to parse JSON data: {message}"))
269        }
270        _ => bad_copy_data(format!("failed to parse JSON data: {error}")),
271    }
272}
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277    use crate::postgres::copy_in::codec::CopyFormat;
278    use crate::postgres::copy_in::options::{CopyOptionSet, CopyOptionValue};
279    use api::v1::value::ValueData;
280    use datatypes::schema::ColumnSchema;
281
282    fn columns() -> Vec<ColumnSchema> {
283        vec![
284            ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
285            ColumnSchema::new("val", ConcreteDataType::float64_datatype(), true),
286            ColumnSchema::new(
287                "ts",
288                ConcreteDataType::timestamp_millisecond_datatype(),
289                false,
290            ),
291        ]
292    }
293
294    fn codec() -> JsonlCodec {
295        match build_jsonl_codec(CopyOptionSet::default()).unwrap() {
296            CopyFormat::Jsonl(codec) => codec,
297            other => panic!("unexpected format {other:?}"),
298        }
299    }
300
301    fn new_parser(columns: &[ColumnSchema]) -> Box<dyn RecordParser + Send> {
302        codec().create_parser(columns, "UTC").unwrap()
303    }
304
305    fn feed_all(parser: &mut Box<dyn RecordParser + Send>, chunks: &[&[u8]]) -> Vec<ParsedRow> {
306        let mut rows = Vec::new();
307        for chunk in chunks {
308            rows.extend(parser.feed(chunk).unwrap());
309        }
310        rows.extend(parser.finish().unwrap());
311        rows
312    }
313
314    fn string_at(row: &ParsedRow, col: usize) -> Option<String> {
315        row.values[col].value_data.as_ref().map(|v| match v {
316            ValueData::StringValue(s) => s.clone(),
317            other => panic!("expected string, got {other:?}"),
318        })
319    }
320
321    fn f64_at(row: &ParsedRow, col: usize) -> Option<f64> {
322        match row.values[col].value_data.as_ref() {
323            None => None,
324            Some(ValueData::F64Value(v)) => Some(*v),
325            other => panic!("expected f64, got {other:?}"),
326        }
327    }
328
329    fn ts_millis_at(row: &ParsedRow, col: usize) -> Option<i64> {
330        match row.values[col].value_data.as_ref() {
331            None => None,
332            Some(ValueData::TimestampMillisecondValue(v)) => Some(*v),
333            other => panic!("expected timestamp ms, got {other:?}"),
334        }
335    }
336
337    #[test]
338    fn test_jsonl_input_budget_across_chunks() {
339        let record = br#"{"host":"a\"  b\\  ","ts":0}"#;
340        let data = [record.as_slice(), b" \t\r\n", record].concat();
341        for size in 1..=data.len() {
342            let mut parser = new_parser(&columns());
343            let mut total = 0;
344            for mut chunk in data.chunks(size) {
345                while !chunk.is_empty() {
346                    let (len, charge) = parser.plan_input(chunk, 3);
347                    assert!(len > 0 && charge <= 3);
348                    assert_eq!(parser.decode(&chunk[..len]).unwrap(), (len, charge));
349                    total += charge;
350                    chunk = &chunk[len..];
351                }
352            }
353            assert_eq!(total, 2 * record.len());
354            assert_eq!(parser.finish().unwrap().len(), 2);
355        }
356    }
357
358    /// The SQLSTATE a copy error is sent to the client with.
359    fn error_code(error: &PgWireError) -> String {
360        error.code().to_string()
361    }
362
363    /// Feeds `data` then finishes, returning the first error. arrow-json
364    /// reports JSON syntax errors from `feed` but converts values at
365    /// the flush in `finish`, so value-level failures surface there.
366    fn error_feeding(parser: &mut Box<dyn RecordParser + Send>, data: &[u8]) -> PgWireError {
367        match parser.feed(data).and_then(|_| parser.finish()) {
368            Ok(_) => panic!("expected an error for {:?}", String::from_utf8_lossy(data)),
369            Err(error) => error,
370        }
371    }
372
373    #[test]
374    fn test_jsonl_records_across_chunk_boundaries() {
375        let payload: Vec<u8> = br#"{"host":"a","val":1.5,"ts":"2024-01-01 00:00:00"}
376{"host":"b","val":2.5,"ts":"2024-01-01 00:00:01"}"#
377            .to_vec();
378        for chunk in [1usize, 2, 3, 7, 64] {
379            let mut parser = new_parser(&columns());
380            let rows = feed_all(&mut parser, &payload.chunks(chunk).collect::<Vec<_>>());
381            assert_eq!(rows.len(), 2, "chunk={chunk}");
382            assert_eq!(string_at(&rows[0], 0), Some("a".to_string()));
383            assert!(matches!(
384                rows[1].values[0].value_data,
385                Some(ValueData::StringValue(ref s)) if s == "b"
386            ));
387        }
388    }
389
390    #[test]
391    fn test_jsonl_absent_key_is_null() {
392        let mut parser = new_parser(&columns());
393        let rows = feed_all(
394            &mut parser,
395            &[b"{\"val\":3.5,\"ts\":\"2024-01-01 00:00:00\"}\n"],
396        );
397        assert_eq!(rows.len(), 1);
398        assert!(rows[0].values[0].value_data.is_none());
399    }
400
401    #[test]
402    fn test_jsonl_trailing_record_without_newline() {
403        let mut parser = new_parser(&columns());
404        let rows = feed_all(
405            &mut parser,
406            &[
407                b"{\"host\":\"a\",\"val\":1.5,\"ts\":\"2024-01-01 00:00:00\"}\n",
408                b"{\"host\":\"b\",\"val\":2.5,\"ts\":\"2024-01-01 00:00:01\"}",
409            ],
410        );
411        assert_eq!(rows.len(), 2);
412        assert_eq!(f64_at(&rows[1], 1), Some(2.5));
413    }
414
415    #[test]
416    fn test_jsonl_numeric_columns_take_native_and_quoted_numbers() {
417        let mut parser = new_parser(&columns());
418        let rows = feed_all(
419            &mut parser,
420            &[
421                b"{\"val\":2,\"ts\":\"2024-01-01 00:00:00\"}\n",
422                b"{\"val\":\"1.5\",\"ts\":\"2024-01-01 00:00:01\"}\n",
423            ],
424        );
425        assert_eq!(rows.len(), 2);
426        assert_eq!(f64_at(&rows[0], 1), Some(2.0));
427        assert_eq!(f64_at(&rows[1], 1), Some(1.5));
428
429        // Booleans, by contrast, must be JSON booleans.
430        let mut parser = new_parser(&[ColumnSchema::new(
431            "b",
432            ConcreteDataType::boolean_datatype(),
433            true,
434        )]);
435        let error = error_feeding(&mut parser, b"{\"b\":\"true\"}\n");
436        assert_eq!(error_code(&error), "22P02", "{error}");
437        assert!(error.to_string().contains("expected boolean"), "{error}");
438    }
439
440    #[test]
441    fn test_jsonl_numeric_timestamp_is_taken_in_the_column_unit() {
442        let mut parser = new_parser(&columns());
443        let rows = feed_all(
444            &mut parser,
445            &[
446                b"{\"val\":1,\"ts\":1704067200000}\n",
447                // A number is not re-scaled: 1704067200 is an epoch in
448                // the column's unit, milliseconds here.
449                b"{\"val\":2,\"ts\":1704067200}\n",
450                // Explicit offsets in strings win over the session zone.
451                b"{\"val\":3,\"ts\":\"2024-01-01T00:00:00+08:00\"}\n",
452            ],
453        );
454        assert_eq!(rows.len(), 3);
455        assert_eq!(ts_millis_at(&rows[0], 2), Some(1704067200000));
456        assert_eq!(ts_millis_at(&rows[1], 2), Some(1704067200));
457        assert_eq!(ts_millis_at(&rows[2], 2), Some(1704038400000));
458
459        // A quoted number is parsed as a date-time string, and fails.
460        let mut parser = new_parser(&columns());
461        let error = error_feeding(&mut parser, b"{\"ts\":\"1704067200000\"}\n");
462        assert_eq!(error_code(&error), "22P02", "{error}");
463    }
464
465    #[test]
466    fn test_jsonl_unknown_keys_are_ignored() {
467        let mut parser = new_parser(&columns());
468        // A misspelled key does not error: its column stays NULL.
469        let rows = feed_all(
470            &mut parser,
471            &[b"{\"hots\":\"a\",\"val\":1.5,\"ts\":\"2024-01-01 00:00:00\"}\n"],
472        );
473        assert_eq!(rows.len(), 1);
474        assert!(rows[0].values[0].value_data.is_none());
475        assert_eq!(f64_at(&rows[0], 1), Some(1.5));
476    }
477
478    #[test]
479    fn test_jsonl_column_subset_and_reorder_tolerate_extra_keys() {
480        // COPY t (ts, val) FROM STDIN: a reordered subset of the table's
481        // columns, keyed by name; records still carry the other keys.
482        let subset = vec![columns()[2].clone(), columns()[1].clone()];
483        let mut parser = new_parser(&subset);
484        let rows = feed_all(
485            &mut parser,
486            &[b"{\"host\":\"a\",\"val\":1.5,\"ts\":\"2024-01-01 00:00:00\",\"extra\":true}\n"],
487        );
488        assert_eq!(rows.len(), 1);
489        assert_eq!(rows[0].values.len(), 2);
490        assert_eq!(ts_millis_at(&rows[0], 0), Some(1704067200000));
491        assert_eq!(f64_at(&rows[0], 1), Some(1.5));
492    }
493
494    #[test]
495    fn test_jsonl_null_in_non_nullable_column_is_named() {
496        for record in [
497            // Missing key.
498            &b"{\"val\":1.5}\n"[..],
499            // Explicit null.
500            &b"{\"val\":1.5,\"ts\":null}\n"[..],
501        ] {
502            let mut parser = new_parser(&columns());
503            let error = error_feeding(&mut parser, record);
504            assert_eq!(error_code(&error), "22P04", "{record:?}: {error}");
505            let message = error.to_string();
506            assert!(message.contains("\"ts\""), "{message}");
507            assert!(message.contains("non-nullable"), "{message}");
508            assert!(!message.contains("StructArray"), "{message}");
509        }
510    }
511
512    #[test]
513    fn test_jsonl_top_level_array_is_rejected_with_hint() {
514        let mut parser = new_parser(&columns());
515        let error = parser
516            .feed(b"[{\"val\":1.5,\"ts\":\"2024-01-01 00:00:00\"}]\n")
517            .unwrap_err();
518        assert_eq!(error_code(&error), "22P04", "{error}");
519        assert!(error.to_string().contains("one object per line"), "{error}");
520
521        // Leading whitespace, even across chunks, does not hide the `[`.
522        let mut parser = new_parser(&columns());
523        parser.feed(b"\n").unwrap();
524        parser.feed(b" \t").unwrap();
525        let error = parser.feed(b" [{\"val\":1}").unwrap_err();
526        assert!(
527            error.to_string().contains("top-level JSON array"),
528            "{error}"
529        );
530
531        // A `[` later in the stream is a value, not an array of records:
532        // it fails as an ordinary syntax/type error, without the hint.
533        let mut parser = new_parser(&[ColumnSchema::new(
534            "host",
535            ConcreteDataType::string_datatype(),
536            true,
537        )]);
538        let error = error_feeding(&mut parser, b"{\"host\":\"a\"}\n[1]\n");
539        assert!(
540            !error.to_string().contains("top-level JSON array"),
541            "{error}"
542        );
543    }
544
545    #[test]
546    fn test_jsonl_syntax_errors_are_bad_copy_data() {
547        // A syntax error fails the feed itself.
548        let mut parser = new_parser(&columns());
549        let error = parser.feed(b"hello\n").unwrap_err();
550        assert_eq!(error_code(&error), "22P04", "{error}");
551
552        // Value-level failures are invalid text representation.
553        let mut parser = new_parser(&columns());
554        let error = error_feeding(
555            &mut parser,
556            br#"{"host":"a","val":"not a number","ts":"2024-01-01 00:00:00"}
557"#,
558        );
559        assert_eq!(error_code(&error), "22P02", "{error}");
560        assert!(
561            error.to_string().contains("failed to parse JSON data"),
562            "{error}"
563        );
564    }
565
566    #[test]
567    fn test_jsonl_truncated_tail_fails_at_finish() {
568        let mut parser = new_parser(&columns());
569        parser
570            .feed(b"{\"host\":\"a\",\"val\":1.5,\"ts\":\"2024-01-01 00:00:00\"}\n")
571            .unwrap();
572        parser.feed(b"{\"host\":\"b\",\"val\":2.5").unwrap();
573        let error = parser.finish().unwrap_err();
574        assert_eq!(error_code(&error), "22P04", "{error}");
575        assert!(error.to_string().contains("Truncated record"), "{error}");
576    }
577
578    #[test]
579    fn test_jsonl_multi_batch_sweep_flushes_mid_stream() {
580        // More than two full batches, fed in chunks that can split records,
581        // so batches must be detected and flushed before the stream ends.
582        let total = 2 * COPY_IN_FLUSH_ROWS + 137;
583        let mut payload = Vec::new();
584        for i in 0..total {
585            payload.extend_from_slice(format!("{{\"val\":{i},\"ts\":{i}}}\n").as_bytes());
586        }
587        let columns = columns();
588        let mut parser = new_parser(&columns);
589        let mut rows = Vec::new();
590        let mut feeds_with_rows = 0;
591        for chunk in payload.chunks(4093) {
592            let batch = parser.feed(chunk).unwrap();
593            if !batch.is_empty() {
594                feeds_with_rows += 1;
595            }
596            rows.extend(batch);
597        }
598        let tail = parser.finish().unwrap();
599        rows.extend(tail);
600
601        assert_eq!(rows.len(), total);
602        assert!(
603            feeds_with_rows >= 2,
604            "rows only surfaced at finish: the mid-stream flush path was not exercised"
605        );
606        for (i, row) in rows.iter().enumerate() {
607            assert_eq!(ts_millis_at(row, 2), Some(i as i64), "row {i}");
608            assert_eq!(f64_at(row, 1), Some(i as f64), "row {i}");
609        }
610    }
611
612    #[test]
613    fn test_jsonl_decode_error_classes() {
614        let cases = [
615            (ArrowError::ParseError("x".into()), "22P02"),
616            (ArrowError::CastError("x".into()), "22P02"),
617            (
618                ArrowError::JsonError(
619                    "whilst decoding field 'val': failed to parse \"a\" as Float64".into(),
620                ),
621                "22P02",
622            ),
623            (
624                ArrowError::JsonError("Truncated record whilst reading string".into()),
625                "22P04",
626            ),
627            (ArrowError::JsonError("expected { got [".into()), "22P04"),
628            (ArrowError::NotYetImplemented("x".into()), "22P04"),
629            (ArrowError::DivideByZero, "22P04"),
630        ];
631        for (error, expected) in cases {
632            let mapped = decode_error(error);
633            assert_eq!(error_code(&mapped), expected, "{mapped}");
634            // Never an internal error.
635            assert!(!mapped.to_string().contains("XX000"), "{mapped}");
636        }
637    }
638
639    #[test]
640    fn test_jsonl_rejects_options_and_bad_columns() {
641        let mut set = CopyOptionSet::default();
642        set.insert("header".into(), CopyOptionValue::Flag).unwrap();
643        assert!(build_jsonl_codec(set).is_err());
644
645        let codec = codec();
646        assert_eq!(codec.name(), "jsonl");
647        assert!(
648            codec
649                .check_column_type(&ConcreteDataType::json_datatype())
650                .is_err()
651        );
652        assert!(
653            codec
654                .check_column_type(&ConcreteDataType::binary_datatype())
655                .is_err()
656        );
657        assert!(
658            codec
659                .check_column_type(&ConcreteDataType::timestamp_millisecond_datatype())
660                .is_ok()
661        );
662    }
663}