Skip to main content

common_datasource/file_format/
json.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
15use std::collections::HashMap;
16use std::io::{self, BufReader};
17use std::str::FromStr;
18use std::task::Poll;
19
20use arrow::error::ArrowError;
21use arrow::json;
22use arrow::json::WriterBuilder;
23use arrow::json::reader::{ValueIter, infer_json_schema_from_iterator};
24use arrow::json::writer::LineDelimited;
25use arrow::record_batch::RecordBatch;
26use arrow_schema::{Schema, SchemaRef};
27use async_trait::async_trait;
28use bytes::{Buf, Bytes};
29use common_runtime;
30use datafusion::physical_plan::SendableRecordBatchStream;
31use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
32use futures::StreamExt;
33use futures::stream::BoxStream;
34use object_store::ObjectStore;
35use snafu::ResultExt;
36use tokio_util::compat::FuturesAsyncReadCompatExt;
37use tokio_util::io::SyncIoBridge;
38
39use crate::buffered_writer::DfRecordBatchEncoder;
40use crate::compression::CompressionType;
41use crate::error::{self, Result};
42use crate::file_format::{self, FileFormat, stream_to_file};
43use crate::share_buffer::SharedBuffer;
44use crate::util::normalize_infer_schema;
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct JsonFormat {
48    pub schema_infer_max_record: Option<usize>,
49    pub compression_type: CompressionType,
50    pub timestamp_format: Option<String>,
51    pub time_format: Option<String>,
52    pub date_format: Option<String>,
53}
54
55impl TryFrom<&HashMap<String, String>> for JsonFormat {
56    type Error = error::Error;
57
58    fn try_from(value: &HashMap<String, String>) -> Result<Self> {
59        let mut format = JsonFormat::default();
60        if let Some(compression_type) = value.get(file_format::FORMAT_COMPRESSION_TYPE) {
61            format.compression_type = CompressionType::from_str(compression_type)?
62        };
63        if let Some(schema_infer_max_record) =
64            value.get(file_format::FORMAT_SCHEMA_INFER_MAX_RECORD)
65        {
66            format.schema_infer_max_record =
67                Some(schema_infer_max_record.parse::<usize>().map_err(|_| {
68                    error::ParseFormatSnafu {
69                        key: file_format::FORMAT_SCHEMA_INFER_MAX_RECORD,
70                        value: schema_infer_max_record,
71                    }
72                    .build()
73                })?);
74        };
75        format.timestamp_format = value.get(file_format::TIMESTAMP_FORMAT).cloned();
76        format.time_format = value.get(file_format::TIME_FORMAT).cloned();
77        format.date_format = value.get(file_format::DATE_FORMAT).cloned();
78        Ok(format)
79    }
80}
81
82impl Default for JsonFormat {
83    fn default() -> Self {
84        Self {
85            schema_infer_max_record: Some(file_format::DEFAULT_SCHEMA_INFER_MAX_RECORD),
86            compression_type: CompressionType::Uncompressed,
87            timestamp_format: None,
88            time_format: None,
89            date_format: None,
90        }
91    }
92}
93
94#[async_trait]
95impl FileFormat for JsonFormat {
96    async fn infer_schema(&self, store: &ObjectStore, path: &str) -> Result<Schema> {
97        let meta = store
98            .stat(path)
99            .await
100            .context(error::ReadObjectSnafu { path })?;
101
102        let reader = store
103            .reader(path)
104            .await
105            .context(error::ReadObjectSnafu { path })?
106            .into_futures_async_read(0..meta.content_length())
107            .await
108            .context(error::ReadObjectSnafu { path })?
109            .compat();
110
111        let decoded = self.compression_type.convert_async_read(reader);
112
113        let schema_infer_max_record = self.schema_infer_max_record;
114
115        common_runtime::spawn_blocking_global(move || {
116            let mut reader = BufReader::new(SyncIoBridge::new(decoded));
117
118            let iter = ValueIter::new(&mut reader, schema_infer_max_record);
119
120            let schema = infer_json_schema_from_iterator(iter).context(error::InferSchemaSnafu)?;
121
122            Ok(normalize_infer_schema(schema))
123        })
124        .await
125        .context(error::JoinHandleSnafu)?
126    }
127}
128
129/// Returns a stream of the json file at `path` that reads the fields of `schema`.
130///
131/// Unlike the stream of a `JsonSource`, a string column also takes a number or a boolean, as
132/// the text it has in the file. So a column whose numbers must be parsed from every digit can
133/// be read as a string, see [`parse_number_columns`](super::decimal::parse_number_columns).
134pub async fn json_text_stream(
135    store: &ObjectStore,
136    path: &str,
137    schema: SchemaRef,
138    format: &JsonFormat,
139    batch_size: usize,
140) -> Result<SendableRecordBatchStream> {
141    let meta = store
142        .stat(path)
143        .await
144        .context(error::ReadObjectSnafu { path })?;
145
146    let reader = store
147        .reader(path)
148        .await
149        .context(error::ReadObjectSnafu { path })?
150        .into_bytes_stream(0..meta.content_length())
151        .await
152        .context(error::ReadObjectSnafu { path })?;
153
154    let reader = format.compression_type.convert_stream(reader).boxed();
155    json_text_stream_from_reader(reader, schema, batch_size)
156}
157
158fn json_text_stream_from_reader(
159    reader: BoxStream<'static, io::Result<Bytes>>,
160    schema: SchemaRef,
161    batch_size: usize,
162) -> Result<SendableRecordBatchStream> {
163    let mut builder = Some(
164        json::ReaderBuilder::new(schema.clone())
165            .with_coerce_primitive(true)
166            .with_batch_size(batch_size),
167    );
168    let mut decoder = None;
169
170    let mut upstream = reader.fuse();
171    let mut buffered = Bytes::new();
172    let mut input_finished = false;
173    let stream = futures::stream::poll_fn(move |cx| {
174        if let Some(builder) = builder.take() {
175            decoder = Some(builder.build_decoder()?);
176        }
177        let Some(decoder) = decoder.as_mut() else {
178            return Poll::Ready(None);
179        };
180
181        loop {
182            if input_finished {
183                return Poll::Ready(decoder.flush().transpose());
184            }
185
186            if buffered.is_empty() {
187                match futures::ready!(upstream.poll_next_unpin(cx)) {
188                    Some(Ok(bytes)) => buffered = bytes,
189                    Some(Err(error)) => return Poll::Ready(Some(Err(error.into()))),
190                    None => input_finished = true,
191                }
192                continue;
193            }
194
195            let decoded = decoder.decode(buffered.as_ref())?;
196            buffered.advance(decoded);
197            // The decoder stops before the end of the input once it holds a full batch.
198            if !buffered.is_empty()
199                && let Some(batch) = decoder.flush()?
200            {
201                return Poll::Ready(Some(Ok(batch)));
202            }
203        }
204    })
205    .map(|result: std::result::Result<RecordBatch, ArrowError>| result.map_err(Into::into));
206
207    Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream)))
208}
209
210pub async fn stream_to_json(
211    stream: SendableRecordBatchStream,
212    store: ObjectStore,
213    path: &str,
214    threshold: usize,
215    concurrency: usize,
216    format: &JsonFormat,
217) -> Result<usize> {
218    stream_to_file(
219        stream,
220        store,
221        path,
222        threshold,
223        concurrency,
224        format.compression_type,
225        |buffer| {
226            let mut builder = WriterBuilder::new().with_explicit_nulls(true);
227            if let Some(timestamp_format) = &format.timestamp_format {
228                builder = builder.with_timestamp_format(timestamp_format.to_owned());
229            }
230            if let Some(time_format) = &format.time_format {
231                builder = builder.with_time_format(time_format.to_owned());
232            }
233            if let Some(date_format) = &format.date_format {
234                builder = builder.with_date_format(date_format.to_owned());
235            }
236            builder.build::<_, LineDelimited>(buffer)
237        },
238    )
239    .await
240}
241
242impl DfRecordBatchEncoder for json::Writer<SharedBuffer, LineDelimited> {
243    fn write(&mut self, batch: &RecordBatch) -> Result<()> {
244        self.write(batch).context(error::WriteRecordBatchSnafu)
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use std::sync::Arc;
251
252    use arrow::array::AsArray;
253    use common_recordbatch::adapter::DfRecordBatchStreamAdapter;
254    use common_recordbatch::{RecordBatch, RecordBatches};
255    use common_test_util::find_workspace_path;
256    use datafusion::datasource::physical_plan::{FileSource, JsonSource};
257    use datatypes::prelude::ConcreteDataType;
258    use datatypes::schema::{ColumnSchema, Schema};
259    use datatypes::vectors::{Float64Vector, StringVector, UInt32Vector, VectorRef};
260    use futures::TryStreamExt;
261
262    use super::*;
263    use crate::file_format::{
264        FORMAT_COMPRESSION_TYPE, FORMAT_SCHEMA_INFER_MAX_RECORD, FileFormat, file_to_stream,
265    };
266    use crate::test_util::{format_schema, test_store};
267
268    fn test_data_root() -> String {
269        find_workspace_path("/src/common/datasource/tests/json")
270            .display()
271            .to_string()
272    }
273
274    #[tokio::test]
275    async fn test_json_text_stream() {
276        let schema = Arc::new(arrow_schema::Schema::new(vec![
277            arrow_schema::Field::new("price", arrow_schema::DataType::Utf8, true),
278            arrow_schema::Field::new("k", arrow_schema::DataType::Utf8, true),
279            arrow_schema::Field::new("n", arrow_schema::DataType::Int64, true),
280        ]));
281        let input: &[u8] = br#"{"k":"a","price":1.2500000000000000000000000000000000000000e0,"n":1}
282{"k":"b","price":0e0,"n":2,"unknown":true}
283{"k":"c","price":null}
284{"n":4,"price":123456789012345678.12,"k":"d"}
285{"k":"e","price":"5"}"#;
286
287        // Every size of input chunk and of batch gives the same rows.
288        for chunk_size in [1, 7, input.len()] {
289            for batch_size in [1, 2, 8192] {
290                let chunks = input
291                    .chunks(chunk_size)
292                    .map(|chunk| Ok(Bytes::copy_from_slice(chunk)))
293                    .collect::<Vec<_>>();
294                let stream = json_text_stream_from_reader(
295                    futures::stream::iter(chunks).boxed(),
296                    schema.clone(),
297                    batch_size,
298                )
299                .unwrap();
300                let batches = stream.try_collect::<Vec<_>>().await.unwrap();
301                assert!(batches.iter().all(|batch| batch.num_rows() <= batch_size));
302                let batch = arrow::compute::concat_batches(&schema, &batches).unwrap();
303
304                let prices = batch.column(0).as_string::<i32>();
305                assert_eq!(
306                    prices.iter().collect::<Vec<_>>(),
307                    vec![
308                        Some("1.2500000000000000000000000000000000000000e0"),
309                        Some("0e0"),
310                        None,
311                        Some("123456789012345678.12"),
312                        Some("5"),
313                    ]
314                );
315                let keys = batch.column(1).as_string::<i32>();
316                assert_eq!(
317                    keys.iter().collect::<Vec<_>>(),
318                    vec![Some("a"), Some("b"), Some("c"), Some("d"), Some("e")]
319                );
320                let numbers = batch
321                    .column(2)
322                    .as_primitive::<arrow::datatypes::Int64Type>();
323                assert_eq!(
324                    numbers.iter().collect::<Vec<_>>(),
325                    vec![Some(1), Some(2), None, Some(4), None]
326                );
327            }
328        }
329
330        // A record that is cut off is an error.
331        let stream = json_text_stream_from_reader(
332            futures::stream::iter(vec![Ok(Bytes::from_static(br#"{"k":"a","price":1"#))]).boxed(),
333            schema,
334            8192,
335        )
336        .unwrap();
337        assert!(stream.try_collect::<Vec<_>>().await.is_err());
338    }
339
340    #[tokio::test]
341    async fn infer_schema_basic() {
342        let json = JsonFormat::default();
343        let store = test_store(&test_data_root());
344        let schema = json.infer_schema(&store, "simple.json").await.unwrap();
345        let formatted: Vec<_> = format_schema(schema);
346
347        assert_eq!(
348            vec![
349                "a: Int64: NULL",
350                "b: Float64: NULL",
351                "c: Boolean: NULL",
352                "d: Utf8: NULL",
353            ],
354            formatted
355        );
356    }
357
358    #[tokio::test]
359    async fn normalize_infer_schema() {
360        let json = JsonFormat {
361            schema_infer_max_record: Some(3),
362            ..JsonFormat::default()
363        };
364        let store = test_store(&test_data_root());
365        let schema = json.infer_schema(&store, "max_infer.json").await.unwrap();
366        let formatted: Vec<_> = format_schema(schema);
367
368        assert_eq!(vec!["num: Int64: NULL", "str: Utf8: NULL"], formatted,);
369    }
370
371    #[tokio::test]
372    async fn infer_schema_with_limit() {
373        let json = JsonFormat {
374            schema_infer_max_record: Some(3),
375            ..JsonFormat::default()
376        };
377        let store = test_store(&test_data_root());
378        let schema = json
379            .infer_schema(&store, "schema_infer_limit.json")
380            .await
381            .unwrap();
382        let formatted: Vec<_> = format_schema(schema);
383
384        assert_eq!(
385            vec!["a: Int64: NULL", "b: Float64: NULL", "c: Boolean: NULL"],
386            formatted
387        );
388    }
389
390    #[test]
391    fn test_try_from() {
392        let map = HashMap::new();
393        let format = JsonFormat::try_from(&map).unwrap();
394
395        assert_eq!(format, JsonFormat::default());
396
397        let map = HashMap::from([
398            (
399                FORMAT_SCHEMA_INFER_MAX_RECORD.to_string(),
400                "2000".to_string(),
401            ),
402            (FORMAT_COMPRESSION_TYPE.to_string(), "zstd".to_string()),
403        ]);
404        let format = JsonFormat::try_from(&map).unwrap();
405
406        assert_eq!(
407            format,
408            JsonFormat {
409                compression_type: CompressionType::Zstd,
410                schema_infer_max_record: Some(2000),
411                ..JsonFormat::default()
412            }
413        );
414    }
415
416    #[tokio::test]
417    async fn test_compressed_json() {
418        // Create test data
419        let column_schemas = vec![
420            ColumnSchema::new("id", ConcreteDataType::uint32_datatype(), false),
421            ColumnSchema::new("name", ConcreteDataType::string_datatype(), false),
422            ColumnSchema::new("value", ConcreteDataType::float64_datatype(), false),
423        ];
424        let schema = Arc::new(Schema::new(column_schemas));
425
426        // Create multiple record batches with different data
427        let batch1_columns: Vec<VectorRef> = vec![
428            Arc::new(UInt32Vector::from_slice(vec![1, 2, 3])),
429            Arc::new(StringVector::from(vec!["Alice", "Bob", "Charlie"])),
430            Arc::new(Float64Vector::from_slice(vec![10.5, 20.3, 30.7])),
431        ];
432        let batch1 = RecordBatch::new(schema.clone(), batch1_columns).unwrap();
433
434        let batch2_columns: Vec<VectorRef> = vec![
435            Arc::new(UInt32Vector::from_slice(vec![4, 5, 6])),
436            Arc::new(StringVector::from(vec!["David", "Eva", "Frank"])),
437            Arc::new(Float64Vector::from_slice(vec![40.1, 50.2, 60.3])),
438        ];
439        let batch2 = RecordBatch::new(schema.clone(), batch2_columns).unwrap();
440
441        let batch3_columns: Vec<VectorRef> = vec![
442            Arc::new(UInt32Vector::from_slice(vec![7, 8, 9])),
443            Arc::new(StringVector::from(vec!["Grace", "Henry", "Ivy"])),
444            Arc::new(Float64Vector::from_slice(vec![70.4, 80.5, 90.6])),
445        ];
446        let batch3 = RecordBatch::new(schema.clone(), batch3_columns).unwrap();
447
448        // Combine all batches into a RecordBatches collection
449        let recordbatches = RecordBatches::try_new(schema, vec![batch1, batch2, batch3]).unwrap();
450
451        // Test with different compression types
452        let compression_types = vec![
453            CompressionType::Gzip,
454            CompressionType::Bzip2,
455            CompressionType::Xz,
456            CompressionType::Zstd,
457        ];
458
459        // Create a temporary file path
460        let temp_dir = common_test_util::temp_dir::create_temp_dir("test_compressed_json");
461        for compression_type in compression_types {
462            let format = JsonFormat {
463                compression_type,
464                ..JsonFormat::default()
465            };
466
467            let compressed_file_name =
468                format!("test_compressed_json.{}", compression_type.file_extension());
469            let compressed_file_path = temp_dir.path().join(&compressed_file_name);
470
471            // Create a simple file store for testing
472            let store = test_store(temp_dir.path().to_str().unwrap());
473
474            // Export JSON with compression
475            let rows = stream_to_json(
476                Box::pin(DfRecordBatchStreamAdapter::new(recordbatches.as_stream())),
477                store,
478                &compressed_file_name,
479                1024,
480                1,
481                &format,
482            )
483            .await
484            .unwrap();
485
486            assert_eq!(rows, 9);
487
488            // Verify compressed file was created and has content
489            assert!(compressed_file_path.exists());
490            let file_size = std::fs::metadata(&compressed_file_path).unwrap().len();
491            assert!(file_size > 0);
492
493            // Verify the file is actually compressed
494            let file_content = std::fs::read(&compressed_file_path).unwrap();
495            // Compressed files should not start with '{' (JSON character)
496            // They should have compression magic bytes
497            match compression_type {
498                CompressionType::Gzip => {
499                    // Gzip magic bytes: 0x1f 0x8b
500                    assert_eq!(file_content[0], 0x1f, "Gzip file should start with 0x1f");
501                    assert_eq!(
502                        file_content[1], 0x8b,
503                        "Gzip file should have 0x8b as second byte"
504                    );
505                }
506                CompressionType::Bzip2 => {
507                    // Bzip2 magic bytes: 'BZ'
508                    assert_eq!(file_content[0], b'B', "Bzip2 file should start with 'B'");
509                    assert_eq!(
510                        file_content[1], b'Z',
511                        "Bzip2 file should have 'Z' as second byte"
512                    );
513                }
514                CompressionType::Xz => {
515                    // XZ magic bytes: 0xFD '7zXZ'
516                    assert_eq!(file_content[0], 0xFD, "XZ file should start with 0xFD");
517                }
518                CompressionType::Zstd => {
519                    // Zstd magic bytes: 0x28 0xB5 0x2F 0xFD
520                    assert_eq!(file_content[0], 0x28, "Zstd file should start with 0x28");
521                    assert_eq!(
522                        file_content[1], 0xB5,
523                        "Zstd file should have 0xB5 as second byte"
524                    );
525                }
526                _ => {}
527            }
528
529            // Verify the compressed file can be decompressed and content matches original data
530            let store = test_store(temp_dir.path().to_str().unwrap());
531            let schema = Arc::new(
532                JsonFormat {
533                    compression_type,
534                    ..Default::default()
535                }
536                .infer_schema(&store, &compressed_file_name)
537                .await
538                .unwrap(),
539            );
540            let json_source = JsonSource::new(schema).with_batch_size(8192);
541
542            let stream = file_to_stream(
543                &store,
544                &compressed_file_name,
545                json_source.clone(),
546                None,
547                compression_type,
548            )
549            .await
550            .unwrap();
551
552            let batches = stream.try_collect::<Vec<_>>().await.unwrap();
553            let pretty_print = arrow::util::pretty::pretty_format_batches(&batches)
554                .unwrap()
555                .to_string();
556            let expected = r#"+----+---------+-------+
557| id | name    | value |
558+----+---------+-------+
559| 1  | Alice   | 10.5  |
560| 2  | Bob     | 20.3  |
561| 3  | Charlie | 30.7  |
562| 4  | David   | 40.1  |
563| 5  | Eva     | 50.2  |
564| 6  | Frank   | 60.3  |
565| 7  | Grace   | 70.4  |
566| 8  | Henry   | 80.5  |
567| 9  | Ivy     | 90.6  |
568+----+---------+-------+"#;
569            assert_eq!(expected, pretty_print);
570        }
571    }
572}