From b46e2afc4a5fca825c959545b92eef9cd8c83d53 Mon Sep 17 00:00:00 2001 From: kinggo <30891428+longlihale@users.noreply.github.com> Date: Fri, 8 Oct 2021 13:47:01 +0800 Subject: [PATCH] fix : update miss where's condition when primary key use "<-:create" tag (#4738) * fix:update miss where condition * fix:rename test case --- callbacks/update.go | 4 ++-- tests/upsert_test.go | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/callbacks/update.go b/callbacks/update.go index 7d5ea4a4..a0a2c579 100644 --- a/callbacks/update.go +++ b/callbacks/update.go @@ -235,7 +235,7 @@ func ConvertToAssignments(stmt *gorm.Statement) (set clause.Set) { case reflect.Struct: set = make([]clause.Assignment, 0, len(stmt.Schema.FieldsByDBName)) for _, dbName := range stmt.Schema.DBNames { - if field := updatingSchema.LookUpField(dbName); field != nil && field.Updatable { + if field := updatingSchema.LookUpField(dbName); field != nil { if !field.PrimaryKey || !updatingValue.CanAddr() || stmt.Dest != stmt.Model { if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && (!restricted || (!stmt.SkipHooks && field.AutoUpdateTime > 0))) { value, isZero := field.ValueOf(updatingValue) @@ -252,7 +252,7 @@ func ConvertToAssignments(stmt *gorm.Statement) (set clause.Set) { isZero = false } - if ok || !isZero { + if (ok || !isZero) && field.Updatable { set = append(set, clause.Assignment{Column: clause.Column{Name: field.DBName}, Value: value}) assignValue(field, value) } diff --git a/tests/upsert_test.go b/tests/upsert_test.go index 0e247caa..a7b53ab7 100644 --- a/tests/upsert_test.go +++ b/tests/upsert_test.go @@ -309,3 +309,22 @@ func TestFindOrCreate(t *testing.T) { t.Errorf("belongs to association should be saved") } } + +func TestUpdateWithMissWhere(t *testing.T) { + type User struct { + ID uint `gorm:"column:id;<-:create"` + Name string `gorm:"column:name"` + } + user := User{ID: 1, Name: "king"} + tx := DB.Session(&gorm.Session{DryRun: true}).Save(&user) + + if err := tx.Error; err != nil { + t.Fatalf("failed to update user,missing where condtion,err=%+v", err) + + } + + if !regexp.MustCompile("WHERE .id. = [^ ]+$").MatchString(tx.Statement.SQL.String()) { + t.Fatalf("invalid updating SQL, got %v", tx.Statement.SQL.String()) + } + +}