-
Notifications
You must be signed in to change notification settings - Fork 22
/
schema.go
1183 lines (996 loc) · 31.2 KB
/
schema.go
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
package avro
import (
"encoding/json"
"fmt"
"io/ioutil"
"math"
"reflect"
"strings"
)
// ***********************
// NOTICE this file was changed beginning in November 2016 by the team maintaining
// https://github.com/go-avro/avro. This notice is required to be here due to the
// terms of the Apache license, see LICENSE for details.
// ***********************
const (
// Record schema type constant
Record int = iota
// Enum schema type constant
Enum
// Array schema type constant
Array
// Map schema type constant
Map
// Union schema type constant
Union
// Fixed schema type constant
Fixed
// String schema type constant
String
// Bytes schema type constant
Bytes
// Int schema type constant
Int
// Long schema type constant
Long
// Float schema type constant
Float
// Double schema type constant
Double
// Boolean schema type constant
Boolean
// Null schema type constant
Null
// Recursive schema type constant. Recursive is an artificial type that means a Record schema without its definition
// that should be looked up in some registry.
Recursive
)
const (
typeRecord = "record"
typeUnion = "union"
typeEnum = "enum"
typeArray = "array"
typeMap = "map"
typeFixed = "fixed"
typeString = "string"
typeBytes = "bytes"
typeInt = "int"
typeLong = "long"
typeFloat = "float"
typeDouble = "double"
typeBoolean = "boolean"
typeNull = "null"
)
const (
schemaAliasesField = "aliases"
schemaDefaultField = "default"
schemaDocField = "doc"
schemaFieldsField = "fields"
schemaItemsField = "items"
schemaNameField = "name"
schemaNamespaceField = "namespace"
schemaSizeField = "size"
schemaSymbolsField = "symbols"
schemaTypeField = "type"
schemaValuesField = "values"
)
// Schema is an interface representing a single Avro schema (both primitive and complex).
type Schema interface {
// Returns an integer constant representing this schema type.
Type() int
// If this is a record, enum or fixed, returns its name, otherwise the name of the primitive type.
GetName() string
// Gets a custom non-reserved property from this schema and a bool representing if it exists.
Prop(key string) (interface{}, bool)
// Converts this schema to its JSON representation.
String() string
// Checks whether the given value is writeable to this schema.
Validate(v reflect.Value) bool
}
// StringSchema implements Schema and represents Avro string type.
type StringSchema struct{}
// Returns a JSON representation of StringSchema.
func (*StringSchema) String() string {
return `{"type": "string"}`
}
// Type returns a type constant for this StringSchema.
func (*StringSchema) Type() int {
return String
}
// GetName returns a type name for this StringSchema.
func (*StringSchema) GetName() string {
return typeString
}
// Prop doesn't return anything valuable for StringSchema.
func (*StringSchema) Prop(key string) (interface{}, bool) {
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (*StringSchema) Validate(v reflect.Value) bool {
_, ok := dereference(v).Interface().(string)
return ok
}
// MarshalJSON serializes the given schema as JSON. Never returns an error.
func (*StringSchema) MarshalJSON() ([]byte, error) {
return []byte(`"string"`), nil
}
// BytesSchema implements Schema and represents Avro bytes type.
type BytesSchema struct{}
// String returns a JSON representation of BytesSchema.
func (*BytesSchema) String() string {
return `{"type": "bytes"}`
}
// Type returns a type constant for this BytesSchema.
func (*BytesSchema) Type() int {
return Bytes
}
// GetName returns a type name for this BytesSchema.
func (*BytesSchema) GetName() string {
return typeBytes
}
// Prop doesn't return anything valuable for BytesSchema.
func (*BytesSchema) Prop(key string) (interface{}, bool) {
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (*BytesSchema) Validate(v reflect.Value) bool {
v = dereference(v)
return v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8
}
// MarshalJSON serializes the given schema as JSON. Never returns an error.
func (*BytesSchema) MarshalJSON() ([]byte, error) {
return []byte(`"bytes"`), nil
}
// IntSchema implements Schema and represents Avro int type.
type IntSchema struct{}
// String returns a JSON representation of IntSchema.
func (*IntSchema) String() string {
return `{"type": "int"}`
}
// Type returns a type constant for this IntSchema.
func (*IntSchema) Type() int {
return Int
}
// GetName returns a type name for this IntSchema.
func (*IntSchema) GetName() string {
return typeInt
}
// Prop doesn't return anything valuable for IntSchema.
func (*IntSchema) Prop(key string) (interface{}, bool) {
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (*IntSchema) Validate(v reflect.Value) bool {
return reflect.TypeOf(dereference(v).Interface()).Kind() == reflect.Int32
}
// MarshalJSON serializes the given schema as JSON. Never returns an error.
func (*IntSchema) MarshalJSON() ([]byte, error) {
return []byte(`"int"`), nil
}
// LongSchema implements Schema and represents Avro long type.
type LongSchema struct{}
// Returns a JSON representation of LongSchema.
func (*LongSchema) String() string {
return `{"type": "long"}`
}
// Type returns a type constant for this LongSchema.
func (*LongSchema) Type() int {
return Long
}
// GetName returns a type name for this LongSchema.
func (*LongSchema) GetName() string {
return typeLong
}
// Prop doesn't return anything valuable for LongSchema.
func (*LongSchema) Prop(key string) (interface{}, bool) {
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (*LongSchema) Validate(v reflect.Value) bool {
return reflect.TypeOf(dereference(v).Interface()).Kind() == reflect.Int64
}
// MarshalJSON serializes the given schema as JSON. Never returns an error.
func (*LongSchema) MarshalJSON() ([]byte, error) {
return []byte(`"long"`), nil
}
// FloatSchema implements Schema and represents Avro float type.
type FloatSchema struct{}
// String returns a JSON representation of FloatSchema.
func (*FloatSchema) String() string {
return `{"type": "float"}`
}
// Type returns a type constant for this FloatSchema.
func (*FloatSchema) Type() int {
return Float
}
// GetName returns a type name for this FloatSchema.
func (*FloatSchema) GetName() string {
return typeFloat
}
// Prop doesn't return anything valuable for FloatSchema.
func (*FloatSchema) Prop(key string) (interface{}, bool) {
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (*FloatSchema) Validate(v reflect.Value) bool {
return reflect.TypeOf(dereference(v).Interface()).Kind() == reflect.Float32
}
// MarshalJSON serializes the given schema as JSON. Never returns an error.
func (*FloatSchema) MarshalJSON() ([]byte, error) {
return []byte(`"float"`), nil
}
// DoubleSchema implements Schema and represents Avro double type.
type DoubleSchema struct{}
// Returns a JSON representation of DoubleSchema.
func (*DoubleSchema) String() string {
return `{"type": "double"}`
}
// Type returns a type constant for this DoubleSchema.
func (*DoubleSchema) Type() int {
return Double
}
// GetName returns a type name for this DoubleSchema.
func (*DoubleSchema) GetName() string {
return typeDouble
}
// Prop doesn't return anything valuable for DoubleSchema.
func (*DoubleSchema) Prop(key string) (interface{}, bool) {
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (*DoubleSchema) Validate(v reflect.Value) bool {
return reflect.TypeOf(dereference(v).Interface()).Kind() == reflect.Float64
}
// MarshalJSON serializes the given schema as JSON. Never returns an error.
func (*DoubleSchema) MarshalJSON() ([]byte, error) {
return []byte(`"double"`), nil
}
// BooleanSchema implements Schema and represents Avro boolean type.
type BooleanSchema struct{}
// String returns a JSON representation of BooleanSchema.
func (*BooleanSchema) String() string {
return `{"type": "boolean"}`
}
// Type returns a type constant for this BooleanSchema.
func (*BooleanSchema) Type() int {
return Boolean
}
// GetName returns a type name for this BooleanSchema.
func (*BooleanSchema) GetName() string {
return typeBoolean
}
// Prop doesn't return anything valuable for BooleanSchema.
func (*BooleanSchema) Prop(key string) (interface{}, bool) {
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (*BooleanSchema) Validate(v reflect.Value) bool {
return reflect.TypeOf(dereference(v).Interface()).Kind() == reflect.Bool
}
// MarshalJSON serializes the given schema as JSON. Never returns an error.
func (*BooleanSchema) MarshalJSON() ([]byte, error) {
return []byte(`"boolean"`), nil
}
// NullSchema implements Schema and represents Avro null type.
type NullSchema struct{}
// String returns a JSON representation of NullSchema.
func (*NullSchema) String() string {
return `{"type": "null"}`
}
// Type returns a type constant for this NullSchema.
func (*NullSchema) Type() int {
return Null
}
// GetName returns a type name for this NullSchema.
func (*NullSchema) GetName() string {
return typeNull
}
// Prop doesn't return anything valuable for NullSchema.
func (*NullSchema) Prop(key string) (interface{}, bool) {
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (*NullSchema) Validate(v reflect.Value) bool {
// Check if the value is something that can be null
switch v.Kind() {
case reflect.Interface:
return v.IsNil()
case reflect.Array:
return v.Cap() == 0
case reflect.Slice:
return v.IsNil() || v.Cap() == 0
case reflect.Map:
return len(v.MapKeys()) == 0
case reflect.String:
return len(v.String()) == 0
case reflect.Float32:
// Should NaN floats be treated as null?
return math.IsNaN(v.Float())
case reflect.Float64:
// Should NaN floats be treated as null?
return math.IsNaN(v.Float())
case reflect.Ptr:
return v.IsNil()
case reflect.Invalid:
return true
}
// Nothing else in particular, so this should not validate?
return false
}
// MarshalJSON serializes the given schema as JSON. Never returns an error.
func (*NullSchema) MarshalJSON() ([]byte, error) {
return []byte(`"null"`), nil
}
// RecordSchema implements Schema and represents Avro record type.
type RecordSchema struct {
Name string `json:"name,omitempty"`
Namespace string `json:"namespace,omitempty"`
Doc string `json:"doc,omitempty"`
Aliases []string `json:"aliases,omitempty"`
Properties map[string]interface{}
Fields []*SchemaField `json:"fields"`
}
// String returns a JSON representation of RecordSchema.
func (s *RecordSchema) String() string {
bytes, err := json.MarshalIndent(s, "", " ")
if err != nil {
panic(err)
}
return string(bytes)
}
// MarshalJSON serializes the given schema as JSON.
func (s *RecordSchema) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type,omitempty"`
Namespace string `json:"namespace,omitempty"`
Name string `json:"name,omitempty"`
Doc string `json:"doc,omitempty"`
Aliases []string `json:"aliases,omitempty"`
Fields []*SchemaField `json:"fields"`
}{
Type: "record",
Namespace: s.Namespace,
Name: s.Name,
Doc: s.Doc,
Aliases: s.Aliases,
Fields: s.Fields,
})
}
// Type returns a type constant for this RecordSchema.
func (*RecordSchema) Type() int {
return Record
}
// GetName returns a record name for this RecordSchema.
func (s *RecordSchema) GetName() string {
return s.Name
}
// Prop gets a custom non-reserved property from this schema and a bool representing if it exists.
func (s *RecordSchema) Prop(key string) (interface{}, bool) {
if s.Properties != nil {
if prop, ok := s.Properties[key]; ok {
return prop, true
}
}
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (s *RecordSchema) Validate(v reflect.Value) bool {
v = dereference(v)
if v.Kind() != reflect.Struct || !v.CanAddr() || !v.CanInterface() {
return false
}
rec, ok := v.Interface().(GenericRecord)
if !ok {
// This is not a generic record and is likely a specific record. Hence
// use the basic check.
return v.Kind() == reflect.Struct
}
fieldCount := 0
for key, val := range rec.fields {
for idx := range s.Fields {
// key.Name must have rs.Fields[idx].Name as a suffix
if len(s.Fields[idx].Name) <= len(key) {
lhs := key[len(key)-len(s.Fields[idx].Name):]
if lhs == s.Fields[idx].Name {
if !s.Fields[idx].Type.Validate(reflect.ValueOf(val)) {
return false
}
fieldCount++
break
}
}
}
}
// All of the fields set must be accounted for in the union.
if fieldCount < len(rec.fields) {
return false
}
return true
}
// RecursiveSchema implements Schema and represents Avro record type without a definition (e.g. that should be looked up).
type RecursiveSchema struct {
Actual *RecordSchema
}
func newRecursiveSchema(parent *RecordSchema) *RecursiveSchema {
return &RecursiveSchema{
Actual: parent,
}
}
// String returns a JSON representation of RecursiveSchema.
func (s *RecursiveSchema) String() string {
return fmt.Sprintf(`{"type": "%s"}`, s.Actual.GetName())
}
// Type returns a type constant for this RecursiveSchema.
func (*RecursiveSchema) Type() int {
return Recursive
}
// GetName returns a record name for enclosed RecordSchema.
func (s *RecursiveSchema) GetName() string {
return s.Actual.GetName()
}
// Prop doesn't return anything valuable for RecursiveSchema.
func (*RecursiveSchema) Prop(key string) (interface{}, bool) {
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (s *RecursiveSchema) Validate(v reflect.Value) bool {
return s.Actual.Validate(v)
}
// MarshalJSON serializes the given schema as JSON. Never returns an error.
func (s *RecursiveSchema) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, s.Actual.GetName())), nil
}
// SchemaField represents a schema field for Avro record.
type SchemaField struct {
Name string `json:"name,omitempty"`
Doc string `json:"doc,omitempty"`
Default interface{} `json:"default"`
Type Schema `json:"type,omitempty"`
Properties map[string]interface{}
}
// Gets a custom non-reserved property from this schemafield and a bool representing if it exists.
func (this *SchemaField) Prop(key string) (interface{}, bool) {
if this.Properties != nil {
if prop, ok := this.Properties[key]; ok {
return prop, true
}
}
return nil, false
}
// MarshalJSON serializes the given schema field as JSON.
func (s *SchemaField) MarshalJSON() ([]byte, error) {
if s.Type.Type() == Null || (s.Type.Type() == Union && s.Type.(*UnionSchema).Types[0].Type() == Null) {
return json.Marshal(struct {
Name string `json:"name,omitempty"`
Doc string `json:"doc,omitempty"`
Default interface{} `json:"default"`
Type Schema `json:"type,omitempty"`
}{
Name: s.Name,
Doc: s.Doc,
Default: s.Default,
Type: s.Type,
})
}
return json.Marshal(struct {
Name string `json:"name,omitempty"`
Doc string `json:"doc,omitempty"`
Default interface{} `json:"default,omitempty"`
Type Schema `json:"type,omitempty"`
}{
Name: s.Name,
Doc: s.Doc,
Default: s.Default,
Type: s.Type,
})
}
// String returns a JSON representation of SchemaField.
func (s *SchemaField) String() string {
return fmt.Sprintf("[SchemaField: Name: %s, Doc: %s, Default: %v, Type: %s]", s.Name, s.Doc, s.Default, s.Type)
}
// EnumSchema implements Schema and represents Avro enum type.
type EnumSchema struct {
Name string
Namespace string
Aliases []string
Doc string
Symbols []string
Properties map[string]interface{}
}
// String returns a JSON representation of EnumSchema.
func (s *EnumSchema) String() string {
bytes, err := json.MarshalIndent(s, "", " ")
if err != nil {
panic(err)
}
return string(bytes)
}
// Type returns a type constant for this EnumSchema.
func (*EnumSchema) Type() int {
return Enum
}
// GetName returns an enum name for this EnumSchema.
func (s *EnumSchema) GetName() string {
return s.Name
}
// Prop gets a custom non-reserved property from this schema and a bool representing if it exists.
func (s *EnumSchema) Prop(key string) (interface{}, bool) {
if s.Properties != nil {
if prop, ok := s.Properties[key]; ok {
return prop, true
}
}
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (*EnumSchema) Validate(v reflect.Value) bool {
//TODO implement
return true
}
// MarshalJSON serializes the given schema as JSON.
func (s *EnumSchema) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type,omitempty"`
Namespace string `json:"namespace,omitempty"`
Name string `json:"name,omitempty"`
Doc string `json:"doc,omitempty"`
Symbols []string `json:"symbols,omitempty"`
}{
Type: "enum",
Namespace: s.Namespace,
Name: s.Name,
Doc: s.Doc,
Symbols: s.Symbols,
})
}
// ArraySchema implements Schema and represents Avro array type.
type ArraySchema struct {
Items Schema
Properties map[string]interface{}
}
// String returns a JSON representation of ArraySchema.
func (s *ArraySchema) String() string {
bytes, err := json.MarshalIndent(s, "", " ")
if err != nil {
panic(err)
}
return string(bytes)
}
// Type returns a type constant for this ArraySchema.
func (*ArraySchema) Type() int {
return Array
}
// GetName returns a type name for this ArraySchema.
func (*ArraySchema) GetName() string {
return typeArray
}
// Prop gets a custom non-reserved property from this schema and a bool representing if it exists.
func (s *ArraySchema) Prop(key string) (interface{}, bool) {
if s.Properties != nil {
if prop, ok := s.Properties[key]; ok {
return prop, true
}
}
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (s *ArraySchema) Validate(v reflect.Value) bool {
v = dereference(v)
// This needs to be a slice
return v.Kind() == reflect.Slice || v.Kind() == reflect.Array
}
// MarshalJSON serializes the given schema as JSON.
func (s *ArraySchema) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type,omitempty"`
Items Schema `json:"items,omitempty"`
}{
Type: "array",
Items: s.Items,
})
}
// MapSchema implements Schema and represents Avro map type.
type MapSchema struct {
Values Schema
Properties map[string]interface{}
}
// String returns a JSON representation of MapSchema.
func (s *MapSchema) String() string {
bytes, err := json.MarshalIndent(s, "", " ")
if err != nil {
panic(err)
}
return string(bytes)
}
// Type returns a type constant for this MapSchema.
func (*MapSchema) Type() int {
return Map
}
// GetName returns a type name for this MapSchema.
func (*MapSchema) GetName() string {
return typeMap
}
// Prop gets a custom non-reserved property from this schema and a bool representing if it exists.
func (s *MapSchema) Prop(key string) (interface{}, bool) {
if s.Properties != nil {
if prop, ok := s.Properties[key]; ok {
return prop, true
}
}
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (s *MapSchema) Validate(v reflect.Value) bool {
v = dereference(v)
return v.Kind() == reflect.Map && v.Type().Key().Kind() == reflect.String
}
// MarshalJSON serializes the given schema as JSON.
func (s *MapSchema) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type,omitempty"`
Values Schema `json:"values,omitempty"`
}{
Type: "map",
Values: s.Values,
})
}
// UnionSchema implements Schema and represents Avro union type.
type UnionSchema struct {
Types []Schema
}
// String returns a JSON representation of UnionSchema.
func (s *UnionSchema) String() string {
bytes, err := json.MarshalIndent(s, "", " ")
if err != nil {
panic(err)
}
return fmt.Sprintf(`{"type": %s}`, string(bytes))
}
// Type returns a type constant for this UnionSchema.
func (*UnionSchema) Type() int {
return Union
}
// GetName returns a type name for this UnionSchema.
func (*UnionSchema) GetName() string {
return typeUnion
}
// Prop doesn't return anything valuable for UnionSchema.
func (*UnionSchema) Prop(key string) (interface{}, bool) {
return nil, false
}
// GetType gets the index of actual union type for a given value.
func (s *UnionSchema) GetType(v reflect.Value) int {
if s.Types != nil {
for i := range s.Types {
if t := s.Types[i]; t.Validate(v) {
return i
}
}
}
return -1
}
// Validate checks whether the given value is writeable to this schema.
func (s *UnionSchema) Validate(v reflect.Value) bool {
v = dereference(v)
for i := range s.Types {
if t := s.Types[i]; t.Validate(v) {
return true
}
}
return false
}
// MarshalJSON serializes the given schema as JSON.
func (s *UnionSchema) MarshalJSON() ([]byte, error) {
return json.Marshal(s.Types)
}
// FixedSchema implements Schema and represents Avro fixed type.
type FixedSchema struct {
Namespace string
Name string
Size int
Properties map[string]interface{}
}
// String returns a JSON representation of FixedSchema.
func (s *FixedSchema) String() string {
bytes, err := json.MarshalIndent(s, "", " ")
if err != nil {
panic(err)
}
return string(bytes)
}
// Type returns a type constant for this FixedSchema.
func (*FixedSchema) Type() int {
return Fixed
}
// GetName returns a fixed name for this FixedSchema.
func (s *FixedSchema) GetName() string {
return s.Name
}
// Prop gets a custom non-reserved property from this schema and a bool representing if it exists.
func (s *FixedSchema) Prop(key string) (interface{}, bool) {
if s.Properties != nil {
if prop, ok := s.Properties[key]; ok {
return prop, true
}
}
return nil, false
}
// Validate checks whether the given value is writeable to this schema.
func (s *FixedSchema) Validate(v reflect.Value) bool {
v = dereference(v)
return (v.Kind() == reflect.Array || v.Kind() == reflect.Slice) && v.Type().Elem().Kind() == reflect.Uint8 && v.Len() == s.Size
}
// MarshalJSON serializes the given schema as JSON.
func (s *FixedSchema) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type,omitempty"`
Size int `json:"size,omitempty"`
Name string `json:"name,omitempty"`
}{
Type: "fixed",
Size: s.Size,
Name: s.Name,
})
}
// GetFullName returns a fully-qualified name for a schema if possible. The format is namespace.name.
func GetFullName(schema Schema) string {
switch sch := schema.(type) {
case *RecordSchema:
return getFullName(sch.GetName(), sch.Namespace)
case *EnumSchema:
return getFullName(sch.GetName(), sch.Namespace)
case *FixedSchema:
return getFullName(sch.GetName(), sch.Namespace)
default:
return schema.GetName()
}
}
// ParseSchemaFile parses a given file.
// May return an error if schema is not parsable or file does not exist.
func ParseSchemaFile(file string) (Schema, error) {
fileContents, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
return ParseSchema(string(fileContents))
}
// ParseSchema parses a given schema without provided schemas to reuse.
// Equivalent to call ParseSchemaWithResistry(rawSchema, make(map[string]Schema))
// May return an error if schema is not parsable or has insufficient information about any type.
func ParseSchema(rawSchema string) (Schema, error) {
return ParseSchemaWithRegistry(rawSchema, make(map[string]Schema))
}
// ParseSchemaWithRegistry parses a given schema using the provided registry for type lookup.
// Registry will be filled up during parsing.
// May return an error if schema is not parsable or has insufficient information about any type.
func ParseSchemaWithRegistry(rawSchema string, schemas map[string]Schema) (Schema, error) {
var schema interface{}
if err := json.Unmarshal([]byte(rawSchema), &schema); err != nil {
schema = rawSchema
}
return schemaByType(schema, schemas, "")
}
// MustParseSchema is like ParseSchema, but panics if the given schema cannot be parsed.
func MustParseSchema(rawSchema string) Schema {
s, err := ParseSchema(rawSchema)
if err != nil {
panic(err)
}
return s
}
func schemaByType(i interface{}, registry map[string]Schema, namespace string) (Schema, error) {
switch v := i.(type) {
case nil:
return new(NullSchema), nil
case string:
switch v {
case typeNull:
return new(NullSchema), nil
case typeBoolean:
return new(BooleanSchema), nil
case typeInt:
return new(IntSchema), nil
case typeLong:
return new(LongSchema), nil
case typeFloat:
return new(FloatSchema), nil
case typeDouble:
return new(DoubleSchema), nil
case typeBytes:
return new(BytesSchema), nil
case typeString:
return new(StringSchema), nil
default:
// If a name reference contains a dot, we consider it a full name reference.
// Otherwise, use the getFullName helper to look up the name.
// See https://avro.apache.org/docs/1.7.7/spec.html#Names
fullName := v
if !strings.ContainsRune(fullName, '.') {
fullName = getFullName(v, namespace)
}
schema, ok := registry[fullName]
if !ok {
return nil, fmt.Errorf("Unknown type name: %s", v)
}
return schema, nil
}
case map[string][]interface{}:
return parseUnionSchema(v[schemaTypeField], registry, namespace)
case map[string]interface{}:
switch v[schemaTypeField] {
case typeNull:
return new(NullSchema), nil
case typeBoolean:
return new(BooleanSchema), nil
case typeInt:
return new(IntSchema), nil
case typeLong:
return new(LongSchema), nil
case typeFloat:
return new(FloatSchema), nil
case typeDouble:
return new(DoubleSchema), nil
case typeBytes:
return new(BytesSchema), nil
case typeString:
return new(StringSchema), nil