Skip to content

Commit

Permalink
Merge pull request #240 from stephenafamo/enum-valid-scan
Browse files Browse the repository at this point in the history
Check if value is valid after scanning an enum
  • Loading branch information
stephenafamo authored Jun 20, 2024
2 parents af2abb7 + 48401e9 commit 1787fe5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
27 changes: 21 additions & 6 deletions gen/templates/models/singleton/bob_enums.go.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
Expand All @@ -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 -}}
Expand Down

0 comments on commit 1787fe5

Please sign in to comment.