-
Notifications
You must be signed in to change notification settings - Fork 95
/
schema.go
1792 lines (1536 loc) · 42 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 (
"bytes"
"crypto/md5"
"crypto/sha256"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"github.com/hamba/avro/v2/pkg/crc64"
jsoniter "github.com/json-iterator/go"
)
type nullDefaultType struct{}
func (nullDefaultType) MarshalJSON() ([]byte, error) {
return []byte("null"), nil
}
var nullDefault nullDefaultType = struct{}{}
var (
// Note: order matches the order of properties as they are named in the spec.
// https://avro.apache.org/docs/1.12.0/specification
recordReserved = []string{"type", "name", "namespace", "doc", "aliases", "fields"}
fieldReserved = []string{"name", "doc", "type", "order", "aliases", "default"}
enumReserved = []string{"type", "name", "namespace", "aliases", "doc", "symbols", "default"}
arrayReserved = []string{"type", "items"}
mapReserved = []string{"type", "values"}
fixedReserved = []string{"type", "name", "namespace", "aliases", "size"}
fixedWithLogicalTypeReserved = []string{"type", "name", "namespace", "aliases", "size", "logicalType"}
fixedWithDecimalTypeReserved = []string{
"type", "name", "namespace", "aliases", "size", "logicalType", "precision", "scale",
}
primitiveReserved = []string{"type"}
primitiveWithLogicalTypeReserved = []string{"type", "logicalType"}
primitiveWithDecimalTypeReserved = []string{"type", "logicalType", "precision", "scale"}
)
// Type is a schema type.
type Type string
// Schema type constants.
const (
Record Type = "record"
Error Type = "error"
Ref Type = "<ref>"
Enum Type = "enum"
Array Type = "array"
Map Type = "map"
Union Type = "union"
Fixed Type = "fixed"
String Type = "string"
Bytes Type = "bytes"
Int Type = "int"
Long Type = "long"
Float Type = "float"
Double Type = "double"
Boolean Type = "boolean"
Null Type = "null"
)
// Order is a field order.
type Order string
// Field orders.
const (
Asc Order = "ascending"
Desc Order = "descending"
Ignore Order = "ignore"
)
// LogicalType is a schema logical type.
type LogicalType string
// Schema logical type constants.
const (
Decimal LogicalType = "decimal"
UUID LogicalType = "uuid"
Date LogicalType = "date"
TimeMillis LogicalType = "time-millis"
TimeMicros LogicalType = "time-micros"
TimestampMillis LogicalType = "timestamp-millis"
TimestampMicros LogicalType = "timestamp-micros"
LocalTimestampMillis LogicalType = "local-timestamp-millis"
LocalTimestampMicros LogicalType = "local-timestamp-micros"
Duration LogicalType = "duration"
)
// Action is a field action used during decoding process.
type Action string
// Action type constants.
const (
FieldIgnore Action = "ignore"
FieldSetDefault Action = "set_default"
)
// FingerprintType is a fingerprinting algorithm.
type FingerprintType string
// Fingerprint type constants.
const (
CRC64Avro FingerprintType = "CRC64-AVRO"
MD5 FingerprintType = "MD5"
SHA256 FingerprintType = "SHA256"
)
// SchemaCache is a cache of schemas.
type SchemaCache struct {
cache sync.Map // map[string]Schema
}
// Add adds a schema to the cache with the given name.
func (c *SchemaCache) Add(name string, schema Schema) {
c.cache.Store(name, schema)
}
// Get returns the Schema if it exists.
func (c *SchemaCache) Get(name string) Schema {
if v, ok := c.cache.Load(name); ok {
return v.(Schema)
}
return nil
}
// Schemas is a slice of Schemas.
type Schemas []Schema
// Get gets a schema and position by type or name if it is a named schema.
func (s Schemas) Get(name string) (Schema, int) {
for i, schema := range s {
if schemaTypeName(schema) == name {
return schema, i
}
}
return nil, -1
}
// Schema represents an Avro schema.
type Schema interface {
// Type returns the type of the schema.
Type() Type
// String returns the canonical form of the schema.
String() string
// Fingerprint returns the SHA256 fingerprint of the schema.
Fingerprint() [32]byte
// FingerprintUsing returns the fingerprint of the schema using the given algorithm or an error.
FingerprintUsing(FingerprintType) ([]byte, error)
// CacheFingerprint returns the unique identity of the schema.
// This returns a unique identity for schemas resolved from a writer schema, otherwise it returns
// the schemas Fingerprint.
CacheFingerprint() [32]byte
}
// LogicalSchema represents an Avro schema with a logical type.
type LogicalSchema interface {
// Type returns the type of the logical schema.
Type() LogicalType
// String returns the canonical form of the logical schema.
String() string
}
// PropertySchema represents a schema with properties.
type PropertySchema interface {
// Prop gets a property from the schema.
Prop(string) any
}
// NamedSchema represents a schema with a name.
type NamedSchema interface {
Schema
PropertySchema
// Name returns the name of the schema.
Name() string
// Namespace returns the namespace of a schema.
Namespace() string
// FullName returns the full qualified name of a schema.
FullName() string
// Aliases returns the full qualified aliases of a schema.
Aliases() []string
}
// LogicalTypeSchema represents a schema that can contain a logical type.
type LogicalTypeSchema interface {
// Logical returns the logical schema or nil.
Logical() LogicalSchema
}
type name struct {
name string
namespace string
full string
aliases []string
}
func newName(n, ns string, aliases []string) (name, error) {
if idx := strings.LastIndexByte(n, '.'); idx > -1 {
ns = n[:idx]
n = n[idx+1:]
}
full := n
if ns != "" {
full = ns + "." + n
}
for _, part := range strings.Split(full, ".") {
if err := validateName(part); err != nil {
return name{}, fmt.Errorf("avro: invalid name part %q in name %q: %w", full, part, err)
}
}
a := make([]string, 0, len(aliases))
for _, alias := range aliases {
if !strings.Contains(alias, ".") {
if err := validateName(alias); err != nil {
return name{}, fmt.Errorf("avro: invalid name %q: %w", alias, err)
}
if ns == "" {
a = append(a, alias)
continue
}
a = append(a, ns+"."+alias)
continue
}
for _, part := range strings.Split(alias, ".") {
if err := validateName(part); err != nil {
return name{}, fmt.Errorf("avro: invalid name part %q in name %q: %w", full, part, err)
}
}
a = append(a, alias)
}
return name{
name: n,
namespace: ns,
full: full,
aliases: a,
}, nil
}
// Name returns the name of a schema.
func (n name) Name() string {
return n.name
}
// Namespace returns the namespace of a schema.
func (n name) Namespace() string {
return n.namespace
}
// FullName returns the fully qualified name of a schema.
func (n name) FullName() string {
return n.full
}
// Aliases returns the fully qualified aliases of a schema.
func (n name) Aliases() []string {
return n.aliases
}
type fingerprinter struct {
fingerprint atomic.Value // [32]byte
cache sync.Map // map[FingerprintType][]byte
}
// Fingerprint returns the SHA256 fingerprint of the schema.
func (f *fingerprinter) Fingerprint(stringer fmt.Stringer) [32]byte {
if v := f.fingerprint.Load(); v != nil {
return v.([32]byte)
}
fingerprint := sha256.Sum256([]byte(stringer.String()))
f.fingerprint.Store(fingerprint)
return fingerprint
}
// FingerprintUsing returns the fingerprint of the schema using the given algorithm or an error.
func (f *fingerprinter) FingerprintUsing(typ FingerprintType, stringer fmt.Stringer) ([]byte, error) {
if v, ok := f.cache.Load(typ); ok {
return v.([]byte), nil
}
data := []byte(stringer.String())
var fingerprint []byte
switch typ {
case CRC64Avro:
h := crc64.Sum(data)
fingerprint = h[:]
case MD5:
h := md5.Sum(data)
fingerprint = h[:]
case SHA256:
h := sha256.Sum256(data)
fingerprint = h[:]
default:
return nil, fmt.Errorf("avro: unknown fingerprint algorithm %s", typ)
}
f.cache.Store(typ, fingerprint)
return fingerprint, nil
}
type cacheFingerprinter struct {
writerFingerprint *[32]byte
cache atomic.Value // [32]byte
}
// CacheFingerprint returns the SHA256 identity of the schema.
func (i *cacheFingerprinter) CacheFingerprint(schema Schema, fn func() []byte) [32]byte {
if v := i.cache.Load(); v != nil {
return v.([32]byte)
}
if i.writerFingerprint == nil {
fp := schema.Fingerprint()
i.cache.Store(fp)
return fp
}
fp := schema.Fingerprint()
d := append([]byte{}, fp[:]...)
d = append(d, (*i.writerFingerprint)[:]...)
if fn != nil {
d = append(d, fn()...)
}
ident := sha256.Sum256(d)
i.cache.Store(ident)
return ident
}
type properties struct {
props map[string]any
}
func newProperties(props map[string]any, res []string) properties {
p := properties{props: map[string]any{}}
for k, v := range props {
if isReserved(res, k) {
continue
}
p.props[k] = v
}
return p
}
func isReserved(res []string, k string) bool {
for _, r := range res {
if k == r {
return true
}
}
return false
}
// Prop gets a property from the schema.
func (p properties) Prop(name string) any {
if p.props == nil {
return nil
}
return p.props[name]
}
// Props returns a map that contains all schema custom properties.
// Any accidental change to the returned map will directly modify the schema custom properties.
func (p properties) Props() map[string]any {
return p.props
}
func (p properties) marshalPropertiesToJSON(buf *bytes.Buffer) error {
sortedPropertyKeys := make([]string, 0, len(p.props))
for k := range p.props {
sortedPropertyKeys = append(sortedPropertyKeys, k)
}
sort.Strings(sortedPropertyKeys)
for _, k := range sortedPropertyKeys {
vv, err := jsoniter.Marshal(p.props[k])
if err != nil {
return err
}
kk, err := jsoniter.Marshal(k)
if err != nil {
return err
}
buf.WriteString(`,`)
buf.Write(kk)
buf.WriteString(`:`)
buf.Write(vv)
}
return nil
}
type schemaConfig struct {
aliases []string
doc string
def any
order Order
props map[string]any
wfp *[32]byte
}
// SchemaOption is a function that sets a schema option.
type SchemaOption func(*schemaConfig)
// WithAliases sets the aliases on a schema.
func WithAliases(aliases []string) SchemaOption {
return func(opts *schemaConfig) {
opts.aliases = aliases
}
}
// WithDoc sets the doc on a schema.
func WithDoc(doc string) SchemaOption {
return func(opts *schemaConfig) {
opts.doc = doc
}
}
// WithDefault sets the default on a schema.
func WithDefault(def any) SchemaOption {
return func(opts *schemaConfig) {
opts.def = def
}
}
// WithOrder sets the order on a schema.
func WithOrder(order Order) SchemaOption {
return func(opts *schemaConfig) {
opts.order = order
}
}
// WithProps sets the properties on a schema.
func WithProps(props map[string]any) SchemaOption {
return func(opts *schemaConfig) {
opts.props = props
}
}
func withWriterFingerprint(fp [32]byte) SchemaOption {
return func(opts *schemaConfig) {
opts.wfp = &fp
}
}
func withWriterFingerprintIfResolved(fp [32]byte, resolved bool) SchemaOption {
return func(opts *schemaConfig) {
if resolved {
opts.wfp = &fp
}
}
}
// PrimitiveSchema is an Avro primitive type schema.
type PrimitiveSchema struct {
properties
fingerprinter
cacheFingerprinter
typ Type
logical LogicalSchema
// encodedType is the type of the encoded value, if it is different from the typ.
// It's only used in the context of write-read schema resolution.
encodedType Type
}
// NewPrimitiveSchema creates a new PrimitiveSchema.
func NewPrimitiveSchema(t Type, l LogicalSchema, opts ...SchemaOption) *PrimitiveSchema {
var cfg schemaConfig
for _, opt := range opts {
opt(&cfg)
}
reservedProps := primitiveReserved
if l != nil {
if l.Type() == Decimal {
reservedProps = primitiveWithDecimalTypeReserved
} else {
reservedProps = primitiveWithLogicalTypeReserved
}
}
return &PrimitiveSchema{
properties: newProperties(cfg.props, reservedProps),
cacheFingerprinter: cacheFingerprinter{writerFingerprint: cfg.wfp},
typ: t,
logical: l,
}
}
// Type returns the type of the schema.
func (s *PrimitiveSchema) Type() Type {
return s.typ
}
// Logical returns the logical schema or nil.
func (s *PrimitiveSchema) Logical() LogicalSchema {
return s.logical
}
// String returns the canonical form of the schema.
func (s *PrimitiveSchema) String() string {
if s.logical == nil {
return `"` + string(s.typ) + `"`
}
return `{"type":"` + string(s.typ) + `",` + s.logical.String() + `}`
}
// MarshalJSON marshals the schema to json.
func (s *PrimitiveSchema) MarshalJSON() ([]byte, error) {
if s.logical == nil && len(s.props) == 0 {
return jsoniter.Marshal(s.typ)
}
buf := new(bytes.Buffer)
buf.WriteString(`{"type":"` + string(s.typ) + `"`)
if s.logical != nil {
buf.WriteString(`,"logicalType":"` + string(s.logical.Type()) + `"`)
if d, ok := s.logical.(*DecimalLogicalSchema); ok {
buf.WriteString(`,"precision":` + strconv.Itoa(d.prec))
if d.scale > 0 {
buf.WriteString(`,"scale":` + strconv.Itoa(d.scale))
}
}
}
if err := s.marshalPropertiesToJSON(buf); err != nil {
return nil, err
}
buf.WriteString("}")
return buf.Bytes(), nil
}
// Fingerprint returns the SHA256 fingerprint of the schema.
func (s *PrimitiveSchema) Fingerprint() [32]byte {
return s.fingerprinter.Fingerprint(s)
}
// FingerprintUsing returns the fingerprint of the schema using the given algorithm or an error.
func (s *PrimitiveSchema) FingerprintUsing(typ FingerprintType) ([]byte, error) {
return s.fingerprinter.FingerprintUsing(typ, s)
}
// CacheFingerprint returns unique identity of the schema.
func (s *PrimitiveSchema) CacheFingerprint() [32]byte {
return s.cacheFingerprinter.CacheFingerprint(s, nil)
}
// RecordSchema is an Avro record type schema.
type RecordSchema struct {
name
properties
fingerprinter
cacheFingerprinter
isError bool
fields []*Field
doc string
}
// NewRecordSchema creates a new record schema instance.
func NewRecordSchema(name, namespace string, fields []*Field, opts ...SchemaOption) (*RecordSchema, error) {
var cfg schemaConfig
for _, opt := range opts {
opt(&cfg)
}
n, err := newName(name, namespace, cfg.aliases)
if err != nil {
return nil, err
}
return &RecordSchema{
name: n,
properties: newProperties(cfg.props, recordReserved),
cacheFingerprinter: cacheFingerprinter{writerFingerprint: cfg.wfp},
fields: fields,
doc: cfg.doc,
}, nil
}
// NewErrorRecordSchema creates a new error record schema instance.
func NewErrorRecordSchema(name, namespace string, fields []*Field, opts ...SchemaOption) (*RecordSchema, error) {
rec, err := NewRecordSchema(name, namespace, fields, opts...)
if err != nil {
return nil, err
}
rec.isError = true
return rec, nil
}
// Type returns the type of the schema.
func (s *RecordSchema) Type() Type {
return Record
}
// Doc returns the documentation of a record.
func (s *RecordSchema) Doc() string {
return s.doc
}
// IsError determines is this is an error record.
func (s *RecordSchema) IsError() bool {
return s.isError
}
// Fields returns the fields of a record.
func (s *RecordSchema) Fields() []*Field {
return s.fields
}
// String returns the canonical form of the schema.
func (s *RecordSchema) String() string {
typ := "record"
if s.isError {
typ = "error"
}
fields := ""
for _, f := range s.fields {
fields += f.String() + ","
}
if len(fields) > 0 {
fields = fields[:len(fields)-1]
}
return `{"name":"` + s.FullName() + `","type":"` + typ + `","fields":[` + fields + `]}`
}
// MarshalJSON marshals the schema to json.
func (s *RecordSchema) MarshalJSON() ([]byte, error) {
buf := new(bytes.Buffer)
buf.WriteString(`{"name":"` + s.full + `"`)
if len(s.aliases) > 0 {
aliasesJSON, err := jsoniter.Marshal(s.aliases)
if err != nil {
return nil, err
}
buf.WriteString(`,"aliases":`)
buf.Write(aliasesJSON)
}
if s.doc != "" {
docJSON, err := jsoniter.Marshal(s.doc)
if err != nil {
return nil, err
}
buf.WriteString(`,"doc":`)
buf.Write(docJSON)
}
if s.isError {
buf.WriteString(`,"type":"error"`)
} else {
buf.WriteString(`,"type":"record"`)
}
fieldsJSON, err := jsoniter.Marshal(s.fields)
if err != nil {
return nil, err
}
buf.WriteString(`,"fields":`)
buf.Write(fieldsJSON)
if err := s.marshalPropertiesToJSON(buf); err != nil {
return nil, err
}
buf.WriteString("}")
return buf.Bytes(), nil
}
// Fingerprint returns the SHA256 fingerprint of the schema.
func (s *RecordSchema) Fingerprint() [32]byte {
return s.fingerprinter.Fingerprint(s)
}
// FingerprintUsing returns the fingerprint of the schema using the given algorithm or an error.
func (s *RecordSchema) FingerprintUsing(typ FingerprintType) ([]byte, error) {
return s.fingerprinter.FingerprintUsing(typ, s)
}
// CacheFingerprint returns unique identity of the schema.
func (s *RecordSchema) CacheFingerprint() [32]byte {
return s.cacheFingerprinter.CacheFingerprint(s, func() []byte {
var defs []any
for _, field := range s.fields {
if !field.HasDefault() {
continue
}
defs = append(defs, field.Default())
}
b, _ := jsoniter.Marshal(defs)
return b
})
}
// Field is an Avro record type field.
type Field struct {
properties
name string
aliases []string
doc string
typ Schema
hasDef bool
def any
order Order
// action mainly used when decoding data that lack the field for schema evolution purposes.
action Action
// encodedDef mainly used when decoding data that lack the field for schema evolution purposes.
// Its value remains empty unless the field's encodeDefault function is called.
encodedDef atomic.Value
}
type noDef struct{}
// NoDefault is used when no default exists for a field.
var NoDefault = noDef{}
// NewField creates a new field instance.
func NewField(name string, typ Schema, opts ...SchemaOption) (*Field, error) {
cfg := schemaConfig{def: NoDefault}
for _, opt := range opts {
opt(&cfg)
}
if err := validateName(name); err != nil {
return nil, err
}
for _, a := range cfg.aliases {
if err := validateName(a); err != nil {
return nil, err
}
}
switch cfg.order {
case "":
cfg.order = Asc
case Asc, Desc, Ignore:
default:
return nil, fmt.Errorf("avro: field %q order %q is invalid", name, cfg.order)
}
f := &Field{
properties: newProperties(cfg.props, fieldReserved),
name: name,
aliases: cfg.aliases,
doc: cfg.doc,
typ: typ,
order: cfg.order,
}
if cfg.def != NoDefault {
def, err := validateDefault(name, typ, cfg.def)
if err != nil {
return nil, err
}
f.def = def
f.hasDef = true
}
return f, nil
}
// Name returns the name of a field.
func (f *Field) Name() string {
return f.name
}
// Aliases return the field aliases.
func (f *Field) Aliases() []string {
return f.aliases
}
// Type returns the schema of a field.
func (f *Field) Type() Schema {
return f.typ
}
// HasDefault determines if the field has a default value.
func (f *Field) HasDefault() bool {
return f.hasDef
}
// Default returns the default of a field or nil.
//
// The only time a nil default is valid is for a Null Type.
func (f *Field) Default() any {
if f.def == nullDefault {
return nil
}
return f.def
}
func (f *Field) encodeDefault(encode func(any) ([]byte, error)) ([]byte, error) {
if v := f.encodedDef.Load(); v != nil {
return v.([]byte), nil
}
if !f.hasDef {
return nil, fmt.Errorf("avro: '%s' field must have a non-empty default value", f.name)
}
if encode == nil {
return nil, fmt.Errorf("avro: failed to encode '%s' default value", f.name)
}
b, err := encode(f.Default())
if err != nil {
return nil, err
}
f.encodedDef.Store(b)
return b, nil
}
// Doc returns the documentation of a field.
func (f *Field) Doc() string {
return f.doc
}
// Order returns the field order.
func (f *Field) Order() Order {
return f.order
}
// String returns the canonical form of a field.
func (f *Field) String() string {
return `{"name":"` + f.name + `","type":` + f.typ.String() + `}`
}
// MarshalJSON marshals the schema to json.
func (f *Field) MarshalJSON() ([]byte, error) {
buf := new(bytes.Buffer)
buf.WriteString(`{"name":"` + f.name + `"`)
if len(f.aliases) > 0 {
aliasesJSON, err := jsoniter.Marshal(f.aliases)
if err != nil {
return nil, err
}
buf.WriteString(`,"aliases":`)
buf.Write(aliasesJSON)
}
if f.doc != "" {
docJSON, err := jsoniter.Marshal(f.doc)
if err != nil {
return nil, err
}
buf.WriteString(`,"doc":`)
buf.Write(docJSON)
}
typeJSON, err := jsoniter.Marshal(f.typ)
if err != nil {
return nil, err
}
buf.WriteString(`,"type":`)
buf.Write(typeJSON)
if f.hasDef {
defaultValueJSON, err := jsoniter.Marshal(f.Default())
if err != nil {
return nil, err
}
buf.WriteString(`,"default":`)
buf.Write(defaultValueJSON)
}
if f.order != "" && f.order != Asc {
buf.WriteString(`,"order":"` + string(f.order) + `"`)
}
if err := f.marshalPropertiesToJSON(buf); err != nil {
return nil, err
}
buf.WriteString("}")
return buf.Bytes(), nil
}
// EnumSchema is an Avro enum type schema.
type EnumSchema struct {
name
properties
fingerprinter
cacheFingerprinter
symbols []string
def string
doc string
// encodedSymbols is the symbols of the encoded value.
// It's only used in the context of write-read schema resolution.
encodedSymbols []string
}
// NewEnumSchema creates a new enum schema instance.
func NewEnumSchema(name, namespace string, symbols []string, opts ...SchemaOption) (*EnumSchema, error) {
var cfg schemaConfig
for _, opt := range opts {
opt(&cfg)
}
n, err := newName(name, namespace, cfg.aliases)
if err != nil {
return nil, err
}
if len(symbols) == 0 {
return nil, errors.New("avro: enum must have a non-empty array of symbols")
}
for _, sym := range symbols {
if err = validateName(sym); err != nil {
return nil, fmt.Errorf("avro: invalid symbol %q", sym)
}
}
var def string
if d, ok := cfg.def.(string); ok && d != "" {
if !hasSymbol(symbols, d) {
return nil, fmt.Errorf("avro: symbol default %q must be a symbol", d)
}
def = d
}
return &EnumSchema{
name: n,
properties: newProperties(cfg.props, enumReserved),
cacheFingerprinter: cacheFingerprinter{writerFingerprint: cfg.wfp},
symbols: symbols,
def: def,
doc: cfg.doc,
}, nil
}
func hasSymbol(symbols []string, sym string) bool {
for _, s := range symbols {
if s == sym {
return true
}
}
return false
}
// Type returns the type of the schema.
func (s *EnumSchema) Type() Type {
return Enum
}
// Doc returns the schema doc.
func (s *EnumSchema) Doc() string {
return s.doc
}
// Symbols returns the symbols of an enum.
func (s *EnumSchema) Symbols() []string {
return s.symbols
}
// Symbol returns the symbol for the given index.
// It might return the default value in the context of write-read schema resolution.
func (s *EnumSchema) Symbol(i int) (string, bool) {
resolv := len(s.encodedSymbols) > 0
symbols := s.symbols
if resolv {
// A different set of symbols is encoded.
symbols = s.encodedSymbols
}
if i < 0 || i >= len(symbols) {
return "", false
}
symbol := symbols[i]
if resolv && !hasSymbol(s.symbols, symbol) {
if !s.HasDefault() {
return "", false
}
return s.Default(), true
}
return symbol, true
}
// Default returns the default of an enum or an empty string.
func (s *EnumSchema) Default() string {
return s.def
}
// HasDefault determines if the schema has a default value.