diff --git a/CHANGELOG.md b/CHANGELOG.md index 43e1e7a2..e9085aa3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -67,6 +67,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Do not add `FROM` clause to `SELECT` queries that are used as subqueries. +- Enum values are now checked for validity after scanning. ## [v0.27.1] - 2024-06-05 diff --git a/gen/templates/models/singleton/bob_enums.go.tpl b/gen/templates/models/singleton/bob_enums.go.tpl index e514e796..2e13dbd5 100644 --- a/gen/templates/models/singleton/bob_enums.go.tpl +++ b/gen/templates/models/singleton/bob_enums.go.tpl @@ -4,19 +4,21 @@ {{end}} {{- range $enum := $.Enums}} - {{$allvals := "\n"}} + {{$allvals := list }} // Enum values for {{$enum.Type}} const ( {{range $val := $enum.Values -}} {{- $enumValue := enumVal $val -}} {{$enum.Type}}{{$enumValue}} {{$enum.Type}} = {{quote $val}} - {{$allvals = printf "%s%s%s,\n" $allvals $enum.Type $enumValue -}} + {{$allvals = append $allvals (printf "%s%s" $enum.Type $enumValue) -}} {{end -}} ) func All{{$enum.Type}}() []{{$enum.Type}} { - return []{{$enum.Type}}{ {{$allvals}} } + return []{{$enum.Type}}{ + {{join ",\n" $allvals}}, + } } type {{$enum.Type}} string @@ -25,6 +27,15 @@ return string(e) } + func (e {{$enum.Type}}) Valid() bool { + switch e { + case {{join ",\n" $allvals}}: + return true + default: + return false + } + } + func (e {{$enum.Type}}) MarshalText() ([]byte, error) { return []byte(e), nil } @@ -49,15 +60,19 @@ switch x := value.(type) { case string: *e = {{$enum.Type}}(x) - return nil case []byte: *e = {{$enum.Type}}(x) - return nil case nil: - return nil + return fmt.Errorf("cannot nil into {{$enum.Type}}") default: return fmt.Errorf("cannot scan type %T: %v", value, value) } + + if !e.Valid() { + return fmt.Errorf("invalid {{$enum.Type}} value: %s", *e) + } + + return nil } {{end -}}