Skip to content

Commit

Permalink
Merge pull request cockroachdb#75 from crowdflux/feature/selectJoin
Browse files Browse the repository at this point in the history
Feature/select join
  • Loading branch information
himanshu144141 authored Dec 9, 2016
2 parents 2c95a3b + c2b8f96 commit d598aa7
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
51 changes: 50 additions & 1 deletion app/DAL/clients/postgres/postgres_join.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ func (pg *postgres_db) SelectOneJoin(holder interface{}, query string, args ...i

// Get the underlying val of pointer
v = reflect.Indirect(v)

// get column names in order according to sql query
columns, err := r.Columns()
if err != nil {
Expand Down Expand Up @@ -123,3 +122,53 @@ func mapColumnsToInterfaces(inVal reflect.Value, columns []string) []interface{}
}
return rvalues
}

func (pg *postgres_db) SelectJoin(holder interface{}, query string, args ...interface{}) error {

//Db.query --> native sql drive's query method
r, err := pg.gorpDbMap.Db.Query(query, args...)
if err != nil {
return err
}

//verify the type and get the underlying value of array
t, err := toSliceType(holder)
if err != nil {
return err
}
v := reflect.New(t).Elem()
sliceValue := reflect.Indirect(reflect.ValueOf(holder))

for r.Next() {

// get column names in order according to sql query
columns, err := r.Columns()
if err != nil {
return err
}

rvalues := mapColumnsToInterfaces(v, columns)
err = r.Scan(rvalues...)
if err != nil {
return err
}
//This will append result to slice
sliceValue.Set(reflect.Append(sliceValue, v))
}
return nil
}

func toSliceType(i interface{}) (reflect.Type, error) {
t := reflect.TypeOf(i)
if t.Kind() != reflect.Ptr {
// If it's a slice, return a more helpful error message
if t.Kind() == reflect.Slice {
return nil, fmt.Errorf("gorp: Cannot Join into a non-pointer slice: %v", t)
}
return nil, fmt.Errorf("Invalid Type for Join: %v", t)
}
if t = t.Elem(); t.Kind() != reflect.Slice {
return nil, fmt.Errorf("Invalid Type for Join: %v", t)
}
return t.Elem(), nil
}
13 changes: 13 additions & 0 deletions app/DAL/clients/postgres/postgres_join_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,16 @@ func TestPostgres_db_SelectOneJoin(t *testing.T) {
assert.NoError(t, err)
assert.EqualValues(t, macroUser.User.ID.String(), macroUser.CreatorId.String())
}
func TestPostgres_db_SelectJoin(t *testing.T) {
pg := postgres.GetPostgresClient()

type MacroTaskWithCreator struct {
models.User
models.Client
}

var macroUser []MacroTaskWithCreator

err := pg.SelectJoin(&macroUser, `select * from users inner join clients on users.id = clients.user_id`)
assert.NoError(t, err)
}

0 comments on commit d598aa7

Please sign in to comment.