improve package gdb of empty value handling for struct convertion

This commit is contained in:
John Guo 2021-01-09 23:02:16 +08:00
parent 92b791eb08
commit bb2dad6d5e
2 changed files with 12 additions and 8 deletions

View File

@ -48,8 +48,11 @@ func (r Record) GMap() *gmap.StrAnyMap {
// Note that it returns sql.ErrNoRows if <r> is empty.
func (r Record) Struct(pointer interface{}) error {
// If the record is empty, it returns error.
if r.IsEmpty() && !empty.IsNil(pointer, true) {
return sql.ErrNoRows
if r.IsEmpty() {
if !empty.IsNil(pointer, true) {
return sql.ErrNoRows
}
return nil
}
// Special handling for parameter type: reflect.Value
if _, ok := pointer.(reflect.Value); ok {

View File

@ -7,6 +7,7 @@
package gdb_test
import (
"database/sql"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/os/gtime"
"github.com/gogf/gf/test/gtest"
@ -252,10 +253,10 @@ func Test_Struct_Empty(t *testing.T) {
}
gtest.C(t, func(t *gtest.T) {
one, err := db.Table(table).Where("id=100").One()
t.Assert(err, nil)
user := new(User)
t.AssertNE(one.Struct(user), nil)
err := db.Table(table).Where("id=100").Struct(user)
t.Assert(err, sql.ErrNoRows)
t.AssertNE(user, nil)
})
gtest.C(t, func(t *gtest.T) {
@ -267,10 +268,10 @@ func Test_Struct_Empty(t *testing.T) {
})
gtest.C(t, func(t *gtest.T) {
one, err := db.Table(table).Where("id=100").One()
t.Assert(err, nil)
var user *User
t.AssertNE(one.Struct(user), nil)
err := db.Table(table).Where("id=100").Struct(&user)
t.Assert(err, nil)
t.Assert(user, nil)
})
}