File: schema.go

package info (click to toggle)
golang-github-pzhin-go-sophia 0.0~git20180715.8bdc218-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 924 kB
  • sloc: ansic: 23,001; makefile: 4
file content (48 lines) | stat: -rw-r--r-- 1,275 bytes parent folder | download | duplicates (4)
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
package sophia

import "fmt"

// Schema is a structure for configuring fields which record will contain
type Schema struct {
	// name -> type
	keys      map[string]FieldType
	keysNames []string
	// name -> type
	values      map[string]FieldType
	valuesNames []string
}

// AddKey adds new key field for record.
// If record have already had field with such name error will be returned
func (s *Schema) AddKey(name string, typ FieldType) error {
	if s.keys == nil {
		s.keys = make(map[string]FieldType)
	}
	if _, ok := s.keys[name]; ok {
		return fmt.Errorf("duplicate key, '%v' has been already defined", name)
	}
	s.keysNames = append(s.keysNames, name)
	s.keys[name] = typ
	return nil
}

// AddKey adds new value field for record.
// If record have already had field with such name error will be returned
func (s *Schema) AddValue(name string, typ FieldType) error {
	if s.values == nil {
		s.values = make(map[string]FieldType)
	}
	if _, ok := s.values[name]; ok {
		return fmt.Errorf("duplicate value, '%v' is already defined", name)
	}
	s.valuesNames = append(s.valuesNames, name)
	s.values[name] = typ
	return nil
}

func defaultSchema() *Schema {
	schema := &Schema{}
	schema.AddKey("key", FieldTypeString)
	schema.AddValue("value", FieldTypeString)
	return schema
}