From afac9e27a74e7abc743e7661e1ff5e080fe073b0 Mon Sep 17 00:00:00 2001 From: Deviller Date: Thu, 19 Nov 2020 12:15:58 +0300 Subject: [PATCH] Fix Association.Replace() error returning --- association.go | 4 ++-- tests/associations_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/association.go b/association.go index 0f2102f7..7adb8c91 100644 --- a/association.go +++ b/association.go @@ -118,7 +118,7 @@ func (association *Association) Replace(values ...interface{}) error { if _, pvs := schema.GetIdentityFieldValuesMap(reflectValue, primaryFields); len(pvs) > 0 { column, values := schema.ToQueryValues(rel.FieldSchema.Table, foreignKeys, pvs) - tx.Where(clause.IN{Column: column, Values: values}).UpdateColumns(updateMap) + association.Error = tx.Where(clause.IN{Column: column, Values: values}).UpdateColumns(updateMap).Error } case schema.Many2Many: var ( @@ -154,7 +154,7 @@ func (association *Association) Replace(values ...interface{}) error { tx.Where(clause.Not(clause.IN{Column: relColumn, Values: relValues})) } - tx.Delete(modelValue) + association.Error = tx.Delete(modelValue).Error } } return association.Error diff --git a/tests/associations_test.go b/tests/associations_test.go index c1a4e2b2..cb76b7bd 100644 --- a/tests/associations_test.go +++ b/tests/associations_test.go @@ -32,6 +32,41 @@ func TestInvalidAssociation(t *testing.T) { } } +func TestAssociationNotNullClear(t *testing.T) { + type Profile struct { + ID uint + Number string + MemberID uint `gorm:"not null"` + } + + type Member struct { + ID uint + Profiles []Profile + } + + DB.Migrator().DropTable(&Member{}, &Profile{}) + + if err := DB.AutoMigrate(&Member{}, &Profile{}); err != nil { + t.Fatalf("Failed to migrate, got error: %v", err) + } + + member := &Member{ + Profiles: []Profile{{ + Number: "1", + }, { + Number: "2", + }}, + } + + if err := DB.Create(&member).Error; err != nil { + t.Fatalf("Failed to create test data, got error: %v", err) + } + + if err := DB.Model(member).Association("Profiles").Clear(); err == nil { + t.Fatalf("No error occured during clearind not null association") + } +} + func TestForeignKeyConstraints(t *testing.T) { type Profile struct { ID uint