Skip to content

Support JSON tags for nullable enum structs #2121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jun 9, 2023
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/batch/postgresql/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions examples/ondeck/mysql/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions examples/ondeck/postgresql/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions internal/codegen/golang/enum.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ type Enum struct {
Name string
Comment string
Constants []Constant
NameTags map[string]string
ValidTags map[string]string
}

func (e Enum) NameTag() string {
return TagsToString(e.NameTags)
}

func (e Enum) ValidTag() string {
return TagsToString(e.ValidTags)
}

func EnumReplace(value string) string {
Expand Down
72 changes: 2 additions & 70 deletions internal/codegen/golang/field.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package golang

import (
"fmt"
"regexp"
"sort"
"strings"

"github.com/kyleconroy/sqlc/internal/plugin"
Expand All @@ -16,83 +13,18 @@ type Field struct {
Tags map[string]string
Comment string
Column *plugin.Column
// EmbedFields contains the embedded fields that reuqire scanning.
// EmbedFields contains the embedded fields that require scanning.
EmbedFields []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, " ")
return TagsToString(gf.Tags)
}

func (gf Field) HasSqlcSlice() bool {
return gf.Column.IsSqlcSlice
}

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))
}
}

var camelPattern = regexp.MustCompile("[^A-Z][A-Z]+")

func toSnakeCase(s string) string {
if !strings.ContainsRune(s, '_') {
s = camelPattern.ReplaceAllStringFunc(s, func(x string) string {
return x[:1] + "_" + x[1:]
})
}
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
}

