From 89b7cbe89ca97f5fd395cd7bdbe4944e291271b8 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Fri, 21 Oct 2016 11:30:17 +0800 Subject: [PATCH] Fix RowsAffected not returned for FirstOrCreate --- main.go | 6 +++--- main_test.go | 10 ++++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 52a536d0..d5582685 100644 --- a/main.go +++ b/main.go @@ -330,13 +330,13 @@ func (s *DB) FirstOrInit(out interface{}, where ...interface{}) *DB { // https://jinzhu.github.io/gorm/curd.html#firstorcreate func (s *DB) FirstOrCreate(out interface{}, where ...interface{}) *DB { c := s.clone() - if result := c.First(out, where...); result.Error != nil { + if result := s.First(out, where...); result.Error != nil { if !result.RecordNotFound() { return result } - c.AddError(c.NewScope(out).inlineCondition(where...).initialize().callCallbacks(c.parent.callbacks.creates).db.Error) + return c.NewScope(out).inlineCondition(where...).initialize().callCallbacks(c.parent.callbacks.creates).db } else if len(c.search.assignAttrs) > 0 { - c.AddError(c.NewScope(out).InstanceSet("gorm:update_interface", c.search.assignAttrs).callCallbacks(c.parent.callbacks.updates).db.Error) + return c.NewScope(out).InstanceSet("gorm:update_interface", c.search.assignAttrs).callCallbacks(c.parent.callbacks.updates).db } return c } diff --git a/main_test.go b/main_test.go index 3084b733..7b62f46f 100644 --- a/main_test.go +++ b/main_test.go @@ -315,8 +315,14 @@ func TestNullValuesWithFirstOrCreate(t *testing.T) { } var nv2 NullValue - if err := DB.Where(nv1).FirstOrCreate(&nv2).Error; err != nil { - t.Errorf("Should not raise any error, but got %v", err) + result := DB.Where(nv1).FirstOrCreate(&nv2) + + if result.RowsAffected != 1 { + t.Errorf("RowsAffected should be 1 after create some record") + } + + if result.Error != nil { + t.Errorf("Should not raise any error, but got %v", result.Error) } if nv2.Name.String != "first_or_create" || nv2.Gender.String != "M" {