diff --git a/callbacks/delete.go b/callbacks/delete.go index 85f11f4b..0f4bcd6b 100644 --- a/callbacks/delete.go +++ b/callbacks/delete.go @@ -135,7 +135,7 @@ func Delete(db *gorm.DB) { db.Statement.Build("DELETE", "FROM", "WHERE") } - if _, ok := db.Statement.Clauses["WHERE"]; !db.AllowGlobalUpdate && !ok { + if _, ok := db.Statement.Clauses["WHERE"]; !db.AllowGlobalUpdate && !ok && db.Error == nil { db.AddError(gorm.ErrMissingWhereClause) return } diff --git a/soft_delete.go b/soft_delete.go index 284129a1..cb56035d 100644 --- a/soft_delete.go +++ b/soft_delete.go @@ -124,6 +124,12 @@ func (sd SoftDeleteDeleteClause) ModifyStatement(stmt *Statement) { } } + if _, ok := stmt.Clauses["WHERE"]; !stmt.DB.AllowGlobalUpdate && !ok { + stmt.DB.AddError(ErrMissingWhereClause) + } else { + SoftDeleteQueryClause{Field: sd.Field}.ModifyStatement(stmt) + } + stmt.AddClauseIfNotExists(clause.Update{}) stmt.Build("UPDATE", "SET", "WHERE") } diff --git a/tests/delete_test.go b/tests/delete_test.go index ecd5ec39..954c7097 100644 --- a/tests/delete_test.go +++ b/tests/delete_test.go @@ -49,7 +49,7 @@ func TestDelete(t *testing.T) { t.Errorf("errors happened when delete: %v", err) } - if err := DB.Delete(User{}).Error; err != gorm.ErrMissingWhereClause { + if err := DB.Delete(&User{}).Error; err != gorm.ErrMissingWhereClause { t.Errorf("errors happened when delete: %v", err) } diff --git a/tests/soft_delete_test.go b/tests/soft_delete_test.go index 283a4c34..f1ea8a51 100644 --- a/tests/soft_delete_test.go +++ b/tests/soft_delete_test.go @@ -3,6 +3,7 @@ package tests_test import ( "encoding/json" "errors" + "regexp" "testing" "gorm.io/gorm" @@ -28,6 +29,11 @@ func TestSoftDelete(t *testing.T) { t.Fatalf("No error should happen when soft delete user, but got %v", err) } + sql := DB.Session(&gorm.Session{DryRun: true}).Delete(&user).Statement.SQL.String() + if !regexp.MustCompile(`UPDATE .users. SET .deleted_at.=.* WHERE .users.\..id. = .* AND .users.\..deleted_at. IS NULL`).MatchString(sql) { + t.Fatalf("invalid sql generated, got %v", sql) + } + if DB.First(&User{}, "name = ?", user.Name).Error == nil { t.Errorf("Can't find a soft deleted record") }