-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.go
59 lines (46 loc) · 1.3 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
package storage
import (
"database/sql"
"path/filepath"
"github.com/YarikRevich/hide-seek-client/internal/core/paths"
_ "github.com/mattn/go-sqlite3"
"github.com/rs/xid"
"github.com/sirupsen/logrus"
)
type DB struct {
db *sql.DB
}
func (d *DB) initTables() {
if _, err := d.db.Exec("CREATE TABLE IF NOT EXISTS user (name VARCHAR(50) UNIQUE)"); err != nil {
logrus.Fatal("initializing of user table failed: ", err)
}
if _, err := d.db.Exec("CREATE TABLE IF NOT EXISTS window (height REAL, width REAL)"); err != nil {
logrus.Fatal("initializing of window table failed: ", err)
}
}
func (d *DB) initDefaultValues() {
q := d.db.QueryRow("SELECT COUNT(*) FROM user")
var count int
if err := q.Scan(&count); err != nil {
logrus.Fatal("selecting count of rows user failed: ", err)
}
if count == 0 {
if _, err := d.db.Exec("INSERT INTO user (name) VALUES (?)", xid.New().String()); err != nil {
logrus.Fatal("inserting default username failed:", err)
}
}
}
func (d *DB) init() {
d.initTables()
d.initDefaultValues()
}
func NewDB() *sql.DB {
//filepath.Join(paths.GAME_STORAGE_DIR, "/storage.db")
d, err := sql.Open("sqlite3", filepath.Join(paths.GAME_STORAGE_DIR, "storage.db"))
if err != nil {
logrus.Fatal("connection to db failed: ", err)
}
session := &DB{d}
session.init()
return d
}