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
import (
"errors"
"strconv"
"database/sql"
"errors"
"strconv"
)
type Orm struct {

View File

@ -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)
fmt.Println(user)
if user.Name != "jinzhu" {
t.Errorf("Should found out user with name 'jinzhu'")
}
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
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{}) {