Skip to main content

arrow_integration_test/
datatype.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
5use arrow::datatypes::{DataType, Field, Fields, IntervalUnit, TimeUnit, UnionMode};
6use arrow::error::{ArrowError, Result};
7use std::sync::Arc;
8
9/// Read a JSON number as an integer of type `T`.
10pub(crate) fn json_int<T: TryFrom<i64>>(what: &str, value: &serde_json::Value) -> Result<T> {
11    let int = value
12        .as_i64()
13        .ok_or_else(|| ArrowError::ParseError(format!("Expecting {what} to be an integer")))?;
14    T::try_from(int)
15        .map_err(|_| ArrowError::ParseError(format!("{what} is out of range for its type: {int}")))
16}
17
18/// Read a JSON number as an unsigned integer of type `T`.
19pub(crate) fn json_uint<T: TryFrom<u64>>(what: &str, value: &serde_json::Value) -> Result<T> {
20    let int = value
21        .as_u64()
22        .ok_or_else(|| ArrowError::ParseError(format!("Expecting {what} to be an integer")))?;
23    T::try_from(int)
24        .map_err(|_| ArrowError::ParseError(format!("{what} is out of range for its type: {int}")))
25}
26
27/// Parse a data type from a JSON representation.
28pub fn data_type_from_json(json: &serde_json::Value) -> Result<DataType> {
29    use serde_json::Value;
30    let default_field = Arc::new(Field::new("", DataType::Boolean, true));
31    match *json {
32        Value::Object(ref map) => match map.get("name") {
33            Some(s) if s == "null" => Ok(DataType::Null),
34            Some(s) if s == "bool" => Ok(DataType::Boolean),
35            Some(s) if s == "binary" => Ok(DataType::Binary),
36            Some(s) if s == "largebinary" => Ok(DataType::LargeBinary),
37            Some(s) if s == "binaryview" => Ok(DataType::BinaryView),
38            Some(s) if s == "utf8view" => Ok(DataType::Utf8View),
39            Some(s) if s == "utf8" => Ok(DataType::Utf8),
40            Some(s) if s == "largeutf8" => Ok(DataType::LargeUtf8),
41            Some(s) if s == "fixedsizebinary" => {
42                // return a list with any type as its child isn't defined in the map
43                if let Some(Value::Number(size)) = map.get("byteWidth") {
44                    Ok(DataType::FixedSizeBinary(json_int(
45                        "byteWidth",
46                        &Value::Number(size.clone()),
47                    )?))
48                } else {
49                    Err(ArrowError::ParseError(
50                        "Expecting a byteWidth for fixedsizebinary".to_string(),
51                    ))
52                }
53            }
54            Some(s) if s == "decimal" => {
55                // return a list with any type as its child isn't defined in the map
56                let precision = match map.get("precision") {
57                    Some(p) => json_int("precision", p),
58                    None => Err(ArrowError::ParseError(
59                        "Expecting a precision for decimal".to_string(),
60                    )),
61                }?;
62                let scale = match map.get("scale") {
63                    Some(s) => json_int("scale", s),
64                    _ => Err(ArrowError::ParseError(
65                        "Expecting a scale for decimal".to_string(),
66                    )),
67                }?;
68                let bit_width: usize = match map.get("bitWidth") {
69                    Some(b) => json_int("bitWidth", b)?,
70                    _ => 128, // Default bit width
71                };
72
73                match bit_width {
74                    32 => Ok(DataType::Decimal32(precision, scale)),
75                    64 => Ok(DataType::Decimal64(precision, scale)),
76                    128 => Ok(DataType::Decimal128(precision, scale)),
77                    256 => Ok(DataType::Decimal256(precision, scale)),
78                    _ => Err(ArrowError::ParseError(
79                        "Decimal bit_width invalid".to_string(),
80                    )),
81                }
82            }
83            Some(s) if s == "floatingpoint" => match map.get("precision") {
84                Some(p) if p == "HALF" => Ok(DataType::Float16),
85                Some(p) if p == "SINGLE" => Ok(DataType::Float32),
86                Some(p) if p == "DOUBLE" => Ok(DataType::Float64),
87                _ => Err(ArrowError::ParseError(
88                    "floatingpoint precision missing or invalid".to_string(),
89                )),
90            },
91            Some(s) if s == "timestamp" => {
92                let unit = match map.get("unit") {
93                    Some(p) if p == "SECOND" => Ok(TimeUnit::Second),
94                    Some(p) if p == "MILLISECOND" => Ok(TimeUnit::Millisecond),
95                    Some(p) if p == "MICROSECOND" => Ok(TimeUnit::Microsecond),
96                    Some(p) if p == "NANOSECOND" => Ok(TimeUnit::Nanosecond),
97                    _ => Err(ArrowError::ParseError(
98                        "timestamp unit missing or invalid".to_string(),
99                    )),
100                };
101                let tz = match map.get("timezone") {
102                    None => Ok(None),
103                    Some(Value::String(tz)) => Ok(Some(tz.as_str().into())),
104                    _ => Err(ArrowError::ParseError(
105                        "timezone must be a string".to_string(),
106                    )),
107                };
108                Ok(DataType::Timestamp(unit?, tz?))
109            }
110            Some(s) if s == "date" => match map.get("unit") {
111                Some(p) if p == "DAY" => Ok(DataType::Date32),
112                Some(p) if p == "MILLISECOND" => Ok(DataType::Date64),
113                _ => Err(ArrowError::ParseError(
114                    "date unit missing or invalid".to_string(),
115                )),
116            },
117            Some(s) if s == "time" => {
118                let unit = match map.get("unit") {
119                    Some(p) if p == "SECOND" => Ok(TimeUnit::Second),
120                    Some(p) if p == "MILLISECOND" => Ok(TimeUnit::Millisecond),
121                    Some(p) if p == "MICROSECOND" => Ok(TimeUnit::Microsecond),
122                    Some(p) if p == "NANOSECOND" => Ok(TimeUnit::Nanosecond),
123                    _ => Err(ArrowError::ParseError(
124                        "time unit missing or invalid".to_string(),
125                    )),
126                };
127                match map.get("bitWidth") {
128                    Some(p) if p == 32 => Ok(DataType::Time32(unit?)),
129                    Some(p) if p == 64 => Ok(DataType::Time64(unit?)),
130                    _ => Err(ArrowError::ParseError(
131                        "time bitWidth missing or invalid".to_string(),
132                    )),
133                }
134            }
135            Some(s) if s == "duration" => match map.get("unit") {
136                Some(p) if p == "SECOND" => Ok(DataType::Duration(TimeUnit::Second)),
137                Some(p) if p == "MILLISECOND" => Ok(DataType::Duration(TimeUnit::Millisecond)),
138                Some(p) if p == "MICROSECOND" => Ok(DataType::Duration(TimeUnit::Microsecond)),
139                Some(p) if p == "NANOSECOND" => Ok(DataType::Duration(TimeUnit::Nanosecond)),
140                _ => Err(ArrowError::ParseError(
141                    "time unit missing or invalid".to_string(),
142                )),
143            },
144            Some(s) if s == "interval" => match map.get("unit") {
145                Some(p) if p == "DAY_TIME" => Ok(DataType::Interval(IntervalUnit::DayTime)),
146                Some(p) if p == "YEAR_MONTH" => Ok(DataType::Interval(IntervalUnit::YearMonth)),
147                Some(p) if p == "MONTH_DAY_NANO" => {
148                    Ok(DataType::Interval(IntervalUnit::MonthDayNano))
149                }
150                _ => Err(ArrowError::ParseError(
151                    "interval unit missing or invalid".to_string(),
152                )),
153            },
154            Some(s) if s == "int" => match map.get("isSigned") {
155                Some(&Value::Bool(true)) => match map.get("bitWidth") {
156                    Some(Value::Number(n)) => match n.as_u64() {
157                        Some(8) => Ok(DataType::Int8),
158                        Some(16) => Ok(DataType::Int16),
159                        Some(32) => Ok(DataType::Int32),
160                        Some(64) => Ok(DataType::Int64),
161                        _ => Err(ArrowError::ParseError(
162                            "int bitWidth missing or invalid".to_string(),
163                        )),
164                    },
165                    _ => Err(ArrowError::ParseError(
166                        "int bitWidth missing or invalid".to_string(),
167                    )),
168                },
169                Some(&Value::Bool(false)) => match map.get("bitWidth") {
170                    Some(Value::Number(n)) => match n.as_u64() {
171                        Some(8) => Ok(DataType::UInt8),
172                        Some(16) => Ok(DataType::UInt16),
173                        Some(32) => Ok(DataType::UInt32),
174                        Some(64) => Ok(DataType::UInt64),
175                        _ => Err(ArrowError::ParseError(
176                            "int bitWidth missing or invalid".to_string(),
177                        )),
178                    },
179                    _ => Err(ArrowError::ParseError(
180                        "int bitWidth missing or invalid".to_string(),
181                    )),
182                },
183                _ => Err(ArrowError::ParseError(
184                    "int signed missing or invalid".to_string(),
185                )),
186            },
187            Some(s) if s == "list" => {
188                // return a list with any type as its child isn't defined in the map
189                Ok(DataType::List(default_field))
190            }
191            Some(s) if s == "largelist" => {
192                // return a largelist with any type as its child isn't defined in the map
193                Ok(DataType::LargeList(default_field))
194            }
195            Some(s) if s == "listview" => {
196                // return a listview with any type as its child isn't defined in the map
197                Ok(DataType::ListView(default_field))
198            }
199            Some(s) if s == "largelistview" => {
200                // return a large listview with any type as its child isn't defined in the map
201                Ok(DataType::LargeListView(default_field))
202            }
203            Some(s) if s == "fixedsizelist" => {
204                // return a list with any type as its child isn't defined in the map
205                if let Some(Value::Number(size)) = map.get("listSize") {
206                    Ok(DataType::FixedSizeList(
207                        default_field,
208                        json_int("listSize", &Value::Number(size.clone()))?,
209                    ))
210                } else {
211                    Err(ArrowError::ParseError(
212                        "Expecting a listSize for fixedsizelist".to_string(),
213                    ))
214                }
215            }
216            Some(s) if s == "struct" => {
217                // return an empty `struct` type as its children aren't defined in the map
218                Ok(DataType::Struct(Fields::empty()))
219            }
220            Some(s) if s == "runendencoded" => {
221                // return a run end encoded with placeholder types as children aren't defined in the map
222                Ok(DataType::RunEndEncoded(
223                    Arc::new(Field::new(
224                        Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
225                        DataType::Int32,
226                        false,
227                    )),
228                    default_field,
229                ))
230            }
231            Some(s) if s == "map" => {
232                if let Some(Value::Bool(keys_sorted)) = map.get("keysSorted") {
233                    // Return a map with an empty type as its children aren't defined in the map
234                    Ok(DataType::Map(default_field, *keys_sorted))
235                } else {
236                    Err(ArrowError::ParseError(
237                        "Expecting a keysSorted for map".to_string(),
238                    ))
239                }
240            }
241            Some(s) if s == "union" => {
242                if let Some(Value::String(mode)) = map.get("mode") {
243                    let union_mode = if mode == "SPARSE" {
244                        UnionMode::Sparse
245                    } else if mode == "DENSE" {
246                        UnionMode::Dense
247                    } else {
248                        return Err(ArrowError::ParseError(format!(
249                            "Unknown union mode {mode:?} for union"
250                        )));
251                    };
252                    if let Some(values) = map.get("typeIds") {
253                        let values = values.as_array().ok_or_else(|| {
254                            ArrowError::ParseError("Expecting typeIds to be an array".to_string())
255                        })?;
256                        let fields = values
257                            .iter()
258                            .map(|t| Ok((json_int::<i8>("a type id", t)?, default_field.clone())))
259                            .collect::<Result<Vec<_>>>()?
260                            .into_iter()
261                            .collect();
262
263                        Ok(DataType::Union(fields, union_mode))
264                    } else {
265                        Err(ArrowError::ParseError(
266                            "Expecting a typeIds for union ".to_string(),
267                        ))
268                    }
269                } else {
270                    Err(ArrowError::ParseError(
271                        "Expecting a mode for union".to_string(),
272                    ))
273                }
274            }
275            Some(other) => Err(ArrowError::ParseError(format!(
276                "invalid or unsupported type name: {other} in {json:?}"
277            ))),
278            None => Err(ArrowError::ParseError("type name missing".to_string())),
279        },
280        _ => Err(ArrowError::ParseError(
281            "invalid json value type".to_string(),
282        )),
283    }
284}
285
286/// Generate a JSON representation of the data type.
287pub fn data_type_to_json(data_type: &DataType) -> serde_json::Value {
288    use serde_json::json;
289    match data_type {
290        DataType::Null => json!({"name": "null"}),
291        DataType::Boolean => json!({"name": "bool"}),
292        DataType::Int8 => json!({"name": "int", "bitWidth": 8, "isSigned": true}),
293        DataType::Int16 => json!({"name": "int", "bitWidth": 16, "isSigned": true}),
294        DataType::Int32 => json!({"name": "int", "bitWidth": 32, "isSigned": true}),
295        DataType::Int64 => json!({"name": "int", "bitWidth": 64, "isSigned": true}),
296        DataType::UInt8 => json!({"name": "int", "bitWidth": 8, "isSigned": false}),
297        DataType::UInt16 => json!({"name": "int", "bitWidth": 16, "isSigned": false}),
298        DataType::UInt32 => json!({"name": "int", "bitWidth": 32, "isSigned": false}),
299        DataType::UInt64 => json!({"name": "int", "bitWidth": 64, "isSigned": false}),
300        DataType::Float16 => json!({"name": "floatingpoint", "precision": "HALF"}),
301        DataType::Float32 => json!({"name": "floatingpoint", "precision": "SINGLE"}),
302        DataType::Float64 => json!({"name": "floatingpoint", "precision": "DOUBLE"}),
303        DataType::Utf8 => json!({"name": "utf8"}),
304        DataType::LargeUtf8 => json!({"name": "largeutf8"}),
305        DataType::Binary => json!({"name": "binary"}),
306        DataType::LargeBinary => json!({"name": "largebinary"}),
307        DataType::BinaryView => json!({"name": "binaryview"}),
308        DataType::Utf8View => json!({"name": "utf8view"}),
309        DataType::FixedSizeBinary(byte_width) => {
310            json!({"name": "fixedsizebinary", "byteWidth": byte_width})
311        }
312        DataType::Struct(_) => json!({"name": "struct"}),
313        DataType::Union(_, _) => json!({"name": "union"}),
314        DataType::List(_) => json!({ "name": "list"}),
315        DataType::LargeList(_) => json!({ "name": "largelist"}),
316        DataType::ListView(_) => json!({ "name": "listview"}),
317        DataType::LargeListView(_) => json!({ "name": "largelistview"}),
318        DataType::FixedSizeList(_, length) => {
319            json!({"name":"fixedsizelist", "listSize": length})
320        }
321        DataType::Time32(unit) => {
322            json!({"name": "time", "bitWidth": 32, "unit": match unit {
323                TimeUnit::Second => "SECOND",
324                TimeUnit::Millisecond => "MILLISECOND",
325                TimeUnit::Microsecond => "MICROSECOND",
326                TimeUnit::Nanosecond => "NANOSECOND",
327            }})
328        }
329        DataType::Time64(unit) => {
330            json!({"name": "time", "bitWidth": 64, "unit": match unit {
331                TimeUnit::Second => "SECOND",
332                TimeUnit::Millisecond => "MILLISECOND",
333                TimeUnit::Microsecond => "MICROSECOND",
334                TimeUnit::Nanosecond => "NANOSECOND",
335            }})
336        }
337        DataType::Date32 => {
338            json!({"name": "date", "unit": "DAY"})
339        }
340        DataType::Date64 => {
341            json!({"name": "date", "unit": "MILLISECOND"})
342        }
343        DataType::Timestamp(unit, None) => {
344            json!({"name": "timestamp", "unit": match unit {
345                TimeUnit::Second => "SECOND",
346                TimeUnit::Millisecond => "MILLISECOND",
347                TimeUnit::Microsecond => "MICROSECOND",
348                TimeUnit::Nanosecond => "NANOSECOND",
349            }})
350        }
351        DataType::Timestamp(unit, Some(tz)) => {
352            json!({"name": "timestamp", "unit": match unit {
353                    TimeUnit::Second => "SECOND",
354                    TimeUnit::Millisecond => "MILLISECOND",
355                    TimeUnit::Microsecond => "MICROSECOND",
356                    TimeUnit::Nanosecond => "NANOSECOND",
357                }, "timezone": tz})
358        }
359        DataType::Interval(unit) => json!({"name": "interval", "unit": match unit {
360            IntervalUnit::YearMonth => "YEAR_MONTH",
361            IntervalUnit::DayTime => "DAY_TIME",
362            IntervalUnit::MonthDayNano => "MONTH_DAY_NANO",
363        }}),
364        DataType::Duration(unit) => json!({"name": "duration", "unit": match unit {
365            TimeUnit::Second => "SECOND",
366            TimeUnit::Millisecond => "MILLISECOND",
367            TimeUnit::Microsecond => "MICROSECOND",
368            TimeUnit::Nanosecond => "NANOSECOND",
369        }}),
370        DataType::Dictionary(_, _) => json!({ "name": "dictionary"}),
371        DataType::Decimal32(precision, scale) => {
372            json!({"name": "decimal", "precision": precision, "scale": scale, "bitWidth": 32})
373        }
374        DataType::Decimal64(precision, scale) => {
375            json!({"name": "decimal", "precision": precision, "scale": scale, "bitWidth": 64})
376        }
377        DataType::Decimal128(precision, scale) => {
378            json!({"name": "decimal", "precision": precision, "scale": scale, "bitWidth": 128})
379        }
380        DataType::Decimal256(precision, scale) => {
381            json!({"name": "decimal", "precision": precision, "scale": scale, "bitWidth": 256})
382        }
383        DataType::Map(_, keys_sorted) => {
384            json!({"name": "map", "keysSorted": keys_sorted})
385        }
386        DataType::RunEndEncoded(_, _) => json!({"name": "runendencoded"}),
387    }
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393    use serde_json::Value;
394
395    #[test]
396    fn parse_utf8_from_json() {
397        let json = "{\"name\":\"utf8\"}";
398        let value: Value = serde_json::from_str(json).unwrap();
399        let dt = data_type_from_json(&value).unwrap();
400        assert_eq!(DataType::Utf8, dt);
401    }
402
403    #[test]
404    fn parse_int32_from_json() {
405        let json = "{\"name\": \"int\", \"isSigned\": true, \"bitWidth\": 32}";
406        let value: Value = serde_json::from_str(json).unwrap();
407        let dt = data_type_from_json(&value).unwrap();
408        assert_eq!(DataType::Int32, dt);
409    }
410}