mirror of https://github.com/go-gorm/gorm.git
Add deleted_at check when soft deleting, fix #3720
This commit is contained in:
parent
560d303e71
commit
fcf2ab6c0e
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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")
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
||||
|
|
|
@ -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")
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue