From 03f7bbfe7415ab45c5901a4491a49100ff2f45af Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sat, 26 Oct 2013 15:02:14 +0800 Subject: [PATCH] When search one record, should return error when nothing found --- orm.go | 6 ++---- orm_test.go | 21 +++++++++++++++------ sql.go | 14 ++++++++++++-- 3 files changed, 29 insertions(+), 12 deletions(-) diff --git a/orm.go b/orm.go index 1207597d..99439d2e 100644 --- a/orm.go +++ b/orm.go @@ -1,11 +1,9 @@ package gorm import ( - "errors" - - "strconv" - "database/sql" + "errors" + "strconv" ) type Orm struct { diff --git a/orm_test.go b/orm_test.go index 2b934f2a..405ba0eb 100644 --- a/orm_test.go +++ b/orm_test.go @@ -1,10 +1,6 @@ package gorm -import ( - "fmt" - - "testing" -) +import "testing" type User struct { Name string @@ -43,6 +39,19 @@ func TestWhere(t *testing.T) { user := &User{} db.Where("Name = ?", "jinzhu").First(user) + if user.Name != "jinzhu" { + t.Errorf("Should found out user with name 'jinzhu'") + } - fmt.Println(user) + user = &User{} + orm := db.Where("Name = ?", "jinzhu-noexisting").First(user) + if orm.Error == nil { + t.Errorf("Should return error when looking for unexist record, %+v", user) + } + + users := &[]User{} + orm = db.Where("Name = ?", "jinzhu-noexisting").First(users) + if orm.Error != nil { + t.Errorf("Shouldn't return error when looking for unexist records, %+v", users) + } } diff --git a/sql.go b/sql.go index 67f6b60a..b729f6c7 100644 --- a/sql.go +++ b/sql.go @@ -1,6 +1,7 @@ package gorm import ( + "errors" "fmt" "reflect" "strconv" @@ -38,9 +39,16 @@ func (s *Orm) query(out interface{}) { } rows, err := s.db.Query(s.Sql, s.SqlVars...) - s.Error = err + defer rows.Close() + s.Error = err + if rows.Err() != nil { + s.Error = rows.Err() + } + + counts := 0 for rows.Next() { + counts += 1 var dest reflect.Value if is_slice { dest = reflect.New(dest_type).Elem() @@ -55,7 +63,9 @@ func (s *Orm) query(out interface{}) { } s.Error = rows.Scan(values...) } - return + if (counts == 0) && !is_slice { + s.Error = errors.New("Record not found!") + } } func (s *Orm) saveSql(value interface{}) {