improve Record.Struct for package gdb

This commit is contained in:
John
2020-04-29 09:12:13 +08:00
parent 1e844d505a
commit 8a13d94526
3 changed files with 8 additions and 9 deletions

View File

@ -44,9 +44,12 @@ func (r Record) GMap() *gmap.StrAnyMap {
// Struct converts <r> to a struct.
// Note that the parameter <pointer> should be type of *struct/**struct.
//
// Note that if returns error if <r> is nil an given <pointer> is a pointer to an existing
// struct.
// 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() {
return sql.ErrNoRows
}
// Special handling for parameter type: reflect.Value
if _, ok := pointer.(reflect.Value); ok {
return mapToStruct(r.Map(), pointer)
@ -66,10 +69,6 @@ func (r Record) Struct(pointer interface{}) error {
if reflectKind != reflect.Ptr && reflectKind != reflect.Struct {
return errors.New("parameter should be type of *struct/**struct")
}
// If the record is nil, check if returning error.
if r == nil && reflectKind == reflect.Struct {
return sql.ErrNoRows
}
return mapToStruct(r.Map(), pointer)
}

View File

@ -153,12 +153,12 @@ func (r Result) Structs(pointer interface{}) (err error) {
reflectKind = reflectValue.Kind()
)
if reflectKind != reflect.Ptr {
return fmt.Errorf("pointer should be type of pointer to struct slice, but got: %v", reflectKind)
return fmt.Errorf("parameter should be type of *[]struct/*[]*struct, but got: %v", reflectKind)
}
reflectValue = reflectValue.Elem()
reflectKind = reflectValue.Kind()
if reflectKind != reflect.Slice && reflectKind != reflect.Array {
return fmt.Errorf("pointer should be type of pointer to struct slice, but got: %v", reflectKind)
return fmt.Errorf("parameter should be type of *[]struct/*[]*struct, but got: %v", reflectKind)
}
length := len(r)
if length == 0 {

View File

@ -118,7 +118,7 @@ func Test_Struct_Empty(t *testing.T) {
one, err := db.Table(table).Where("id=100").One()
t.Assert(err, nil)
var user *User
t.Assert(one.Struct(&user), nil)
t.AssertNE(one.Struct(&user), nil)
})
gtest.C(t, func(t *gtest.T) {