forked from spring1843/go-dsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
in_memory_database.go
70 lines (60 loc) · 1.04 KB
/
in_memory_database.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
69
70
package strings
import (
"strings"
)
var dbs []map[string]string
// RunDBCommand solves the problem in O(1) time and O(n) space.
func RunDBCommand(cmd string) string {
splitCmd := strings.Split(cmd, " ")
switch splitCmd[0] {
case `SET`:
set(splitCmd[1], splitCmd[2])
case `GET`:
return get(splitCmd[1])
case `EXISTS`:
return exists(splitCmd[1])
case `UNSET`:
unset(splitCmd[1])
case `BEGIN`:
begin()
case `ROLLBACK`:
rollback()
case `COMMIT`:
commit()
}
return ""
}
func set(key, value string) {
db := dbs[len(dbs)-1]
db[key] = value
}
func get(key string) string {
db := dbs[len(dbs)-1]
v, ok := db[key]
if !ok {
return "nil"
}
return v
}
func exists(key string) string {
db := dbs[len(dbs)-1]
if _, ok := db[key]; !ok {
return "false"
}
return "true"
}
func unset(key string) {
db := dbs[len(dbs)-1]
delete(db, key)
}
func begin() {
clonedDB := make(map[string]string)
dbs = append(dbs, clonedDB)
}
func rollback() {
dbs = dbs[:len(dbs)-1]
}
func commit() {
dbs[len(dbs)-2] = dbs[len(dbs)-1]
rollback()
}