-
Notifications
You must be signed in to change notification settings - Fork 10
/
ast.rs
1268 lines (1191 loc) · 41.9 KB
/
ast.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::casing::to_snake_case;
use super::jsonschema;
use super::Context;
use super::TranslateFrom;
use onig::Regex;
use std::collections::{HashMap, HashSet};
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
#[serde(rename_all = "lowercase")]
pub enum Atom {
Boolean,
Integer,
Number,
String,
Datetime,
JSON,
Bytes,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Object {
pub fields: HashMap<String, Box<Tag>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub required: Option<HashSet<String>>,
}
impl Object {
pub fn new(fields: HashMap<String, Tag>, required: Option<HashSet<String>>) -> Self {
let fields: HashMap<String, Box<Tag>> =
fields.into_iter().map(|(k, v)| (k, Box::new(v))).collect();
Object { fields, required }
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Array {
pub items: Box<Tag>,
}
impl Array {
pub fn new(items: Tag) -> Self {
Array {
items: Box::new(items),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Tuple {
pub items: Vec<Tag>,
}
impl Tuple {
pub fn new(items: Vec<Tag>) -> Self {
Tuple {
items: items.clone(),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Map {
pub key: Box<Tag>,
pub value: Box<Tag>,
}
impl Map {
pub fn new(key: Option<String>, value: Tag) -> Self {
Map {
key: Box::new(Tag {
name: key,
namespace: None,
data_type: Type::Atom(Atom::String),
nullable: false,
is_root: false,
}),
value: Box::new(value),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Union {
items: Vec<Tag>,
}
impl Union {
pub fn new(items: Vec<Tag>) -> Self {
Union { items }
}
/// Collapse a union of types into a structurally compatible type.
///
/// Typically, variant types are not allowed in a table schema. If a variant type
/// type is found, it will be converted into a JSON type. Because of the ambiguity
/// around finding structure in a JSON blob, the union of any type with JSON will
/// be consumed by the JSON type. In a similar fashion, a table schema is determined
/// to be nullable or required via occurances of null types in unions.
pub fn collapse(&self) -> Tag {
let is_null = self.items.iter().any(Tag::is_null);
if self.items.is_empty() {
panic!("empty union is not allowed")
} else if self.items.len() == 1 {
return Tag {
name: None,
namespace: None,
nullable: is_null,
is_root: false,
data_type: self.items[0].data_type.clone(),
};
}
let items: Vec<Tag> = self
.items
.iter()
.filter(|x| !x.is_null())
.map(|x| {
if let Type::Union(union) = &x.data_type {
let mut tag = union.collapse();
tag.name = x.name.clone();
tag
} else {
x.clone()
}
})
.collect();
// after collapsing nulls in the base case and collapsing nested unions in
// the preprocessing step, check for nullability based on the immediate level of tags
let nullable = is_null || items.iter().any(|tag| tag.nullable);
let data_type: Type = if items.iter().all(Tag::is_atom) {
items
.into_iter()
.fold(Type::Null, |acc, x| match (acc, &x.data_type) {
(Type::Null, Type::Atom(atom)) => Type::Atom(*atom),
(Type::Atom(left), Type::Atom(right)) => {
let atom = match (left, right) {
(Atom::Boolean, Atom::Boolean) => Atom::Boolean,
(Atom::Integer, Atom::Integer) => Atom::Integer,
(Atom::Number, Atom::Number)
| (Atom::Integer, Atom::Number)
| (Atom::Number, Atom::Integer) => Atom::Number,
(Atom::String, Atom::String) => Atom::String,
(lhs, rhs) => {
trace!("Invalid union collapse of atoms {:?} and {:?}", lhs, rhs);
Atom::JSON
}
};
Type::Atom(atom)
}
_ => {
trace!("Invalid union collapse of atoms found during fold");
Type::Atom(Atom::JSON)
}
})
} else if items.iter().all(Tag::is_object) {
items
.into_iter()
.fold(Type::Null, |acc, x| match (&acc, &x.data_type) {
(Type::Null, Type::Object(object)) => Type::Object(object.clone()),
(Type::Object(left), Type::Object(right)) => {
// union each sub-property, recursively collapse, and rebuild
let mut union: HashMap<String, Vec<Tag>> = HashMap::new();
for (key, value) in &left.fields {
union.insert(key.to_string(), vec![*value.clone()]);
}
for (key, value) in &right.fields {
if let Some(vec) = union.get_mut(key) {
vec.push(*value.clone())
} else {
union.insert(key.to_string(), vec![*value.clone()]);
}
}
let result: HashMap<String, Tag> = union
.into_iter()
.map(|(k, v)| (k, Union::new(v).collapse()))
.collect();
// Recursively invalidate the tree if any of the subschemas are incompatible.
// Atom::JSON is a catch-all value and marks inconsistent objects.
let is_consistent = !result.iter().any(|(_, v)| match v.data_type {
Type::Atom(Atom::JSON) => true,
_ => false,
});
if is_consistent {
let required: Option<HashSet<String>> =
match (&left.required, &right.required) {
(Some(x), Some(y)) => {
Some(x.intersection(&y).map(ToString::to_string).collect())
}
(Some(x), None) | (None, Some(x)) => Some(x.clone()),
_ => None,
};
Type::Object(Object::new(result, required))
} else {
trace!("Incompatible subschemas found during union collapse");
Type::Atom(Atom::JSON)
}
}
_ => {
trace!("Inconsistent union collapse of object");
Type::Atom(Atom::JSON)
}
})
} else if items.iter().all(Tag::is_map) {
let tags: Vec<Tag> = items
.into_iter()
.map(|x| match &x.data_type {
Type::Map(map) => *map.value.clone(),
_ => panic!("Invalid map found during union collapse"),
})
.collect();
Type::Map(Map::new(None, Union::new(tags).collapse()))
} else if items.iter().all(Tag::is_array) {
let tags: Vec<Tag> = items
.into_iter()
.map(|x| match &x.data_type {
Type::Array(array) => *array.items.clone(),
_ => panic!("Invalid array found during union collapse"),
})
.collect();
Type::Array(Array::new(Union::new(tags).collapse()))
} else {
trace!("Incompatible union collapse found");
Type::Atom(Atom::JSON)
};
let mut tag = Tag {
name: None,
namespace: None,
nullable,
data_type,
is_root: false,
};
tag.infer_nullability(false);
tag
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "lowercase")]
pub enum Type {
Null,
Atom(Atom),
Object(Object),
Map(Map),
Array(Array),
Tuple(Tuple),
Union(Union),
// Intersection
// Not
}
impl Default for Type {
fn default() -> Self {
Type::Null
}
}
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
#[serde(tag = "type")]
pub struct Tag {
#[serde(rename = "type")]
pub data_type: Type,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
// The namespace of the current object
#[serde(skip_serializing_if = "Option::is_none")]
pub namespace: Option<String>,
#[serde(default)]
pub nullable: bool,
#[serde(default, skip_serializing)]
pub is_root: bool,
}
impl Tag {
pub fn new(data_type: Type, name: Option<String>, nullable: bool) -> Self {
Tag {
data_type,
name,
namespace: None,
nullable,
is_root: false,
}
}
pub fn is_null(&self) -> bool {
match self.data_type {
Type::Null => true,
_ => false,
}
}
pub fn is_atom(&self) -> bool {
match self.data_type {
Type::Atom(_) => true,
_ => false,
}
}
pub fn is_object(&self) -> bool {
match self.data_type {
Type::Object(_) => true,
_ => false,
}
}
pub fn is_map(&self) -> bool {
match self.data_type {
Type::Map(_) => true,
_ => false,
}
}
pub fn is_array(&self) -> bool {
match self.data_type {
Type::Array(_) => true,
_ => false,
}
}
/// Get the path to the current tag in the context of the larger schema.
///
/// Each tag in the schema can be unambiguously referenced by concatenating
/// the name of tag with the tag's namespace. For example, a document may
/// contain a `timestamp` field nested under different sub-documents.
///
/// ```json
/// {
/// "environment": { "timestamp": 64 },
/// "payload": {
/// "measurement": 10,
/// "timestamp": 64
/// }
/// }
/// ```
///
/// The fully qualified names are as follows:
///
/// * `root.environment.timestamp`
/// * `root.payload.measurement`
/// * `root.payload.timestamp`
pub fn fully_qualified_name(&self) -> String {
let name = match &self.name {
Some(name) => name.clone(),
None => "__unknown__".to_string(),
};
match &self.namespace {
Some(ns) => format!("{}.{}", ns, name),
None => name,
}
}
/// If a name starts with a number, prefix it with an underscore.
fn normalize_numeric_prefix(name: String) -> String {
if name.chars().next().unwrap().is_numeric() {
format!("_{}", name)
} else {
name
}
}
/// Renames a column name so it contains only letters, numbers, and
/// underscores while starting with a letter or underscore. This requirement
/// is enforced by BigQuery during table creation.
fn normalize_name_bigquery(string: &str) -> Option<String> {
let re = Regex::new(r"^[a-zA-Z_][a-zA-Z0-9_]*$").unwrap();
let renamed = Tag::normalize_numeric_prefix(string.replace(".", "_").replace("-", "_"));
if re.is_match(&renamed) {
Some(renamed)
} else {
None
}
}
/// Fix properties of an object to adhere the BigQuery column name
/// specification.
///
/// This removes invalid field names from the schema when inferring the
/// names for the schema (e.g. `$schema`). It also applies rules to be
/// consistent with BigQuery's naming scheme, like avoiding columns that
/// start with a number.
///
/// This modifies field names as well as required fields.
/// See: https://cloud.google.com/bigquery/docs/schemas
pub fn normalize_properties(&mut self, normalize_case: bool) {
if let Type::Object(ref mut object) = self.data_type {
let fields = &mut object.fields;
let keys: Vec<String> = fields.keys().cloned().collect();
for key in keys {
// Replace property names with the normalized property name
if let Some(mut renamed) = Tag::normalize_name_bigquery(&key) {
renamed = if normalize_case {
// snake_casing strips symbols outside of word
// boundaries e.g. _64bit -> 64bit
Tag::normalize_numeric_prefix(to_snake_case(&renamed))
} else {
renamed
};
if renamed.as_str() != key.as_str() {
warn!("{} replaced with {}", key, renamed);
fields.insert(renamed, fields[&key].clone());
fields.remove(&key);
}
} else {
warn!("Omitting {} - not a valid property name", key);
fields.remove(&key);
}
}
// Replace the corresponding names in the required field
object.required = match &object.required {
Some(required) => {
let renamed: HashSet<String> = required
.iter()
.map(String::as_str)
.map(Tag::normalize_name_bigquery)
.filter(Option::is_some)
.map(Option::unwrap)
.collect();
if normalize_case {
Some(
renamed
.iter()
.map(|s| Tag::normalize_numeric_prefix(to_snake_case(&s)))
.collect(),
)
} else {
Some(renamed)
}
}
None => None,
};
}
}
/// Sets a tag with references to the name and the namespace.
fn set_name(&mut self, name: &str, namespace: &str) {
self.name = Some(name.to_string());
if !namespace.is_empty() {
self.namespace = Some(namespace.to_string());
}
}
/// A helper function for calculating the names and namespaces within the
/// schema.
///
/// The namespaces are built from the top-down and follows the depth-first
/// traversal of the schema.
fn recurse_infer_name(&mut self, namespace: String, normalize_case: bool) {
self.normalize_properties(normalize_case);
let set_and_recurse = |tag: &mut Tag, name: &str| {
tag.set_name(name, &namespace);
tag.recurse_infer_name(format!("{}.{}", &namespace, name), normalize_case)
};
match &mut self.data_type {
Type::Object(object) => {
for (key, value) in object.fields.iter_mut() {
set_and_recurse(value, key)
}
}
Type::Map(map) => {
set_and_recurse(&mut map.key, "key");
set_and_recurse(&mut map.value, "value");
}
Type::Array(array) => {
set_and_recurse(&mut array.items, "items");
}
Type::Union(union) => {
for item in union.items.iter_mut() {
set_and_recurse(item, "__union__");
}
}
Type::Tuple(tuple) => {
for (i, item) in tuple.items.iter_mut().enumerate() {
let name = format!("f{}_", i);
set_and_recurse(item, &name);
}
}
_ => (),
}
}
/// Assign names and namespaces to tags from parent tags.
pub fn infer_name(&mut self, normalize_case: bool) {
let namespace = match &self.name {
Some(name) => name.clone(),
None => "".into(),
};
self.recurse_infer_name(namespace, normalize_case);
}
/// Infer whether the current tag in the schema allows for the value to be
/// null.
///
/// These rules are primarily focused on BigQuery, although they should
/// translate into other schemas. This should be run after unions have been
/// eliminated from the tree since the behavior is currently order
/// dependent.
pub fn infer_nullability(&mut self, force_nullable: bool) {
match &mut self.data_type {
Type::Null => {
self.nullable = true;
}
Type::Object(object) => {
let required = match &object.required {
Some(required) => required.clone(),
None => HashSet::new(),
};
for (key, value) in &mut object.fields {
// Infer whether the value is nullable
value.infer_nullability(force_nullable);
// A required nullable field is still nullable
value.nullable |= !required.contains(key);
// All fields are nullable if enforced
if force_nullable {
value.nullable = true;
}
}
}
Type::Map(map) => map.value.infer_nullability(force_nullable),
Type::Array(array) => array.items.infer_nullability(force_nullable),
Type::Tuple(tuple) => {
for item in tuple.items.iter_mut() {
item.infer_nullability(force_nullable);
}
}
Type::Union(union) => {
for item in union.items.iter_mut() {
item.infer_nullability(force_nullable);
}
}
_ => (),
}
if force_nullable {
self.nullable = true
}
}
/// Factor out the shared parts of the union between two schemas.
pub fn collapse(&mut self) {
match &mut self.data_type {
Type::Object(object) => {
for value in &mut object.fields.values_mut() {
value.collapse()
}
}
Type::Map(map) => map.value.collapse(),
Type::Array(array) => array.items.collapse(),
Type::Tuple(tuple) => {
for item in tuple.items.iter_mut() {
item.collapse()
}
}
Type::Union(union) => {
let tag = union.collapse();
self.data_type = tag.data_type;
self.nullable = tag.nullable;
}
_ => (),
}
}
}
impl TranslateFrom<jsonschema::Tag> for Tag {
type Error = &'static str;
fn translate_from(tag: jsonschema::Tag, context: Context) -> Result<Self, Self::Error> {
let mut tag = tag.type_into_ast(context)?;
tag.infer_name(context.normalize_case);
tag.infer_nullability(context.force_nullable);
tag.is_root = true;
Ok(tag)
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use serde_json::{json, Value};
#[test]
fn test_serialize_null() {
let null_tag = Tag {
..Default::default()
};
let expect = json!({
"type": "null",
"nullable": false,
});
assert_eq!(expect, json!(null_tag))
}
#[test]
fn test_serialize_atom() {
let atom = Tag {
data_type: Type::Atom(Atom::Integer),
name: Some("test-int".into()),
nullable: true,
..Default::default()
};
let expect = json!({
"type": {"atom": "integer"},
"name": "test-int",
"nullable": true,
});
assert_eq!(expect, json!(atom));
}
#[test]
fn test_serialize_object() {
let mut field = Tag {
data_type: Type::Object(Object::new(HashMap::new(), None)),
name: Some("test-object".into()),
..Default::default()
};
if let Type::Object(object) = &mut field.data_type {
object.fields.insert(
"test-int".into(),
Box::new(Tag {
data_type: Type::Atom(Atom::Integer),
name: Some("test-int".into()),
..Default::default()
}),
);
object.fields.insert(
"test-bool".into(),
Box::new(Tag {
data_type: Type::Atom(Atom::Boolean),
name: Some("test-bool".into()),
..Default::default()
}),
);
}
let expect = json!({
"name": "test-object",
"nullable": false,
"type": {
"object": {
"fields": {
"test-int": {
"name": "test-int",
"type": {"atom": "integer"},
"nullable": false
},
"test-bool": {
"name": "test-bool",
"type": {"atom": "boolean"},
"nullable": false
}
}
}
}
});
assert_eq!(expect, json!(field))
}
#[test]
fn test_serialize_map() {
let atom = Tag {
data_type: Type::Atom(Atom::Integer),
name: Some("test-value".into()),
nullable: false,
..Default::default()
};
let field = Tag {
data_type: Type::Map(Map::new(Some("test-key".into()), atom)),
name: Some("test-map".into()),
nullable: true,
..Default::default()
};
let expect = json!({
"name": "test-map",
"nullable": true,
"type": {
"map": {
"key": {
"name": "test-key",
"nullable": false,
"type": {"atom": "string"},
},
"value": {
"name": "test-value",
"nullable": false,
"type": {"atom": "integer"},
}
}
}
});
assert_eq!(expect, json!(field));
}
#[test]
fn test_serialize_array() {
// represent multi-set with nulls
let atom = Tag {
data_type: Type::Atom(Atom::Integer),
name: Some("test-int".into()),
nullable: true,
..Default::default()
};
let field = Tag {
data_type: Type::Array(Array::new(atom)),
name: Some("test-array".into()),
nullable: false,
..Default::default()
};
let expect = json!({
"type": {
"array": {
"items": {
"name": "test-int",
"type": {"atom": "integer"},
"nullable": true,
}
}
},
"name": "test-array",
"nullable": false
});
assert_eq!(expect, json!(field))
}
#[test]
fn test_serialize_union() {
let test_int = Tag {
data_type: Type::Atom(Atom::Integer),
..Default::default()
};
let test_null = Tag {
..Default::default()
};
let union = Tag {
data_type: Type::Union(Union {
items: vec![test_int, test_null],
}),
..Default::default()
};
let expect = json!({
"type": {
"union": {
"items": [
{"type": {"atom": "integer"}, "nullable": false},
{"type": "null", "nullable": false},
]
}
},
"nullable": false
});
assert_eq!(expect, json!(union))
}
#[test]
fn test_union_collapse_atom() {
let data = json!({
"union": {
"items": [
{"type": {"atom": "integer"}},
]}});
let dtype: Type = serde_json::from_value(data).unwrap();
let expect = json!({
"atom": "integer",
});
if let Type::Union(union) = dtype {
assert_eq!(expect, json!(union.collapse().data_type))
} else {
panic!()
}
}
#[test]
fn test_union_collapse_atom_repeats() {
let data = json!({
"union": {
"items": [
{"type": {"atom": "integer"}},
{"type": {"atom": "integer"}},
{"type": {"atom": "integer"}},
]}});
let dtype: Type = serde_json::from_value(data).unwrap();
let expect = json!({
"atom": "integer",
});
if let Type::Union(union) = dtype {
assert_eq!(expect, json!(union.collapse().data_type))
} else {
panic!()
}
}
#[test]
fn test_union_collapse_nullable_atom() {
let data = json!({
"union": {
"items": [
{"type": "null"},
{"type": {"atom": "integer"}},
]}});
let dtype: Type = serde_json::from_value(data).unwrap();
let expect = json!({
"atom": "integer",
});
if let Type::Union(union) = dtype {
assert_eq!(expect, json!(union.collapse().data_type))
} else {
panic!()
}
}
#[test]
fn test_union_collapse_type_conflict() {
let data = json!({
"union": {
"items": [
{"type": {"atom": "string"}},
{"type": {"atom": "integer"}},
]}});
let dtype: Type = serde_json::from_value(data).unwrap();
let expect = json!({
"atom": "json",
});
if let Type::Union(union) = dtype {
assert_eq!(expect, json!(union.collapse().data_type))
} else {
panic!()
}
}
#[test]
fn test_union_collapse_object_merge() {
let data = json!({
"union": {
"items": [
{
"type": {
"object": {
"fields": {
"atom_0": {"type": {"atom": "boolean"}},
"atom_1": {"type": {"atom": "integer"}},
}}}},
{
"type": {
"object": {
"fields": {
"atom_1": {"type": {"atom": "integer"}},
"atom_2": {"type": {"atom": "string"}},
}}}},
]}});
let dtype: Type = serde_json::from_value(data).unwrap();
let expect = json!({
"object": {
"fields": {
"atom_0": {"type": {"atom": "boolean"}, "nullable": true},
"atom_1": {"type": {"atom": "integer"}, "nullable": true},
"atom_2": {"type": {"atom": "string"}, "nullable": true},
}}});
if let Type::Union(union) = dtype {
assert_eq!(expect, json!(union.collapse().data_type))
} else {
panic!()
}
}
#[test]
fn test_union_collapse_object_conflict() {
let data = json!({
"union": {
"items": [
{"type": {"atom": "string"}},
{"type": {"atom": "integer"}},
]}});
let dtype: Type = serde_json::from_value(data).unwrap();
let expect = json!({
"atom": "json",
});
if let Type::Union(union) = dtype {
assert_eq!(expect, json!(union.collapse().data_type))
} else {
panic!()
}
}
#[test]
fn test_union_collapse_array_nullable_atom() {
let data = json!({
"union": {
"items": [
{"type": {"array": {"items": {"type": {"atom": "integer"}}}}},
{"type": {"array": {"items": {"type": "null"}}}},
]}});
let dtype: Type = serde_json::from_value(data).unwrap();
let expect = json!({
"array": {"items": {"type": {"atom": "integer"}, "nullable": true}}
});
if let Type::Union(union) = dtype {
assert_eq!(expect, json!(union.collapse().data_type))
} else {
panic!()
}
}
#[test]
fn test_union_collapse_map_nullable_atom() {
let dtype = Type::Union(Union::new(vec![
Tag::new(
Type::Map(Map::new(
None,
Tag::new(Type::Atom(Atom::Integer), None, false),
)),
None,
false,
),
Tag::new(
Type::Map(Map::new(None, Tag::new(Type::Null, None, false))),
None,
false,
),
]));
let expect = json!({
"map": {
"key": {
"type": {"atom": "string"},
"nullable": false,
},
"value": {
"type": {"atom": "integer"},
"nullable": true,
}}});
if let Type::Union(union) = dtype {
assert_eq!(expect, json!(union.collapse().data_type))
} else {
panic!()
}
}
#[test]
fn test_union_collapse_nested_union() {
let data = json!({
"union": {
"items": [
{"type": {"union": {"items": [
{"type": "null"},
{"type": {"atom": "number"}},
]}}},
{"type": {"atom": "integer"}},
]}});
let dtype: Type = serde_json::from_value(data).unwrap();
let expect = json!({
"nullable": true,
"type": {"atom": "number"}
});
if let Type::Union(union) = dtype {
assert_eq!(expect, json!(union.collapse()))
} else {
panic!()
}
}
fn assert_infer_name(expect: Value, actual: Value) {
let mut tag: Tag = serde_json::from_value(actual).unwrap();
tag.infer_name(false);
assert_eq!(expect, json!(tag))
}
#[test]
fn test_tag_infer_name_object() {
let data = json!({
"type": {
"object": {
"fields": {
"atom_0": {"type": {"atom": "integer"}},
"atom_1": {"type": {"atom": "integer"}},
"atom_2": {"type": {"atom": "integer"}},
}}}});
let expect = json!({
"nullable": false,
"type": {
"object": {
"fields": {
"atom_0": {"name": "atom_0", "type": {"atom": "integer"}, "nullable": false},
"atom_1": {"name": "atom_1", "type": {"atom": "integer"}, "nullable": false},
"atom_2": {"name": "atom_2", "type": {"atom": "integer"}, "nullable": false},
}}}});
assert_infer_name(expect, data);
}
#[test]
fn test_tag_infer_name_array_object() {
let data = json!({
"name": "foo",
"type": {