-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
57 lines (50 loc) · 1.11 KB
/
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
package main
import (
"fmt"
"os"
"path"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/mitchellh/go-homedir"
)
type Task struct {
ID uint
Project string
Name string
Logs []Log
}
type Log struct {
ID uint
TimeFrom time.Time
TimeTo *time.Time
TaskId uint
}
func EndOpenTasks(db *gorm.DB, t time.Time) {
var openLogs []Log
db.Where("time_to is NULL").Find(&openLogs)
for _, l := range openLogs {
var to time.Time = t
l.TimeTo = &to
db.Save(&l)
duration := to.Sub(l.TimeFrom)
fmt.Printf("ended log for task %d %s\n", l.TaskId, FormatTime(duration.Seconds()))
}
}
func GetDatabase() *gorm.DB {
homeDir, errHomeDir := homedir.Dir()
if errHomeDir != nil {
panic("Unable to get home directory")
}
ttrackPath := path.Join(homeDir, "ttrack")
os.MkdirAll(ttrackPath, os.ModePerm)
fullPath := path.Join(ttrackPath, "ttrack.db")
fmt.Printf("Using database at %s\n", fullPath)
db, err := gorm.Open("sqlite3", fullPath)
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(&Log{})
db.AutoMigrate(&Task{})
return db
}