-
Notifications
You must be signed in to change notification settings - Fork 0
/
enums.go
100 lines (89 loc) · 2.19 KB
/
enums.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
package genpgfuncs
import (
"fmt"
"io"
"sort"
"strings"
"github.com/jmoiron/sqlx"
)
type Enum struct {
Name string
Values []string
}
func (enum *Enum) GoName() string {
name := enum.Name
p := strings.LastIndexByte(name, '.')
name = name[p+1:]
return exportedGoName(name)
}
func (enum *Enum) GoConstsAndValues() (constsAndValues []string) {
baseName := enum.GoName()
for _, enumValue := range enum.Values {
constName := baseName + exportedGoName(enumValue)
constsAndValues = append(constsAndValues, constName, enumValue)
}
return constsAndValues
}
func (enum *Enum) Fprint(writer io.Writer) {
fmt.Fprintf(writer, "type %s string\n", enum.GoName())
fmt.Fprint(writer, "const (\n")
constsAndValues := enum.GoConstsAndValues()
for i := 0; i < len(constsAndValues); i += 2 {
name := constsAndValues[i]
value := constsAndValues[i+1]
fmt.Fprintf(writer, "%s %s = \"%s\" \n", name, enum.GoName(), value)
}
fmt.Fprint(writer, ")\n")
fmt.Fprintf(writer, "func (c %s) Valid() bool {\n", enum.GoName())
fmt.Fprint(writer, "switch c {\n")
fmt.Fprint(writer, "case ")
for i := 0; i < len(constsAndValues); i += 2 {
name := constsAndValues[i]
if i > 0 {
fmt.Fprint(writer, ", ")
}
fmt.Fprint(writer, name)
}
fmt.Fprint(writer, ":\n")
fmt.Fprint(writer, "return true\n")
fmt.Fprint(writer, "}\n")
fmt.Fprint(writer, "return false\n")
fmt.Fprint(writer, "}\n")
}
type Enums map[string]Enum
func (enums Enums) Fprint(writer io.Writer) {
sorted := make([]Enum, 0, len(enums))
for _, enum := range enums {
sorted = append(sorted, enum)
}
sort.Slice(sorted, func(i, j int) bool {
return sorted[i].Name < sorted[j].Name
})
for _, enum := range sorted {
enum.Fprint(writer)
}
}
func GetEnumValues(conn *sqlx.DB, enum string) (values []string, err error) {
const query = `
SELECT e.enumlabel
FROM pg_enum AS e
JOIN pg_type t ON e.enumtypid = t.oid
WHERE t.typname = $1`
rows, err := conn.Query(query, enum)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var value string
err = rows.Scan(&value)
if err != nil {
return nil, err
}
values = append(values, value)
}
if rows.Err() != nil {
return nil, rows.Err()
}
return values, nil
}