Skip to content

Commit 1787fe5

Browse files
authored
Merge pull request #240 from stephenafamo/enum-valid-scan
Check if value is valid after scanning an enum
2 parents af2abb7 + 48401e9 commit 1787fe5

2 files changed

Lines changed: 22 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6767
### Fixed
6868

6969
- Do not add `FROM` clause to `SELECT` queries that are used as subqueries.
70+
- Enum values are now checked for validity after scanning.
7071

7172
## [v0.27.1] - 2024-06-05
7273

‎gen/templates/models/singleton/bob_enums.go.tpl‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,21 @@
44
{{end}}
55

66
{{- range $enum := $.Enums}}
7-
{{$allvals := "\n"}}
7+
{{$allvals := list }}
88

99
// Enum values for {{$enum.Type}}
1010
const (
1111
{{range $val := $enum.Values -}}
1212
{{- $enumValue := enumVal $val -}}
1313
{{$enum.Type}}{{$enumValue}} {{$enum.Type}} = {{quote $val}}
14-
{{$allvals = printf "%s%s%s,\n" $allvals $enum.Type $enumValue -}}
14+
{{$allvals = append $allvals (printf "%s%s" $enum.Type $enumValue) -}}
1515
{{end -}}
1616
)
1717

1818
func All{{$enum.Type}}() []{{$enum.Type}} {
19-
return []{{$enum.Type}}{ {{$allvals}} }
19+
return []{{$enum.Type}}{
20+
{{join ",\n" $allvals}},
21+
}
2022
}
2123

2224
type {{$enum.Type}} string
@@ -25,6 +27,15 @@
2527
return string(e)
2628
}
2729

30+
func (e {{$enum.Type}}) Valid() bool {
31+
switch e {
32+
case {{join ",\n" $allvals}}:
33+
return true
34+
default:
35+
return false
36+
}
37+
}
38+
2839
func (e {{$enum.Type}}) MarshalText() ([]byte, error) {
2940
return []byte(e), nil
3041
}
@@ -49,15 +60,19 @@
4960
switch x := value.(type) {
5061
case string:
5162
*e = {{$enum.Type}}(x)
52-
return nil
5363
case []byte:
5464
*e = {{$enum.Type}}(x)
55-
return nil
5665
case nil:
57-
return nil
66+
return fmt.Errorf("cannot nil into {{$enum.Type}}")
5867
default:
5968
return fmt.Errorf("cannot scan type %T: %v", value, value)
6069
}
70+
71+
if !e.Valid() {
72+
return fmt.Errorf("invalid {{$enum.Type}} value: %s", *e)
73+
}
74+
75+
return nil
6176
}
6277

6378
{{end -}}

0 commit comments

Comments
 (0)