While trying to insert logs to detect my models' values changes using gorm in golang, I'm doing it using plugins:
type MyModel struct {
Id
Name
}
type Log struct {
Id
NewValue
OldValue
CreatedAt
}
My plugin definition is something like this:
func ChangelogCreatePlugin(db *gorm.DB) {
log := &Log{NewValue: "the new value", OldValue: "the old value", CreatedAt: "current time"}
// Here is the problem
db.Save(log) <- this is not acceptable
}
Inserting a different data model using the db *gorm.DB argument in the plugin is not acceptable as that argument is initialized to accept data from the same model which triggered the plugin.
My requirement is to store my log in the same db transaction, so if one of them failed they should both fail. How to do such thing in gorm?
I'm aware of hooks. Hooks are not useful in my case as I want my logs to track different models, so I'm looking for more "reusable" solution, rather than copy/paste hooks implementations in my models.