-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
69 lines (59 loc) · 1.29 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package simpledb
import (
"bytes"
"errors"
"sync"
)
type DB struct {
mu sync.RWMutex
index *index
datalog *datalog
}
// Get returns the value for the given key stored in the DB or nil if the key doesn't exist.
func (db *DB) Get(key []byte) ([]byte, error) {
hash := hash(key)
slot, err := db.index.get(hash)
if err != nil {
return nil, err
}
if slot == nil {
return nil, nil
}
keyRead, value, err := db.datalog.readKeyValue(slot)
if err != nil {
return nil, err
}
if bytes.Equal(key, keyRead) {
return value, nil
} else {
return nil, errors.New("key stored in segment is not consistent "+
"with the index")
}
}
// Put sets the value for the given key. It updates the value for the existing key.
func (db *DB) Put(key []byte, value []byte) error {
hash := hash(key)
// write the record to the segment
record := record{
key: key,
value: value,
}
segmentID, offset, err := db.datalog.writeRecord(record.encode())
if err != nil {
return err
}
// update the index
slot := &slot{
hash: hash,
segmentID: segmentID,
keySize: uint16(len(key)),
valueSize: uint32(len(value)),
offset: uint32(offset),
}
db.index.put(slot)
return nil
}
// Delete deletes the given key from the DB.
func (db *DB) Delete(key []byte) error {
return nil
}