diff --git a/callbacks/create.go b/callbacks/create.go index aec0afe9..a58549a5 100644 --- a/callbacks/create.go +++ b/callbacks/create.go @@ -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 { diff --git a/gorm.go b/gorm.go index 2dfbb855..3bf2479a 100644 --- a/gorm.go +++ b/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 } diff --git a/tests/hooks_test.go b/tests/hooks_test.go index d8b1770e..7e3ae4e4 100644 --- a/tests/hooks_test.go +++ b/tests/hooks_test.go @@ -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)