Skip to content

Commit

Permalink
Support binding of anonymous struct members
Browse files Browse the repository at this point in the history
  • Loading branch information
leporo committed Oct 7, 2021
1 parent b8e0a96 commit 80d957b
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 4 deletions.
6 changes: 5 additions & 1 deletion bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,13 @@ func BenchmarkManyFields(b *testing.B) {
}

func BenchmarkBind(b *testing.B) {
var u struct {
type Record struct {
ID int64 `db:"id"`
}
var u struct {
Record
Name string `db:"name"`
}

b.ResetTimer()

Expand Down
19 changes: 19 additions & 0 deletions executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,25 @@ func TestBind(t *testing.T) {
})
}

func TestBindNested(t *testing.T) {
forEveryDB(t, func(ctx context.Context, env *dbEnv) {
type Parent struct {
ID int64 `db:"id"`
}
var u struct {
Parent
Name string `db:"name"`
}
err := env.sqlf.From("users").
Bind(&u).
Where("id = ?", 2).
QueryRowAndClose(ctx, env.db)
assert.NoError(t, err, "Failed to execute a query: %v", err)
assert.Equal(t, "User 2", u.Name)
assert.EqualValues(t, 2, u.ID)
})
}

func TestExec(t *testing.T) {
forEveryDB(t, func(ctx context.Context, env *dbEnv) {
var (
Expand Down
14 changes: 11 additions & 3 deletions stmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -644,9 +644,17 @@ func (q *Stmt) Bind(data interface{}) *Stmt {

for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
dbFieldName := typ.Field(i).Tag.Get("db")
if dbFieldName != "" {
q.Select(dbFieldName).To(field.Addr().Interface())
switch field.Kind() {
case reflect.Struct:
t := typ.Field(i)
if t.Anonymous {
q.Bind(field.Addr().Interface())
}
default:
dbFieldName := typ.Field(i).Tag.Get("db")
if dbFieldName != "" {
q.Select(dbFieldName).To(field.Addr().Interface())
}
}
}
return q
Expand Down
19 changes: 19 additions & 0 deletions stmt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,22 @@ func TestLimit(t *testing.T) {
assert.Equal(t, "SELECT id FROM items WHERE id > ? LIMIT ?", q.String())
assert.Equal(t, []interface{}{42, 20}, q.Args())
}

func TestBindStruct(t *testing.T) {
type Parent struct {
ID int64 `db:"id"`
Skipped string
}
var u struct {
Parent
Name string `db:"name"`
Extra int64
}
q := sqlf.From("users").
Bind(&u).
Where("id = ?", 2)
defer q.Close()
assert.Equal(t, "SELECT id, name FROM users WHERE id = ?", q.String())
assert.Equal(t, []interface{}{2}, q.Args())
assert.EqualValues(t, []interface{}{&u.ID, &u.Name}, q.Dest())
}

0 comments on commit 80d957b

Please sign in to comment.