From 3e7e110590bc8b3e5ba7fb982194b34347aa2dd2 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sat, 26 Oct 2013 12:33:05 +0800 Subject: [PATCH] Can't believe this, Find works! --- orm.go | 6 ++---- orm_test.go | 8 ++++++++ sql.go | 24 ++++++++++++++++++++---- 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/orm.go b/orm.go index bcd97edf..83ba9d5c 100644 --- a/orm.go +++ b/orm.go @@ -85,14 +85,12 @@ func (s *Orm) Select(value interface{}) *Orm { } func (s *Orm) Save(value interface{}) *Orm { - s.explain(value, "Save") - s.Exec() + s.explain(value, "Save").Exec() return s } func (s *Orm) Delete(value interface{}) *Orm { - s.explain(value, "Delete") - s.Exec() + s.explain(value, "Delete").Exec() return s } diff --git a/orm_test.go b/orm_test.go index 7f872982..a1f87d43 100644 --- a/orm_test.go +++ b/orm_test.go @@ -26,6 +26,14 @@ func TestSaveAndFirst(t *testing.T) { if user.Name != "jinzhu" { t.Errorf("User should be saved and fetched correctly") } + + users := []User{} + db.Find(&users) + for _, user := range users { + if user.Name != "jinzhu" { + t.Errorf("User should be saved and fetched correctly") + } + } } func TestWhere(t *testing.T) { diff --git a/sql.go b/sql.go index ef1968d1..4e5a92f2 100644 --- a/sql.go +++ b/sql.go @@ -1,10 +1,9 @@ package gorm import ( + "fmt" "reflect" "strings" - - "fmt" ) func (s *Orm) explain(value interface{}, operation string) *Orm { @@ -26,11 +25,28 @@ func (s *Orm) querySql(out interface{}) { } func (s *Orm) query(out interface{}) { + var ( + is_slice bool + dest_type reflect.Type + ) + dest_out := reflect.Indirect(reflect.ValueOf(out)) + + if x := dest_out.Kind(); x == reflect.Slice { + is_slice = true + dest_type = dest_out.Type().Elem() + } + rows, err := s.db.Query(s.Sql) s.Error = err + for rows.Next() { - dest := reflect.ValueOf(out).Elem() - fmt.Printf("%+v", dest) + var dest reflect.Value + if is_slice { + dest = reflect.New(dest_type).Elem() + } else { + dest = reflect.ValueOf(out).Elem() + } + columns, _ := rows.Columns() var values []interface{} for _, value := range columns {