UpsertFunc
This commit is contained in:
		| @@ -287,6 +287,36 @@ func (c *Collection[T]) upsert(tx *Snapshot, item *T) error { | |||||||
| 	return err | 	return err | ||||||
| } | } | ||||||
|  |  | ||||||
|  | func (c *Collection[T]) UpsertFunc(tx *Snapshot, id uint64, update func(item *T) error) error { | ||||||
|  | 	if tx == nil { | ||||||
|  | 		c.db.Update(func(tx *Snapshot) error { | ||||||
|  | 			return c.upsertFunc(tx, id, update) | ||||||
|  | 		}) | ||||||
|  | 	} | ||||||
|  | 	return c.upsertFunc(tx, id, update) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (c *Collection[T]) upsertFunc(tx *Snapshot, id uint64, update func(item *T) error) error { | ||||||
|  | 	insert := false | ||||||
|  |  | ||||||
|  | 	item := c.Get(tx, id) | ||||||
|  | 	if item == nil { | ||||||
|  | 		item = new(T) | ||||||
|  | 		insert = true | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if err := update(item); err != nil { | ||||||
|  | 		return err | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	c.setID(item, id) // Don't allow the ID to change. | ||||||
|  |  | ||||||
|  | 	if insert { | ||||||
|  | 		return c.insert(tx, item) | ||||||
|  | 	} | ||||||
|  | 	return c.update(tx, item) | ||||||
|  | } | ||||||
|  |  | ||||||
| func (c *Collection[T]) Delete(tx *Snapshot, itemID uint64) error { | func (c *Collection[T]) Delete(tx *Snapshot, itemID uint64) error { | ||||||
| 	if tx == nil { | 	if tx == nil { | ||||||
| 		return c.db.Update(func(tx *Snapshot) error { | 		return c.db.Update(func(tx *Snapshot) error { | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user