Skip to content
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

Support JSON tags for nullable enum structs #2121

Merged
merged 13 commits into from
Jun 9, 2023
Merged
5 changes: 5 additions & 0 deletions docs/reference/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ The `gen` mapping supports the following keys:
- If true, autogenerated SQL statement can be exported to be accessed by another package.
- `emit_json_tags`:
- If true, add JSON tags to generated structs. Defaults to `false`.
- `emit_json_tags_on_null_enum_structs`:
- If true, and `emit_json_tags` is also true, add JSON tags to generated null enum structs. Defaults to `false`.
- `emit_result_struct_pointers`:
- If true, query results are returned as pointers to structs. Queries returning multiple results are returned as slices of pointers. Defaults to `false`.
- `emit_params_struct_pointers`:
Expand Down Expand Up @@ -341,6 +343,7 @@ packages:
emit_empty_slices: false
emit_exported_queries: false
emit_json_tags: true
emit_json_tags_on_null_enum_structs: true
emit_result_struct_pointers: false
emit_params_struct_pointers: false
emit_methods_with_db_argument: false
Expand Down Expand Up @@ -384,6 +387,8 @@ Each mapping in the `packages` collection has the following keys:
- If true, autogenerated SQL statement can be exported to be accessed by another package.
- `emit_json_tags`:
- If true, add JSON tags to generated structs. Defaults to `false`.
- `emit_json_tags_on_null_enum_structs`:
- If true, and `emit_json_tags` is also true, add JSON tags to generated null enum structs. Defaults to `false`.
- `emit_result_struct_pointers`:
- If true, query results are returned as pointers to structs. Queries returning multiple results are returned as slices of pointers. Defaults to `false`.
- `emit_params_struct_pointers`:
Expand Down
51 changes: 26 additions & 25 deletions internal/cmd/shim.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,31 +81,32 @@ func pluginGoCode(s config.SQLGo) *plugin.GoCode {
}

return &plugin.GoCode{
EmitInterface: s.EmitInterface,
EmitJsonTags: s.EmitJSONTags,
EmitDbTags: s.EmitDBTags,
EmitPreparedQueries: s.EmitPreparedQueries,
EmitExactTableNames: s.EmitExactTableNames,
EmitEmptySlices: s.EmitEmptySlices,
EmitExportedQueries: s.EmitExportedQueries,
EmitResultStructPointers: s.EmitResultStructPointers,
EmitParamsStructPointers: s.EmitParamsStructPointers,
EmitMethodsWithDbArgument: s.EmitMethodsWithDBArgument,
EmitPointersForNullTypes: s.EmitPointersForNullTypes,
EmitEnumValidMethod: s.EmitEnumValidMethod,
EmitAllEnumValues: s.EmitAllEnumValues,
JsonTagsCaseStyle: s.JSONTagsCaseStyle,
Package: s.Package,
Out: s.Out,
SqlPackage: s.SQLPackage,
SqlDriver: s.SQLDriver,
OutputDbFileName: s.OutputDBFileName,
OutputBatchFileName: s.OutputBatchFileName,
OutputModelsFileName: s.OutputModelsFileName,
OutputQuerierFileName: s.OutputQuerierFileName,
OutputFilesSuffix: s.OutputFilesSuffix,
InflectionExcludeTableNames: s.InflectionExcludeTableNames,
QueryParameterLimit: s.QueryParameterLimit,
EmitInterface: s.EmitInterface,
EmitJsonTags: s.EmitJSONTags,
EmitJsonTagsOnNullEnumStructs: s.EmitJSONTagsOnNullEnumStructs,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately, EmitJsonTagsOnNullEnumStructs is the longest config property name so causes go fmt to realign all the config structs, making the PR look a bit busier than it should in places like this.

EmitDbTags: s.EmitDBTags,
EmitPreparedQueries: s.EmitPreparedQueries,
EmitExactTableNames: s.EmitExactTableNames,
EmitEmptySlices: s.EmitEmptySlices,
EmitExportedQueries: s.EmitExportedQueries,
EmitResultStructPointers: s.EmitResultStructPointers,
EmitParamsStructPointers: s.EmitParamsStructPointers,
EmitMethodsWithDbArgument: s.EmitMethodsWithDBArgument,
EmitPointersForNullTypes: s.EmitPointersForNullTypes,
EmitEnumValidMethod: s.EmitEnumValidMethod,
EmitAllEnumValues: s.EmitAllEnumValues,
JsonTagsCaseStyle: s.JSONTagsCaseStyle,
Package: s.Package,
Out: s.Out,
SqlPackage: s.SQLPackage,
SqlDriver: s.SQLDriver,
OutputDbFileName: s.OutputDBFileName,
OutputBatchFileName: s.OutputBatchFileName,
OutputModelsFileName: s.OutputModelsFileName,
OutputQuerierFileName: s.OutputQuerierFileName,
OutputFilesSuffix: s.OutputFilesSuffix,
InflectionExcludeTableNames: s.InflectionExcludeTableNames,
QueryParameterLimit: s.QueryParameterLimit,
}
}

Expand Down
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
67 changes: 3 additions & 64 deletions internal/codegen/golang/field.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
package golang

import (
"fmt"
"sort"
"strings"

"github.com/kyleconroy/sqlc/internal/plugin"
"strings"
)

type Field struct {
Expand All @@ -15,76 +12,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))
}
}

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
}

func toLowerCase(str string) string {
if str == "" {
return ""
Expand Down
21 changes: 11 additions & 10 deletions internal/codegen/golang/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,17 @@ type tmplCtx struct {
// TODO: Race conditions
SourceName string

EmitJSONTags bool
EmitDBTags bool
EmitPreparedQueries bool
EmitInterface bool
EmitEmptySlices bool
EmitMethodsWithDBArgument bool
EmitEnumValidMethod bool
EmitAllEnumValues bool
UsesCopyFrom bool
UsesBatch bool
EmitJSONTags bool
EmitJSONTagsOnNullEnumStructs bool
EmitDBTags bool
EmitPreparedQueries bool
EmitInterface bool
EmitEmptySlices bool
EmitMethodsWithDBArgument bool
EmitEnumValidMethod bool
EmitAllEnumValues bool
UsesCopyFrom bool
UsesBatch bool
}

func (t *tmplCtx) OutputQuery(sourceName string) bool {
Expand Down
15 changes: 13 additions & 2 deletions internal/codegen/golang/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,21 @@ func buildEnums(req *plugin.CodeGenRequest) []Enum {
} else {
enumName = schema.Name + "_" + enum.Name
}

nameTags := map[string]string{}
validTags := map[string]string{}
if req.Settings.Go.EmitJsonTags && req.Settings.Go.EmitJsonTagsOnNullEnumStructs {
nameTags["json"] = JSONTagName(enumName, req.Settings)
validTags["json"] = JSONTagName("valid", req.Settings)
}

e := Enum{
Name: StructName(enumName, req.Settings),
Comment: enum.Comment,
Name: StructName(enumName, req.Settings),
Comment: enum.Comment,
NameTags: nameTags,
ValidTags: validTags,
}

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 @@ -116,33 +116,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
Loading