Fix panic when delet without pointer, close #3308

This commit is contained in:
Jinzhu 2020-08-25 17:27:28 +08:00
parent 84dbb36d3b
commit 3dfa8a66f1
3 changed files with 10 additions and 11 deletions

View File

@ -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...)

View File

@ -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")
}

View File

@ -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)
}