forked from sqlc-dev/sqlc
/
field.go
79 lines (69 loc) · 1.46 KB
/
field.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
package golang
import (
"fmt"
"sort"
"strings"
"github.com/booleangate/sqlc/internal/plugin"
)
type Field struct {
Name string // CamelCased name for Go
DBName string // Name as used in the DB
Type string
Tags map[string]string
Comment string
}
func (gf Field) Tag() string {
tags := make([]string, 0, len(gf.Tags))
for key, val := range gf.Tags {
tags = append(tags, fmt.Sprintf("%s\"%s\"", key, val))
}
if len(tags) == 0 {
return ""
}
sort.Strings(tags)
return strings.Join(tags, " ")
}
func JSONTagName(name string, settings *plugin.Settings) string {
style := settings.Go.JsonTagsCaseStyle
if style == "" || style == "none" {
return name
} else {
return SetCaseStyle(name, style)
}
}
func SetCaseStyle(name string, style string) string {
switch style {
case "camel":
return toCamelCase(name)
case "pascal":
return toPascalCase(name)
case "snake":
return toSnakeCase(name)
default:
panic(fmt.Sprintf("unsupported JSON tags case style: '%s'", style))
}
}
func toSnakeCase(s string) string {
return strings.ToLower(s)
}
func toCamelCase(s string) string {
return toCamelInitCase(s, false)
}
func toPascalCase(s string) string {
return toCamelInitCase(s, true)
}
func toCamelInitCase(name string, initUpper bool) string {
out := ""
for i, p := range strings.Split(name, "_") {
if !initUpper && i == 0 {
out += p
continue
}
if p == "id" {
out += "ID"
} else {
out += strings.Title(p)
}
}
return out
}