Upsert combines insert and update: it associates a key with a value, silently replacing any value already stored under that key. This choice suits a cache where a newer value is usually more useful than an older one; another API might reject duplicate keys instead. section 7.1.3
Listing 7.4 cache.go: Implementing the Upsert function on the cache
// Upsert overrides the value for a given key.
func (c *Cache[K, V]) Upsert(key K, value V) error {
c.data[key] = value
// Do not return an error for the moment,
// but it can happen in the near future.
return nil
}
The initial generic cache implements Upsert with a map assignment. Its error return leaves room for future failure cases, although this implementation always returns nil. section 7.1.3
A size-limited cache needs more bookkeeping. It keeps keys in chronological order, removes an existing key before adding its replacement, and evicts the oldest key when adding a new one to a full cache. Replacing a value also resets its expiration timestamp. A slice supports removing a key from the middle, unlike the channel considered for this design. section 7.4.2
Listing 7.20 cache.go: Upsert with the new helper functions
func (c *Cache[K, V]) Upsert(key K, value V) {
c.mu.Lock()
defer c.mu.Unlock()
_, alreadyPresent := c.data[key]
switch {
case alreadyPresent:
c.deleteKeyValue(key) #1
case len(c.data) == c.maxSize: #2
c.deleteKeyValue(c.chronologicalKeys[0])
}
c.addKeyValue(key, value) #3
}
The bounded-cache version locks the operation and uses helper functions to keep the map and chronological key slice in sync. Unlike the initial version, this listing has no error return. section 7.4.2 section 7.1.3
Test replacement and eviction
With capacity three, insert keys 1, 2, and 3, then update key 1. Adding key 4 should evict key 2: updating key 1 made it newer in the ordering. section 7.4.2
Upsert is not always the right repository API. Separate create and update operations can validate that an entity is not created twice and that an update does not insert a missing entity. section 8.4.2
