forked from xo/xo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgres.enum.go.tpl
62 lines (50 loc) · 1.8 KB
/
postgres.enum.go.tpl
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
{{- $type := .Name -}}
{{- $short := (shortname $type "enumVal" "text" "buf" "ok" "src") -}}
{{- $reverseNames := .ReverseConstNames -}}
// {{ $type }} is the '{{ .Enum.EnumName }}' enum type from schema '{{ .Schema }}'.
type {{ $type }} uint16
const (
{{- range .Values }}
// {{ if $reverseNames }}{{ .Name }}{{ $type }}{{ else }}{{ $type }}{{ .Name }}{{ end }} is the '{{ .Val.EnumValue }}' {{ $type }}.
{{ if $reverseNames }}{{ .Name }}{{ $type }}{{ else }}{{ $type }}{{ .Name }}{{ end }} = {{ $type }}({{ .Val.ConstValue }})
{{ end -}}
)
// String returns the string value of the {{ $type }}.
func ({{ $short }} {{ $type }}) String() string {
var enumVal string
switch {{ $short }} {
{{- range .Values }}
case {{ if $reverseNames }}{{ .Name }}{{ $type }}{{ else }}{{ $type }}{{ .Name }}{{ end }}:
enumVal = "{{ .Val.EnumValue }}"
{{ end -}}
}
return enumVal
}
// MarshalText marshals {{ $type }} into text.
func ({{ $short }} {{ $type }}) MarshalText() ([]byte, error) {
return []byte({{ $short }}.String()), nil
}
// UnmarshalText unmarshals {{ $type }} from text.
func ({{ $short }} *{{ $type }}) UnmarshalText(text []byte) error {
switch string(text) {
{{- range .Values }}
case "{{ .Val.EnumValue }}":
*{{ $short }} = {{ if $reverseNames }}{{ .Name }}{{ $type }}{{ else }}{{ $type }}{{ .Name }}{{ end }}
{{ end }}
default:
return errors.New("invalid {{ $type }}")
}
return nil
}
// Value satisfies the sql/driver.Valuer interface for {{ $type }}.
func ({{ $short }} {{ $type }}) Value() (driver.Value, error) {
return {{ $short }}.String(), nil
}
// Scan satisfies the database/sql.Scanner interface for {{ $type }}.
func ({{ $short }} *{{ $type }}) Scan(src interface{}) error {
buf, ok := src.([]byte)
if !ok {
return errors.New("invalid {{ $type }}")
}
return {{ $short }}.UnmarshalText(buf)
}