diff --git a/sqlstruct.go b/sqlstruct.go index bd9756b..402d10d 100644 --- a/sqlstruct.go +++ b/sqlstruct.go @@ -13,10 +13,20 @@ with "encoding/json" package. For example: + type T1 struct { + F4 string `sql:"field4"` + } + + type T2 struct { + F5 string `sql:"field5"` + } + type T struct { - F1 string - F2 string `sql:"field2"` - F3 string `sql:"-"` + F1 string + F2 string `sql:"field2"` + F3 string `sql:"-"` + fieldT1 T1 `sql:"..."` + T2 } rows, err := db.Query(fmt.Sprintf("SELECT %s FROM tablename", sqlstruct.Columns(T{}))) @@ -146,7 +156,7 @@ func getFieldInfo(typ reflect.Type) fieldInfo { } // Handle embedded structs - if f.Anonymous && f.Type.Kind() == reflect.Struct { + if (f.Anonymous || tag == "...") && f.Type.Kind() == reflect.Struct { for k, v := range getFieldInfo(f.Type) { finfo[k] = append([]int{i}, v...) } diff --git a/sqlstruct_test.go b/sqlstruct_test.go index be6e940..61b5b8e 100644 --- a/sqlstruct_test.go +++ b/sqlstruct_test.go @@ -25,6 +25,11 @@ type testType2 struct { FieldSec string `sql:"field_sec"` } +type testType3 struct { + FieldA string `sql:"field_a"` + EmbeddedType EmbeddedType `sql:"..."` +} + // testRows is a mock version of sql.Rows which can only scan strings type testRows struct { columns []string @@ -67,6 +72,16 @@ func TestColumns(t *testing.T) { } } +func TestColumnDeep(t *testing.T) { + var v testType3 + e := "field_a, field_e" + c := Columns(v) + + if c != e { + t.Errorf("expected %q got %q", e, c) + } +} + func TestColumnsAliased(t *testing.T) { var t1 testType var t2 testType2