-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathschema.rs
6954 lines (6351 loc) · 224 KB
/
schema.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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Logic for parsing and interacting with schemas in Avro format.
use crate::{
error::Error,
schema_equality, types,
util::MapHelper,
validator::{
validate_enum_symbol_name, validate_namespace, validate_record_field_name,
validate_schema_name,
},
AvroResult,
};
use digest::Digest;
use log::{debug, error, warn};
use serde::{
ser::{SerializeMap, SerializeSeq},
Deserialize, Serialize, Serializer,
};
use serde_json::{Map, Value};
use std::{
borrow::{Borrow, Cow},
collections::{BTreeMap, HashMap, HashSet},
fmt,
fmt::Debug,
hash::Hash,
io::Read,
str::FromStr,
};
use strum_macros::{Display, EnumDiscriminants, EnumString};
/// Represents an Avro schema fingerprint
/// More information about Avro schema fingerprints can be found in the
/// [Avro Schema Fingerprint documentation](https://avro.apache.org/docs/current/specification/#schema-fingerprints)
pub struct SchemaFingerprint {
pub bytes: Vec<u8>,
}
impl fmt::Display for SchemaFingerprint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
self.bytes
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<Vec<String>>()
.join("")
)
}
}
/// Represents any valid Avro schema
/// More information about Avro schemas can be found in the
/// [Avro Specification](https://avro.apache.org/docs/current/specification/#schema-declaration)
#[derive(Clone, Debug, EnumDiscriminants, Display)]
#[strum_discriminants(name(SchemaKind), derive(Hash, Ord, PartialOrd))]
pub enum Schema {
/// A `null` Avro schema.
Null,
/// A `boolean` Avro schema.
Boolean,
/// An `int` Avro schema.
Int,
/// A `long` Avro schema.
Long,
/// A `float` Avro schema.
Float,
/// A `double` Avro schema.
Double,
/// A `bytes` Avro schema.
/// `Bytes` represents a sequence of 8-bit unsigned bytes.
Bytes,
/// A `string` Avro schema.
/// `String` represents a unicode character sequence.
String,
/// A `array` Avro schema. Avro arrays are required to have the same type for each element.
/// This variant holds the `Schema` for the array element type.
Array(ArraySchema),
/// A `map` Avro schema.
/// `Map` holds a pointer to the `Schema` of its values, which must all be the same schema.
/// `Map` keys are assumed to be `string`.
Map(MapSchema),
/// A `union` Avro schema.
Union(UnionSchema),
/// A `record` Avro schema.
Record(RecordSchema),
/// An `enum` Avro schema.
Enum(EnumSchema),
/// A `fixed` Avro schema.
Fixed(FixedSchema),
/// Logical type which represents `Decimal` values. The underlying type is serialized and
/// deserialized as `Schema::Bytes` or `Schema::Fixed`.
Decimal(DecimalSchema),
/// Logical type which represents `Decimal` values without predefined scale.
/// The underlying type is serialized and deserialized as `Schema::Bytes`
BigDecimal,
/// A universally unique identifier, annotating a string.
Uuid,
/// Logical type which represents the number of days since the unix epoch.
/// Serialization format is `Schema::Int`.
Date,
/// The time of day in number of milliseconds after midnight with no reference any calendar,
/// time zone or date in particular.
TimeMillis,
/// The time of day in number of microseconds after midnight with no reference any calendar,
/// time zone or date in particular.
TimeMicros,
/// An instant in time represented as the number of milliseconds after the UNIX epoch.
TimestampMillis,
/// An instant in time represented as the number of microseconds after the UNIX epoch.
TimestampMicros,
/// An instant in time represented as the number of nanoseconds after the UNIX epoch.
TimestampNanos,
/// An instant in localtime represented as the number of milliseconds after the UNIX epoch.
LocalTimestampMillis,
/// An instant in local time represented as the number of microseconds after the UNIX epoch.
LocalTimestampMicros,
/// An instant in local time represented as the number of nanoseconds after the UNIX epoch.
LocalTimestampNanos,
/// An amount of time defined by a number of months, days and milliseconds.
Duration,
/// A reference to another schema.
Ref { name: Name },
}
#[derive(Clone, Debug, PartialEq)]
pub struct MapSchema {
pub types: Box<Schema>,
pub attributes: BTreeMap<String, Value>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ArraySchema {
pub items: Box<Schema>,
pub attributes: BTreeMap<String, Value>,
}
impl PartialEq for Schema {
/// Assess equality of two `Schema` based on [Parsing Canonical Form].
///
/// [Parsing Canonical Form]:
/// https://avro.apache.org/docs/1.11.1/specification/#parsing-canonical-form-for-schemas
fn eq(&self, other: &Self) -> bool {
schema_equality::compare_schemata(self, other)
}
}
impl SchemaKind {
pub fn is_primitive(self) -> bool {
matches!(
self,
SchemaKind::Null
| SchemaKind::Boolean
| SchemaKind::Int
| SchemaKind::Long
| SchemaKind::Double
| SchemaKind::Float
| SchemaKind::Bytes
| SchemaKind::String,
)
}
pub fn is_named(self) -> bool {
matches!(
self,
SchemaKind::Record | SchemaKind::Enum | SchemaKind::Fixed | SchemaKind::Ref
)
}
}
impl From<&types::Value> for SchemaKind {
fn from(value: &types::Value) -> Self {
use crate::types::Value;
match value {
Value::Null => Self::Null,
Value::Boolean(_) => Self::Boolean,
Value::Int(_) => Self::Int,
Value::Long(_) => Self::Long,
Value::Float(_) => Self::Float,
Value::Double(_) => Self::Double,
Value::Bytes(_) => Self::Bytes,
Value::String(_) => Self::String,
Value::Array(_) => Self::Array,
Value::Map(_) => Self::Map,
Value::Union(_, _) => Self::Union,
Value::Record(_) => Self::Record,
Value::Enum(_, _) => Self::Enum,
Value::Fixed(_, _) => Self::Fixed,
Value::Decimal { .. } => Self::Decimal,
Value::BigDecimal(_) => Self::BigDecimal,
Value::Uuid(_) => Self::Uuid,
Value::Date(_) => Self::Date,
Value::TimeMillis(_) => Self::TimeMillis,
Value::TimeMicros(_) => Self::TimeMicros,
Value::TimestampMillis(_) => Self::TimestampMillis,
Value::TimestampMicros(_) => Self::TimestampMicros,
Value::TimestampNanos(_) => Self::TimestampNanos,
Value::LocalTimestampMillis(_) => Self::LocalTimestampMillis,
Value::LocalTimestampMicros(_) => Self::LocalTimestampMicros,
Value::LocalTimestampNanos(_) => Self::LocalTimestampNanos,
Value::Duration { .. } => Self::Duration,
}
}
}
/// Represents names for `record`, `enum` and `fixed` Avro schemas.
///
/// Each of these `Schema`s have a `fullname` composed of two parts:
/// * a name
/// * a namespace
///
/// `aliases` can also be defined, to facilitate schema evolution.
///
/// More information about schema names can be found in the
/// [Avro specification](https://avro.apache.org/docs/current/specification/#names)
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Name {
pub name: String,
pub namespace: Namespace,
}
/// Represents documentation for complex Avro schemas.
pub type Documentation = Option<String>;
/// Represents the aliases for Named Schema
pub type Aliases = Option<Vec<Alias>>;
/// Represents Schema lookup within a schema env
pub(crate) type Names = HashMap<Name, Schema>;
/// Represents Schema lookup within a schema
pub type NamesRef<'a> = HashMap<Name, &'a Schema>;
/// Represents the namespace for Named Schema
pub type Namespace = Option<String>;
impl Name {
/// Create a new `Name`.
/// Parses the optional `namespace` from the `name` string.
/// `aliases` will not be defined.
pub fn new(name: &str) -> AvroResult<Self> {
let (name, namespace) = Name::get_name_and_namespace(name)?;
Ok(Self {
name,
namespace: namespace.filter(|ns| !ns.is_empty()),
})
}
fn get_name_and_namespace(name: &str) -> AvroResult<(String, Namespace)> {
validate_schema_name(name)
}
/// Parse a `serde_json::Value` into a `Name`.
pub(crate) fn parse(
complex: &Map<String, Value>,
enclosing_namespace: &Namespace,
) -> AvroResult<Self> {
let (name, namespace_from_name) = complex
.name()
.map(|name| Name::get_name_and_namespace(name.as_str()).unwrap())
.ok_or(Error::GetNameField)?;
// FIXME Reading name from the type is wrong ! The name there is just a metadata (AVRO-3430)
let type_name = match complex.get("type") {
Some(Value::Object(complex_type)) => complex_type.name().or(None),
_ => None,
};
let namespace = namespace_from_name
.or_else(|| {
complex
.string("namespace")
.or_else(|| enclosing_namespace.clone())
})
.filter(|ns| !ns.is_empty());
if let Some(ref ns) = namespace {
validate_namespace(ns)?;
}
Ok(Self {
name: type_name.unwrap_or(name),
namespace,
})
}
/// Return the `fullname` of this `Name`
///
/// More information about fullnames can be found in the
/// [Avro specification](https://avro.apache.org/docs/current/specification/#names)
pub fn fullname(&self, default_namespace: Namespace) -> String {
if self.name.contains('.') {
self.name.clone()
} else {
let namespace = self.namespace.clone().or(default_namespace);
match namespace {
Some(ref namespace) if !namespace.is_empty() => {
format!("{}.{}", namespace, self.name)
}
_ => self.name.clone(),
}
}
}
/// Return the fully qualified name needed for indexing or searching for the schema within a schema/schema env context. Puts the enclosing namespace into the name's namespace for clarity in schema/schema env parsing
/// ```ignore
/// use apache_avro::schema::Name;
///
/// assert_eq!(
/// Name::new("some_name")?.fully_qualified_name(&Some("some_namespace".into())),
/// Name::new("some_namespace.some_name")?
/// );
/// assert_eq!(
/// Name::new("some_namespace.some_name")?.fully_qualified_name(&Some("other_namespace".into())),
/// Name::new("some_namespace.some_name")?
/// );
/// ```
pub fn fully_qualified_name(&self, enclosing_namespace: &Namespace) -> Name {
Name {
name: self.name.clone(),
namespace: self
.namespace
.clone()
.or_else(|| enclosing_namespace.clone().filter(|ns| !ns.is_empty())),
}
}
}
impl From<&str> for Name {
fn from(name: &str) -> Self {
Name::new(name).unwrap()
}
}
impl fmt::Display for Name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.fullname(None)[..])
}
}
impl<'de> Deserialize<'de> for Name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
Value::deserialize(deserializer).and_then(|value| {
use serde::de::Error;
if let Value::Object(json) = value {
Name::parse(&json, &None).map_err(Error::custom)
} else {
Err(Error::custom(format!("Expected a JSON object: {value:?}")))
}
})
}
}
/// Newtype pattern for `Name` to better control the `serde_json::Value` representation.
/// Aliases are serialized as an array of plain strings in the JSON representation.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Alias(Name);
impl Alias {
pub fn new(name: &str) -> AvroResult<Self> {
Name::new(name).map(Self)
}
pub fn name(&self) -> String {
self.0.name.clone()
}
pub fn namespace(&self) -> Namespace {
self.0.namespace.clone()
}
pub fn fullname(&self, default_namespace: Namespace) -> String {
self.0.fullname(default_namespace)
}
pub fn fully_qualified_name(&self, default_namespace: &Namespace) -> Name {
self.0.fully_qualified_name(default_namespace)
}
}
impl From<&str> for Alias {
fn from(name: &str) -> Self {
Alias::new(name).unwrap()
}
}
impl Serialize for Alias {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.fullname(None))
}
}
#[derive(Debug)]
pub struct ResolvedSchema<'s> {
names_ref: NamesRef<'s>,
schemata: Vec<&'s Schema>,
}
impl<'s> TryFrom<&'s Schema> for ResolvedSchema<'s> {
type Error = Error;
fn try_from(schema: &'s Schema) -> AvroResult<Self> {
let names = HashMap::new();
let mut rs = ResolvedSchema {
names_ref: names,
schemata: vec![schema],
};
rs.resolve(rs.get_schemata(), &None, None)?;
Ok(rs)
}
}
impl<'s> TryFrom<Vec<&'s Schema>> for ResolvedSchema<'s> {
type Error = Error;
fn try_from(schemata: Vec<&'s Schema>) -> AvroResult<Self> {
let names = HashMap::new();
let mut rs = ResolvedSchema {
names_ref: names,
schemata,
};
rs.resolve(rs.get_schemata(), &None, None)?;
Ok(rs)
}
}
impl<'s> ResolvedSchema<'s> {
pub fn get_schemata(&self) -> Vec<&'s Schema> {
self.schemata.clone()
}
pub fn get_names(&self) -> &NamesRef<'s> {
&self.names_ref
}
/// Creates `ResolvedSchema` with some already known schemas.
///
/// Those schemata would be used to resolve references if needed.
pub fn new_with_known_schemata<'n>(
schemata_to_resolve: Vec<&'s Schema>,
enclosing_namespace: &Namespace,
known_schemata: &'n NamesRef<'n>,
) -> AvroResult<Self> {
let names = HashMap::new();
let mut rs = ResolvedSchema {
names_ref: names,
schemata: schemata_to_resolve,
};
rs.resolve(rs.get_schemata(), enclosing_namespace, Some(known_schemata))?;
Ok(rs)
}
fn resolve<'n>(
&mut self,
schemata: Vec<&'s Schema>,
enclosing_namespace: &Namespace,
known_schemata: Option<&'n NamesRef<'n>>,
) -> AvroResult<()> {
for schema in schemata {
match schema {
Schema::Array(schema) => {
self.resolve(vec![&schema.items], enclosing_namespace, known_schemata)?
}
Schema::Map(schema) => {
self.resolve(vec![&schema.types], enclosing_namespace, known_schemata)?
}
Schema::Union(UnionSchema { schemas, .. }) => {
for schema in schemas {
self.resolve(vec![schema], enclosing_namespace, known_schemata)?
}
}
Schema::Enum(EnumSchema { name, .. }) | Schema::Fixed(FixedSchema { name, .. }) => {
let fully_qualified_name = name.fully_qualified_name(enclosing_namespace);
if self
.names_ref
.insert(fully_qualified_name.clone(), schema)
.is_some()
{
return Err(Error::AmbiguousSchemaDefinition(fully_qualified_name));
}
}
Schema::Record(RecordSchema { name, fields, .. }) => {
let fully_qualified_name = name.fully_qualified_name(enclosing_namespace);
if self
.names_ref
.insert(fully_qualified_name.clone(), schema)
.is_some()
{
return Err(Error::AmbiguousSchemaDefinition(fully_qualified_name));
} else {
let record_namespace = fully_qualified_name.namespace;
for field in fields {
self.resolve(vec![&field.schema], &record_namespace, known_schemata)?
}
}
}
Schema::Ref { name } => {
let fully_qualified_name = name.fully_qualified_name(enclosing_namespace);
// first search for reference in current schemata, then look into external references.
if !self.names_ref.contains_key(&fully_qualified_name) {
let is_resolved_with_known_schemas = known_schemata
.as_ref()
.map(|names| names.contains_key(&fully_qualified_name))
.unwrap_or(false);
if !is_resolved_with_known_schemas {
return Err(Error::SchemaResolutionError(fully_qualified_name));
}
}
}
_ => (),
}
}
Ok(())
}
}
pub(crate) struct ResolvedOwnedSchema {
names: Names,
root_schema: Schema,
}
impl TryFrom<Schema> for ResolvedOwnedSchema {
type Error = Error;
fn try_from(schema: Schema) -> AvroResult<Self> {
let names = HashMap::new();
let mut rs = ResolvedOwnedSchema {
names,
root_schema: schema,
};
resolve_names(&rs.root_schema, &mut rs.names, &None)?;
Ok(rs)
}
}
impl ResolvedOwnedSchema {
pub(crate) fn get_root_schema(&self) -> &Schema {
&self.root_schema
}
pub(crate) fn get_names(&self) -> &Names {
&self.names
}
}
pub(crate) fn resolve_names(
schema: &Schema,
names: &mut Names,
enclosing_namespace: &Namespace,
) -> AvroResult<()> {
match schema {
Schema::Array(schema) => resolve_names(&schema.items, names, enclosing_namespace),
Schema::Map(schema) => resolve_names(&schema.types, names, enclosing_namespace),
Schema::Union(UnionSchema { schemas, .. }) => {
for schema in schemas {
resolve_names(schema, names, enclosing_namespace)?
}
Ok(())
}
Schema::Enum(EnumSchema { name, .. }) | Schema::Fixed(FixedSchema { name, .. }) => {
let fully_qualified_name = name.fully_qualified_name(enclosing_namespace);
if names
.insert(fully_qualified_name.clone(), schema.clone())
.is_some()
{
Err(Error::AmbiguousSchemaDefinition(fully_qualified_name))
} else {
Ok(())
}
}
Schema::Record(RecordSchema { name, fields, .. }) => {
let fully_qualified_name = name.fully_qualified_name(enclosing_namespace);
if names
.insert(fully_qualified_name.clone(), schema.clone())
.is_some()
{
Err(Error::AmbiguousSchemaDefinition(fully_qualified_name))
} else {
let record_namespace = fully_qualified_name.namespace;
for field in fields {
resolve_names(&field.schema, names, &record_namespace)?
}
Ok(())
}
}
Schema::Ref { name } => {
let fully_qualified_name = name.fully_qualified_name(enclosing_namespace);
names
.get(&fully_qualified_name)
.map(|_| ())
.ok_or(Error::SchemaResolutionError(fully_qualified_name))
}
_ => Ok(()),
}
}
pub(crate) fn resolve_names_with_schemata(
schemata: &Vec<&Schema>,
names: &mut Names,
enclosing_namespace: &Namespace,
) -> AvroResult<()> {
for schema in schemata {
resolve_names(schema, names, enclosing_namespace)?;
}
Ok(())
}
/// Represents a `field` in a `record` Avro schema.
#[derive(Clone, Debug, PartialEq)]
pub struct RecordField {
/// Name of the field.
pub name: String,
/// Documentation of the field.
pub doc: Documentation,
/// Aliases of the field's name. They have no namespace.
pub aliases: Option<Vec<String>>,
/// Default value of the field.
/// This value will be used when reading Avro datum if schema resolution
/// is enabled.
pub default: Option<Value>,
/// Schema of the field.
pub schema: Schema,
/// Order of the field.
///
/// **NOTE** This currently has no effect.
pub order: RecordFieldOrder,
/// Position of the field in the list of `field` of its parent `Schema`
pub position: usize,
/// A collection of all unknown fields in the record field.
pub custom_attributes: BTreeMap<String, Value>,
}
/// Represents any valid order for a `field` in a `record` Avro schema.
#[derive(Clone, Debug, Eq, PartialEq, EnumString)]
#[strum(serialize_all = "kebab_case")]
pub enum RecordFieldOrder {
Ascending,
Descending,
Ignore,
}
impl RecordField {
/// Parse a `serde_json::Value` into a `RecordField`.
fn parse(
field: &Map<String, Value>,
position: usize,
parser: &mut Parser,
enclosing_record: &Name,
) -> AvroResult<Self> {
let name = field.name().ok_or(Error::GetNameFieldFromRecord)?;
validate_record_field_name(&name)?;
// TODO: "type" = "<record name>"
let schema = parser.parse_complex(
field,
&enclosing_record.namespace,
RecordSchemaParseLocation::FromField,
)?;
let default = field.get("default").cloned();
Self::resolve_default_value(
&schema,
&name,
&enclosing_record.fullname(None),
&parser.parsed_schemas,
&default,
)?;
let aliases = field.get("aliases").and_then(|aliases| {
aliases.as_array().map(|aliases| {
aliases
.iter()
.flat_map(|alias| alias.as_str())
.map(|alias| alias.to_string())
.collect::<Vec<String>>()
})
});
let order = field
.get("order")
.and_then(|order| order.as_str())
.and_then(|order| RecordFieldOrder::from_str(order).ok())
.unwrap_or(RecordFieldOrder::Ascending);
Ok(RecordField {
name,
doc: field.doc(),
default,
aliases,
order,
position,
custom_attributes: RecordField::get_field_custom_attributes(field, &schema),
schema,
})
}
fn resolve_default_value(
field_schema: &Schema,
field_name: &str,
record_name: &str,
names: &Names,
default: &Option<Value>,
) -> AvroResult<()> {
if let Some(value) = default {
let avro_value = types::Value::from(value.clone());
match field_schema {
Schema::Union(union_schema) => {
let schemas = &union_schema.schemas;
let resolved = schemas.iter().any(|schema| {
avro_value
.to_owned()
.resolve_internal(schema, names, &schema.namespace(), &None)
.is_ok()
});
if !resolved {
let schema: Option<&Schema> = schemas.first();
return match schema {
Some(first_schema) => Err(Error::GetDefaultUnion(
SchemaKind::from(first_schema),
types::ValueKind::from(avro_value),
)),
None => Err(Error::EmptyUnion),
};
}
}
_ => {
let resolved = avro_value
.resolve_internal(field_schema, names, &field_schema.namespace(), &None)
.is_ok();
if !resolved {
return Err(Error::GetDefaultRecordField(
field_name.to_string(),
record_name.to_string(),
field_schema.canonical_form(),
));
}
}
};
}
Ok(())
}
fn get_field_custom_attributes(
field: &Map<String, Value>,
schema: &Schema,
) -> BTreeMap<String, Value> {
let mut custom_attributes: BTreeMap<String, Value> = BTreeMap::new();
for (key, value) in field {
match key.as_str() {
"type" | "name" | "doc" | "default" | "order" | "position" | "aliases"
| "logicalType" => continue,
key if key == "symbols" && matches!(schema, Schema::Enum(_)) => continue,
key if key == "size" && matches!(schema, Schema::Fixed(_)) => continue,
_ => custom_attributes.insert(key.clone(), value.clone()),
};
}
custom_attributes
}
/// Returns true if this `RecordField` is nullable, meaning the schema is a `UnionSchema` where the first variant is `Null`.
pub fn is_nullable(&self) -> bool {
match self.schema {
Schema::Union(ref inner) => inner.is_nullable(),
_ => false,
}
}
}
/// A description of an Enum schema.
#[derive(Debug, Clone)]
pub struct RecordSchema {
/// The name of the schema
pub name: Name,
/// The aliases of the schema
pub aliases: Aliases,
/// The documentation of the schema
pub doc: Documentation,
/// The set of fields of the schema
pub fields: Vec<RecordField>,
/// The `lookup` table maps field names to their position in the `Vec`
/// of `fields`.
pub lookup: BTreeMap<String, usize>,
/// The custom attributes of the schema
pub attributes: BTreeMap<String, Value>,
}
/// A description of an Enum schema.
#[derive(Debug, Clone)]
pub struct EnumSchema {
/// The name of the schema
pub name: Name,
/// The aliases of the schema
pub aliases: Aliases,
/// The documentation of the schema
pub doc: Documentation,
/// The set of symbols of the schema
pub symbols: Vec<String>,
/// An optional default symbol used for compatibility
pub default: Option<String>,
/// The custom attributes of the schema
pub attributes: BTreeMap<String, Value>,
}
/// A description of a Union schema.
#[derive(Debug, Clone)]
pub struct FixedSchema {
/// The name of the schema
pub name: Name,
/// The aliases of the schema
pub aliases: Aliases,
/// The documentation of the schema
pub doc: Documentation,
/// The size of the fixed schema
pub size: usize,
/// An optional default symbol used for compatibility
pub default: Option<String>,
/// The custom attributes of the schema
pub attributes: BTreeMap<String, Value>,
}
impl FixedSchema {
fn serialize_to_map<S>(&self, mut map: S::SerializeMap) -> Result<S::SerializeMap, S::Error>
where
S: Serializer,
{
map.serialize_entry("type", "fixed")?;
if let Some(ref n) = self.name.namespace {
map.serialize_entry("namespace", n)?;
}
map.serialize_entry("name", &self.name.name)?;
if let Some(ref docstr) = self.doc {
map.serialize_entry("doc", docstr)?;
}
map.serialize_entry("size", &self.size)?;
if let Some(ref aliases) = self.aliases {
map.serialize_entry("aliases", aliases)?;
}
for attr in &self.attributes {
map.serialize_entry(attr.0, attr.1)?;
}
Ok(map)
}
}
/// A description of a Union schema.
///
/// `scale` defaults to 0 and is an integer greater than or equal to 0 and `precision` is an
/// integer greater than 0.
#[derive(Debug, Clone)]
pub struct DecimalSchema {
/// The number of digits in the unscaled value
pub precision: DecimalMetadata,
/// The number of digits to the right of the decimal point
pub scale: DecimalMetadata,
/// The inner schema of the decimal (fixed or bytes)
pub inner: Box<Schema>,
}
/// A description of a Union schema
#[derive(Debug, Clone)]
pub struct UnionSchema {
/// The schemas that make up this union
pub(crate) schemas: Vec<Schema>,
// Used to ensure uniqueness of schema inputs, and provide constant time finding of the
// schema index given a value.
// **NOTE** that this approach does not work for named types, and will have to be modified
// to support that. A simple solution is to also keep a mapping of the names used.
variant_index: BTreeMap<SchemaKind, usize>,
}
impl UnionSchema {
/// Creates a new UnionSchema from a vector of schemas.
pub fn new(schemas: Vec<Schema>) -> AvroResult<Self> {
let mut vindex = BTreeMap::new();
for (i, schema) in schemas.iter().enumerate() {
if let Schema::Union(_) = schema {
return Err(Error::GetNestedUnion);
}
let kind = SchemaKind::from(schema);
if !kind.is_named() && vindex.insert(kind, i).is_some() {
return Err(Error::GetUnionDuplicate);
}
}
Ok(UnionSchema {
schemas,
variant_index: vindex,
})
}
/// Returns a slice to all variants of this schema.
pub fn variants(&self) -> &[Schema] {
&self.schemas
}
/// Returns true if the any of the variants of this `UnionSchema` is `Null`.
pub fn is_nullable(&self) -> bool {
self.schemas.iter().any(|x| matches!(x, Schema::Null))
}
/// Optionally returns a reference to the schema matched by this value, as well as its position
/// within this union.
#[deprecated(
since = "0.15.0",
note = "Please use `find_schema_with_known_schemata` instead"
)]
pub fn find_schema(&self, value: &types::Value) -> Option<(usize, &Schema)> {
self.find_schema_with_known_schemata::<Schema>(value, None, &None)
}
/// Optionally returns a reference to the schema matched by this value, as well as its position
/// within this union.
///
/// Extra arguments:
/// - `known_schemata` - mapping between `Name` and `Schema` - if passed, additional external schemas would be used to resolve references.
pub fn find_schema_with_known_schemata<S: Borrow<Schema> + Debug>(
&self,
value: &types::Value,
known_schemata: Option<&HashMap<Name, S>>,
enclosing_namespace: &Namespace,
) -> Option<(usize, &Schema)> {
let schema_kind = SchemaKind::from(value);
if let Some(&i) = self.variant_index.get(&schema_kind) {
// fast path
Some((i, &self.schemas[i]))
} else {
// slow path (required for matching logical or named types)
// first collect what schemas we already know
let mut collected_names: HashMap<Name, &Schema> = known_schemata
.map(|names| {
names
.iter()
.map(|(name, schema)| (name.clone(), schema.borrow()))
.collect()
})
.unwrap_or_default();
self.schemas.iter().enumerate().find(|(_, schema)| {
let resolved_schema = ResolvedSchema::new_with_known_schemata(
vec![*schema],
enclosing_namespace,
&collected_names,
)
.expect("Schema didn't successfully parse");
let resolved_names = resolved_schema.names_ref;
// extend known schemas with just resolved names
collected_names.extend(resolved_names);
let namespace = &schema.namespace().or_else(|| enclosing_namespace.clone());
value
.clone()
.resolve_internal(schema, &collected_names, namespace, &None)
.is_ok()
})
}
}
}
// No need to compare variant_index, it is derivative of schemas.
impl PartialEq for UnionSchema {
fn eq(&self, other: &UnionSchema) -> bool {
self.schemas.eq(&other.schemas)
}
}
type DecimalMetadata = usize;
pub(crate) type Precision = DecimalMetadata;
pub(crate) type Scale = DecimalMetadata;
fn parse_json_integer_for_decimal(value: &serde_json::Number) -> Result<DecimalMetadata, Error> {
Ok(if value.is_u64() {
let num = value
.as_u64()
.ok_or_else(|| Error::GetU64FromJson(value.clone()))?;
num.try_into()