mirror of https://github.com/go-gorm/gorm.git
Add skip hooks support
This commit is contained in:
parent
f5c2126c29
commit
f6e1786ca2
|
@ -10,7 +10,7 @@ import (
|
|||
)
|
||||
|
||||
func BeforeCreate(db *gorm.DB) {
|
||||
if db.Error == nil && db.Statement.Schema != nil && (db.Statement.Schema.BeforeSave || db.Statement.Schema.BeforeCreate) {
|
||||
if db.Error == nil && db.Statement.Schema != nil && !db.Statement.UpdatingColumn && (db.Statement.Schema.BeforeSave || db.Statement.Schema.BeforeCreate) {
|
||||
callMethod(db, func(value interface{}, tx *gorm.DB) (called bool) {
|
||||
if db.Statement.Schema.BeforeSave {
|
||||
if i, ok := value.(BeforeSaveInterface); ok {
|
||||
|
@ -203,7 +203,7 @@ func CreateWithReturning(db *gorm.DB) {
|
|||
}
|
||||
|
||||
func AfterCreate(db *gorm.DB) {
|
||||
if db.Error == nil && db.Statement.Schema != nil && (db.Statement.Schema.AfterSave || db.Statement.Schema.AfterCreate) {
|
||||
if db.Error == nil && db.Statement.Schema != nil && !db.Statement.UpdatingColumn && (db.Statement.Schema.AfterSave || db.Statement.Schema.AfterCreate) {
|
||||
callMethod(db, func(value interface{}, tx *gorm.DB) (called bool) {
|
||||
if db.Statement.Schema.AfterSave {
|
||||
if i, ok := value.(AfterSaveInterface); ok {
|
||||
|
|
11
gorm.go
11
gorm.go
|
@ -64,6 +64,7 @@ type Session struct {
|
|||
DryRun bool
|
||||
PrepareStmt bool
|
||||
WithConditions bool
|
||||
SkipHooks bool
|
||||
SkipDefaultTransaction bool
|
||||
AllowGlobalUpdate bool
|
||||
FullSaveAssociations bool
|
||||
|
@ -169,15 +170,17 @@ func (db *DB) Session(config *Session) *DB {
|
|||
txConfig.FullSaveAssociations = true
|
||||
}
|
||||
|
||||
if config.Context != nil {
|
||||
if config.Context != nil || config.PrepareStmt || config.SkipHooks {
|
||||
tx.Statement = tx.Statement.clone()
|
||||
tx.Statement.DB = tx
|
||||
}
|
||||
|
||||
if config.Context != nil {
|
||||
tx.Statement.Context = config.Context
|
||||
}
|
||||
|
||||
if config.PrepareStmt {
|
||||
if v, ok := db.cacheStore.Load("preparedStmt"); ok {
|
||||
tx.Statement = tx.Statement.clone()
|
||||
preparedStmt := v.(*PreparedStmtDB)
|
||||
tx.Statement.ConnPool = &PreparedStmtDB{
|
||||
ConnPool: db.Config.ConnPool,
|
||||
|
@ -189,6 +192,10 @@ func (db *DB) Session(config *Session) *DB {
|
|||
}
|
||||
}
|
||||
|
||||
if config.SkipHooks {
|
||||
tx.Statement.UpdatingColumn = true
|
||||
}
|
||||
|
||||
if config.WithConditions {
|
||||
tx.clone = 2
|
||||
}
|
||||
|
|
|
@ -371,6 +371,11 @@ func TestSetColumn(t *testing.T) {
|
|||
t.Errorf("invalid data after update, got %+v", product)
|
||||
}
|
||||
|
||||
DB.Model(&product).Session(&gorm.Session{SkipHooks: true}).Updates(Product3{Code: "L1216"})
|
||||
if product.Price != 270 || product.Code != "L1216" {
|
||||
t.Errorf("invalid data after update, got %+v", product)
|
||||
}
|
||||
|
||||
var result2 Product3
|
||||
DB.First(&result2, product.ID)
|
||||
|
||||
|
|
Loading…
Reference in New Issue