kvrepl/db.go

55 lines
1.2 KiB
Go

package kvrepl
import "fmt"
// DB is struct defining two maps, pkv (points to kv) and nest, which
// aids figuring out how nested the commits are for current transaction
type DB struct {
KV1 map[string]string
KV2 map[string]string
PKV bool
nest int
}
// read reads a key out of a map and checks for parsing errors
func read(args []string, kv map[string]string) (string, error) {
if len(args) != 1 {
return "", fmt.Errorf("incorrect usage: READ <key>")
}
i, ok := kv[args[0]]
if !ok {
return "", fmt.Errorf("key does not exist")
}
return i, nil
}
// write writes key/value to map and checks for parsing errors
func write(args []string, kv map[string]string) error {
if len(args) != 2 {
return fmt.Errorf("incorrect usage: WRITE <key> <value>")
}
kv[args[0]] = args[1]
return nil
}
// del deletes a key from map and checks for parsing errors
func del(args []string, kv map[string]string) error {
if len(args) != 1 {
return fmt.Errorf("incorrect usage: DELETE <key>")
}
_, ok := kv[args[0]]
if !ok {
return fmt.Errorf("key does not exist")
}
delete(kv, args[0])
return nil
}
// whichDB returns which db is currently being written to
func whichDB(d *DB) map[string]string {
if d.PKV {
return d.KV1
}
return d.KV2
}