Skip to content

Feature filter unused structs in models #2336

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

Closed
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions docs/reference/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ The `gen` mapping supports the following keys:
- `emit_all_enum_values`:
- If true, emit a function per enum type
that returns all valid enum values.
- `emit_filter_unused_models`:
- If true, emit a filter unused models for `models.go` file.
- `json_tags_case_style`:
- `camel` for camelCase, `pascal` for PascalCase, `snake` for snake_case or `none` to use the column name in the DB. Defaults to `none`.
- `output_batch_file_name`:
Expand Down
1 change: 1 addition & 0 deletions internal/cmd/shim.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ func pluginGoCode(s config.SQLGo) *plugin.GoCode {

return &plugin.GoCode{
EmitInterface: s.EmitInterface,
EmitFilterUnusedModels: s.EmitFilterUnusedModels,
EmitJsonTags: s.EmitJSONTags,
EmitDbTags: s.EmitDBTags,
EmitPreparedQueries: s.EmitPreparedQueries,
Expand Down
3 changes: 3 additions & 0 deletions internal/codegen/golang/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ func Generate(ctx context.Context, req *plugin.CodeGenRequest) (*plugin.CodeGenR
if err != nil {
return nil, err
}
if req.Settings.Go.EmitFilterUnusedModels {
enums, structs = removeUnused(enums, structs, queries)
}
return generate(req, enums, structs, queries)
}

Expand Down
62 changes: 62 additions & 0 deletions internal/codegen/golang/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -430,3 +430,65 @@ func checkIncompatibleFieldTypes(fields []Field) error {
}
return nil
}
func findStructByName(structs []Struct, structName string) (Struct, bool) {
for _, s := range structs {
if s.Name == structName {
return s, true
}
}
return Struct{}, false
}
func findEnumByName(enums []Enum, enumName string) (Enum, bool) {
for _, e := range enums {
if e.Name == enumName {
return e, true
}
}
return Enum{}, false
}

func removeUnused(enums []Enum, structs []Struct, queries []Query) ([]Enum, []Struct) {
filteredStructs := make(map[string]Struct, len(structs))
for _, query := range queries {
if query.hasRetType() && query.Ret.IsStruct() {
structName := query.Ret.Struct.Name
_, ok := filteredStructs[structName]
if !ok {
s, ok := findStructByName(structs, structName)
if ok {
filteredStructs[structName] = s
}
}
}
if query.Arg.IsStruct() {
structName := query.Arg.Struct.Name
_, ok := filteredStructs[structName]
if !ok {
s, ok := findStructByName(structs, structName)
if ok {
filteredStructs[structName] = s
}
}
}
}
filteredStructsSlice := make([]Struct, 0, len(filteredStructs))
filteredEnums := make(map[string]Enum, len(enums))
for _, s := range filteredStructs {
for _, field := range s.Fields {
if _, ok := filteredEnums[field.Type]; ok {
continue
}
enum, ok := findEnumByName(enums, field.Type)
if !ok {
continue
}
filteredEnums[field.Type] = enum
}
filteredStructsSlice = append(filteredStructsSlice, s)
}
filteredEnumsSlice := make([]Enum, 0, len(filteredEnums))
for _, enum := range filteredEnums {
filteredEnumsSlice = append(filteredEnumsSlice, enum)
}
return filteredEnumsSlice, filteredStructsSlice
}
134 changes: 134 additions & 0 deletions internal/codegen/golang/result_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package golang

import (
"reflect"
"testing"

"github.com/kyleconroy/sqlc/internal/metadata"
Expand Down Expand Up @@ -76,3 +77,136 @@ func TestPutOutColumns_AlwaysTrueWhenQueryHasColumns(t *testing.T) {
t.Error("should be true when we have columns")
}
}

func Test_removeUnused(t *testing.T) {
type args struct {
enums []Enum
structs []Struct
queries []Query
}
tests := []struct {
name string
args args
want map[string]Enum
want1 map[string]Struct
}{
{
name: "remove unused structs and enums",
args: args{
enums: []Enum{
{
Name: "enum1",
},
{
Name: "enum2",
},
},
structs: []Struct{
{
Name: "struct1",
},
{
Name: "struct2",
},
{
Name: "struct3",
},
{
Name: "struct4",
Fields: []Field{
{
Type: "enum1",
},
{
Type: "notenum",
},
},
},
{
Name: "struct5",
},
},
queries: []Query{
{
Cmd: metadata.CmdOne,
Ret: QueryValue{
Struct: &Struct{
Name: "struct1",
},
},
Arg: QueryValue{
Struct: &Struct{
Name: "struct2",
},
},
},
{
Cmd: metadata.CmdOne,
Ret: QueryValue{
Struct: &Struct{
Name: "struct3",
},
},
Arg: QueryValue{
Struct: &Struct{
Name: "struct4",
Fields: []Field{
{
Type: "enum1",
},
{
Type: "notenum",
},
},
},
},
},
},
},
want: map[string]Enum{
"enum1": {Name: "enum1"},
},
want1: map[string]Struct{
"struct1": {
Name: "struct1",
},
"struct2": {
Name: "struct2",
},
"struct3": {
Name: "struct3",
},
"struct4": {
Name: "struct4",
Fields: []Field{
{
Type: "enum1",
},
{
Type: "notenum",
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, got1 := removeUnused(tt.args.enums, tt.args.structs, tt.args.queries)
gotMap := map[string]Enum{}
got1Map := map[string]Struct{}
for _, enum := range got {
gotMap[enum.Name] = enum
}
for _, s := range got1 {
got1Map[s.Name] = s
}
if !reflect.DeepEqual(gotMap, tt.want) {
t.Errorf("removeUnused() got = %v, want %v", got, tt.want)
}
if !reflect.DeepEqual(got1Map, tt.want1) {
t.Errorf("removeUnused() got1 = %v, want %v", got1, tt.want1)
}
})
}
}
1 change: 1 addition & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ type SQLGen struct {

type SQLGo struct {
EmitInterface bool `json:"emit_interface" yaml:"emit_interface"`
EmitFilterUnusedModels bool `json:"emit_filter_unused_models" yaml:"emit_filter_unused_models"`
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"`
Expand Down
2 changes: 2 additions & 0 deletions internal/config/v_one.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type v1PackageSettings struct {
Schema Paths `json:"schema" yaml:"schema"`
Queries Paths `json:"queries" yaml:"queries"`
EmitInterface bool `json:"emit_interface" yaml:"emit_interface"`
EmitFilterUnusedModels bool `json:"emit_filter_unused_models" yaml:"emit_filter_unused_models"`
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"`
Expand Down Expand Up @@ -142,6 +143,7 @@ func (c *V1GenerateSettings) Translate() Config {
Gen: SQLGen{
Go: &SQLGo{
EmitInterface: pkg.EmitInterface,
EmitFilterUnusedModels: pkg.EmitFilterUnusedModels,
EmitJSONTags: pkg.EmitJSONTags,
EmitDBTags: pkg.EmitDBTags,
EmitPreparedQueries: pkg.EmitPreparedQueries,
Expand Down
3 changes: 2 additions & 1 deletion internal/endtoend/testdata/codegen_json/gen/codegen.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"inflection_exclude_table_names": [],
"emit_pointers_for_null_types": false,
"query_parameter_limit": 1,
"output_batch_file_name": ""
"output_batch_file_name": "",
"emit_filter_unused_models": false
},
"json": {
"out": "gen",
Expand Down
Loading