From 0491675ae87abc57b323328e95862bf91dbe6c81 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sat, 26 Oct 2013 11:59:58 +0800 Subject: [PATCH] Break find code into sql.go file --- orm.go | 17 ++--------------- sql.go | 26 +++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/orm.go b/orm.go index e1001cf1..bcd97edf 100644 --- a/orm.go +++ b/orm.go @@ -2,8 +2,6 @@ package gorm import ( "errors" - "fmt" - "reflect" "strconv" @@ -116,23 +114,12 @@ func (s *Orm) Exec(sql ...string) *Orm { } func (s *Orm) First(out interface{}) *Orm { - s.setModel(out) - rows, err := s.db.Query("SELECT * from users limit 1") - s.Error = err - for rows.Next() { - dest := reflect.ValueOf(out).Elem() - fmt.Printf("%+v", dest) - columns, _ := rows.Columns() - var values []interface{} - for _, value := range columns { - values = append(values, dest.FieldByName(value).Addr().Interface()) - } - s.Error = rows.Scan(values...) - } + s.explain(out, "Query").query(out) return s } func (s *Orm) Find(out interface{}) *Orm { + s.explain(out, "Query").query(out) return s } diff --git a/sql.go b/sql.go index e39c6242..ef1968d1 100644 --- a/sql.go +++ b/sql.go @@ -1,18 +1,42 @@ package gorm import ( + "reflect" "strings" "fmt" ) -func (s *Orm) explain(value interface{}, operation string) { +func (s *Orm) explain(value interface{}, operation string) *Orm { s.setModel(value) switch operation { case "Save": s.saveSql(value) case "Delete": s.deleteSql(value) + case "Query": + s.querySql(value) + } + return s +} + +func (s *Orm) querySql(out interface{}) { + s.Sql = "SELECT * from users limit 1" + return +} + +func (s *Orm) query(out interface{}) { + rows, err := s.db.Query(s.Sql) + s.Error = err + for rows.Next() { + dest := reflect.ValueOf(out).Elem() + fmt.Printf("%+v", dest) + columns, _ := rows.Columns() + var values []interface{} + for _, value := range columns { + values = append(values, dest.FieldByName(value).Addr().Interface()) + } + s.Error = rows.Scan(values...) } return }