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

Refactor schema merging logic for embedded fields #4

Merged
merged 1 commit into from
Feb 28, 2024
Merged
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
18 changes: 16 additions & 2 deletions infer.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ func Infer(data any) (bigquery.Schema, error) {

func inferObject(data reflect.Value) (bigquery.Schema, error) {
var schema bigquery.Schema
var embedded bigquery.Schema

switch data.Kind() {
case reflect.Ptr, reflect.Interface:
Expand All @@ -29,11 +30,11 @@ func inferObject(data reflect.Value) (bigquery.Schema, error) {

fieldInfo := data.Type().Field(i)
if fieldInfo.Anonymous {
embeddedSchema, err := inferObject(field)
resp, err := inferObject(field)
if err != nil {
return nil, err
}
schema = append(schema, embeddedSchema...)
embedded = append(embedded, resp...)
continue
}

Expand Down Expand Up @@ -69,6 +70,19 @@ func inferObject(data reflect.Value) (bigquery.Schema, error) {
return nil, fmt.Errorf("invalid data: %v: %w", data.Kind(), ErrUnsupportedObject)
}

for _, field := range embedded {
var found bool
for _, f := range schema {
if f.Name == field.Name {
found = true
break
}
}
if !found {
schema = append(schema, field)
}
}

return schema, nil
}

Expand Down
22 changes: 17 additions & 5 deletions infer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -476,21 +476,33 @@ func TestInferArray(t *testing.T) {

func TestInferMixIn(t *testing.T) {
type Nest struct {
Str string
Prev string
Str string
Next string
}
type mix struct {
Prev int
Nest
Int int
Next int
Int int
}

schemas := gt.R1(bqs.Infer(mix{})).NoError(t)
gt.A(t, schemas).Length(2).
gt.A(t, schemas).Length(4).
At(0, func(t testing.TB, v *bigquery.FieldSchema) {
gt.Equal(t, v.Name, "Str")
gt.Equal(t, v.Type, bigquery.StringFieldType)
gt.Equal(t, v.Name, "Prev")
gt.Equal(t, v.Type, bigquery.IntegerFieldType)
}).
At(1, func(t testing.TB, v *bigquery.FieldSchema) {
gt.Equal(t, v.Name, "Next")
gt.Equal(t, v.Type, bigquery.IntegerFieldType)
}).
At(2, func(t testing.TB, v *bigquery.FieldSchema) {
gt.Equal(t, v.Name, "Int")
gt.Equal(t, v.Type, bigquery.IntegerFieldType)
}).
At(3, func(t testing.TB, v *bigquery.FieldSchema) {
gt.Equal(t, v.Name, "Str")
gt.Equal(t, v.Type, bigquery.StringFieldType)
})
}
Loading