-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
61 lines (50 loc) · 1018 Bytes
/
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
package main
import (
"fmt"
"log"
"strconv"
"github.com/tidwall/buntdb"
)
type DB struct {
db *buntdb.DB
}
func dbInitialize() *DB {
db, err := buntdb.Open("data.db")
if err != nil {
log.Fatal(err)
}
db.CreateIndex("names", "player:*", buntdb.IndexString)
db.CreateSpatialIndex("playerPos", "player:*:pos", buntdb.IndexRect)
db.CreateSpatialIndex("meshPos", "mesh:*:pos", buntdb.IndexRect)
d := &DB{
db: db,
}
d.ensureIndexExists()
return d
}
/* ----- */
/* UTILS */
/* ----- */
func (db *DB) ensureIndexExists() {
err := db.db.Update(func(tx *buntdb.Tx) error {
_, err := tx.Get("index")
if err != nil {
_, _, err := tx.Set("index", "0", nil)
return err
}
return nil
})
if err != nil {
panic(err)
}
}
func dbNextIndex(tx *buntdb.Tx) string {
index, e := tx.Get("index")
utilsCheck(e)
iindex, e := strconv.ParseInt(index, 10, 64)
utilsCheck(e)
next := iindex + 1
nextIndexStr := fmt.Sprintf("%v", next)
tx.Set("index", nextIndexStr, nil)
return nextIndexStr
}