Added UpdateFunc for safer updates.

This commit is contained in:
jdl 2023-12-06 20:39:08 +01:00
parent 13e53f0c88
commit c2828592ac

View File

@ -237,6 +237,27 @@ func (c *Collection[T]) update(tx *Snapshot, userItem *T) error {
return nil return nil
} }
func (c *Collection[T]) UpdateFunc(tx *Snapshot, id uint64, update func(item *T) error) error {
if tx == nil {
return c.db.Update(func(tx *Snapshot) error {
return c.updateFunc(tx, id, update)
})
}
return c.updateFunc(tx, id, update)
}
func (c *Collection[T]) updateFunc(tx *Snapshot, id uint64, update func(item *T) error) error {
item := c.Get(tx, id)
if item == nil {
return errs.NotFound
}
if err := update(item); err != nil {
return err
}
c.setID(item, id) // Don't allow the ID to change.
return c.update(tx, item)
}
func (c *Collection[T]) Upsert(tx *Snapshot, item *T) error { func (c *Collection[T]) Upsert(tx *Snapshot, item *T) error {
if tx == nil { if tx == nil {
return c.db.Update(func(tx *Snapshot) error { return c.db.Update(func(tx *Snapshot) error {