mirror of https://github.com/go-gorm/gorm.git
When search one record, should return error when nothing found
This commit is contained in:
parent
e935b4772b
commit
03f7bbfe74
6
orm.go
6
orm.go
|
@ -1,11 +1,9 @@
|
||||||
package gorm
|
package gorm
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Orm struct {
|
type Orm struct {
|
||||||
|
|
21
orm_test.go
21
orm_test.go
|
@ -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
14
sql.go
|
@ -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{}) {
|
||||||
|
|
Loading…
Reference in New Issue