-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
executable file
·101 lines (87 loc) · 2.5 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
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
package main
import (
"time"
// "log"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type Gamedb struct {
GID int `gorm:"primary_key"`
Name string `gorm:"unique"`
StartTime time.Time
EndTime time.Time
TotalRun time.Duration
}
var db *gorm.DB
var dberr error
//DbInit 连接数据库,表迁移
func DbInit() {
exist, err := IsExists("./Gamedb.db")
if !exist && err == nil {
//连接数据库
db, dberr = gorm.Open(sqlite.Open("./Gamedb.db"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
if dberr != nil {
panic(dberr)
}
//迁移 schema
db.AutoMigrate(&Gamedb{})
u1 := Gamedb{}
db.Create(&u1)
//log.Println("Db init successful!")
}
//连接数据库
db, dberr = gorm.Open(sqlite.Open("./Gamedb.db"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
if dberr != nil {
panic(dberr)
}
}
func AddNewGame(gname string) {
var FindGame Gamedb
db.Where("Name=?", gname).Find(&FindGame)
if FindGame.Name == "" {
var gamedb Gamedb
db.Last(&gamedb)
currentTime := time.Now()
newgname := Gamedb{gamedb.GID + 1, gname, currentTime, currentTime, 0}
db.Create(&newgname)
// log.Println("Successful add new game:", gname)
} else {
StartTime, _, _ := ShowTime(gname)
if StartTime.String() == "0001-01-01 00:00:00 +0000 UTC" {
AddStartTime(gname)
}
}
}
func AddStartTime(gname string) {
var gamedb Gamedb
StartTime := time.Now()
db.Model(&gamedb).Where("Name=?", gname).Updates(map[string]interface{}{"StartTime": StartTime})
}
func AddEndTime(gname string) {
var gamedb Gamedb
StartTime, _, _ := ShowTime(gname)
if StartTime.String() != "0001-01-01 00:00:00 +0000 UTC" {
currentTime := time.Now()
db.Model(&gamedb).Where("Name=?", gname).Updates(map[string]interface{}{"EndTime": currentTime})
AddTotalTime(gname)
}
ClearTime(gname)
}
func AddTotalTime(gname string) {
var gamedb Gamedb
db.Where("Name=?", gname).Find(&gamedb)
Totaltime := gamedb.TotalRun + gamedb.EndTime.Sub(gamedb.StartTime)
// log.Printf(gamedb.EndTime.String() + gamedb.StartTime.String())
db.Model(&gamedb).Where("Name=?", gname).Updates(map[string]interface{}{"TotalRun": Totaltime})
ClearTime(gname)
}
func ShowTime(gname string) (time.Time, time.Time, time.Duration) {
var gamedb Gamedb
db.Where("Name=?", gname).Find(&gamedb)
return gamedb.StartTime, gamedb.EndTime, gamedb.TotalRun
}
func ClearTime(gname string) {
var gamedb Gamedb
db.Model(&gamedb).Where("Name=?", gname).Updates(map[string]interface{}{"StartTime": "", "EndTime": ""})
}