From dd719e451264a83f621674b14a3ffaf88ef4c5f9 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sun, 27 Oct 2013 09:50:11 +0800 Subject: [PATCH] Support select --- README.md | 2 -- orm_test.go | 13 ++++++++++++- sql.go | 10 +++++++++- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 73dcf1d2..3351915c 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,8 @@ Yet Another ORM library for Go, aims for developer friendly ## TODO -* Pluck * Order * Limit -* Select * Offset * Or query * Not query diff --git a/orm_test.go b/orm_test.go index e6570700..390dd94f 100644 --- a/orm_test.go +++ b/orm_test.go @@ -225,7 +225,18 @@ func TestComplexWhere(t *testing.T) { } } -func TestOrder(t *testing.T) { +func TestSelect(t *testing.T) { + var user User + db.Where("name = ?", "3").Select("name").Find(&user) + if user.Id != 0 { + t.Errorf("Should not got ID because I am only looking for age, %+v", user.Id) + } + if user.Name != "3" { + t.Errorf("Should got Name = 3 when searching it, %+v", user.Id) + } +} + +func TestPluck(t *testing.T) { var ages []int64 db.Model(&[]User{}).Order("age desc").Pluck("age", &ages) debug(ages) diff --git a/sql.go b/sql.go index 87b4c25f..7cffbffe 100644 --- a/sql.go +++ b/sql.go @@ -26,7 +26,7 @@ func (s *Orm) explain(value interface{}, operation string) *Orm { } func (s *Orm) querySql(out interface{}) { - s.Sql = fmt.Sprintf("SELECT * FROM %v %v", s.TableName, s.whereSql()) + s.Sql = fmt.Sprintf("SELECT %v FROM %v %v", s.selectSql(), s.TableName, s.whereSql()) return } @@ -190,6 +190,14 @@ func (s *Orm) whereSql() (sql string) { return } +func (s *Orm) selectSql() string { + if len(s.selectStr) == 0 { + return " * " + } else { + return s.selectStr + } +} + func (s *Orm) addToVars(value interface{}) string { s.SqlVars = append(s.SqlVars, value) return fmt.Sprintf("$%d", len(s.SqlVars))