arrow_integration_test/schema.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 crate::{field_from_json, field_to_json};
6use arrow::datatypes::{Fields, Schema};
7use arrow::error::{ArrowError, Result};
8use std::collections::HashMap;
9
10/// Generate a JSON representation of the `Schema`.
11pub fn schema_to_json(schema: &Schema) -> serde_json::Value {
12 let metadata: serde_json::Map<String, serde_json::Value> = schema
13 .metadata()
14 .iter()
15 .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
16 .collect();
17 serde_json::json!({
18 "fields": schema.fields().iter().map(|f| field_to_json(f.as_ref())).collect::<Vec<_>>(),
19 "metadata": metadata
20 })
21}
22
23/// Parse a `Schema` definition from a JSON representation.
24pub fn schema_from_json(json: &serde_json::Value) -> Result<Schema> {
25 use serde_json::Value;
26 match *json {
27 Value::Object(ref schema) => {
28 let fields: Fields = match schema.get("fields") {
29 Some(Value::Array(fields)) => {
30 fields.iter().map(field_from_json).collect::<Result<_>>()?
31 }
32 _ => {
33 return Err(ArrowError::ParseError(
34 "Schema fields should be an array".to_string(),
35 ));
36 }
37 };
38
39 let metadata = if let Some(value) = schema.get("metadata") {
40 from_metadata(value)?
41 } else {
42 HashMap::default()
43 };
44
45 Ok(Schema::new_with_metadata(fields, metadata))
46 }
47 _ => Err(ArrowError::ParseError(
48 "Invalid json value type for schema".to_string(),
49 )),
50 }
51}
52
53/// Parse a `metadata` definition from a JSON representation.
54/// The JSON can either be an Object or an Array of Objects.
55fn from_metadata(json: &serde_json::Value) -> Result<HashMap<String, String>> {
56 use serde_json::Value;
57 match json {
58 Value::Array(_) => {
59 let mut hashmap = HashMap::new();
60 let values: Vec<MetadataKeyValue> =
61 serde_json::from_value(json.clone()).map_err(|_| {
62 ArrowError::JsonError("Unable to parse object into key-value pair".to_string())
63 })?;
64 for meta in values {
65 hashmap.insert(meta.key.clone(), meta.value);
66 }
67 Ok(hashmap)
68 }
69 Value::Object(md) => md
70 .iter()
71 .map(|(k, v)| {
72 if let Value::String(v) = v {
73 Ok((k.clone(), v.clone()))
74 } else {
75 Err(ArrowError::ParseError(
76 "metadata `value` field must be a string".to_string(),
77 ))
78 }
79 })
80 .collect::<Result<_>>(),
81 _ => Err(ArrowError::ParseError(
82 "`metadata` field must be an object".to_string(),
83 )),
84 }
85}
86
87#[derive(serde::Deserialize)]
88struct MetadataKeyValue {
89 key: String,
90 value: String,
91}
92
93#[cfg(test)]
94mod tests {
95 use super::*;
96 use arrow::datatypes::{DataType, Field, IntervalUnit, TimeUnit};
97 use serde_json::Value;
98 use std::sync::Arc;
99
100 #[test]
101 fn schema_json() {
102 // Add some custom metadata
103 let metadata = HashMap::from([("Key".to_string(), "Value".to_string())]);
104
105 let schema = Schema::new_with_metadata(
106 vec![
107 Field::new("c1", DataType::Utf8, false),
108 Field::new("c2", DataType::Binary, false),
109 Field::new("c3", DataType::FixedSizeBinary(3), false),
110 Field::new("c4", DataType::Boolean, false),
111 Field::new("c5", DataType::Date32, false),
112 Field::new("c6", DataType::Date64, false),
113 Field::new("c7", DataType::Time32(TimeUnit::Second), false),
114 Field::new("c8", DataType::Time32(TimeUnit::Millisecond), false),
115 Field::new("c9", DataType::Time32(TimeUnit::Microsecond), false),
116 Field::new("c10", DataType::Time32(TimeUnit::Nanosecond), false),
117 Field::new("c11", DataType::Time64(TimeUnit::Second), false),
118 Field::new("c12", DataType::Time64(TimeUnit::Millisecond), false),
119 Field::new("c13", DataType::Time64(TimeUnit::Microsecond), false),
120 Field::new("c14", DataType::Time64(TimeUnit::Nanosecond), false),
121 Field::new("c15", DataType::Timestamp(TimeUnit::Second, None), false),
122 Field::new(
123 "c16",
124 DataType::Timestamp(TimeUnit::Millisecond, Some("UTC".into())),
125 false,
126 ),
127 Field::new(
128 "c17",
129 DataType::Timestamp(TimeUnit::Microsecond, Some("Africa/Johannesburg".into())),
130 false,
131 ),
132 Field::new(
133 "c18",
134 DataType::Timestamp(TimeUnit::Nanosecond, None),
135 false,
136 ),
137 Field::new("c19", DataType::Interval(IntervalUnit::DayTime), false),
138 Field::new("c20", DataType::Interval(IntervalUnit::YearMonth), false),
139 Field::new("c21", DataType::Interval(IntervalUnit::MonthDayNano), false),
140 Field::new(
141 "c22",
142 DataType::List(Arc::new(Field::new_list_field(DataType::Boolean, true))),
143 false,
144 ),
145 Field::new(
146 "c23",
147 DataType::FixedSizeList(
148 Arc::new(Field::new("bools", DataType::Boolean, false)),
149 5,
150 ),
151 false,
152 ),
153 Field::new(
154 "c24",
155 DataType::List(Arc::new(Field::new(
156 "inner_list",
157 DataType::List(Arc::new(Field::new(
158 "struct",
159 DataType::Struct(Fields::empty()),
160 true,
161 ))),
162 false,
163 ))),
164 true,
165 ),
166 Field::new(
167 "c25",
168 DataType::Struct(Fields::from(vec![
169 Field::new("a", DataType::Utf8, false),
170 Field::new("b", DataType::UInt16, false),
171 ])),
172 false,
173 ),
174 Field::new("c26", DataType::Interval(IntervalUnit::YearMonth), true),
175 Field::new("c27", DataType::Interval(IntervalUnit::DayTime), true),
176 Field::new("c28", DataType::Interval(IntervalUnit::MonthDayNano), true),
177 Field::new("c29", DataType::Duration(TimeUnit::Second), false),
178 Field::new("c30", DataType::Duration(TimeUnit::Millisecond), false),
179 Field::new("c31", DataType::Duration(TimeUnit::Microsecond), false),
180 Field::new("c32", DataType::Duration(TimeUnit::Nanosecond), false),
181 #[expect(deprecated)]
182 Field::new_dict(
183 "c33",
184 DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
185 true,
186 123,
187 true,
188 ),
189 Field::new("c34", DataType::LargeBinary, true),
190 Field::new("c35", DataType::LargeUtf8, true),
191 Field::new(
192 "c36",
193 DataType::LargeList(Arc::new(Field::new(
194 "inner_large_list",
195 DataType::LargeList(Arc::new(Field::new(
196 "struct",
197 DataType::Struct(Fields::empty()),
198 false,
199 ))),
200 true,
201 ))),
202 true,
203 ),
204 Field::new(
205 "c37",
206 DataType::Map(
207 Arc::new(Field::new(
208 "my_entries",
209 DataType::Struct(Fields::from(vec![
210 Field::new("my_keys", DataType::Utf8, false),
211 Field::new("my_values", DataType::UInt16, true),
212 ])),
213 false,
214 )),
215 true,
216 ),
217 false,
218 ),
219 ],
220 metadata,
221 );
222
223 let expected = schema_to_json(&schema);
224 let json = r#"{
225 "fields": [
226 {
227 "name": "c1",
228 "nullable": false,
229 "type": {
230 "name": "utf8"
231 },
232 "children": []
233 },
234 {
235 "name": "c2",
236 "nullable": false,
237 "type": {
238 "name": "binary"
239 },
240 "children": []
241 },
242 {
243 "name": "c3",
244 "nullable": false,
245 "type": {
246 "name": "fixedsizebinary",
247 "byteWidth": 3
248 },
249 "children": []
250 },
251 {
252 "name": "c4",
253 "nullable": false,
254 "type": {
255 "name": "bool"
256 },
257 "children": []
258 },
259 {
260 "name": "c5",
261 "nullable": false,
262 "type": {
263 "name": "date",
264 "unit": "DAY"
265 },
266 "children": []
267 },
268 {
269 "name": "c6",
270 "nullable": false,
271 "type": {
272 "name": "date",
273 "unit": "MILLISECOND"
274 },
275 "children": []
276 },
277 {
278 "name": "c7",
279 "nullable": false,
280 "type": {
281 "name": "time",
282 "bitWidth": 32,
283 "unit": "SECOND"
284 },
285 "children": []
286 },
287 {
288 "name": "c8",
289 "nullable": false,
290 "type": {
291 "name": "time",
292 "bitWidth": 32,
293 "unit": "MILLISECOND"
294 },
295 "children": []
296 },
297 {
298 "name": "c9",
299 "nullable": false,
300 "type": {
301 "name": "time",
302 "bitWidth": 32,
303 "unit": "MICROSECOND"
304 },
305 "children": []
306 },
307 {
308 "name": "c10",
309 "nullable": false,
310 "type": {
311 "name": "time",
312 "bitWidth": 32,
313 "unit": "NANOSECOND"
314 },
315 "children": []
316 },
317 {
318 "name": "c11",
319 "nullable": false,
320 "type": {
321 "name": "time",
322 "bitWidth": 64,
323 "unit": "SECOND"
324 },
325 "children": []
326 },
327 {
328 "name": "c12",
329 "nullable": false,
330 "type": {
331 "name": "time",
332 "bitWidth": 64,
333 "unit": "MILLISECOND"
334 },
335 "children": []
336 },
337 {
338 "name": "c13",
339 "nullable": false,
340 "type": {
341 "name": "time",
342 "bitWidth": 64,
343 "unit": "MICROSECOND"
344 },
345 "children": []
346 },
347 {
348 "name": "c14",
349 "nullable": false,
350 "type": {
351 "name": "time",
352 "bitWidth": 64,
353 "unit": "NANOSECOND"
354 },
355 "children": []
356 },
357 {
358 "name": "c15",
359 "nullable": false,
360 "type": {
361 "name": "timestamp",
362 "unit": "SECOND"
363 },
364 "children": []
365 },
366 {
367 "name": "c16",
368 "nullable": false,
369 "type": {
370 "name": "timestamp",
371 "unit": "MILLISECOND",
372 "timezone": "UTC"
373 },
374 "children": []
375 },
376 {
377 "name": "c17",
378 "nullable": false,
379 "type": {
380 "name": "timestamp",
381 "unit": "MICROSECOND",
382 "timezone": "Africa/Johannesburg"
383 },
384 "children": []
385 },
386 {
387 "name": "c18",
388 "nullable": false,
389 "type": {
390 "name": "timestamp",
391 "unit": "NANOSECOND"
392 },
393 "children": []
394 },
395 {
396 "name": "c19",
397 "nullable": false,
398 "type": {
399 "name": "interval",
400 "unit": "DAY_TIME"
401 },
402 "children": []
403 },
404 {
405 "name": "c20",
406 "nullable": false,
407 "type": {
408 "name": "interval",
409 "unit": "YEAR_MONTH"
410 },
411 "children": []
412 },
413 {
414 "name": "c21",
415 "nullable": false,
416 "type": {
417 "name": "interval",
418 "unit": "MONTH_DAY_NANO"
419 },
420 "children": []
421 },
422 {
423 "name": "c22",
424 "nullable": false,
425 "type": {
426 "name": "list"
427 },
428 "children": [
429 {
430 "name": "item",
431 "nullable": true,
432 "type": {
433 "name": "bool"
434 },
435 "children": []
436 }
437 ]
438 },
439 {
440 "name": "c23",
441 "nullable": false,
442 "type": {
443 "name": "fixedsizelist",
444 "listSize": 5
445 },
446 "children": [
447 {
448 "name": "bools",
449 "nullable": false,
450 "type": {
451 "name": "bool"
452 },
453 "children": []
454 }
455 ]
456 },
457 {
458 "name": "c24",
459 "nullable": true,
460 "type": {
461 "name": "list"
462 },
463 "children": [
464 {
465 "name": "inner_list",
466 "nullable": false,
467 "type": {
468 "name": "list"
469 },
470 "children": [
471 {
472 "name": "struct",
473 "nullable": true,
474 "type": {
475 "name": "struct"
476 },
477 "children": []
478 }
479 ]
480 }
481 ]
482 },
483 {
484 "name": "c25",
485 "nullable": false,
486 "type": {
487 "name": "struct"
488 },
489 "children": [
490 {
491 "name": "a",
492 "nullable": false,
493 "type": {
494 "name": "utf8"
495 },
496 "children": []
497 },
498 {
499 "name": "b",
500 "nullable": false,
501 "type": {
502 "name": "int",
503 "bitWidth": 16,
504 "isSigned": false
505 },
506 "children": []
507 }
508 ]
509 },
510 {
511 "name": "c26",
512 "nullable": true,
513 "type": {
514 "name": "interval",
515 "unit": "YEAR_MONTH"
516 },
517 "children": []
518 },
519 {
520 "name": "c27",
521 "nullable": true,
522 "type": {
523 "name": "interval",
524 "unit": "DAY_TIME"
525 },
526 "children": []
527 },
528 {
529 "name": "c28",
530 "nullable": true,
531 "type": {
532 "name": "interval",
533 "unit": "MONTH_DAY_NANO"
534 },
535 "children": []
536 },
537 {
538 "name": "c29",
539 "nullable": false,
540 "type": {
541 "name": "duration",
542 "unit": "SECOND"
543 },
544 "children": []
545 },
546 {
547 "name": "c30",
548 "nullable": false,
549 "type": {
550 "name": "duration",
551 "unit": "MILLISECOND"
552 },
553 "children": []
554 },
555 {
556 "name": "c31",
557 "nullable": false,
558 "type": {
559 "name": "duration",
560 "unit": "MICROSECOND"
561 },
562 "children": []
563 },
564 {
565 "name": "c32",
566 "nullable": false,
567 "type": {
568 "name": "duration",
569 "unit": "NANOSECOND"
570 },
571 "children": []
572 },
573 {
574 "name": "c33",
575 "nullable": true,
576 "children": [],
577 "type": {
578 "name": "utf8"
579 },
580 "dictionary": {
581 "id": 123,
582 "indexType": {
583 "name": "int",
584 "bitWidth": 32,
585 "isSigned": true
586 },
587 "isOrdered": true
588 }
589 },
590 {
591 "name": "c34",
592 "nullable": true,
593 "type": {
594 "name": "largebinary"
595 },
596 "children": []
597 },
598 {
599 "name": "c35",
600 "nullable": true,
601 "type": {
602 "name": "largeutf8"
603 },
604 "children": []
605 },
606 {
607 "name": "c36",
608 "nullable": true,
609 "type": {
610 "name": "largelist"
611 },
612 "children": [
613 {
614 "name": "inner_large_list",
615 "nullable": true,
616 "type": {
617 "name": "largelist"
618 },
619 "children": [
620 {
621 "name": "struct",
622 "nullable": false,
623 "type": {
624 "name": "struct"
625 },
626 "children": []
627 }
628 ]
629 }
630 ]
631 },
632 {
633 "name": "c37",
634 "nullable": false,
635 "type": {
636 "name": "map",
637 "keysSorted": true
638 },
639 "children": [
640 {
641 "name": "my_entries",
642 "nullable": false,
643 "type": {
644 "name": "struct"
645 },
646 "children": [
647 {
648 "name": "my_keys",
649 "nullable": false,
650 "type": {
651 "name": "utf8"
652 },
653 "children": []
654 },
655 {
656 "name": "my_values",
657 "nullable": true,
658 "type": {
659 "name": "int",
660 "bitWidth": 16,
661 "isSigned": false
662 },
663 "children": []
664 }
665 ]
666 }
667 ]
668 }
669 ],
670 "metadata" : {
671 "Key": "Value"
672 }
673 }"#;
674 let value: Value = serde_json::from_str(json).unwrap();
675 assert_eq!(expected, value);
676
677 // convert back to a schema
678 let value: Value = serde_json::from_str(json).unwrap();
679 let schema2 = schema_from_json(&value).unwrap();
680
681 assert_eq!(schema, schema2);
682
683 // Check that empty metadata produces empty value in JSON and can be parsed
684 let json = r#"{
685 "fields": [
686 {
687 "name": "c1",
688 "nullable": false,
689 "type": {
690 "name": "utf8"
691 },
692 "children": []
693 }
694 ],
695 "metadata": {}
696 }"#;
697 let value: Value = serde_json::from_str(json).unwrap();
698 let schema = schema_from_json(&value).unwrap();
699 assert!(schema.metadata.is_empty());
700
701 // Check that metadata field is not required in the JSON.
702 let json = r#"{
703 "fields": [
704 {
705 "name": "c1",
706 "nullable": false,
707 "type": {
708 "name": "utf8"
709 },
710 "children": []
711 }
712 ]
713 }"#;
714 let value: Value = serde_json::from_str(json).unwrap();
715 let schema = schema_from_json(&value).unwrap();
716 assert!(schema.metadata.is_empty());
717 }
718
719 #[test]
720 fn field_metadata_json() {
721 let schema = Schema::new(vec![
722 Field::new("field", DataType::Utf8, false)
723 .with_metadata(HashMap::from([("key".to_string(), "value".to_string())])),
724 ]);
725
726 let json = schema_to_json(&schema);
727
728 assert_eq!(
729 json["fields"][0]["metadata"],
730 serde_json::json!({"key": "value"})
731 );
732 assert_eq!(schema_from_json(&json).unwrap(), schema);
733 }
734
735 #[test]
736 fn dictionary_field_metadata_json() {
737 #[expect(deprecated)]
738 let field = Field::new_dict(
739 "dictionary",
740 DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
741 true,
742 42,
743 false,
744 )
745 .with_metadata(HashMap::from([(
746 "dictionary_key".to_string(),
747 "dictionary_value".to_string(),
748 )]));
749 let schema = Schema::new(vec![field]);
750
751 let json = schema_to_json(&schema);
752
753 assert_eq!(
754 json["fields"][0]["metadata"],
755 serde_json::json!({"dictionary_key": "dictionary_value"})
756 );
757 assert_eq!(schema_from_json(&json).unwrap(), schema);
758 }
759}