From 3dfa8a66f1bef0a7469c34968cb298c208e59fb9 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 25 Aug 2020 17:27:28 +0800 Subject: [PATCH] Fix panic when delet without pointer, close #3308 --- callbacks/delete.go | 12 ++++++------ soft_delete.go | 5 ----- tests/delete_test.go | 4 ++++ 3 files changed, 10 insertions(+), 11 deletions(-) diff --git a/callbacks/delete.go b/callbacks/delete.go index f444f020..76b78fb4 100644 --- a/callbacks/delete.go +++ b/callbacks/delete.go @@ -41,7 +41,7 @@ func Delete(db *gorm.DB) { db.Statement.AddClause(clause.Where{Exprs: []clause.Expression{clause.IN{Column: column, Values: values}}}) } - if db.Statement.Dest != db.Statement.Model && db.Statement.Model != nil { + if db.Statement.ReflectValue.CanAddr() && db.Statement.Dest != db.Statement.Model && db.Statement.Model != nil { _, queryValues = schema.GetIdentityFieldValuesMap(reflect.ValueOf(db.Statement.Model), db.Statement.Schema.PrimaryFields) column, values = schema.ToQueryValues(db.Statement.Table, db.Statement.Schema.PrimaryFieldDBNames, queryValues) @@ -51,15 +51,15 @@ func Delete(db *gorm.DB) { } } - if _, ok := db.Statement.Clauses["WHERE"]; !db.AllowGlobalUpdate && !ok { - db.AddError(gorm.ErrMissingWhereClause) - return - } - db.Statement.AddClauseIfNotExists(clause.From{}) db.Statement.Build("DELETE", "FROM", "WHERE") } + if _, ok := db.Statement.Clauses["WHERE"]; !db.AllowGlobalUpdate && !ok { + db.AddError(gorm.ErrMissingWhereClause) + return + } + if !db.DryRun && db.Error == nil { result, err := db.Statement.ConnPool.ExecContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...) diff --git a/soft_delete.go b/soft_delete.go index d33bf866..484f565c 100644 --- a/soft_delete.go +++ b/soft_delete.go @@ -98,11 +98,6 @@ func (sd SoftDeleteDeleteClause) ModifyStatement(stmt *Statement) { } } - if _, ok := stmt.Clauses["WHERE"]; !stmt.DB.AllowGlobalUpdate && !ok { - stmt.DB.AddError(ErrMissingWhereClause) - return - } - stmt.AddClauseIfNotExists(clause.Update{}) stmt.Build("UPDATE", "SET", "WHERE") } diff --git a/tests/delete_test.go b/tests/delete_test.go index 09c1a075..17299677 100644 --- a/tests/delete_test.go +++ b/tests/delete_test.go @@ -48,6 +48,10 @@ func TestDelete(t *testing.T) { t.Errorf("errors happened when delete: %v", err) } + if err := DB.Delete(User{}).Error; err != gorm.ErrMissingWhereClause { + t.Errorf("errors happened when delete: %v", err) + } + if err := DB.Where("id = ?", users[0].ID).First(&result).Error; err == nil || !errors.Is(err, gorm.ErrRecordNotFound) { t.Errorf("should returns record not found error, but got %v", err) }