add skiphook by name/func
This commit is contained in:
wangdong 2021-07-30 18:05:09 +08:00
parent 7a49629fd1
commit 577db27512
3 changed files with 48 additions and 2 deletions

View File

@ -126,8 +126,10 @@ func (p *processor) Execute(db *DB) *DB {
} }
} }
for _, f := range p.fns { for _, c := range p.callbacks {
f(db) if stmt.ShouldSkipHook(c) {
c.handler(db)
}
} }
db.Logger.Trace(stmt.Context, curTime, func() (string, int64) { db.Logger.Trace(stmt.Context, curTime, func() (string, int64) {

View File

@ -635,3 +635,17 @@ func (db *DB) Exec(sql string, values ...interface{}) (tx *DB) {
return tx.callbacks.Raw().Execute(tx) return tx.callbacks.Raw().Execute(tx)
} }
// add SkipHook name
func (db *DB) SkipHookByName(name ...string) (tx *DB) {
tx = db.getInstance()
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

@ -39,6 +39,8 @@ type Statement struct {
Context context.Context Context context.Context
RaiseErrorOnNotFound bool RaiseErrorOnNotFound bool
SkipHooks bool SkipHooks bool
SkipHooksNames []string
SkipHooksFunc []func(*DB)
SQL strings.Builder SQL strings.Builder
Vars []interface{} Vars []interface{}
CurDestIndex int CurDestIndex int
@ -671,3 +673,31 @@ func (stmt *Statement) SelectAndOmitColumns(requireCreate, requireUpdate bool) (
return results, !notRestricted && len(stmt.Selects) > 0 return results, !notRestricted && len(stmt.Selects) > 0
} }
// determine
func (stmt *Statement) ShouldSkipHook(c *callback) (skip bool) {
if stmt.SkipHooks {
// skip all
skip = true
} else {
// skip by name
if len(stmt.SkipHooksNames) > 0 {
for _, hookName := range stmt.SkipHooksNames {
if hookName == c.name {
skip = true
break
}
}
}
// skip by func
if skip || len(stmt.SkipHooksFunc) > 0 {
for _, hookFunc := range stmt.SkipHooksFunc {
// compare with ptr
if &hookFunc == &c.handler {
skip = true
break
}
}
}
}
}