Skip to content

Commit 6a4dcec

Browse files
authored
internal/dinosql: Fix incorrect enum names (#223)
Enums of type enum_type with values like foo-bar should be named EnumTypeFooBar, but were being generated as EnumTypeFoobar. The regex pattern I was using to remove unsupported characters was accidentally stripping out underscores, the character used to split the string.
1 parent 5226cf7 commit 6a4dcec

File tree

2 files changed

+38
-10
lines changed

2 files changed

+38
-10
lines changed

internal/dinosql/gen.go

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import (
1818
"github.com/jinzhu/inflection"
1919
)
2020

21-
var identPattern = regexp.MustCompile("[^a-zA-Z0-9]+")
21+
var identPattern = regexp.MustCompile("[^a-zA-Z0-9_]+")
2222

2323
type GoConstant struct {
2424
Name string
@@ -388,6 +388,18 @@ func (r Result) QueryImports(filename string) [][]string {
388388
return [][]string{stds, pkgs}
389389
}
390390

391+
func enumValueName(value string) string {
392+
name := ""
393+
id := strings.Replace(value, "-", "_", -1)
394+
id = strings.Replace(id, ":", "_", -1)
395+
id = strings.Replace(id, "/", "_", -1)
396+
id = identPattern.ReplaceAllString(id, "")
397+
for _, part := range strings.Split(id, "_") {
398+
name += strings.Title(part)
399+
}
400+
return name
401+
}
402+
391403
func (r Result) Enums() []GoEnum {
392404
var enums []GoEnum
393405
for name, schema := range r.Catalog.Schemas {
@@ -406,16 +418,8 @@ func (r Result) Enums() []GoEnum {
406418
Comment: enum.Comment,
407419
}
408420
for _, v := range enum.Vals {
409-
name := ""
410-
id := strings.Replace(v, "-", "_", -1)
411-
id = strings.Replace(id, ":", "_", -1)
412-
id = strings.Replace(id, "/", "_", -1)
413-
id = identPattern.ReplaceAllString(id, "")
414-
for _, part := range strings.Split(id, "_") {
415-
name += strings.Title(part)
416-
}
417421
e.Constants = append(e.Constants, GoConstant{
418-
Name: e.Name + name,
422+
Name: e.Name + enumValueName(v),
419423
Value: v,
420424
Type: e.Name,
421425
})

internal/dinosql/gen_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,3 +143,27 @@ func TestNullInnerType(t *testing.T) {
143143
})
144144
}
145145
}
146+
147+
func TestEnumValueName(t *testing.T) {
148+
values := map[string]string{
149+
// Valid separators
150+
"foo-bar": "FooBar",
151+
"foo_bar": "FooBar",
152+
"foo:bar": "FooBar",
153+
"foo/bar": "FooBar",
154+
// Strip unknown characters
155+
"foo@bar": "Foobar",
156+
"foo+bar": "Foobar",
157+
"foo!bar": "Foobar",
158+
}
159+
for k, v := range values {
160+
input := k
161+
expected := v
162+
t.Run(k+"-"+v, func(t *testing.T) {
163+
actual := enumValueName(k)
164+
if actual != expected {
165+
t.Errorf("expected name for %s to be %s, not %s", input, expected, actual)
166+
}
167+
})
168+
}
169+
}

0 commit comments

Comments
 (0)