-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
105 lines (87 loc) · 2.06 KB
/
main.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Copyright (c) 2020 Ramon Quitales
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
"github.com/rquitales/go-memdb/memdb"
)
func main() {
db := memdb.NewDB()
reader := bufio.NewReader(os.Stdin)
fmt.Printf("go-memdb CLI package example:\n---------------------\n\n")
for {
query := readStdIn(reader)
if len(query) == 0 {
continue
}
switch strings.ToLower(query[0]) {
case "set":
set(db, query)
case "get":
get(db, query)
case "delete":
deleteEntry(db, query)
case "count":
count(db, query)
case "end":
log.Println("Exiting go-memdb...")
os.Exit(0)
case "rollback":
ok := db.Rollback()
if !ok {
log.Println("[WARN] TRANSACTION NOT FOUND")
}
case "commit":
db.Commit()
case "begin":
db.Begin()
default:
log.Println("[WARN] unsupported query")
}
}
}
func set(db *memdb.MemDB, query []string) {
if len(query) != 3 {
log.Printf("[ERROR] wrong number of variables for set command, need 2 (key value) but found %d", len(query)-1)
return
}
db.Set(query[1], query[2])
}
func get(db *memdb.MemDB, query []string) {
if len(query) != 2 {
log.Printf("[ERROR] wrong number of variables for get command, need 1 (key) but found %d", len(query)-1)
return
}
if value, ok := db.Get(query[1]); ok {
fmt.Println(value)
} else {
fmt.Println("NULL")
}
}
func deleteEntry(db *memdb.MemDB, query []string) {
if len(query) != 2 {
log.Printf("[ERROR] wrong number of variables for delete command, need 1 (key) but found %d", len(query)-1)
return
}
db.Delete(query[1])
}
func count(db *memdb.MemDB, query []string) {
if len(query) != 2 {
log.Printf("[ERROR] wrong number of variables for count command, need 1 (key) but found %d", len(query)-1)
return
}
fmt.Println(db.Count(query[1]))
}
func readStdIn(reader *bufio.Reader) []string {
fmt.Print("go-memdb=> ")
input, _ := reader.ReadString('\n')
// convert CRLF to LF
input = strings.Replace(input, "\n", "", -1)
return strings.Split(input, " ")
}