When search one record, should return error when nothing found

This commit is contained in:
Jinzhu 2013-10-26 15:02:14 +08:00
parent e935b4772b
commit 03f7bbfe74
3 changed files with 29 additions and 12 deletions

6
orm.go
View File

@ -1,11 +1,9 @@
package gorm package gorm
import ( import (
"errors"
"strconv"
"database/sql" "database/sql"
"errors"
"strconv"
) )
type Orm struct { type Orm struct {

View File

@ -1,10 +1,6 @@
package gorm package gorm
import ( import "testing"
"fmt"
"testing"
)
type User struct { type User struct {
Name string Name string
@ -43,6 +39,19 @@ func TestWhere(t *testing.T) {
user := &User{} user := &User{}
db.Where("Name = ?", "jinzhu").First(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)
}
} }

14
sql.go
View File

@ -1,6 +1,7 @@
package gorm package gorm
import ( import (
"errors"
"fmt" "fmt"
"reflect" "reflect"
"strconv" "strconv"
@ -38,9 +39,16 @@ func (s *Orm) query(out interface{}) {
} }
rows, err := s.db.Query(s.Sql, s.SqlVars...) 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() { for rows.Next() {
counts += 1
var dest reflect.Value var dest reflect.Value
if is_slice { if is_slice {
dest = reflect.New(dest_type).Elem() dest = reflect.New(dest_type).Elem()
@ -55,7 +63,9 @@ func (s *Orm) query(out interface{}) {
} }
s.Error = rows.Scan(values...) s.Error = rows.Scan(values...)
} }
return if (counts == 0) && !is_slice {
s.Error = errors.New("Record not found!")
}
} }
func (s *Orm) saveSql(value interface{}) { func (s *Orm) saveSql(value interface{}) {