From fd3ed7ffafd20468af9fa9c526f8c3f51f2bcfa8 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 29 Oct 2013 16:11:51 +0800 Subject: [PATCH] Should fill data to smaller struct correctly --- do.go | 5 ++++- gorm_test.go | 20 ++++++++++++++++---- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/do.go b/do.go index 77d0ea88..796e452f 100644 --- a/do.go +++ b/do.go @@ -250,7 +250,10 @@ func (s *Do) query(where ...interface{}) { for _, value := range columns { field := dest.FieldByName(snakeToUpperCamel(value)) if field.IsValid() { - values = append(values, dest.FieldByName(snakeToUpperCamel(value)).Addr().Interface()) + values = append(values, field.Addr().Interface()) + } else { + var null interface{} + values = append(values, &null) } } s.err(rows.Scan(values...)) diff --git a/gorm_test.go b/gorm_test.go index 5926e576..f7d3f095 100644 --- a/gorm_test.go +++ b/gorm_test.go @@ -558,6 +558,22 @@ func TestRunCallbacksAndGetErrors(t *testing.T) { } } +func TestFillSmallerStructCorrectly(t *testing.T) { + type SimpleUser struct { + Name string + Id int64 + UpdatedAt time.Time + CreatedAt time.Time + } + + var simple_user SimpleUser + db.Table("users").Find(&simple_user) + + if simple_user.Id == 0 || simple_user.Name == "" { + t.Errorf("Should fill data correctly even some column missing") + } +} + func TestNoUnExpectedHappenWithInvalidSql(t *testing.T) { var columns []string if db.Where("sdsd.zaaa = ?", "sd;;;aa").Pluck("aaa", &columns).Error == nil { @@ -611,10 +627,6 @@ func TestSetTableDirectly(t *testing.T) { t.Errorf("Should got some errors if set table to an unexisting table") } - if db.Table("products").Find(&users).Error == nil { - t.Errorf("Should got some errors if set table to an unexisting table") - } - db.Exec("drop table deleted_users;") if db.Table("deleted_users").CreateTable(&User{}).Error != nil { t.Errorf("Should create deleted_users table")