This commit is contained in:
sivyer9303 2021-08-01 19:31:45 +08:00
parent b0f419b02f
commit f21ce964fc
4 changed files with 15 additions and 19 deletions

View File

@ -127,7 +127,7 @@ func (p *processor) Execute(db *DB) *DB {
}
for _, c := range p.callbacks {
if stmt.ShouldSkipHook(c) {
if !stmt.ShouldSkipHook(c) {
c.handler(db)
}
}

View File

@ -642,10 +642,3 @@ func (db *DB) SkipHookByName(name ...string) (tx *DB) {
tx.Statement.SkipHooksNames = append(tx.Statement.SkipHooksNames, name...)
return tx
}
// add SkipHook name
func (db *DB) SkipHookByFunc(fns ...func(*DB)) (tx *DB) {
tx = db.getInstance()
tx.Statement.SkipHooksFunc = append(tx.Statement.SkipHooksFunc, fns...)
return tx
}

View File

@ -40,7 +40,6 @@ type Statement struct {
RaiseErrorOnNotFound bool
SkipHooks bool
SkipHooksNames []string
SkipHooksFunc []func(*DB)
SQL strings.Builder
Vars []interface{}
CurDestIndex int
@ -689,16 +688,6 @@ func (stmt *Statement) ShouldSkipHook(c *callback) (skip bool) {
}
}
}
// skip by func
if !skip && len(stmt.SkipHooksFunc) > 0 {
for _, hookFunc := range stmt.SkipHooksFunc {
// compare with ptr
if &hookFunc == &c.handler {
skip = true
break
}
}
}
}
return
}

View File

@ -493,3 +493,17 @@ func TestFailedToSaveAssociationShouldRollback(t *testing.T) {
t.Errorf("should find product, but got error %v", err)
}
}
func TestSkipHookByName(t *testing.T) {
product := Product3{Name: "Product", Price: 0}
DB.AutoMigrate(&Product3{})
// expect price = 0
DB.SkipHookByName("gorm:before_create").Create(&product)
product2 := Product3{Name: "Product", Price: 0}
// expect price = 100
DB.Create(&product2)
// expect code = code1 , price = 100 + 20(add in before update) + 30(add in before update)
DB.Model(&product2).Update("code", "code1")
// expect code = code2 , price not change
DB.Model(&product).SkipHookByName("gorm:before_update").Update("code", "code2")
}