Skip to content

Commit

Permalink
Allow recursion using ...
Browse files Browse the repository at this point in the history
  • Loading branch information
SilverCory committed Mar 23, 2021
1 parent 5f3e10d commit f39c372
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
18 changes: 14 additions & 4 deletions sqlstruct.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{})))
Expand Down Expand Up @@ -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...)
}
Expand Down
15 changes: 15 additions & 0 deletions sqlstruct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit f39c372

Please sign in to comment.