Skip to main content

parquet_cli/
value.rs

1//! Turning Arrow values into JSON values.
2
3use arrow_array::cast::AsArray;
4use arrow_array::types::*;
5use arrow_array::ArrayRef;
6use arrow_schema::{DataType, Field, TimeUnit};
7use serde_json::{Map, Value};
8
9/// The name of an Arrow type, in a shape that reads well in JSON.
10pub fn data_type_name(data_type: &DataType) -> String {
11    match data_type {
12        DataType::Utf8 => "utf8".into(),
13        DataType::LargeUtf8 => "large_utf8".into(),
14        DataType::Utf8View => "utf8_view".into(),
15        DataType::Binary => "binary".into(),
16        DataType::LargeBinary => "large_binary".into(),
17        DataType::BinaryView => "binary_view".into(),
18        DataType::FixedSizeBinary(len) => format!("fixed_binary({len})"),
19        DataType::Boolean => "bool".into(),
20        DataType::Int8 => "int8".into(),
21        DataType::Int16 => "int16".into(),
22        DataType::Int32 => "int32".into(),
23        DataType::Int64 => "int64".into(),
24        DataType::UInt8 => "uint8".into(),
25        DataType::UInt16 => "uint16".into(),
26        DataType::UInt32 => "uint32".into(),
27        DataType::UInt64 => "uint64".into(),
28        DataType::Float16 => "float16".into(),
29        DataType::Float32 => "float32".into(),
30        DataType::Float64 => "float64".into(),
31        DataType::Decimal128(precision, scale) => format!("decimal128({precision},{scale})"),
32        DataType::Decimal256(precision, scale) => format!("decimal256({precision},{scale})"),
33        DataType::Date32 => "date32".into(),
34        DataType::Date64 => "date64".into(),
35        DataType::Time32(unit) => format!("time32({unit:?})"),
36        DataType::Time64(unit) => format!("time64({unit:?})"),
37        DataType::Timestamp(unit, tz) => match tz {
38            Some(tz) => format!("timestamp({unit:?},{tz})"),
39            None => format!("timestamp({unit:?})"),
40        },
41        DataType::Duration(unit) => format!("duration({unit:?})"),
42        DataType::Interval(_) => "interval".into(),
43        DataType::List(field) => format!("list<{}>", data_type_name(field.data_type())),
44        DataType::LargeList(field) => format!("large_list<{}>", data_type_name(field.data_type())),
45        DataType::FixedSizeList(field, len) => {
46            format!("fixed_list<{}>[{len}]", data_type_name(field.data_type()))
47        }
48        DataType::ListView(field) => format!("list_view<{}>", data_type_name(field.data_type())),
49        DataType::LargeListView(field) => {
50            format!("large_list_view<{}>", data_type_name(field.data_type()))
51        }
52        DataType::Struct(fields) => format!(
53            "struct<{}>",
54            fields
55                .iter()
56                .map(|f| f.name().as_str())
57                .collect::<Vec<_>>()
58                .join(",")
59        ),
60        DataType::Map(field, _) => format!("map<{}>", data_type_name(field.data_type())),
61        DataType::Dictionary(_, value) => format!("dict<{}>", data_type_name(value)),
62        DataType::Null => "null".into(),
63        other => format!("{other}"),
64    }
65}
66
67/// One cell of an Arrow array, as JSON.
68pub fn cell(array: &ArrayRef, index: usize) -> Value {
69    if array.is_null(index) {
70        return Value::Null;
71    }
72    match array.data_type() {
73        DataType::Boolean => Value::Bool(array.as_boolean().value(index)),
74        DataType::Int8 => Value::from(array.as_primitive::<Int8Type>().value(index) as i64),
75        DataType::Int16 => Value::from(array.as_primitive::<Int16Type>().value(index) as i64),
76        DataType::Int32 => Value::from(array.as_primitive::<Int32Type>().value(index) as i64),
77        DataType::Int64 => Value::from(array.as_primitive::<Int64Type>().value(index)),
78        DataType::UInt8 => Value::from(array.as_primitive::<UInt8Type>().value(index) as u64),
79        DataType::UInt16 => Value::from(array.as_primitive::<UInt16Type>().value(index) as u64),
80        DataType::UInt32 => Value::from(array.as_primitive::<UInt32Type>().value(index) as u64),
81        DataType::UInt64 => Value::from(array.as_primitive::<UInt64Type>().value(index)),
82        DataType::Float16 => {
83            Value::from(f64::from(array.as_primitive::<Float16Type>().value(index)))
84        }
85        DataType::Float32 => Value::from(array.as_primitive::<Float32Type>().value(index) as f64),
86        DataType::Float64 => Value::from(array.as_primitive::<Float64Type>().value(index)),
87        DataType::Utf8 => Value::String(array.as_string::<i32>().value(index).to_string()),
88        DataType::LargeUtf8 => Value::String(array.as_string::<i64>().value(index).to_string()),
89        DataType::Utf8View => Value::String(array.as_string_view().value(index).to_string()),
90        DataType::Binary => hex(array.as_binary::<i32>().value(index)),
91        DataType::LargeBinary => hex(array.as_binary::<i64>().value(index)),
92        DataType::BinaryView => hex(array.as_binary_view().value(index)),
93        DataType::FixedSizeBinary(_) => hex(array.as_fixed_size_binary().value(index)),
94        DataType::Date32 => Value::String(civil_date(
95            array.as_primitive::<Date32Type>().value(index) as i64,
96        )),
97        DataType::Date64 => Value::String(civil_date(
98            array
99                .as_primitive::<Date64Type>()
100                .value(index)
101                .div_euclid(86_400_000),
102        )),
103        DataType::Time32(unit) => {
104            let seconds = match unit {
105                TimeUnit::Second => array.as_primitive::<Time32SecondType>().value(index) as i64,
106                _ => array.as_primitive::<Time32MillisecondType>().value(index) as i64 / 1000,
107            };
108            Value::String(civil_time(seconds, false))
109        }
110        DataType::Time64(unit) => {
111            let seconds = match unit {
112                TimeUnit::Microsecond => {
113                    array.as_primitive::<Time64MicrosecondType>().value(index) / 1_000_000
114                }
115                _ => array.as_primitive::<Time64NanosecondType>().value(index) / 1_000_000_000,
116            };
117            Value::String(civil_time(seconds, false))
118        }
119        DataType::Timestamp(unit, _) => {
120            let raw = match unit {
121                TimeUnit::Second => array.as_primitive::<TimestampSecondType>().value(index),
122                TimeUnit::Millisecond => array
123                    .as_primitive::<TimestampMillisecondType>()
124                    .value(index),
125                TimeUnit::Microsecond => array
126                    .as_primitive::<TimestampMicrosecondType>()
127                    .value(index),
128                TimeUnit::Nanosecond => {
129                    array.as_primitive::<TimestampNanosecondType>().value(index)
130                }
131            };
132            Value::String(civil_datetime(raw, *unit))
133        }
134        DataType::Decimal128(_, scale) => {
135            let raw = array.as_primitive::<Decimal128Type>().value(index);
136            Value::String(shift_decimal(&raw.to_string(), *scale as u32))
137        }
138        DataType::Decimal256(_, scale) => {
139            let raw = array.as_primitive::<Decimal256Type>().value(index);
140            Value::String(shift_decimal(&raw.to_string(), *scale as u32))
141        }
142        DataType::List(_) => {
143            let list = array.as_list::<i32>();
144            let values = list.value(index);
145            Value::Array((0..values.len()).map(|i| cell(&values, i)).collect())
146        }
147        DataType::LargeList(_) => {
148            let list = array.as_list::<i64>();
149            let values = list.value(index);
150            Value::Array((0..values.len()).map(|i| cell(&values, i)).collect())
151        }
152        DataType::FixedSizeList(_, len) => {
153            let list = array.as_fixed_size_list();
154            let values = list.value(index);
155            Value::Array((0..(*len as usize)).map(|i| cell(&values, i)).collect())
156        }
157        DataType::Struct(_) => {
158            let structure = array.as_struct();
159            let mut object = Map::new();
160            for (i, field) in structure.fields().iter().enumerate() {
161                object.insert(field.name().clone(), cell(structure.column(i), index));
162            }
163            Value::Object(object)
164        }
165        DataType::Map(_, _) => {
166            let map = array.as_map();
167            let keys = map.keys();
168            let items = map.values();
169            let offsets = map.offsets();
170            let start = offsets[index] as usize;
171            let end = offsets[index + 1] as usize;
172            let mut object = Map::new();
173            for i in start..end {
174                let key = match cell(keys, i) {
175                    Value::String(s) => s,
176                    other => other.to_string(),
177                };
178                object.insert(key, cell(items, i));
179            }
180            Value::Object(object)
181        }
182        DataType::Dictionary(_, _) => {
183            let dictionary = array.as_dictionary::<Int32Type>();
184            let key = dictionary.keys().value(index);
185            let values = dictionary.values();
186            cell(values, key as usize)
187        }
188        _ => Value::String(format!("<{}>", data_type_name(array.data_type()))),
189    }
190}
191
192/// A whole row of an Arrow batch, as a JSON object keyed by column name.
193pub fn row_object(batch: &arrow_array::RecordBatch, index: usize) -> Map<String, Value> {
194    let mut object = Map::new();
195    for (i, field) in batch.schema().fields().iter().enumerate() {
196        object.insert(field.name().clone(), cell(batch.column(i), index));
197    }
198    object
199}
200
201/// The JSON form of a schema field, with its children.
202pub fn field_json(field: &Field) -> Value {
203    let mut object = Map::new();
204    object.insert("name".into(), Value::String(field.name().clone()));
205    object.insert(
206        "type".into(),
207        Value::String(data_type_name(field.data_type())),
208    );
209    object.insert("nullable".into(), Value::Bool(field.is_nullable()));
210    match field.data_type() {
211        DataType::Struct(fields) => {
212            let children: Vec<Value> = fields.iter().map(|f| field_json(f.as_ref())).collect();
213            object.insert("children".into(), Value::Array(children));
214        }
215        DataType::List(inner)
216        | DataType::LargeList(inner)
217        | DataType::ListView(inner)
218        | DataType::LargeListView(inner)
219        | DataType::FixedSizeList(inner, _) => {
220            object.insert("children".into(), Value::Array(vec![field_json(inner)]));
221        }
222        DataType::Map(inner, _) => {
223            object.insert("children".into(), Value::Array(vec![field_json(inner)]));
224        }
225        _ => {}
226    }
227    Value::Object(object)
228}
229
230fn hex(bytes: &[u8]) -> Value {
231    Value::String(bytes.iter().map(|b| format!("{b:02x}")).collect())
232}
233
234/// Days since the epoch as `YYYY-MM-DD`.
235fn civil_date(days: i64) -> String {
236    let (year, month, day) = civil_from_days(days);
237    format!("{year:04}-{month:02}-{day:02}")
238}
239
240/// A timestamp as `YYYY-MM-DDTHH:MM:SS[.fff]Z`.
241fn civil_datetime(raw: i64, unit: TimeUnit) -> String {
242    let (seconds, fraction) = match unit {
243        TimeUnit::Second => (raw, String::new()),
244        TimeUnit::Millisecond => (
245            raw.div_euclid(1_000),
246            format!(".{:03}", raw.rem_euclid(1_000)),
247        ),
248        TimeUnit::Microsecond => (
249            raw.div_euclid(1_000_000),
250            format!(".{:06}", raw.rem_euclid(1_000_000)),
251        ),
252        TimeUnit::Nanosecond => (
253            raw.div_euclid(1_000_000_000),
254            format!(".{:09}", raw.rem_euclid(1_000_000_000)),
255        ),
256    };
257    let days = seconds.div_euclid(86_400);
258    let rest = seconds.rem_euclid(86_400);
259    let (year, month, day) = civil_from_days(days);
260    format!(
261        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}{fraction}Z",
262        rest / 3600,
263        (rest % 3600) / 60,
264        rest % 60
265    )
266}
267
268/// A time of day as `HH:MM:SS[.fff]`.
269fn civil_time(raw: i64, fractional: bool) -> String {
270    let (seconds, fraction) = if fractional {
271        (
272            raw.div_euclid(1_000),
273            format!(".{:03}", raw.rem_euclid(1_000)),
274        )
275    } else {
276        (raw, String::new())
277    };
278    format!(
279        "{:02}:{:02}:{:02}{fraction}",
280        seconds / 3600,
281        (seconds % 3600) / 60,
282        seconds % 60
283    )
284}
285
286/// Days since the epoch as a civil date (Howard Hinnant's algorithm).
287fn civil_from_days(days: i64) -> (i64, u32, u32) {
288    let z = days + 719_468;
289    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
290    let day_of_era = (z - era * 146_097) as u64;
291    let year_of_era =
292        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
293    let year = year_of_era as i64 + era * 400;
294    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
295    let mp = (5 * day_of_year + 2) / 153;
296    let day = (day_of_year - (153 * mp + 2) / 5 + 1) as u32;
297    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
298    (if month <= 2 { year + 1 } else { year }, month, day)
299}
300
301/// Put the decimal point where the scale says it is.
302fn shift_decimal(text: &str, scale: u32) -> String {
303    if scale == 0 {
304        return text.to_string();
305    }
306    let negative = text.starts_with('-');
307    let digits = text.trim_start_matches('-');
308    let padded = if (digits.len() as u32) <= scale {
309        format!(
310            "{}{}",
311            "0".repeat(scale as usize + 1 - digits.len()),
312            digits
313        )
314    } else {
315        digits.to_string()
316    };
317    let split = padded.len() - scale as usize;
318    let sign = if negative { "-" } else { "" };
319    format!("{sign}{}.{}", &padded[..split], &padded[split..])
320}