-
Notifications
You must be signed in to change notification settings - Fork 16
/
avro_types.py
1046 lines (773 loc) · 35.5 KB
/
avro_types.py
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
import abc
import re
import struct
import sys
from typing import Any, Sequence, Mapping, Optional, Set, Union
FIELD_MAPPING = {
'string': 'StringType',
'int': 'IntType',
'long': 'LongType',
'float': 'FloatType',
'double': 'DoubleType',
'boolean': 'BooleanType',
'null': 'NullType',
'bytes': 'BytesType',
'map': 'MapType',
'fixed': 'FixedType',
'array': 'ArrayType',
'union': 'UnionType',
'enum': 'EnumType',
'record': 'RecordType'
}
class Type:
"""Base abstract class to represent avro types"""
@property
def python_type(self):
"""Gets the python type associated with the avro type"""
raise NotImplementedError
@abc.abstractmethod
def validate(self, value: Any) -> bool:
"""Validates the value"""
def check_type(self, value: Any) -> bool:
"""Checks the type of a value against the type defined in python_type.
Args:
value: The value from which to check the type.
Returns:
True if the value has the correct type and False otherwise.
"""
return isinstance(value, self.python_type)
@classmethod
def build(cls, json_repr: Union[Mapping[str, Any], Sequence[Any]]) -> 'Type':
return cls()
class ComplexType(Type):
required_attributes: Set[str] = set()
optional_attributes: Set[str] = set()
@classmethod
def _validate_json_repr(cls, json_repr: Mapping[str, Any]) -> bool:
if cls.required_attributes.intersection(json_repr.keys()) != cls.required_attributes:
raise ValueError(f'The {cls.__name__} must have {cls.required_attributes} defined.')
if not cls.optional_attributes.union(cls.required_attributes).issuperset(json_repr.keys()):
raise ValueError(f'The {cls.__name__} can only contains '
f'{cls.required_attributes.union(cls.optional_attributes)} keys')
return True
@staticmethod
def _get_field_from_json(field_type: Any) -> Type:
if isinstance(field_type, dict):
return getattr(sys.modules[__name__], FIELD_MAPPING[field_type['type']]).build(field_type)
if isinstance(field_type, list):
return UnionType.build(field_type)
if not FIELD_MAPPING.get(field_type):
raise ValueError(
f'The type [{field_type}] is not recognized by Avro')
return getattr(sys.modules[__name__], FIELD_MAPPING[field_type]).build(None)
class IntType(Type):
"""Represents the int primitive type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
- int: 32-bit signed integer
Attributes:
python_type: The python type associated with the int avro type.
"""
python_type: type = int
def check_type(self, value: Any) -> bool:
if isinstance(value, bool):
return False
return super().check_type(value)
def validate(self, value: Any) -> bool:
"""Checks if the value can be used as an integer.
Ensures that the value is smaller than 2.147.483.647.
Args:
value: Value to be validated
Returns:
True is the value is a valid integer
Raises:
ValueError: If the value is greater than 2.147.483.647.
"""
if value > 2_147_483_647:
raise ValueError(f'The value [{value}] is too large for int.')
return True
def __repr__(self): # pragma: no cover
return 'IntType'
class LongType(Type):
"""Represents the long primitive type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
- long: 64-bit signed integer
Attributes:
python_type: The python type associated with the long avro type.
"""
python_type = int
def check_type(self, value: Any) -> bool:
if isinstance(value, bool):
return False
return super().check_type(value)
def validate(self, value: Any) -> bool:
"""Checks if the value can be used as an long.
Ensures that the value is smaller than 9.223.372.036.854.775.807.
Args:
value: Value to be validated
Returns:
True is the value is a valid long
Raises:
ValueError: If the value is greater than 9.223.372.036.854.775.807.
"""
if value > 9_223_372_036_854_775_807:
raise ValueError(f'The value [{value}] is too large for long.')
return True
def __repr__(self): # pragma: no cover
return 'LongType'
class NullType(Type):
"""Represents the null primitive type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
- null: no value
Attributes:
python_type: The python type associated with the null avro type.
"""
python_type = type(None)
def validate(self, value: Any) -> bool:
"""For null values, no validation is needed, the check_type is enough.
Args:
value: The value to be validated.
Returns:
True, since there is no validation needed
"""
return True
def __repr__(self): # pragma: no cover
return 'NullType'
class BooleanType(Type):
"""Represents the boolean primitive type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
- boolean: a binary value
Attributes:
python_type: The python type associated with the boolean avro type.
"""
python_type = bool
def validate(self, value: Any) -> bool:
"""For boolean values, no validation is needed, the check_type is enough.
Args:
value: The value to be validated.
Returns:
True, since there is no validation needed
"""
return True
def __repr__(self): # pragma: no cover
return 'BooleanType'
class StringType(Type):
"""Represents the string primitive type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
- string: unicode character sequence
Attributes:
python_type: The python type associated with the string avro type.
"""
python_type = str
def validate(self, value: Any) -> bool:
"""For string values, no validation is needed, the check_type is enough.
Args:
value: The value to be validated.
Returns:
True, since there is no validation needed
"""
return True
def __repr__(self): # pragma: no cover
return 'StringType'
class FloatType(Type):
"""Represents the float primitive type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
- float: single precision (32-bit) IEEE 754 floating-point number
Attributes:
python_type: The python type associated with the float avro type.
"""
python_type = float
def validate(self, value: Any) -> bool:
"""Checks if the value can be used as an float.
Ensures that the value is not too large for float by using struct.pack.
Args:
value: Value to be validated
Returns:
True is the value is a valid float
Raises:
ValueError: If the value is not too large for float.
"""
if value == float('inf'):
raise ValueError(f'The value [{value}] is too large for float.')
try:
struct.pack('<f', value)
return True
except OverflowError:
raise ValueError(f'The value [{value}] is too large for float.')
def __repr__(self): # pragma: no cover
return 'FloatType'
class DoubleType(Type):
"""Represents the double primitive type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
- double: double precision (64-bit) IEEE 754 floating-point number
Attributes:
python_type: The python type associated with the double avro type.
"""
python_type = float
def validate(self, value: Any) -> bool:
"""Checks if the value can be used as an double.
Ensures that the value is not too large for float by using struct.pack.
Args:
value: Value to be validated
Returns:
True is the value is a valid float
Raises:
ValueError: If the value is not too large for double.
"""
if value == float('inf'):
raise ValueError(f'The value [{value}] is too large for double.')
return True
def __repr__(self): # pragma: no cover
return 'DoubleType'
class BytesType(Type):
"""Represents the bytes primitive type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
- bytes: sequence of 8-bit unsigned bytes
Attributes:
python_type: The python type associated with the bytes avro type.
"""
python_type = bytes
def validate(self, value: Any) -> bool:
"""For bytes values, no validation is needed, the check_type is enough.
Args:
value: The value to be validated.
Returns:
True, since there is no validation needed
"""
return True
def __repr__(self): # pragma: no cover
return 'BytesType'
class RecordTypeField(ComplexType):
"""Represents one field of the record complex type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
Records use the type name "record" and support three attributes:
- name: a JSON string providing the name of the record (required).
- namespace: a JSON string that qualifies the name (optional)
- doc: a JSON string providing documentation to the user of this schema (optional).
- aliases: a JSON array of strings, providing alternate names for this record (optional).
- fields: a JSON array, listing fields (required). Each field is a JSON object with the following attributes:
* name: a JSON string providing the name of the field (required).
* doc: a JSON string describing this field for users (optional).
* type: A JSON object defining a schema, or a JSON string naming a record definition (required).
* default: A default value for this field, used when reading instances that lack this field (optional).
* order: specifies how this field impacts sort ordering of this record (optional).
Valid values are "ascending" (the default), "descending", or "ignore".
* aliases: a JSON array of strings, providing alternate names for this field (optional).
Attributes:
python_type: The python type associated with the record avro type.
"""
required_attributes: Set[str] = {'name', 'type'}
optional_attributes: Set[str] = {'doc', 'default', 'order', 'aliases'}
def __init__(self, name: str = None, field_type: Type = None) -> None:
"""Inits RecordTypeField with the fields.
Args:
name: the name of the field.
field_type: the type of the field.
"""
self.__name: str = name
self.__type: Type = field_type
self.__doc: Optional[str] = None
self.__default: Optional[Any] = None
self.__order: Optional[str] = None
self.__aliases: Optional[Sequence[str]] = None
@property
def type(self) -> Type:
"""Getter for the type of the field.
Returns:
The type of the field.
"""
return self.__type
@classmethod
def __build_field_type(cls, json_repr: Union[Mapping[str, Any], Sequence[Any]]) -> Type:
try:
return cls._get_field_from_json(json_repr['type'])
except ValueError as error:
error_msg = error.args[0]
match = re.match(r'^Error parsing the field \[(.*)\]: (.*)$', error_msg)
if match:
actual_error = match.group(2)
previous_fields = list(reversed(match.group(1).split(',')))
fields = ','.join(reversed(previous_fields + [json_repr['name']]))
else:
actual_error = error_msg
fields = json_repr['name']
raise ValueError(f'Error parsing the field [{fields}]: {actual_error}')
@classmethod
def build(cls, json_repr: Union[Mapping[str, Any], Sequence[Any]]) -> 'RecordTypeField':
"""Build an instance of the RecordTypeField, based on a json representation of it.
Args:
json_repr: The json representation of a RecordTypeField, according to avro specification
Returns:
An newly created instance of RecordTypeField, based on the json representation
"""
cls._validate_json_repr(json_repr)
field = cls()
field.__name = json_repr['name']
field.__type = cls.__build_field_type(json_repr)
field.__doc = json_repr.get('doc')
field.__default = json_repr.get('default')
field.__order = json_repr.get('order')
field.__aliases = json_repr.get('aliases')
return field
def __repr__(self) -> str:
return (f'RecordTypeField <name: {self.__name}, type: {self.__type}, doc: {self.__doc}, '
f'default: {self.__default}, order: {self.__order}, aliases: {self.__aliases}>')
class RecordType(ComplexType):
"""Represents the record complex type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
Records use the type name "record" and support three attributes:
- name: a JSON string providing the name of the record (required).
- namespace: a JSON string that qualifies the name (optional)
- doc: a JSON string providing documentation to the user of this schema (optional).
- aliases: a JSON array of strings, providing alternate names for this record (optional).
- fields: a JSON array, listing fields (required). Each field is a JSON object with the following attributes:
* name: a JSON string providing the name of the field (required).
* doc: a JSON string describing this field for users (optional).
* type: A JSON object defining a schema, or a JSON string naming a record definition (required).
* default: A default value for this field, used when reading instances that lack this field (optional).
* order: specifies how this field impacts sort ordering of this record (optional).
Valid values are "ascending" (the default), "descending", or "ignore".
* aliases: a JSON array of strings, providing alternate names for this field (optional).
Attributes:
python_type: The python type associated with the record avro type.
"""
python_type = dict
optional_attributes: Set[str] = {'type', 'namespace', 'aliases', 'doc'}
required_attributes: Set[str] = {'fields', 'name'}
def __init__(self, fields: Mapping[str, RecordTypeField] = None) -> None:
"""Inits RecordType with the fields.
Args:
fields: the list of dictionaries representing the fields of the record type.
"""
self.__fields: Mapping[str, RecordTypeField] = fields
self.__name: str = ''
self.__namespace: Optional[str] = None
self.__aliases: Optional[str] = None
self.__doc: Optional[str] = None
@property
def fields(self) -> Mapping[str, RecordTypeField]:
"""Getter for the fields of the RecordType.
Returns:
The list of fields for the RecordType.
"""
return self.__fields
def _validate_field(self, field_key: str, field_value: Any) -> bool:
"""Validates a field from the list of fields.
This will check if the field is one of the record fields and validate it.
Assuming the following record::
{
...
"fields": [
{
"name": "age",
"type": "int",
...
},
...
],
...
}
When validating the following value::
{
'age': 30,
...
}
The field_key is 'age' and the field value is '30'. This will be used to scan all the fields and check
if there is a field with name age, then the value 30 will be validated against the 'type' of the field,
which in this case is int.
If the validation of the value against type validations fail, or if the key is not found in the record
fields or if the value has the wrong type, an exception will be raised.
Args:
field_key: the dictionary key that contains the field which will be validated
field_value: the dictionary value of the field that is being validated
Returns:
True, if the field is valid
Raises:
ValueError if the field is not valid, according to the definition above.
"""
if not self.__fields[field_key].type.check_type(field_value):
msg = f'The value [{field_value}] for field [{field_key}] should be [{self.__fields[field_key].type}].'
raise ValueError(msg)
try:
return self.__fields[field_key].type.validate(field_value)
except ValueError as error:
error_msg = error.args[0]
match = re.match(r'^Error validating value for field \[(.*)\]: (.*)$', error_msg)
if match:
actual_error = match.group(2)
previous_fields = list(reversed(match.group(1).split(',')))
fields = ','.join(reversed(previous_fields + [field_key]))
else:
actual_error = error_msg
fields = field_key
raise ValueError(f'Error validating value for field [{fields}]: {actual_error}')
def validate(self, value: Any) -> bool:
"""Validates the value against the record type.
First, the type of the value is checked, and if it is not a dict, an exception is raised.
Then, all the keys in the value are checked to make sure that they are present in the record fields.
Finally, all fields are validated against their definitions.
Args:
value: the value to be validated
Returns:
True if the value is valid.
Raises:
ValueError if the value is not valid according to the record type definition.
"""
if not self.check_type(value):
raise ValueError(f'The value [{value}] should have type dict but it has [{type(value)}].')
value_keys = set(value.keys())
required_fields = set(
[field for (field, field_record) in self.__fields.items()
if not (isinstance(field_record.type, NullType)
or (isinstance(field_record.type, UnionType)
and NullType in [type(t) for t in field_record.type.types]))])
if not required_fields.issubset(value_keys):
missing_fields = required_fields - value_keys
raise ValueError(f'The fields from value [{value_keys}] differs from the fields '
f'of the record type [{required_fields}]. The following fields are '
f'required, but not present: [{missing_fields}].')
if not value_keys.issubset(set(self.__fields.keys())):
extra_fields = set(self.__fields.keys()) - value_keys
raise ValueError(f'The fields from value [{value_keys}] differs from the fields '
f'of the record type [{required_fields}]. The following fields are '
f'not in the schema, but are present: [{extra_fields}].')
for key, field_value in value.items():
self._validate_field(key, field_value)
return True
@classmethod
def build(cls, json_repr: Union[Mapping[str, Any], Sequence[Any]]) -> 'RecordType':
"""Build an instance of the RecordType, based on a json representation of it.
Args:
json_repr: The json representation of a RecordType, according to avro specification
Returns:
An newly created instance of RecordType, based on the json representation
"""
cls._validate_json_repr(json_repr)
record_type = cls()
record_type.__name = json_repr['name']
record_type.__namespace = json_repr.get('namespace')
record_type.__aliases = json_repr.get('aliases')
record_type.__doc = json_repr.get('doc')
record_type.__fields = {field['name']: RecordTypeField.build(field) for field in json_repr['fields']}
return record_type
def __repr__(self) -> str: # pragma: no cover
return f'RecordType <{self.__fields}>'
class EnumType(ComplexType):
"""Represents the enum complex type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
Enums use the type name "enum" and support the following attributes:
- name: a JSON string providing the name of the enum (required).
- namespace: a JSON string that qualifies the name (optional).
- aliases: a JSON array of strings, providing alternate names for this enum (optional).
- doc: a JSON string providing documentation to the user of this schema (optional).
- symbols: a JSON array, listing symbols, as JSON strings (required).
All symbols in an enum must be unique; duplicates are prohibited.
Every symbol must match the regular expression [A-Za-z_][A-Za-z0-9_]*
(the same requirement as for names).
Attributes:
python_type: The python type associated with the enum avro type.
"""
python_type = str
optional_attributes: Set[str] = {'type', 'namespace', 'aliases', 'doc'}
required_attributes: Set[str] = {'symbols', 'name'}
def __init__(self, symbols: Sequence[str] = None) -> None:
"""Inits EnumType with the possible symbols.
Args:
symbols: the list of strings that defines the possible symbols for the enum.
"""
self.__symbols = symbols
self.__name: str = ''
self.__namespace: Optional[str] = None
self.__aliases: Optional[Sequence[str]] = None
self.__doc: Optional[str] = None
@property
def symbols(self) -> Sequence[str]:
"""Getter for the symbols allowed in the enum.
Returns:
The symbols allowed in the EnumType
"""
return self.__symbols
def validate(self, value: Any) -> bool:
"""Validates if the value is one of the has the correct type and if it is contained in the symbols list.
Args:
value: The value to be validated
Returns:
True if the value is valid
Raises:
ValueError: if the value is not str or is not contained in the symbols list.
"""
if not self.check_type(value):
raise ValueError(f'The value [{value}] should have type str but it has [{type(value)}].')
if value not in self.__symbols:
raise ValueError(f'The value [{value}] is not a valid symbol for the symbols [{self.__symbols}]')
return True
@classmethod
def build(cls, json_repr: Union[Mapping[str, Any], Sequence[Any]]) -> 'EnumType':
"""Build an instance of the EnumType, based on a json representation of it.
Args:
json_repr: The json representation of a EnumType, according to avro specification
Returns:
An newly created instance of EnumType, based on the json representation
"""
cls._validate_json_repr(json_repr)
symbols = json_repr['symbols']
if len(symbols) != len(set(symbols)):
raise ValueError('Symbols must be unique for EnumType.')
for symbol in symbols:
if not re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', symbol):
raise ValueError(f'Every symbol must match the regular expression [A-Za-z_][A-Za-z0-9_]*. '
f'Wrong symbol: {symbol}')
enum_type = cls()
enum_type.__symbols = symbols
enum_type.__name = json_repr['name']
enum_type.__namespace = json_repr.get('namespace')
enum_type.__aliases = json_repr.get('aliases')
enum_type.__doc = json_repr.get('doc')
return enum_type
def __repr__(self) -> str: # pragma: no cover
return (f'EnumType <symbols: {self.__symbols}, name: {self.__name}, namespace: {self.__namespace}, '
f'aliases: {self.__aliases}, doc: {self.__doc}>')
class ArrayType(ComplexType):
"""Represents the array complex type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
Arrays use the type name "array" and support a single attribute:
- items: the schema of the array's items.
Attributes:
python_type: The python type associated with the enum avro type.
"""
python_type = list
optional_attributes: Set[str] = {'type'}
required_attributes: Set[str] = {'items'}
def __init__(self, items_type: Type = None) -> None:
"""Inits the array type with the items type
Args:
items_type: the type of the items in the array.
"""
self.__items = items_type
@property
def items(self) -> Type:
"""Getter for the type of the items of the ArrayType
Returns:
The type of the items.
"""
return self.__items
def validate(self, value: Any) -> bool:
"""Validates the value against the array type definition.
First, the type of the value is checked, to make sure that it is a list.
Then the type of all items in the array is checked and finally, the values in the array are validated
using the validate method for the items type.
Args:
value: the value to be validated.
Returns:
True if the value is valid.
Raises:
ValueError: if the value is not valid.
"""
if not self.check_type(value):
raise ValueError(f'The value [{value}] should be list but it is not.')
for index, item in enumerate(value):
if not self.__items.check_type(item):
raise ValueError(f'The item at index [{index}]: [{item}] is not from the type [{self.__items}]')
self.__items.validate(item)
return True
@classmethod
def build(cls, json_repr: Union[Mapping[str, Any], Sequence[Any]]) -> 'ArrayType':
"""Build an instance of the ArrayType, based on a json representation of it.
Args:
json_repr: The json representation of a ArrayType, according to avro specification
Returns:
An newly created instance of ArrayType, based on the json representation
"""
cls._validate_json_repr(json_repr)
array_type = cls()
array_type.__items = ArrayType._get_field_from_json(json_repr['items'])
return array_type
def __repr__(self) -> str: # pragma: no cover
return f'ArrayType <items: {self.__items}>'
class UnionType(ComplexType):
"""Represents the union complex type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
Unions, as mentioned above, are represented using JSON arrays.
For example, ["null", "string"] declares a schema which may be either a null or string.
Unions may not immediately contain other unions.
Attributes:
python_type: The python type associated with the union avro type.
"""
python_type = Any
def __init__(self, types: Sequence[Type] = None) -> None:
"""Inits the enum type with the types allowed.
Args:
types: the list of Types that are allowed in the union type.
"""
self.__types = types
@property
def types(self) -> Sequence[Type]:
"""Getter for the types allowed in the union type.
Returns:
The types allowed.
"""
return self.__types
def check_type(self, value: Any) -> bool:
"""For the union type is not necessary to check the typeof the value, because it can be any.
Args:
value: the value to check the type.
Returns:
True, because the check is not needed
"""
return True
def validate(self, value: Any) -> bool:
"""Validates the value against the Union type definition.
The type of the field os checked against the allowed types for the union, and if the value match one of the
types, the value is validated against this type.
If the value doesn't match any of the allowed types, an exception is raised.
Args:
value: the value to be validated
Returns:
True is the value is valid
Raises:
ValueError: if the value is not valid according to the union type definition
"""
for data_type in self.__types:
if data_type.check_type(value):
return data_type.validate(value)
raise ValueError(f'The value [{value}] is not from one of the following types: [{self.__types}]')
@classmethod
def build(cls, json_repr: Union[Mapping[str, Any], Sequence[Any]]) -> 'UnionType':
"""Build an instance of the UnionType, based on a json representation of it.
Args:
json_repr: The json representation of a UnionType, according to avro specification
Returns:
A newly created instance of UnionType, based on the json representation
"""
for f in json_repr:
if isinstance(f, list):
raise ValueError('Unions may not immediately contain other unions.')
map_type = cls()
map_type.__types = [ComplexType._get_field_from_json(t) for t in json_repr]
return map_type
def __repr__(self) -> str: # pragma: no cover
return f'UnionType <{self.__types}>'
class MapType(ComplexType):
"""Represents the map complex type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
Maps use the type name "map" and support one attribute:
- values: the schema of the map's values
Map keys are assumed to be strings.
Attributes:
python_type: The python type associated with the map avro type.
"""
python_type = dict
optional_attributes: Set[str] = {'type'}
required_attributes: Set[str] = {'values'}
def __init__(self, values: Type = None) -> None:
"""Inits the map type with the type of the values.
Args:
values: the Type instance that represent the type of the values in the map
"""
self.__values = values
@property
def values(self) -> Type:
"""Getter for the type of values for the MapType
Returns:
THe type of values.
"""
return self.__values
def validate(self, value: Any) -> bool:
"""Validated the value against the map definition.
First, the type of the value is checked against the dict type.
Then, the keys are checked to make sure all of them are strings and values are checked to make sure all
of them have the defined Type.
Finally, every value is validated against their Type.
Args:
value: the value to be validated
Returns:
True is the value is valid
Raises:
ValueError: if the value is not valid according to the map type definition
"""
if not self.check_type(value):
raise ValueError(f'The value [{value}] should be dict but it is not.')
for map_key, map_value in value.items():
if not StringType().check_type(map_key):
raise ValueError(f'The key [{map_key}], value [{map_value}] is not from the type StringType')
if not self.__values.check_type(map_value):
raise ValueError(f'The key [{map_key}], value [{map_value}] is not from the type [{self.__values}]')
self.__values.validate(map_value)
return True
@classmethod
def build(cls, json_repr: Union[Mapping[str, Any], Sequence[Any]]) -> 'MapType':
"""Build an instance of the MapType, based on a json representation of it.
Args:
json_repr: The json representation of a MapType, according to avro specification
Returns:
A newly created instance of MapType, based on the json representation
"""
cls._validate_json_repr(json_repr)
map_type = cls()
map_type.__values = MapType._get_field_from_json(json_repr['values'])
return map_type
def __repr__(self) -> str: # pragma: no cover
return f'MapType <values: {self.__values}>'
class FixedType(ComplexType):
"""Represents the fixed complex type in avro.
Avro specification (https://avro.apache.org/docs/1.8.2/spec.html) has the following definition:
Fixed uses the type name "fixed" and supports two attributes:
- name: a string naming this fixed (required).
- namespace: a string that qualifies the name (optional).
- aliases: a JSON array of strings, providing alternate names for this enum (optional).
- size: an integer, specifying the number of bytes per value (required).
Attributes:
python_type: The python type associated with the map avro type.
"""
python_type = bytes
optional_attributes: Set[str] = {'type', 'namespace', 'aliases'}
required_attributes: Set[str] = {'name', 'size'}
def __init__(self, size: int = None) -> None:
"""Inits the map type with the size of the value.
Args:
size: the allowed size of the bytes value.
"""
self.__size: int = size
self.__name: str = ''
self.__namespace: Optional[str] = None
self.__aliases: Optional[Sequence[str]] = None
@property
def fixed_size(self) -> int:
"""Getter for the fixed type size
Returns:
The fixed type size.
"""
return self.__size