Skip to main content

arrow_integration_test/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Partial support for the [Apache Arrow JSON test data format](https://github.com/apache/arrow/blob/master/docs/source/format/Integration.rst#json-test-data-format)
6//!
7//! These utilities define structs that read the integration JSON format for integration testing purposes.
8//!
9//! This is not a canonical format, but provides a human-readable way of verifying language implementations
10//!
11//! <div class="warning">
12//!
13//! This crate is **only intended for integration testing the
14//! [Arrow project](https://github.com/apache/arrow-rs)**. It is not [intended for usage outside of
15//! this context](https://github.com/apache/arrow-rs/issues/8684#issuecomment-3433193158).
16//!
17//! </div>
18//!
19//! # Platform Support
20//!
21//! Only little-endian platforms are officially supported and tested in CI.
22//! Big-endian platforms are not tested in CI and may not work correctly.
23//! Fixes for big-endian platforms are welcome and handled on a best-effort basis,
24//! but compatibility is not guaranteed.
25
26#![doc(
27    html_logo_url = "https://arrow.apache.org/img/arrow-logo_chevrons_black-txt_white-bg.svg",
28    html_favicon_url = "https://arrow.apache.org/img/arrow-logo_chevrons_black-txt_transparent-bg.svg"
29)]
30#![cfg_attr(docsrs, feature(doc_cfg))]
31#![warn(missing_docs)]
32use arrow_buffer::{IntervalDayTime, IntervalMonthDayNano, ScalarBuffer};
33use hex::decode;
34use num_bigint::BigInt;
35use num_traits::Signed;
36use serde::{Deserialize, Serialize};
37use serde_json::{Map as SJMap, Value};
38use std::collections::HashMap;
39use std::sync::Arc;
40
41use arrow::array::*;
42use arrow::buffer::{Buffer, MutableBuffer};
43use arrow::datatypes::*;
44use arrow::error::{ArrowError, Result};
45use arrow::util::bit_util;
46
47mod datatype;
48mod field;
49mod schema;
50
51pub use datatype::*;
52pub use field::*;
53pub use schema::*;
54
55/// A struct that represents an Arrow file with a schema and record batches
56///
57/// See <https://github.com/apache/arrow/blob/master/docs/source/format/Integration.rst#json-test-data-format>
58#[derive(Deserialize, Serialize, Debug)]
59pub struct ArrowJson {
60    /// The Arrow schema for JSON file
61    pub schema: ArrowJsonSchema,
62    /// The `RecordBatch`es in the JSON file
63    pub batches: Vec<ArrowJsonBatch>,
64    /// The dictionaries in the JSON file
65    #[serde(skip_serializing_if = "Option::is_none")]
66    pub dictionaries: Option<Vec<ArrowJsonDictionaryBatch>>,
67}
68
69/// A struct that partially reads the Arrow JSON schema.
70///
71/// Fields are left as JSON `Value` as they vary by `DataType`
72#[derive(Deserialize, Serialize, Debug)]
73pub struct ArrowJsonSchema {
74    /// An array of JSON fields
75    pub fields: Vec<ArrowJsonField>,
76    /// An array of metadata key-value pairs
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub metadata: Option<Vec<HashMap<String, String>>>,
79}
80
81/// Fields are left as JSON `Value` as they vary by `DataType`
82#[derive(Deserialize, Serialize, Debug)]
83pub struct ArrowJsonField {
84    /// The name of the field
85    pub name: String,
86    /// The data type of the field,
87    /// can be any valid JSON value
88    #[serde(rename = "type")]
89    pub field_type: Value,
90    /// Whether the field is nullable
91    pub nullable: bool,
92    /// The children fields
93    pub children: Vec<ArrowJsonField>,
94    /// The dictionary for the field
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub dictionary: Option<ArrowJsonFieldDictionary>,
97    /// The metadata for the field, if any
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub metadata: Option<Value>,
100}
101
102impl From<&FieldRef> for ArrowJsonField {
103    fn from(value: &FieldRef) -> Self {
104        Self::from(value.as_ref())
105    }
106}
107
108impl From<&Field> for ArrowJsonField {
109    fn from(field: &Field) -> Self {
110        let metadata_value = match field.metadata().is_empty() {
111            false => {
112                let mut array = Vec::new();
113                for (k, v) in field.metadata() {
114                    let mut kv_map = SJMap::new();
115                    kv_map.insert(k.clone(), Value::String(v.clone()));
116                    array.push(Value::Object(kv_map));
117                }
118                if !array.is_empty() {
119                    Some(Value::Array(array))
120                } else {
121                    None
122                }
123            }
124            _ => None,
125        };
126
127        Self {
128            name: field.name().clone(),
129            field_type: data_type_to_json(field.data_type()),
130            nullable: field.is_nullable(),
131            children: vec![],
132            dictionary: None, // TODO: not enough info
133            metadata: metadata_value,
134        }
135    }
136}
137
138/// Represents a dictionary-encoded field in the Arrow JSON format
139#[derive(Deserialize, Serialize, Debug)]
140pub struct ArrowJsonFieldDictionary {
141    /// A unique identifier for the dictionary
142    pub id: i64,
143    /// The type of the dictionary index
144    #[serde(rename = "indexType")]
145    pub index_type: DictionaryIndexType,
146    /// Whether the dictionary is ordered
147    #[serde(rename = "isOrdered")]
148    pub is_ordered: bool,
149}
150
151/// Type of an index for a dictionary-encoded field in the Arrow JSON format
152#[derive(Deserialize, Serialize, Debug)]
153pub struct DictionaryIndexType {
154    /// The name of the dictionary index type
155    pub name: String,
156    /// Whether the dictionary index type is signed
157    #[serde(rename = "isSigned")]
158    pub is_signed: bool,
159    /// The bit width of the dictionary index type
160    #[serde(rename = "bitWidth")]
161    pub bit_width: i64,
162}
163
164/// A struct that partially reads the Arrow JSON record batch
165#[derive(Deserialize, Serialize, Debug, Clone)]
166pub struct ArrowJsonBatch {
167    count: usize,
168    /// The columns in the record batch
169    pub columns: Vec<ArrowJsonColumn>,
170}
171
172/// A struct that partially reads the Arrow JSON dictionary batch
173#[derive(Deserialize, Serialize, Debug, Clone)]
174pub struct ArrowJsonDictionaryBatch {
175    /// The unique identifier for the dictionary
176    pub id: i64,
177    /// The data for the dictionary
178    pub data: ArrowJsonBatch,
179}
180
181/// A struct that partially reads the Arrow JSON column/array
182#[derive(Deserialize, Serialize, Clone, Debug)]
183pub struct ArrowJsonColumn {
184    name: String,
185    /// The number of elements in the column
186    pub count: usize,
187    /// The validity bitmap to determine null values
188    #[serde(rename = "VALIDITY")]
189    pub validity: Option<Vec<u8>>,
190    /// The data values in the column
191    #[serde(rename = "DATA")]
192    pub data: Option<Vec<Value>>,
193    /// The offsets for variable-sized data types
194    #[serde(rename = "OFFSET")]
195    pub offset: Option<Vec<Value>>, // leaving as Value as 64-bit offsets are strings
196    /// The type id for union types
197    #[serde(rename = "TYPE_ID")]
198    pub type_id: Option<Vec<i8>>,
199    /// The sizes for ListView/LargeListView types
200    #[serde(rename = "SIZE")]
201    pub size: Option<Vec<Value>>,
202    /// The views for BinaryView/Utf8View types
203    #[serde(rename = "VIEWS")]
204    pub views: Option<Vec<Value>>,
205    /// The variadic data buffers for BinaryView/Utf8View types
206    #[serde(rename = "VARIADIC_DATA_BUFFERS")]
207    pub variadic_data_buffers: Option<Vec<String>>,
208    /// The children columns for nested types
209    pub children: Option<Vec<ArrowJsonColumn>>,
210}
211
212impl ArrowJson {
213    /// Compare the Arrow JSON with a record batch reader
214    pub fn equals_reader(&self, reader: &mut dyn RecordBatchReader) -> Result<bool> {
215        if !self.schema.equals_schema(&reader.schema()) {
216            return Ok(false);
217        }
218
219        for json_batch in self.get_record_batches()? {
220            let batch = reader.next();
221            match batch {
222                Some(Ok(batch)) => {
223                    if json_batch != batch {
224                        println!("json: {json_batch:?}");
225                        println!("batch: {batch:?}");
226                        return Ok(false);
227                    }
228                }
229                Some(Err(e)) => return Err(e),
230                None => return Ok(false),
231            }
232        }
233
234        Ok(true)
235    }
236
237    /// Convert the stored dictionaries to `Vec[RecordBatch]`
238    pub fn get_record_batches(&self) -> Result<Vec<RecordBatch>> {
239        let schema = self.schema.to_arrow_schema()?;
240
241        let mut dictionaries = HashMap::new();
242        self.dictionaries.iter().for_each(|dict_batches| {
243            dict_batches.iter().for_each(|d| {
244                dictionaries.insert(d.id, d.clone());
245            });
246        });
247
248        let batches: Result<Vec<_>> = self
249            .batches
250            .iter()
251            .map(|col| record_batch_from_json(&schema, col.clone(), Some(&dictionaries)))
252            .collect();
253
254        batches
255    }
256}
257
258impl ArrowJsonSchema {
259    /// Compare the Arrow JSON schema with the Arrow `Schema`
260    fn equals_schema(&self, schema: &Schema) -> bool {
261        let field_len = self.fields.len();
262        if field_len != schema.fields().len() {
263            return false;
264        }
265        for i in 0..field_len {
266            let json_field = &self.fields[i];
267            let field = schema.field(i);
268            if !json_field.equals_field(field) {
269                return false;
270            }
271        }
272        true
273    }
274
275    fn to_arrow_schema(&self) -> Result<Schema> {
276        let arrow_fields: Result<Vec<_>> = self
277            .fields
278            .iter()
279            .map(|field| field.to_arrow_field())
280            .collect();
281
282        if let Some(metadatas) = &self.metadata {
283            let mut metadata: HashMap<String, String> = HashMap::new();
284
285            metadatas.iter().for_each(|pair| {
286                let key = pair.get("key").unwrap();
287                let value = pair.get("value").unwrap();
288                metadata.insert(key.clone(), value.clone());
289            });
290
291            Ok(Schema::new_with_metadata(arrow_fields?, metadata))
292        } else {
293            Ok(Schema::new(arrow_fields?))
294        }
295    }
296}
297
298impl ArrowJsonField {
299    /// Compare the Arrow JSON field with the Arrow `Field`
300    fn equals_field(&self, field: &Field) -> bool {
301        // convert to a field
302        match self.to_arrow_field() {
303            Ok(self_field) => {
304                assert_eq!(&self_field, field, "Arrow fields not the same");
305                true
306            }
307            Err(e) => {
308                eprintln!("Encountered error while converting JSON field to Arrow field: {e:?}");
309                false
310            }
311        }
312    }
313
314    /// Convert to an Arrow Field
315    /// TODO: convert to use an Into
316    fn to_arrow_field(&self) -> Result<Field> {
317        // a bit regressive, but we have to convert the field to JSON in order to convert it
318        let field =
319            serde_json::to_value(self).map_err(|error| ArrowError::JsonError(error.to_string()))?;
320        field_from_json(&field)
321    }
322}
323
324/// Generates a [`RecordBatch`] from an Arrow JSON batch, given a schema
325pub fn record_batch_from_json(
326    schema: &Schema,
327    json_batch: ArrowJsonBatch,
328    json_dictionaries: Option<&HashMap<i64, ArrowJsonDictionaryBatch>>,
329) -> Result<RecordBatch> {
330    let mut columns = vec![];
331
332    for (field, json_col) in schema.fields().iter().zip(json_batch.columns) {
333        let col = array_from_json(field, json_col, json_dictionaries)?;
334        columns.push(col);
335    }
336
337    RecordBatch::try_new(Arc::new(schema.clone()), columns)
338}
339
340/// Construct an Arrow array from a partially typed JSON column
341pub fn array_from_json(
342    field: &Field,
343    json_col: ArrowJsonColumn,
344    dictionaries: Option<&HashMap<i64, ArrowJsonDictionaryBatch>>,
345) -> Result<ArrayRef> {
346    match field.data_type() {
347        DataType::Null => Ok(Arc::new(NullArray::new(json_col.count))),
348        DataType::Boolean => {
349            let mut b = BooleanBuilder::with_capacity(json_col.count);
350            for (is_valid, value) in json_col
351                .validity
352                .as_ref()
353                .unwrap()
354                .iter()
355                .zip(json_col.data.unwrap())
356            {
357                match is_valid {
358                    1 => b.append_value(value.as_bool().unwrap()),
359                    _ => b.append_null(),
360                }
361            }
362            Ok(Arc::new(b.finish()))
363        }
364        DataType::Int8 => {
365            let mut b = Int8Builder::with_capacity(json_col.count);
366            for (is_valid, value) in json_col
367                .validity
368                .as_ref()
369                .unwrap()
370                .iter()
371                .zip(json_col.data.unwrap())
372            {
373                match is_valid {
374                    1 => b.append_value(value.as_i64().ok_or_else(|| {
375                        ArrowError::JsonError(format!("Unable to get {value:?} as int64"))
376                    })? as i8),
377                    _ => b.append_null(),
378                }
379            }
380            Ok(Arc::new(b.finish()))
381        }
382        DataType::Int16 => {
383            let mut b = Int16Builder::with_capacity(json_col.count);
384            for (is_valid, value) in json_col
385                .validity
386                .as_ref()
387                .unwrap()
388                .iter()
389                .zip(json_col.data.unwrap())
390            {
391                match is_valid {
392                    1 => b.append_value(value.as_i64().unwrap() as i16),
393                    _ => b.append_null(),
394                }
395            }
396            Ok(Arc::new(b.finish()))
397        }
398        DataType::Int32 | DataType::Date32 | DataType::Time32(_) => {
399            let mut b = Int32Builder::with_capacity(json_col.count);
400            for (is_valid, value) in json_col
401                .validity
402                .as_ref()
403                .unwrap()
404                .iter()
405                .zip(json_col.data.unwrap())
406            {
407                match is_valid {
408                    1 => b.append_value(value.as_i64().unwrap() as i32),
409                    _ => b.append_null(),
410                }
411            }
412            let array = Arc::new(b.finish()) as ArrayRef;
413            arrow::compute::cast(&array, field.data_type())
414        }
415        DataType::Interval(IntervalUnit::YearMonth) => {
416            let mut b = IntervalYearMonthBuilder::with_capacity(json_col.count);
417            for (is_valid, value) in json_col
418                .validity
419                .as_ref()
420                .unwrap()
421                .iter()
422                .zip(json_col.data.unwrap())
423            {
424                match is_valid {
425                    1 => b.append_value(value.as_i64().unwrap() as i32),
426                    _ => b.append_null(),
427                }
428            }
429            Ok(Arc::new(b.finish()))
430        }
431        DataType::Int64
432        | DataType::Date64
433        | DataType::Time64(_)
434        | DataType::Timestamp(_, _)
435        | DataType::Duration(_) => {
436            let mut b = Int64Builder::with_capacity(json_col.count);
437            for (is_valid, value) in json_col
438                .validity
439                .as_ref()
440                .unwrap()
441                .iter()
442                .zip(json_col.data.unwrap())
443            {
444                match is_valid {
445                    1 => b.append_value(match value {
446                        Value::Number(n) => n.as_i64().unwrap(),
447                        Value::String(s) => s.parse().expect("Unable to parse string as i64"),
448                        _ => panic!("Unable to parse {value:?} as number"),
449                    }),
450                    _ => b.append_null(),
451                }
452            }
453            let array = Arc::new(b.finish()) as ArrayRef;
454            arrow::compute::cast(&array, field.data_type())
455        }
456        DataType::Interval(IntervalUnit::DayTime) => {
457            let mut b = IntervalDayTimeBuilder::with_capacity(json_col.count);
458            for (is_valid, value) in json_col
459                .validity
460                .as_ref()
461                .unwrap()
462                .iter()
463                .zip(json_col.data.unwrap())
464            {
465                match is_valid {
466                    1 => b.append_value(match value {
467                        Value::Object(ref map)
468                            if map.contains_key("days") && map.contains_key("milliseconds") =>
469                        {
470                            match field.data_type() {
471                                DataType::Interval(IntervalUnit::DayTime) => {
472                                    let days = map.get("days").unwrap();
473                                    let milliseconds = map.get("milliseconds").unwrap();
474
475                                    match (days, milliseconds) {
476                                        (Value::Number(d), Value::Number(m)) => {
477                                            let days = d.as_i64().unwrap() as _;
478                                            let millis = m.as_i64().unwrap() as _;
479                                            IntervalDayTime::new(days, millis)
480                                        }
481                                        _ => {
482                                            panic!("Unable to parse {value:?} as interval daytime")
483                                        }
484                                    }
485                                }
486                                _ => panic!("Unable to parse {value:?} as interval daytime"),
487                            }
488                        }
489                        _ => panic!("Unable to parse {value:?} as number"),
490                    }),
491                    _ => b.append_null(),
492                }
493            }
494            Ok(Arc::new(b.finish()))
495        }
496        DataType::UInt8 => {
497            let mut b = UInt8Builder::with_capacity(json_col.count);
498            for (is_valid, value) in json_col
499                .validity
500                .as_ref()
501                .unwrap()
502                .iter()
503                .zip(json_col.data.unwrap())
504            {
505                match is_valid {
506                    1 => b.append_value(value.as_u64().unwrap() as u8),
507                    _ => b.append_null(),
508                }
509            }
510            Ok(Arc::new(b.finish()))
511        }
512        DataType::UInt16 => {
513            let mut b = UInt16Builder::with_capacity(json_col.count);
514            for (is_valid, value) in json_col
515                .validity
516                .as_ref()
517                .unwrap()
518                .iter()
519                .zip(json_col.data.unwrap())
520            {
521                match is_valid {
522                    1 => b.append_value(value.as_u64().unwrap() as u16),
523                    _ => b.append_null(),
524                }
525            }
526            Ok(Arc::new(b.finish()))
527        }
528        DataType::UInt32 => {
529            let mut b = UInt32Builder::with_capacity(json_col.count);
530            for (is_valid, value) in json_col
531                .validity
532                .as_ref()
533                .unwrap()
534                .iter()
535                .zip(json_col.data.unwrap())
536            {
537                match is_valid {
538                    1 => b.append_value(value.as_u64().unwrap() as u32),
539                    _ => b.append_null(),
540                }
541            }
542            Ok(Arc::new(b.finish()))
543        }
544        DataType::UInt64 => {
545            let mut b = UInt64Builder::with_capacity(json_col.count);
546            for (is_valid, value) in json_col
547                .validity
548                .as_ref()
549                .unwrap()
550                .iter()
551                .zip(json_col.data.unwrap())
552            {
553                match is_valid {
554                    1 => {
555                        if value.is_string() {
556                            b.append_value(
557                                value
558                                    .as_str()
559                                    .unwrap()
560                                    .parse()
561                                    .expect("Unable to parse string as u64"),
562                            )
563                        } else if value.is_number() {
564                            b.append_value(value.as_u64().expect("Unable to read number as u64"))
565                        } else {
566                            panic!("Unable to parse value {value:?} as u64")
567                        }
568                    }
569                    _ => b.append_null(),
570                }
571            }
572            Ok(Arc::new(b.finish()))
573        }
574        DataType::Interval(IntervalUnit::MonthDayNano) => {
575            let mut b = IntervalMonthDayNanoBuilder::with_capacity(json_col.count);
576            for (is_valid, value) in json_col
577                .validity
578                .as_ref()
579                .unwrap()
580                .iter()
581                .zip(json_col.data.unwrap())
582            {
583                match is_valid {
584                    1 => b.append_value(match value {
585                        Value::Object(v) => {
586                            let months = v.get("months").unwrap();
587                            let days = v.get("days").unwrap();
588                            let nanoseconds = v.get("nanoseconds").unwrap();
589                            match (months, days, nanoseconds) {
590                                (
591                                    Value::Number(months),
592                                    Value::Number(days),
593                                    Value::Number(nanoseconds),
594                                ) => {
595                                    let months = months.as_i64().unwrap() as i32;
596                                    let days = days.as_i64().unwrap() as i32;
597                                    let nanoseconds = nanoseconds.as_i64().unwrap();
598                                    IntervalMonthDayNano::new(months, days, nanoseconds)
599                                }
600                                (_, _, _) => {
601                                    panic!("Unable to parse {v:?} as MonthDayNano")
602                                }
603                            }
604                        }
605                        _ => panic!("Unable to parse {value:?} as MonthDayNano"),
606                    }),
607                    _ => b.append_null(),
608                }
609            }
610            Ok(Arc::new(b.finish()))
611        }
612        DataType::Float32 => {
613            let mut b = Float32Builder::with_capacity(json_col.count);
614            for (is_valid, value) in json_col
615                .validity
616                .as_ref()
617                .unwrap()
618                .iter()
619                .zip(json_col.data.unwrap())
620            {
621                match is_valid {
622                    1 => b.append_value(value.as_f64().unwrap() as f32),
623                    _ => b.append_null(),
624                }
625            }
626            Ok(Arc::new(b.finish()))
627        }
628        DataType::Float64 => {
629            let mut b = Float64Builder::with_capacity(json_col.count);
630            for (is_valid, value) in json_col
631                .validity
632                .as_ref()
633                .unwrap()
634                .iter()
635                .zip(json_col.data.unwrap())
636            {
637                match is_valid {
638                    1 => b.append_value(value.as_f64().unwrap()),
639                    _ => b.append_null(),
640                }
641            }
642            Ok(Arc::new(b.finish()))
643        }
644        DataType::Binary => {
645            let mut b = BinaryBuilder::with_capacity(json_col.count, 1024);
646            for (is_valid, value) in json_col
647                .validity
648                .as_ref()
649                .unwrap()
650                .iter()
651                .zip(json_col.data.unwrap())
652            {
653                match is_valid {
654                    1 => {
655                        let v = decode(value.as_str().unwrap()).unwrap();
656                        b.append_value(&v)
657                    }
658                    _ => b.append_null(),
659                }
660            }
661            Ok(Arc::new(b.finish()))
662        }
663        DataType::LargeBinary => {
664            let mut b = LargeBinaryBuilder::with_capacity(json_col.count, 1024);
665            for (is_valid, value) in json_col
666                .validity
667                .as_ref()
668                .unwrap()
669                .iter()
670                .zip(json_col.data.unwrap())
671            {
672                match is_valid {
673                    1 => {
674                        let v = decode(value.as_str().unwrap()).unwrap();
675                        b.append_value(&v)
676                    }
677                    _ => b.append_null(),
678                }
679            }
680            Ok(Arc::new(b.finish()))
681        }
682        DataType::Utf8 => {
683            let mut b = StringBuilder::with_capacity(json_col.count, 1024);
684            for (is_valid, value) in json_col
685                .validity
686                .as_ref()
687                .unwrap()
688                .iter()
689                .zip(json_col.data.unwrap())
690            {
691                match is_valid {
692                    1 => b.append_value(value.as_str().unwrap()),
693                    _ => b.append_null(),
694                }
695            }
696            Ok(Arc::new(b.finish()))
697        }
698        DataType::LargeUtf8 => {
699            let mut b = LargeStringBuilder::with_capacity(json_col.count, 1024);
700            for (is_valid, value) in json_col
701                .validity
702                .as_ref()
703                .unwrap()
704                .iter()
705                .zip(json_col.data.unwrap())
706            {
707                match is_valid {
708                    1 => b.append_value(value.as_str().unwrap()),
709                    _ => b.append_null(),
710                }
711            }
712            Ok(Arc::new(b.finish()))
713        }
714        DataType::FixedSizeBinary(len) => {
715            let mut b = FixedSizeBinaryBuilder::with_capacity(json_col.count, *len);
716            for (is_valid, value) in json_col
717                .validity
718                .as_ref()
719                .unwrap()
720                .iter()
721                .zip(json_col.data.unwrap())
722            {
723                match is_valid {
724                    1 => {
725                        let v = hex::decode(value.as_str().unwrap()).unwrap();
726                        b.append_value(&v)?
727                    }
728                    _ => b.append_null(),
729                }
730            }
731            Ok(Arc::new(b.finish()))
732        }
733        DataType::List(child_field) => {
734            let null_buf = create_null_buf(&json_col);
735            let children = json_col.children.clone().unwrap();
736            let child_array = array_from_json(child_field, children[0].clone(), dictionaries)?;
737            let offsets: Vec<i32> = json_col
738                .offset
739                .unwrap()
740                .iter()
741                .map(|v| v.as_i64().unwrap() as i32)
742                .collect();
743            let list_data = ArrayData::builder(field.data_type().clone())
744                .len(json_col.count)
745                .offset(0)
746                .add_buffer(Buffer::from(offsets.to_byte_slice()))
747                .add_child_data(child_array.into_data())
748                .null_bit_buffer(Some(null_buf))
749                .build()
750                .unwrap();
751            Ok(Arc::new(ListArray::from(list_data)))
752        }
753        DataType::LargeList(child_field) => {
754            let null_buf = create_null_buf(&json_col);
755            let children = json_col.children.clone().unwrap();
756            let child_array = array_from_json(child_field, children[0].clone(), dictionaries)?;
757            let offsets: Vec<i64> = json_col
758                .offset
759                .unwrap()
760                .iter()
761                .map(|v| match v {
762                    Value::Number(n) => n.as_i64().unwrap(),
763                    Value::String(s) => s.parse::<i64>().unwrap(),
764                    _ => panic!("64-bit offset must be either string or number"),
765                })
766                .collect();
767            let list_data = ArrayData::builder(field.data_type().clone())
768                .len(json_col.count)
769                .offset(0)
770                .add_buffer(Buffer::from(offsets.to_byte_slice()))
771                .add_child_data(child_array.into_data())
772                .null_bit_buffer(Some(null_buf))
773                .build()
774                .unwrap();
775            Ok(Arc::new(LargeListArray::from(list_data)))
776        }
777        DataType::ListView(child_field) => {
778            let null_buf = create_null_buf(&json_col);
779            let children = json_col.children.clone().unwrap();
780            let child_array = array_from_json(child_field, children[0].clone(), dictionaries)?;
781            let offsets: Vec<i32> = json_col
782                .offset
783                .unwrap()
784                .iter()
785                .map(|v| v.as_i64().unwrap() as i32)
786                .collect();
787            let sizes: Vec<i32> = json_col
788                .size
789                .unwrap()
790                .iter()
791                .map(|v| v.as_i64().unwrap() as i32)
792                .collect();
793            let list_data = ArrayData::builder(field.data_type().clone())
794                .len(json_col.count)
795                .add_buffer(Buffer::from(offsets.to_byte_slice()))
796                .add_buffer(Buffer::from(sizes.to_byte_slice()))
797                .add_child_data(child_array.into_data())
798                .null_bit_buffer(Some(null_buf))
799                .build()
800                .unwrap();
801            Ok(Arc::new(ListViewArray::from(list_data)))
802        }
803        DataType::LargeListView(child_field) => {
804            let null_buf = create_null_buf(&json_col);
805            let children = json_col.children.clone().unwrap();
806            let child_array = array_from_json(child_field, children[0].clone(), dictionaries)?;
807            let offsets: Vec<i64> = json_col
808                .offset
809                .unwrap()
810                .iter()
811                .map(|v| match v {
812                    Value::Number(n) => n.as_i64().unwrap(),
813                    Value::String(s) => s.parse::<i64>().unwrap(),
814                    _ => panic!("64-bit offset must be either string or number"),
815                })
816                .collect();
817            let sizes: Vec<i64> = json_col
818                .size
819                .unwrap()
820                .iter()
821                .map(|v| match v {
822                    Value::Number(n) => n.as_i64().unwrap(),
823                    Value::String(s) => s.parse::<i64>().unwrap(),
824                    _ => panic!("64-bit size must be either string or number"),
825                })
826                .collect();
827            let list_data = ArrayData::builder(field.data_type().clone())
828                .len(json_col.count)
829                .add_buffer(Buffer::from(offsets.to_byte_slice()))
830                .add_buffer(Buffer::from(sizes.to_byte_slice()))
831                .add_child_data(child_array.into_data())
832                .null_bit_buffer(Some(null_buf))
833                .build()
834                .unwrap();
835            Ok(Arc::new(LargeListViewArray::from(list_data)))
836        }
837        DataType::FixedSizeList(child_field, _) => {
838            let children = json_col.children.clone().unwrap();
839            let child_array = array_from_json(child_field, children[0].clone(), dictionaries)?;
840            let null_buf = create_null_buf(&json_col);
841            let list_data = ArrayData::builder(field.data_type().clone())
842                .len(json_col.count)
843                .add_child_data(child_array.into_data())
844                .null_bit_buffer(Some(null_buf))
845                .build()
846                .unwrap();
847            Ok(Arc::new(FixedSizeListArray::from(list_data)))
848        }
849        DataType::Struct(fields) => {
850            // construct struct with null data
851            let null_buf = create_null_buf(&json_col);
852            let mut array_data = ArrayData::builder(field.data_type().clone())
853                .len(json_col.count)
854                .null_bit_buffer(Some(null_buf));
855
856            for (field, col) in fields.iter().zip(json_col.children.unwrap()) {
857                let array = array_from_json(field, col, dictionaries)?;
858                array_data = array_data.add_child_data(array.into_data());
859            }
860
861            let array = StructArray::from(array_data.build().unwrap());
862            Ok(Arc::new(array))
863        }
864        DataType::Dictionary(key_type, value_type) => {
865            #[expect(deprecated)]
866            let dict_id = field.dict_id().ok_or_else(|| {
867                ArrowError::JsonError(format!("Unable to find dict_id for field {field}"))
868            })?;
869            // find dictionary
870            let dictionary = dictionaries
871                .ok_or_else(|| {
872                    ArrowError::JsonError(format!(
873                        "Unable to find any dictionaries for field {field}"
874                    ))
875                })?
876                .get(&dict_id);
877            match dictionary {
878                Some(dictionary) => dictionary_array_from_json(
879                    field,
880                    json_col,
881                    key_type,
882                    value_type,
883                    dictionary,
884                    dictionaries,
885                ),
886                None => Err(ArrowError::JsonError(format!(
887                    "Unable to find dictionary for field {field}"
888                ))),
889            }
890        }
891        DataType::Decimal32(precision, scale) => {
892            let mut b = Decimal32Builder::with_capacity(json_col.count);
893            for (is_valid, value) in json_col
894                .validity
895                .as_ref()
896                .unwrap()
897                .iter()
898                .zip(json_col.data.unwrap())
899            {
900                match is_valid {
901                    1 => b.append_value(value.as_str().unwrap().parse::<i32>().unwrap()),
902                    _ => b.append_null(),
903                }
904            }
905            Ok(Arc::new(
906                b.finish().with_precision_and_scale(*precision, *scale)?,
907            ))
908        }
909        DataType::Decimal64(precision, scale) => {
910            let mut b = Decimal64Builder::with_capacity(json_col.count);
911            for (is_valid, value) in json_col
912                .validity
913                .as_ref()
914                .unwrap()
915                .iter()
916                .zip(json_col.data.unwrap())
917            {
918                match is_valid {
919                    1 => b.append_value(value.as_str().unwrap().parse::<i64>().unwrap()),
920                    _ => b.append_null(),
921                }
922            }
923            Ok(Arc::new(
924                b.finish().with_precision_and_scale(*precision, *scale)?,
925            ))
926        }
927        DataType::Decimal128(precision, scale) => {
928            let mut b = Decimal128Builder::with_capacity(json_col.count);
929            for (is_valid, value) in json_col
930                .validity
931                .as_ref()
932                .unwrap()
933                .iter()
934                .zip(json_col.data.unwrap())
935            {
936                match is_valid {
937                    1 => b.append_value(value.as_str().unwrap().parse::<i128>().unwrap()),
938                    _ => b.append_null(),
939                }
940            }
941            Ok(Arc::new(
942                b.finish().with_precision_and_scale(*precision, *scale)?,
943            ))
944        }
945        DataType::Decimal256(precision, scale) => {
946            let mut b = Decimal256Builder::with_capacity(json_col.count);
947            for (is_valid, value) in json_col
948                .validity
949                .as_ref()
950                .unwrap()
951                .iter()
952                .zip(json_col.data.unwrap())
953            {
954                match is_valid {
955                    1 => {
956                        let str = value.as_str().unwrap();
957                        let integer = BigInt::parse_bytes(str.as_bytes(), 10).unwrap();
958                        let integer_bytes = integer.to_signed_bytes_le();
959                        // Sign-extend the minimal-length two's-complement
960                        // encoding to the full 32 bytes: 0x00 fill for
961                        // non-negative values, 0xFF for negative ones.
962                        let mut bytes = if integer.is_negative() {
963                            [255_u8; 32]
964                        } else {
965                            [0_u8; 32]
966                        };
967                        bytes[0..integer_bytes.len()].copy_from_slice(integer_bytes.as_slice());
968                        b.append_value(i256::from_le_bytes(bytes));
969                    }
970                    _ => b.append_null(),
971                }
972            }
973            Ok(Arc::new(
974                b.finish().with_precision_and_scale(*precision, *scale)?,
975            ))
976        }
977        DataType::Map(child_field, _) => {
978            let null_buf = create_null_buf(&json_col);
979            let children = json_col.children.clone().unwrap();
980            let child_array = array_from_json(child_field, children[0].clone(), dictionaries)?;
981            let offsets: Vec<i32> = json_col
982                .offset
983                .unwrap()
984                .iter()
985                .map(|v| v.as_i64().unwrap() as i32)
986                .collect();
987            let array_data = ArrayData::builder(field.data_type().clone())
988                .len(json_col.count)
989                .add_buffer(Buffer::from(offsets.to_byte_slice()))
990                .add_child_data(child_array.into_data())
991                .null_bit_buffer(Some(null_buf))
992                .build()
993                .unwrap();
994
995            let array = MapArray::from(array_data);
996            Ok(Arc::new(array))
997        }
998        DataType::Union(fields, _) => {
999            let Some(type_ids) = json_col.type_id else {
1000                return Err(ArrowError::JsonError(
1001                    "Cannot find expected type_id in json column".to_string(),
1002                ));
1003            };
1004
1005            let offset: Option<ScalarBuffer<i32>> = json_col
1006                .offset
1007                .map(|offsets| offsets.iter().map(|v| v.as_i64().unwrap() as i32).collect());
1008
1009            let mut children = Vec::with_capacity(fields.len());
1010            for ((_, field), col) in fields.iter().zip(json_col.children.unwrap()) {
1011                let array = array_from_json(field, col, dictionaries)?;
1012                children.push(array);
1013            }
1014
1015            let array =
1016                UnionArray::try_new(fields.clone(), type_ids.into(), offset, children).unwrap();
1017            Ok(Arc::new(array))
1018        }
1019        DataType::Utf8View => {
1020            let views = json_col.views.ok_or_else(|| {
1021                ArrowError::JsonError("Utf8View requires VIEWS field".to_string())
1022            })?;
1023            let variadic_buffers = json_col.variadic_data_buffers.unwrap_or_default();
1024            let validity = json_col.validity.as_ref();
1025
1026            let mut builder = StringViewBuilder::new();
1027            for (i, view) in views.iter().enumerate() {
1028                let is_valid = validity.map_or(1, |v| v[i]);
1029                if is_valid == 0 {
1030                    builder.append_null();
1031                } else {
1032                    let view_obj = view.as_object().unwrap();
1033                    let size = view_obj["SIZE"].as_u64().unwrap() as usize;
1034                    // Check for INLINED key presence - inlined if SIZE <= 12
1035                    if let Some(inlined) = view_obj.get("INLINED") {
1036                        builder.append_value(inlined.as_str().unwrap());
1037                    } else {
1038                        // Reference to variadic buffer
1039                        let buffer_index = view_obj["BUFFER_INDEX"].as_u64().unwrap() as usize;
1040                        let offset = view_obj["OFFSET"].as_u64().unwrap() as usize;
1041                        let buffer_data = hex::decode(&variadic_buffers[buffer_index]).unwrap();
1042                        let s = std::str::from_utf8(&buffer_data[offset..offset + size]).unwrap();
1043                        builder.append_value(s);
1044                    }
1045                }
1046            }
1047            Ok(Arc::new(builder.finish()))
1048        }
1049        DataType::BinaryView => {
1050            let views = json_col.views.ok_or_else(|| {
1051                ArrowError::JsonError("BinaryView requires VIEWS field".to_string())
1052            })?;
1053            let variadic_buffers = json_col.variadic_data_buffers.unwrap_or_default();
1054            let validity = json_col.validity.as_ref();
1055
1056            let mut builder = BinaryViewBuilder::new();
1057            for (i, view) in views.iter().enumerate() {
1058                let is_valid = validity.map_or(1, |v| v[i]);
1059                if is_valid == 0 {
1060                    builder.append_null();
1061                } else {
1062                    let view_obj = view.as_object().unwrap();
1063                    let size = view_obj["SIZE"].as_u64().unwrap() as usize;
1064                    // Check for INLINED key presence - inlined if SIZE <= 12
1065                    if let Some(inlined) = view_obj.get("INLINED") {
1066                        let data = hex::decode(inlined.as_str().unwrap()).unwrap();
1067                        builder.append_value(&data);
1068                    } else {
1069                        // Reference to variadic buffer
1070                        let buffer_index = view_obj["BUFFER_INDEX"].as_u64().unwrap() as usize;
1071                        let offset = view_obj["OFFSET"].as_u64().unwrap() as usize;
1072                        let buffer_data = hex::decode(&variadic_buffers[buffer_index]).unwrap();
1073                        builder.append_value(&buffer_data[offset..offset + size]);
1074                    }
1075                }
1076            }
1077            Ok(Arc::new(builder.finish()))
1078        }
1079        DataType::RunEndEncoded(run_ends_field, values_field) => {
1080            let children = json_col.children.clone().unwrap();
1081            if children.len() != 2 {
1082                return Err(ArrowError::JsonError(
1083                    "RunEndEncoded requires exactly 2 children".to_string(),
1084                ));
1085            }
1086            let run_ends_array =
1087                array_from_json(run_ends_field, children[0].clone(), dictionaries)?;
1088            let values_array = array_from_json(values_field, children[1].clone(), dictionaries)?;
1089
1090            let run_array_data = ArrayData::builder(field.data_type().clone())
1091                .len(json_col.count)
1092                .add_child_data(run_ends_array.into_data())
1093                .add_child_data(values_array.into_data())
1094                .build()
1095                .unwrap();
1096
1097            Ok(make_array(run_array_data))
1098        }
1099        t => Err(ArrowError::JsonError(format!(
1100            "data type {t} not supported"
1101        ))),
1102    }
1103}
1104
1105/// Construct a [`DictionaryArray`] from a partially typed JSON column
1106pub fn dictionary_array_from_json(
1107    field: &Field,
1108    json_col: ArrowJsonColumn,
1109    dict_key: &DataType,
1110    dict_value: &DataType,
1111    dictionary: &ArrowJsonDictionaryBatch,
1112    dictionaries: Option<&HashMap<i64, ArrowJsonDictionaryBatch>>,
1113) -> Result<ArrayRef> {
1114    match dict_key {
1115        DataType::Int8
1116        | DataType::Int16
1117        | DataType::Int32
1118        | DataType::Int64
1119        | DataType::UInt8
1120        | DataType::UInt16
1121        | DataType::UInt32
1122        | DataType::UInt64 => {
1123            let null_buf = create_null_buf(&json_col);
1124
1125            // build the key data into a buffer, then construct values separately
1126            #[expect(deprecated)]
1127            let key_field = Field::new_dict(
1128                "key",
1129                dict_key.clone(),
1130                field.is_nullable(),
1131                #[expect(deprecated)]
1132                field
1133                    .dict_id()
1134                    .expect("Dictionary fields must have a dict_id value"),
1135                field
1136                    .dict_is_ordered()
1137                    .expect("Dictionary fields must have a dict_is_ordered value"),
1138            );
1139            let keys = array_from_json(&key_field, json_col, None)?;
1140            // note: not enough info on nullability of dictionary
1141            let value_field = Field::new("value", dict_value.clone(), true);
1142            let values = array_from_json(
1143                &value_field,
1144                dictionary.data.columns[0].clone(),
1145                dictionaries,
1146            )?;
1147
1148            // convert key and value to dictionary data
1149            let dict_data = ArrayData::builder(field.data_type().clone())
1150                .len(keys.len())
1151                .add_buffer(keys.to_data().buffers()[0].clone())
1152                .null_bit_buffer(Some(null_buf))
1153                .add_child_data(values.into_data())
1154                .build()
1155                .unwrap();
1156
1157            let array = match dict_key {
1158                DataType::Int8 => Arc::new(Int8DictionaryArray::from(dict_data)) as ArrayRef,
1159                DataType::Int16 => Arc::new(Int16DictionaryArray::from(dict_data)),
1160                DataType::Int32 => Arc::new(Int32DictionaryArray::from(dict_data)),
1161                DataType::Int64 => Arc::new(Int64DictionaryArray::from(dict_data)),
1162                DataType::UInt8 => Arc::new(UInt8DictionaryArray::from(dict_data)),
1163                DataType::UInt16 => Arc::new(UInt16DictionaryArray::from(dict_data)),
1164                DataType::UInt32 => Arc::new(UInt32DictionaryArray::from(dict_data)),
1165                DataType::UInt64 => Arc::new(UInt64DictionaryArray::from(dict_data)),
1166                _ => unreachable!(),
1167            };
1168            Ok(array)
1169        }
1170        _ => Err(ArrowError::JsonError(format!(
1171            "Dictionary key type {dict_key:?} not supported"
1172        ))),
1173    }
1174}
1175
1176/// A helper to create a null buffer from a `Vec<bool>`
1177fn create_null_buf(json_col: &ArrowJsonColumn) -> Buffer {
1178    let num_bytes = bit_util::ceil(json_col.count, 8);
1179    let mut null_buf = MutableBuffer::new(num_bytes).with_bitset(num_bytes, false);
1180    json_col
1181        .validity
1182        .clone()
1183        .unwrap()
1184        .iter()
1185        .enumerate()
1186        .for_each(|(i, v)| {
1187            let null_slice = null_buf.as_slice_mut();
1188            if *v != 0 {
1189                bit_util::set_bit(null_slice, i);
1190            }
1191        });
1192    null_buf.into()
1193}
1194
1195impl ArrowJsonBatch {
1196    /// Convert a [`RecordBatch`] to an [`ArrowJsonBatch`]
1197    ///
1198    /// <div class="warning">
1199    ///
1200    /// This function is **deliberately incomplete**! As noted in the crate-level documentation,
1201    /// this crate is only intended for use within the Arrow project itself.
1202    ///
1203    /// Right now, this function only supports `DataType::Int8` columns. Other data types will lead
1204    /// to an empty `ArrowJsonColumn`.
1205    ///
1206    /// </div>
1207    pub fn from_batch(batch: &RecordBatch) -> ArrowJsonBatch {
1208        let mut json_batch = ArrowJsonBatch {
1209            count: batch.num_rows(),
1210            columns: Vec::with_capacity(batch.num_columns()),
1211        };
1212
1213        for (col, field) in batch.columns().iter().zip(batch.schema().fields.iter()) {
1214            let json_col = match field.data_type() {
1215                DataType::Int8 => {
1216                    let col = col.as_any().downcast_ref::<Int8Array>().unwrap();
1217
1218                    let mut validity: Vec<u8> = Vec::with_capacity(col.len());
1219                    let mut data: Vec<Value> = Vec::with_capacity(col.len());
1220
1221                    for i in 0..col.len() {
1222                        if col.is_null(i) {
1223                            validity.push(1);
1224                            data.push(0i8.into());
1225                        } else {
1226                            validity.push(0);
1227                            data.push(col.value(i).into());
1228                        }
1229                    }
1230
1231                    ArrowJsonColumn {
1232                        name: field.name().clone(),
1233                        count: col.len(),
1234                        validity: Some(validity),
1235                        data: Some(data),
1236                        offset: None,
1237                        type_id: None,
1238                        size: None,
1239                        views: None,
1240                        variadic_data_buffers: None,
1241                        children: None,
1242                    }
1243                }
1244                _ => ArrowJsonColumn {
1245                    name: field.name().clone(),
1246                    count: col.len(),
1247                    validity: None,
1248                    data: None,
1249                    offset: None,
1250                    type_id: None,
1251                    size: None,
1252                    views: None,
1253                    variadic_data_buffers: None,
1254                    children: None,
1255                },
1256            };
1257
1258            json_batch.columns.push(json_col);
1259        }
1260
1261        json_batch
1262    }
1263}
1264
1265#[cfg(test)]
1266mod tests {
1267    use super::*;
1268
1269    #[test]
1270    fn test_decimal256_from_json() {
1271        let field = Field::new("c", DataType::Decimal256(76, 0), false);
1272        let col: ArrowJsonColumn = serde_json::from_str(
1273            r#"{
1274                "name": "c",
1275                "count": 5,
1276                "VALIDITY": [1, 1, 1, 1, 1],
1277                "DATA": [
1278                    "0",
1279                    "1",
1280                    "-1",
1281                    "123456789012345678901234567890",
1282                    "-123456789012345678901234567890"
1283                ]
1284            }"#,
1285        )
1286        .unwrap();
1287        let arr = array_from_json(&field, col, None).unwrap();
1288        let arr = arr.as_any().downcast_ref::<Decimal256Array>().unwrap();
1289        assert_eq!(arr.value(0), i256::ZERO);
1290        assert_eq!(arr.value(1), i256::from_i128(1));
1291        assert_eq!(arr.value(2), i256::from_i128(-1));
1292        let big = i256::from_string("123456789012345678901234567890").unwrap();
1293        assert_eq!(arr.value(3), big);
1294        assert_eq!(arr.value(4), i256::ZERO - big);
1295    }
1296
1297    #[test]
1298    fn test_schema_equality() {
1299        let json = r#"
1300        {
1301            "fields": [
1302                {
1303                    "name": "c1",
1304                    "type": {"name": "int", "isSigned": true, "bitWidth": 32},
1305                    "nullable": true,
1306                    "children": []
1307                },
1308                {
1309                    "name": "c2",
1310                    "type": {"name": "floatingpoint", "precision": "DOUBLE"},
1311                    "nullable": true,
1312                    "children": []
1313                },
1314                {
1315                    "name": "c3",
1316                    "type": {"name": "utf8"},
1317                    "nullable": true,
1318                    "children": []
1319                },
1320                {
1321                    "name": "c4",
1322                    "type": {
1323                        "name": "list"
1324                    },
1325                    "nullable": true,
1326                    "children": [
1327                        {
1328                            "name": "custom_item",
1329                            "type": {
1330                                "name": "int",
1331                                "isSigned": true,
1332                                "bitWidth": 32
1333                            },
1334                            "nullable": false,
1335                            "children": []
1336                        }
1337                    ]
1338                }
1339            ]
1340        }"#;
1341        let json_schema: ArrowJsonSchema = serde_json::from_str(json).unwrap();
1342        let schema = Schema::new(vec![
1343            Field::new("c1", DataType::Int32, true),
1344            Field::new("c2", DataType::Float64, true),
1345            Field::new("c3", DataType::Utf8, true),
1346            Field::new(
1347                "c4",
1348                DataType::List(Arc::new(Field::new("custom_item", DataType::Int32, false))),
1349                true,
1350            ),
1351        ]);
1352        assert!(json_schema.equals_schema(&schema));
1353    }
1354
1355    #[test]
1356    fn test_arrow_data_equality() {
1357        let secs_tz = Some("Europe/Budapest".into());
1358        let millis_tz = Some("America/New_York".into());
1359        let micros_tz = Some("UTC".into());
1360        let nanos_tz = Some("Africa/Johannesburg".into());
1361
1362        let schema = Schema::new(vec![
1363            Field::new("bools-with-metadata-map", DataType::Boolean, true)
1364                .with_metadata([("k", "v")]),
1365            Field::new("bools-with-metadata-vec", DataType::Boolean, true)
1366                .with_metadata([("k2", "v2")]),
1367            Field::new("bools", DataType::Boolean, true),
1368            Field::new("int8s", DataType::Int8, true),
1369            Field::new("int16s", DataType::Int16, true),
1370            Field::new("int32s", DataType::Int32, true),
1371            Field::new("int64s", DataType::Int64, true),
1372            Field::new("uint8s", DataType::UInt8, true),
1373            Field::new("uint16s", DataType::UInt16, true),
1374            Field::new("uint32s", DataType::UInt32, true),
1375            Field::new("uint64s", DataType::UInt64, true),
1376            Field::new("float32s", DataType::Float32, true),
1377            Field::new("float64s", DataType::Float64, true),
1378            Field::new("date_days", DataType::Date32, true),
1379            Field::new("date_millis", DataType::Date64, true),
1380            Field::new("time_secs", DataType::Time32(TimeUnit::Second), true),
1381            Field::new("time_millis", DataType::Time32(TimeUnit::Millisecond), true),
1382            Field::new("time_micros", DataType::Time64(TimeUnit::Microsecond), true),
1383            Field::new("time_nanos", DataType::Time64(TimeUnit::Nanosecond), true),
1384            Field::new("ts_secs", DataType::Timestamp(TimeUnit::Second, None), true),
1385            Field::new(
1386                "ts_millis",
1387                DataType::Timestamp(TimeUnit::Millisecond, None),
1388                true,
1389            ),
1390            Field::new(
1391                "ts_micros",
1392                DataType::Timestamp(TimeUnit::Microsecond, None),
1393                true,
1394            ),
1395            Field::new(
1396                "ts_nanos",
1397                DataType::Timestamp(TimeUnit::Nanosecond, None),
1398                true,
1399            ),
1400            Field::new(
1401                "ts_secs_tz",
1402                DataType::Timestamp(TimeUnit::Second, secs_tz.clone()),
1403                true,
1404            ),
1405            Field::new(
1406                "ts_millis_tz",
1407                DataType::Timestamp(TimeUnit::Millisecond, millis_tz.clone()),
1408                true,
1409            ),
1410            Field::new(
1411                "ts_micros_tz",
1412                DataType::Timestamp(TimeUnit::Microsecond, micros_tz.clone()),
1413                true,
1414            ),
1415            Field::new(
1416                "ts_nanos_tz",
1417                DataType::Timestamp(TimeUnit::Nanosecond, nanos_tz.clone()),
1418                true,
1419            ),
1420            Field::new("utf8s", DataType::Utf8, true),
1421            Field::new(
1422                "lists",
1423                DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true))),
1424                true,
1425            ),
1426            Field::new(
1427                "structs",
1428                DataType::Struct(Fields::from(vec![
1429                    Field::new("int32s", DataType::Int32, true),
1430                    Field::new("utf8s", DataType::Utf8, true),
1431                ])),
1432                true,
1433            ),
1434            Field::new("utf8views", DataType::Utf8View, true),
1435            Field::new("binaryviews", DataType::BinaryView, true),
1436            Field::new(
1437                "listviews",
1438                DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, true))),
1439                true,
1440            ),
1441            Field::new(
1442                "largelistviews",
1443                DataType::LargeListView(Arc::new(Field::new_list_field(DataType::Int32, true))),
1444                true,
1445            ),
1446            Field::new(
1447                "runendencoded",
1448                DataType::RunEndEncoded(
1449                    Arc::new(Field::new(
1450                        Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
1451                        DataType::Int16,
1452                        false,
1453                    )),
1454                    Arc::new(Field::new(
1455                        Field::REE_VALUES_FIELD_DEFAULT_NAME,
1456                        DataType::Int32,
1457                        true,
1458                    )),
1459                ),
1460                true,
1461            ),
1462        ]);
1463
1464        let bools_with_metadata_map = BooleanArray::from(vec![Some(true), None, Some(false)]);
1465        let bools_with_metadata_vec = BooleanArray::from(vec![Some(true), None, Some(false)]);
1466        let bools = BooleanArray::from(vec![Some(true), None, Some(false)]);
1467        let int8s = Int8Array::from(vec![Some(1), None, Some(3)]);
1468        let int16s = Int16Array::from(vec![Some(1), None, Some(3)]);
1469        let int32s = Int32Array::from(vec![Some(1), None, Some(3)]);
1470        let int64s = Int64Array::from(vec![Some(1), None, Some(3)]);
1471        let uint8s = UInt8Array::from(vec![Some(1), None, Some(3)]);
1472        let uint16s = UInt16Array::from(vec![Some(1), None, Some(3)]);
1473        let uint32s = UInt32Array::from(vec![Some(1), None, Some(3)]);
1474        let uint64s = UInt64Array::from(vec![Some(1), None, Some(3)]);
1475        let float32s = Float32Array::from(vec![Some(1.0), None, Some(3.0)]);
1476        let float64s = Float64Array::from(vec![Some(1.0), None, Some(3.0)]);
1477        let date_days = Date32Array::from(vec![Some(1196848), None, None]);
1478        let date_millis = Date64Array::from(vec![
1479            Some(167903550396207),
1480            Some(29923997007884),
1481            Some(30612271819236),
1482        ]);
1483        let time_secs = Time32SecondArray::from(vec![Some(27974), Some(78592), Some(43207)]);
1484        let time_millis =
1485            Time32MillisecondArray::from(vec![Some(6613125), Some(74667230), Some(52260079)]);
1486        let time_micros = Time64MicrosecondArray::from(vec![Some(62522958593), None, None]);
1487        let time_nanos =
1488            Time64NanosecondArray::from(vec![Some(73380123595985), None, Some(16584393546415)]);
1489        let ts_secs = TimestampSecondArray::from(vec![None, Some(193438817552), None]);
1490        let ts_millis =
1491            TimestampMillisecondArray::from(vec![None, Some(38606916383008), Some(58113709376587)]);
1492        let ts_micros = TimestampMicrosecondArray::from(vec![None, None, None]);
1493        let ts_nanos = TimestampNanosecondArray::from(vec![None, None, Some(-6473623571954960143)]);
1494        let ts_secs_tz = TimestampSecondArray::from(vec![None, Some(193438817552), None])
1495            .with_timezone_opt(secs_tz);
1496        let ts_millis_tz =
1497            TimestampMillisecondArray::from(vec![None, Some(38606916383008), Some(58113709376587)])
1498                .with_timezone_opt(millis_tz);
1499        let ts_micros_tz =
1500            TimestampMicrosecondArray::from(vec![None, None, None]).with_timezone_opt(micros_tz);
1501        let ts_nanos_tz =
1502            TimestampNanosecondArray::from(vec![None, None, Some(-6473623571954960143)])
1503                .with_timezone_opt(nanos_tz);
1504        let utf8s = StringArray::from(vec![Some("aa"), None, Some("bbb")]);
1505
1506        let value_data = Int32Array::from(vec![None, Some(2), None, None]);
1507        let value_offsets = Buffer::from_slice_ref([0, 3, 4, 4]);
1508        let list_data_type = DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true)));
1509        let list_data = ArrayData::builder(list_data_type)
1510            .len(3)
1511            .add_buffer(value_offsets)
1512            .add_child_data(value_data.into_data())
1513            .null_bit_buffer(Some(Buffer::from([0b00000011])))
1514            .build()
1515            .unwrap();
1516        let lists = ListArray::from(list_data);
1517
1518        let structs_int32s = Int32Array::from(vec![None, Some(-2), None]);
1519        let structs_utf8s = StringArray::from(vec![None, None, Some("aaaaaa")]);
1520        let struct_data_type = DataType::Struct(Fields::from(vec![
1521            Field::new("int32s", DataType::Int32, true),
1522            Field::new("utf8s", DataType::Utf8, true),
1523        ]));
1524        let struct_data = ArrayData::builder(struct_data_type)
1525            .len(3)
1526            .add_child_data(structs_int32s.into_data())
1527            .add_child_data(structs_utf8s.into_data())
1528            .null_bit_buffer(Some(Buffer::from([0b00000011])))
1529            .build()
1530            .unwrap();
1531        let structs = StructArray::from(struct_data);
1532
1533        let utf8views =
1534            StringViewArray::from(vec![Some("hello"), None, Some("this is not inlined")]);
1535        let binaryviews = BinaryViewArray::from_iter(vec![
1536            Some(b"\xf3\x4d".as_slice()),
1537            Some(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f".as_slice()),
1538            None,
1539        ]);
1540
1541        let listview_value_data = Int32Array::from(vec![Some(1), Some(2), Some(3), None, Some(5)]);
1542        let listview_offsets = Buffer::from_slice_ref([0i32, 2, 2]);
1543        let listview_sizes = Buffer::from_slice_ref([2i32, 0, 3]);
1544        let listview_data_type =
1545            DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, true)));
1546        let listview_data = ArrayData::builder(listview_data_type)
1547            .len(3)
1548            .add_buffer(listview_offsets)
1549            .add_buffer(listview_sizes)
1550            .add_child_data(listview_value_data.into_data())
1551            .null_bit_buffer(Some(Buffer::from([0b00000101])))
1552            .build()
1553            .unwrap();
1554        let listviews = ListViewArray::from(listview_data);
1555
1556        let largelistview_value_data = Int32Array::from(vec![Some(10), None, Some(30)]);
1557        let largelistview_offsets = Buffer::from_slice_ref([0i64, 2, 3]);
1558        let largelistview_sizes = Buffer::from_slice_ref([2i64, 1, 0]);
1559        let largelistview_data_type =
1560            DataType::LargeListView(Arc::new(Field::new_list_field(DataType::Int32, true)));
1561        let largelistview_data = ArrayData::builder(largelistview_data_type)
1562            .len(3)
1563            .add_buffer(largelistview_offsets)
1564            .add_buffer(largelistview_sizes)
1565            .add_child_data(largelistview_value_data.into_data())
1566            .null_bit_buffer(Some(Buffer::from([0b00000011])))
1567            .build()
1568            .unwrap();
1569        let largelistviews = LargeListViewArray::from(largelistview_data);
1570
1571        let ree_run_ends = Int16Array::from(vec![2, 3]);
1572        let ree_values = Int32Array::from(vec![Some(100), None]);
1573        let ree_data_type = DataType::RunEndEncoded(
1574            Arc::new(Field::new(
1575                Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
1576                DataType::Int16,
1577                false,
1578            )),
1579            Arc::new(Field::new(
1580                Field::REE_VALUES_FIELD_DEFAULT_NAME,
1581                DataType::Int32,
1582                true,
1583            )),
1584        );
1585        let ree_data = ArrayData::builder(ree_data_type)
1586            .len(3)
1587            .add_child_data(ree_run_ends.into_data())
1588            .add_child_data(ree_values.into_data())
1589            .build()
1590            .unwrap();
1591        let runendencoded = RunArray::<Int16Type>::from(ree_data);
1592
1593        let record_batch = RecordBatch::try_new(
1594            Arc::new(schema.clone()),
1595            vec![
1596                Arc::new(bools_with_metadata_map),
1597                Arc::new(bools_with_metadata_vec),
1598                Arc::new(bools),
1599                Arc::new(int8s),
1600                Arc::new(int16s),
1601                Arc::new(int32s),
1602                Arc::new(int64s),
1603                Arc::new(uint8s),
1604                Arc::new(uint16s),
1605                Arc::new(uint32s),
1606                Arc::new(uint64s),
1607                Arc::new(float32s),
1608                Arc::new(float64s),
1609                Arc::new(date_days),
1610                Arc::new(date_millis),
1611                Arc::new(time_secs),
1612                Arc::new(time_millis),
1613                Arc::new(time_micros),
1614                Arc::new(time_nanos),
1615                Arc::new(ts_secs),
1616                Arc::new(ts_millis),
1617                Arc::new(ts_micros),
1618                Arc::new(ts_nanos),
1619                Arc::new(ts_secs_tz),
1620                Arc::new(ts_millis_tz),
1621                Arc::new(ts_micros_tz),
1622                Arc::new(ts_nanos_tz),
1623                Arc::new(utf8s),
1624                Arc::new(lists),
1625                Arc::new(structs),
1626                Arc::new(utf8views),
1627                Arc::new(binaryviews),
1628                Arc::new(listviews),
1629                Arc::new(largelistviews),
1630                Arc::new(runendencoded),
1631            ],
1632        )
1633        .unwrap();
1634        let json = std::fs::read_to_string("data/integration.json").unwrap();
1635        let arrow_json: ArrowJson = serde_json::from_str(&json).unwrap();
1636        // test schemas
1637        assert!(arrow_json.schema.equals_schema(&schema));
1638        // test record batch
1639        assert_eq!(arrow_json.get_record_batches().unwrap()[0], record_batch);
1640    }
1641}