-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
99 lines (82 loc) · 2.01 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
package main
import (
"errors"
"log"
"time"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type githubTraffic struct {
gorm.Model
User string `gorm:"index:idx_user_reponame_type_timestamp"`
RepoName string `gorm:"column:repo_name;index:idx_user_reponame_type_timestamp"`
Type string `gorm:"index:idx_user_reponame_type_timestamp"`
Uniques int
Count int
Timestamp string `gorm:"index:idx_user_reponame_type_timestamp"`
}
func (g *githubTraffic) TableName() string {
return "github_traffic"
}
var (
db *gorm.DB
dbfile = "./github_traffic.db"
)
func init() {
var err error
db, err = gorm.Open(sqlite.Open(dbfile), &gorm.Config{})
if err != nil {
panic(err)
}
if err := db.AutoMigrate(&githubTraffic{}); err != nil {
panic(err)
}
}
type clonesTotal struct {
Count int
Uniques int
}
func updateGithubTrafficClones(githubClones []clonesItem, user, repoName string) {
todayTimestamp := time.Now().Format("2006-01-02") + "T00:00:00Z"
for _, v := range githubClones {
var record githubTraffic
err := db.Where(
"user = ? and repo_name = ? and type = ? and timestamp = ?",
user,
repoName,
typeClones,
v.Timestamp,
).First(&record).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
recordNew := &githubTraffic{
User: user,
RepoName: repoName,
Type: typeClones,
Uniques: v.Uniques,
Count: v.Count,
Timestamp: v.Timestamp,
}
if err := db.Create(&recordNew).Error; err != nil {
log.Printf("create %v failed: %v", *recordNew, err)
}
continue
}
if v.Timestamp == todayTimestamp {
record.Uniques = v.Uniques
record.Count = v.Count
if err := db.Save(&record).Error; err != nil {
log.Printf("update %v failed: %v", record, err)
}
}
}
}
func getClonesTotal(user, repoName string) *clonesTotal {
var total clonesTotal
db.Raw(
"select sum(count) as count, sum(uniques) as uniques from github_traffic where user=? and repo_name=? and type=?",
user,
repoName,
typeClones,
).Scan(&total)
return &total
}