gorm/callbacks/callbacks.go

52 lines
2.3 KiB
Go
Raw Normal View History

2020-02-02 03:35:01 +03:00
package callbacks
2020-02-04 03:56:15 +03:00
import (
2020-06-02 04:16:07 +03:00
"gorm.io/gorm"
2020-02-04 03:56:15 +03:00
)
2020-02-02 03:35:01 +03:00
2020-03-12 08:05:22 +03:00
type Config struct {
LastInsertIDReversed bool
WithReturning bool
}
func RegisterDefaultCallbacks(db *gorm.DB, config *Config) {
2020-02-02 14:32:27 +03:00
enableTransaction := func(db *gorm.DB) bool {
return !db.SkipDefaultTransaction
}
createCallback := db.Callback().Create()
createCallback.Match(enableTransaction).Register("gorm:begin_transaction", BeginTransaction)
createCallback.Register("gorm:before_create", BeforeCreate)
createCallback.Register("gorm:save_before_associations", SaveBeforeAssociations(true))
2020-03-12 08:05:22 +03:00
createCallback.Register("gorm:create", Create(config))
createCallback.Register("gorm:save_after_associations", SaveAfterAssociations(true))
2020-02-02 14:32:27 +03:00
createCallback.Register("gorm:after_create", AfterCreate)
createCallback.Match(enableTransaction).Register("gorm:commit_or_rollback_transaction", CommitOrRollbackTransaction)
queryCallback := db.Callback().Query()
2020-02-04 03:56:15 +03:00
queryCallback.Register("gorm:query", Query)
2020-02-02 14:32:27 +03:00
queryCallback.Register("gorm:preload", Preload)
queryCallback.Register("gorm:after_query", AfterQuery)
deleteCallback := db.Callback().Delete()
deleteCallback.Match(enableTransaction).Register("gorm:begin_transaction", BeginTransaction)
deleteCallback.Register("gorm:before_delete", BeforeDelete)
deleteCallback.Register("gorm:delete_before_associations", DeleteBeforeAssociations)
2020-02-02 14:32:27 +03:00
deleteCallback.Register("gorm:delete", Delete)
deleteCallback.Register("gorm:after_delete", AfterDelete)
deleteCallback.Match(enableTransaction).Register("gorm:commit_or_rollback_transaction", CommitOrRollbackTransaction)
updateCallback := db.Callback().Update()
updateCallback.Match(enableTransaction).Register("gorm:begin_transaction", BeginTransaction)
2020-06-01 14:41:33 +03:00
updateCallback.Register("gorm:setup_reflect_value", SetupUpdateReflectValue)
2020-02-02 14:32:27 +03:00
updateCallback.Register("gorm:before_update", BeforeUpdate)
updateCallback.Register("gorm:save_before_associations", SaveBeforeAssociations(false))
2020-02-02 14:32:27 +03:00
updateCallback.Register("gorm:update", Update)
updateCallback.Register("gorm:save_after_associations", SaveAfterAssociations(false))
2020-02-02 14:32:27 +03:00
updateCallback.Register("gorm:after_update", AfterUpdate)
updateCallback.Match(enableTransaction).Register("gorm:commit_or_rollback_transaction", CommitOrRollbackTransaction)
2020-02-22 14:41:01 +03:00
2020-07-22 10:05:38 +03:00
db.Callback().Row().Register("gorm:row", RowQuery)
2020-02-22 14:41:01 +03:00
db.Callback().Raw().Register("gorm:raw", RawExec)
2020-02-02 03:35:01 +03:00
}