From 8a13d945262cad22b80a835601c2b4e70a00fe4a Mon Sep 17 00:00:00 2001 From: John Date: Wed, 29 Apr 2020 09:12:13 +0800 Subject: [PATCH] improve Record.Struct for package gdb --- database/gdb/gdb_type_record.go | 11 +++++------ database/gdb/gdb_type_result.go | 4 ++-- database/gdb/gdb_unit_z_mysql_struct_test.go | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/database/gdb/gdb_type_record.go b/database/gdb/gdb_type_record.go index 04582b5b8..fc58ac095 100644 --- a/database/gdb/gdb_type_record.go +++ b/database/gdb/gdb_type_record.go @@ -44,9 +44,12 @@ func (r Record) GMap() *gmap.StrAnyMap { // Struct converts to a struct. // Note that the parameter should be type of *struct/**struct. // -// Note that if returns error if is nil an given is a pointer to an existing -// struct. +// Note that it returns sql.ErrNoRows if 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) } diff --git a/database/gdb/gdb_type_result.go b/database/gdb/gdb_type_result.go index 34a90b7d0..bb6eaa63f 100644 --- a/database/gdb/gdb_type_result.go +++ b/database/gdb/gdb_type_result.go @@ -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 { diff --git a/database/gdb/gdb_unit_z_mysql_struct_test.go b/database/gdb/gdb_unit_z_mysql_struct_test.go index 845e4b85d..d0c4a7000 100644 --- a/database/gdb/gdb_unit_z_mysql_struct_test.go +++ b/database/gdb/gdb_unit_z_mysql_struct_test.go @@ -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) {