You can use the plugin to keep a history of your GORM models changes. Basically it keeps a ledger of your model state. Each model must be associated with a history model which will be a copy of the modified record.
go get github.com/vcraescu/gorm-history
db.Use(history.New())
:type Person struct {
gorm.Model
FirstName string
LastName string
}
type PersonHistory struct {
gorm.Model
Entry
}
func main() {
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
if err != nil {
panic(err)
}
db = db.Session(&gorm.Session{})
err = db.AutoMigrate(Person{}, PersonHistory{})
if err != nil {
panic(err)
}
plugin := New()
if err := db.Use(plugin); err != nil {
return
}
db = SetUser(db, history.User{
ID: 123,
Email: "john@doe.com",
})
db = SetSource(db, history.Source{
ID: "1c059a03-3b14-4017-ae33-5337860ec35f",
Type: "ampq",
})
p := Person{
FirstName: "John",
LastName: "Doe",
}
if err := db.Save(&p).Error; err != nil {
panic(err)
}
}
history.Recordable
interface:func (Person) CreateHistory() interface{} {
return PersonHistory{}
}
if err := db.Model(&p).Update("first_name", "Jane").Error; err != nil {
panic(err)
}
By default, the plugin generates a new ULID for each history record. You can implement your own versioning function.
type PersonHistory struct {
gorm.Model
history.Entry
}
// or
type PersonHistory struct {
gorm.Model
Version Version `gorm-history:"version"`
ObjectID uint `gorm:"index" gorm-history:"objectID"`
Action Action `gorm:"type: string" gorm-history:"action"`
}
You can change the versioning function when you register the plugin:
if err := db.Use(history.New(history.WithVersionFunc(MyVersionFunc))); err != nil {
panic(err)
}
history.DefaultCopyFunc
- copies all the values of the recordable model to history model.You can change the copy function when you register the plugin if you defined your own copying function:
func myCopyFunc(r Recordable, history interface{}) error {
// ...
}
//...
if err := db.Use(history.New(history.WithCopyFunc(myCopyFunc))); err != nil {
panic(err)
}
gorm-history is licensed under the MIT License.
Version | Tag | Published |
---|---|---|
v2.0.0 | 1yr ago |