Skip to content

Commit 3d025a2

Browse files
committed
fix: Use field name in json type schema if json tag is missing
1 parent b12dc10 commit 3d025a2

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

transformers/name.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,16 @@ func DefaultNameTransformer(field reflect.StructField) (string, error) {
2626
return defaultCaser.ToSnake(name), nil
2727
}
2828

29+
func JsonTagOrFieldName(field reflect.StructField) (string, error) {
30+
name := field.Name
31+
if jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]; len(jsonTag) > 0 {
32+
// return empty string if the field is not related api response
33+
if jsonTag == "-" {
34+
return "", nil
35+
}
36+
return jsonTag, nil
37+
}
38+
return name, nil
39+
}
40+
2941
var _ NameTransformer = DefaultNameTransformer

transformers/struct.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ func (t *structTransformer) fieldToJSONSchema(field reflect.StructField, depth i
284284
if !structField.IsExported() || isTypeIgnored(structField.Type) {
285285
continue
286286
}
287-
name, err := t.nameTransformer(structField)
287+
name, err := JsonTagOrFieldName(structField)
288288
if err != nil {
289289
continue
290290
}

transformers/struct_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"github.com/cloudquery/plugin-sdk/v4/schema"
1313
"github.com/cloudquery/plugin-sdk/v4/types"
1414
"github.com/google/go-cmp/cmp"
15+
"github.com/stretchr/testify/require"
1516
)
1617

1718
type (
@@ -665,6 +666,23 @@ func TestJSONTypeSchema(t *testing.T) {
665666
"item": `{"exported":"utf8"}`,
666667
},
667668
},
669+
{
670+
name: "no json tags",
671+
testStruct: struct {
672+
Tags map[string]string
673+
Item struct {
674+
Name string
675+
Tags map[string]string
676+
FlatItems []string
677+
ComplexItems []struct {
678+
Name string
679+
}
680+
}
681+
}{},
682+
want: map[string]string{
683+
"item": `{"ComplexItems":[{"Name":"utf8"}],"FlatItems":["utf8"],"Name":"utf8","Tags":{"utf8":"utf8"}}`,
684+
},
685+
},
668686
}
669687

670688
for _, tt := range tests {
@@ -684,6 +702,7 @@ func TestJSONTypeSchema(t *testing.T) {
684702
}
685703
for col, schema := range tt.want {
686704
column := table.Column(col)
705+
require.NotNil(t, column, "column %q not found", col)
687706
if diff := cmp.Diff(column.TypeSchema, schema); diff != "" {
688707
t.Fatalf("table does not match expected. diff (-got, +want): %v", diff)
689708
}

0 commit comments

Comments
 (0)