Add AllowGlobalUpdate mode

This commit is contained in:
Jinzhu 2020-08-23 20:08:23 +08:00
parent cc6a64adfb
commit ebdb4edda8
6 changed files with 18 additions and 3 deletions

View File

@ -51,7 +51,7 @@ func Delete(db *gorm.DB) {
}
}
if _, ok := db.Statement.Clauses["WHERE"]; !ok {
if _, ok := db.Statement.Clauses["WHERE"]; !db.AllowGlobalUpdate && !ok {
db.AddError(gorm.ErrMissingWhereClause)
return
}

View File

@ -69,7 +69,7 @@ func Update(db *gorm.DB) {
db.Statement.Build("UPDATE", "SET", "WHERE")
}
if _, ok := db.Statement.Clauses["WHERE"]; !ok {
if _, ok := db.Statement.Clauses["WHERE"]; !db.AllowGlobalUpdate && !ok {
db.AddError(gorm.ErrMissingWhereClause)
return
}

View File

@ -32,6 +32,8 @@ type Config struct {
DisableAutomaticPing bool
// DisableForeignKeyConstraintWhenMigrating
DisableForeignKeyConstraintWhenMigrating bool
// AllowGlobalUpdate allow global update
AllowGlobalUpdate bool
// ClauseBuilders clause builder
ClauseBuilders map[string]clause.ClauseBuilder
@ -61,6 +63,7 @@ type Session struct {
PrepareStmt bool
WithConditions bool
SkipDefaultTransaction bool
AllowGlobalUpdate bool
Context context.Context
Logger logger.Interface
NowFunc func() time.Time
@ -154,6 +157,10 @@ func (db *DB) Session(config *Session) *DB {
tx.Config.SkipDefaultTransaction = true
}
if config.AllowGlobalUpdate {
txConfig.AllowGlobalUpdate = true
}
if config.Context != nil {
tx.Statement = tx.Statement.clone()
tx.Statement.DB = tx

View File

@ -98,7 +98,7 @@ func (sd SoftDeleteDeleteClause) ModifyStatement(stmt *Statement) {
}
}
if _, ok := stmt.Clauses["WHERE"]; !ok {
if _, ok := stmt.Clauses["WHERE"]; !stmt.DB.AllowGlobalUpdate && !ok {
stmt.DB.AddError(ErrMissingWhereClause)
return
}

View File

@ -118,4 +118,8 @@ func TestBlockGlobalDelete(t *testing.T) {
if err := DB.Delete(&User{}).Error; err == nil || !errors.Is(err, gorm.ErrMissingWhereClause) {
t.Errorf("should returns missing WHERE clause while deleting error")
}
if err := DB.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(&User{}).Error; err != nil {
t.Errorf("should returns no error while enable global update, but got err %v", err)
}
}

View File

@ -222,6 +222,10 @@ func TestBlockGlobalUpdate(t *testing.T) {
if err := DB.Model(&User{}).Update("name", "jinzhu").Error; err == nil || !errors.Is(err, gorm.ErrMissingWhereClause) {
t.Errorf("should returns missing WHERE clause while updating error, got err %v", err)
}
if err := DB.Session(&gorm.Session{AllowGlobalUpdate: true}).Model(&User{}).Update("name", "jinzhu").Error; err != nil {
t.Errorf("should returns no error while enable global update, but got err %v", err)
}
}
func TestSelectWithUpdate(t *testing.T) {