func toLowerCase(str string) string {
if str == "" {
return ""
Expand Down
12 changes: 10 additions & 2 deletions internal/codegen/golang/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,18 @@ func buildEnums(req *plugin.CodeGenRequest) []Enum {
} else {
enumName = schema.Name + "_" + enum.Name
}

e := Enum{
Name: StructName(enumName, req.Settings),
Comment: enum.Comment,
Name: StructName(enumName, req.Settings),
Comment: enum.Comment,
NameTags: map[string]string{},
ValidTags: map[string]string{},
}
if req.Settings.Go.EmitJsonTags {
e.NameTags["json"] = JSONTagName(enumName, req.Settings)
e.ValidTags["json"] = JSONTagName("valid", req.Settings)
}

seen := make(map[string]struct{}, len(enum.Vals))
for i, v := range enum.Vals {
value := EnumReplace(v)
Expand Down
70 changes: 70 additions & 0 deletions internal/codegen/golang/tags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package golang

import (
"fmt"
"github.com/kyleconroy/sqlc/internal/plugin"
"sort"
"strings"
)

func TagsToString(tags map[string]string) string {
if len(tags) == 0 {
return ""
}
tagParts := make([]string, 0, len(tags))
for key, val := range tags {
tagParts = append(tagParts, fmt.Sprintf("%s:\"%s\"", key, val))
}
sort.Strings(tagParts)
return strings.Join(tagParts, " ")
}

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
}
4 changes: 2 additions & 2 deletions internal/codegen/golang/templates/template.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ func (e *{{.Name}}) Scan(src interface{}) error {
}

type Null{{.Name}} struct {
{{.Name}} {{.Name}}
Valid bool // Valid is true if {{.Name}} is not NULL
{{.Name}} {{.Name}} {{if .NameTag}}{{$.Q}}{{.NameTag}}{{$.Q}}{{end}}
Valid bool {{if .ValidTag}}{{$.Q}}{{.ValidTag}}{{$.Q}}{{end}} // Valid is true if {{.Name}} is not NULL
}

// Scan implements the Scanner interface.
Expand Down
55 changes: 28 additions & 27 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,33 +117,34 @@ type SQLGen struct {
}

type SQLGo struct {
EmitInterface bool `json:"emit_interface" yaml:"emit_interface"`
EmitJSONTags bool `json:"emit_json_tags" yaml:"emit_json_tags"`
EmitDBTags bool `json:"emit_db_tags" yaml:"emit_db_tags"`
EmitPreparedQueries bool `json:"emit_prepared_queries" yaml:"emit_prepared_queries"`
EmitExactTableNames bool `json:"emit_exact_table_names,omitempty" yaml:"emit_exact_table_names"`
EmitEmptySlices bool `json:"emit_empty_slices,omitempty" yaml:"emit_empty_slices"`
EmitExportedQueries bool `json:"emit_exported_queries" yaml:"emit_exported_queries"`
EmitResultStructPointers bool `json:"emit_result_struct_pointers" yaml:"emit_result_struct_pointers"`
EmitParamsStructPointers bool `json:"emit_params_struct_pointers" yaml:"emit_params_struct_pointers"`
EmitMethodsWithDBArgument bool `json:"emit_methods_with_db_argument,omitempty" yaml:"emit_methods_with_db_argument"`
EmitPointersForNullTypes bool `json:"emit_pointers_for_null_types" yaml:"emit_pointers_for_null_types"`
EmitEnumValidMethod bool `json:"emit_enum_valid_method,omitempty" yaml:"emit_enum_valid_method"`
EmitAllEnumValues bool `json:"emit_all_enum_values,omitempty" yaml:"emit_all_enum_values"`
JSONTagsCaseStyle string `json:"json_tags_case_style,omitempty" yaml:"json_tags_case_style"`
Package string `json:"package" yaml:"package"`
Out string `json:"out" yaml:"out"`
Overrides []Override `json:"overrides,omitempty" yaml:"overrides"`
Rename map[string]string `json:"rename,omitempty" yaml:"rename"`
SQLPackage string `json:"sql_package" yaml:"sql_package"`
SQLDriver string `json:"sql_driver" yaml:"sql_driver"`
OutputBatchFileName string `json:"output_batch_file_name,omitempty" yaml:"output_batch_file_name"`
OutputDBFileName string `json:"output_db_file_name,omitempty" yaml:"output_db_file_name"`
OutputModelsFileName string `json:"output_models_file_name,omitempty" yaml:"output_models_file_name"`
OutputQuerierFileName string `json:"output_querier_file_name,omitempty" yaml:"output_querier_file_name"`
OutputFilesSuffix string `json:"output_files_suffix,omitempty" yaml:"output_files_suffix"`
InflectionExcludeTableNames []string `json:"inflection_exclude_table_names,omitempty" yaml:"inflection_exclude_table_names"`
QueryParameterLimit *int32 `json:"query_parameter_limit,omitempty" yaml:"query_parameter_limit"`
EmitInterface bool `json:"emit_interface" yaml:"emit_interface"`
EmitJSONTags bool `json:"emit_json_tags" yaml:"emit_json_tags"`
EmitJSONTagsOnNullEnumStructs bool `json:"emit_json_tags_on_null_enum_structs" yaml:"emit_json_tags_on_null_enum_structs"`
EmitDBTags bool `json:"emit_db_tags" yaml:"emit_db_tags"`
EmitPreparedQueries bool `json:"emit_prepared_queries" yaml:"emit_prepared_queries"`
EmitExactTableNames bool `json:"emit_exact_table_names,omitempty" yaml:"emit_exact_table_names"`
EmitEmptySlices bool `json:"emit_empty_slices,omitempty" yaml:"emit_empty_slices"`
EmitExportedQueries bool `json:"emit_exported_queries" yaml:"emit_exported_queries"`
EmitResultStructPointers bool `json:"emit_result_struct_pointers" yaml:"emit_result_struct_pointers"`
EmitParamsStructPointers bool `json:"emit_params_struct_pointers" yaml:"emit_params_struct_pointers"`
EmitMethodsWithDBArgument bool `json:"emit_methods_with_db_argument,omitempty" yaml:"emit_methods_with_db_argument"`
EmitPointersForNullTypes bool `json:"emit_pointers_for_null_types" yaml:"emit_pointers_for_null_types"`
EmitEnumValidMethod bool `json:"emit_enum_valid_method,omitempty" yaml:"emit_enum_valid_method"`
EmitAllEnumValues bool `json:"emit_all_enum_values,omitempty" yaml:"emit_all_enum_values"`
JSONTagsCaseStyle string `json:"json_tags_case_style,omitempty" yaml:"json_tags_case_style"`
Package string `json:"package" yaml:"package"`
Out string `json:"out" yaml:"out"`
Overrides []Override `json:"overrides,omitempty" yaml:"overrides"`
Rename map[string]string `json:"rename,omitempty" yaml:"rename"`
SQLPackage string `json:"sql_package" yaml:"sql_package"`
SQLDriver string `json:"sql_driver" yaml:"sql_driver"`
OutputBatchFileName string `json:"output_batch_file_name,omitempty" yaml:"output_batch_file_name"`
OutputDBFileName string `json:"output_db_file_name,omitempty" yaml:"output_db_file_name"`
OutputModelsFileName string `json:"output_models_file_name,omitempty" yaml:"output_models_file_name"`
OutputQuerierFileName string `json:"output_querier_file_name,omitempty" yaml:"output_querier_file_name"`
OutputFilesSuffix string `json:"output_files_suffix,omitempty" yaml:"output_files_suffix"`
InflectionExcludeTableNames []string `json:"inflection_exclude_table_names,omitempty" yaml:"inflection_exclude_table_names"`
QueryParameterLimit *int32 `json:"query_parameter_limit,omitempty" yaml:"query_parameter_limit"`
}

type SQLJSON struct {
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading