⚠
The web version only has simple instructions since chapter 04, while the full book has detailed explanations and background info.
0203: Update Modes
We can now map SQL operations to KV. For example, select → get, delete → del.
But the KV set operation seems to be both insert and update. In fact, it is insert ... on duplicate update. This is a common use case. PostgreSQL adds an upsert statement to match the KV set operation.
We need to add insert and update behavior to KV. Add SetEx():
type UpdateMode int
const (
ModeUpsert UpdateMode = 0 // insert or update
ModeInsert UpdateMode = 1 // insert new
ModeUpdate UpdateMode = 2 // update existing
)
func (kv *KV) SetEx(key []byte, val []byte, mode UpdateMode) (bool, error)Requirements:
ModeInsert: if the key already exists, do not update and return false.ModeUpdate: only update existing keys.ModeUpsert: same as the oldSet(), insert or overwrite:
func (kv *KV) Set(key []byte, val []byte) (updated bool, err error) {
return kv.SetEx(key, val, ModeUpsert)
}ⓘ
CodeCrafters.io has similar courses in many programming languages, including build your own Redis, SQLite, Docker, etc. It’s worth checking out.