Skip to content
This repository has been archived by the owner on Nov 27, 2023. It is now read-only.

Commit

Permalink
Be able to pass pointer struct as data
Browse files Browse the repository at this point in the history
  • Loading branch information
YamiOdymel committed Mar 4, 2021
1 parent 702b17e commit fd7b722
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
14 changes: 12 additions & 2 deletions query_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -553,8 +553,18 @@ func (q *Query) flattenH(data H) (columns []string, values []interface{}) {
func (q *Query) structToH(data interface{}) H {
h := make(H)

t := reflect.TypeOf(data)
v := reflect.ValueOf(data)
var t reflect.Type
var v reflect.Value

// Get the real data type underneath the pointer if the data is a pointer.
if reflect.TypeOf(data).Kind() == reflect.Ptr {
t = reflect.Indirect(reflect.ValueOf(data)).Type()
v = reflect.Indirect(reflect.ValueOf(data))
} else {
t = reflect.TypeOf(data)
v = reflect.ValueOf(data)
}

for i := 0; i < t.NumField(); i++ {
k := t.Field(i).Name
if name, ok := t.Field(i).Tag.Lookup("rushia"); ok {
Expand Down
15 changes: 15 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,21 @@ func TestInsertStruct(t *testing.T) {
assertParams(assert, []interface{}{"YamiOdymel", "test"}, params)
}

func TestInsertStructPointer(t *testing.T) {
type user struct {
Username string
Password string
}
u := &user{
Username: "YamiOdymel",
Password: "test",
}
assert := assert.New(t)
query, params := Build(NewQuery("Users").Insert(u))
assertEqual(assert, "INSERT INTO Users (Username, Password) VALUES (?, ?)", query)
assertParams(assert, []interface{}{"YamiOdymel", "test"}, params)
}

func TestInsert(t *testing.T) {
assert := assert.New(t)
query, params := Build(NewQuery("Users").Insert(H{
Expand Down

0 comments on commit fd7b722

Please sign in to comment.