From 5fffde3d34fddf95b3383b74f9e4175287eda952 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Garcia?= Date: Thu, 23 Dec 2021 23:06:29 -0300 Subject: [PATCH] Ignore structs not tagged with tablename on joined structs --- ksql.go | 15 ++++++++++++--- ksql_test.go | 5 +++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/ksql.go b/ksql.go index 8c525fc..7bc5848 100644 --- a/ksql.go +++ b/ksql.go @@ -985,6 +985,10 @@ func scanRowsFromType( func getScanArgsForNestedStructs(dialect Dialect, rows Rows, t reflect.Type, v reflect.Value, info kstructs.StructInfo) ([]interface{}, error) { scanArgs := []interface{}{} for i := 0; i < v.NumField(); i++ { + if !info.ByIndex(i).Valid { + continue + } + // TODO(vingarcia00): Handle case where type is pointer nestedStructInfo, err := kstructs.GetTagInfo(t.Field(i).Type) if err != nil { @@ -1151,7 +1155,12 @@ func buildSelectQueryForNestedStructs( ) (string, error) { var fields []string for i := 0; i < structType.NumField(); i++ { - nestedStructName := info.ByIndex(i).Name + nestedStructInfo := info.ByIndex(i) + if !nestedStructInfo.Valid { + continue + } + + nestedStructName := nestedStructInfo.Name nestedStructType := structType.Field(i).Type if nestedStructType.Kind() != reflect.Struct { return "", fmt.Errorf( @@ -1160,13 +1169,13 @@ func buildSelectQueryForNestedStructs( ) } - nestedStructInfo, err := kstructs.GetTagInfo(nestedStructType) + nestedStructTagInfo, err := kstructs.GetTagInfo(nestedStructType) if err != nil { return "", err } for j := 0; j < structType.Field(i).Type.NumField(); j++ { - fieldInfo := nestedStructInfo.ByIndex(j) + fieldInfo := nestedStructTagInfo.ByIndex(j) if !fieldInfo.Valid { continue } diff --git a/ksql_test.go b/ksql_test.go index 047ae98..5fe772e 100644 --- a/ksql_test.go +++ b/ksql_test.go @@ -192,6 +192,11 @@ func TestQuery(t *testing.T) { var rows []struct { User User `tablename:"u"` Post Post `tablename:"p"` + + // This one has no ksql or tablename tag, + // so it should just be ignored to avoid strange + // unexpected errors: + ExtraStructThatShouldBeIgnored User } err = c.Query(ctx, &rows, fmt.Sprint( `FROM users u JOIN posts p ON p.user_id = u.id`,