From c2828592acbba6b54e75ca390670b609a19a986a Mon Sep 17 00:00:00 2001 From: jdl Date: Wed, 6 Dec 2023 20:39:08 +0100 Subject: [PATCH] Added UpdateFunc for safer updates. --- mdb/collection.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/mdb/collection.go b/mdb/collection.go index 3a15fb1..57970a8 100644 --- a/mdb/collection.go +++ b/mdb/collection.go @@ -237,6 +237,27 @@ func (c *Collection[T]) update(tx *Snapshot, userItem *T) error { 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 { if tx == nil { return c.db.Update(func(tx *Snapshot) error {