-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
74 lines (62 loc) · 1.26 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"github.com/jinzhu/gorm"
"log"
"os"
)
type User struct {
gorm.Model
Username string
Address string
Balance float64
}
type Params struct {
Limit int
}
type Tip struct {
gorm.Model
FromId int
ToId int
MessageId int
Amount float64
From User
To User
TelegramMessageId int
}
var DB *gorm.DB
func initDB() {
log.Println("Connecting to DB...")
var err error
DB, err = gorm.Open("mysql", os.Getenv("DB_USER")+":"+os.Getenv("DB_PASSWORD")+"@/"+os.Getenv("DB_NAME")+"?parseTime=true")
if err != nil {
log.Fatal(err)
}
log.Println("Connected to DB")
}
func (tip *Tip) Find(p Params) ([]Tip, error) {
var tips []Tip
if p.Limit == 0 {
DB.Preload("From").Preload("To").Find(&tips ,tip)
return tips, DB.Error
}
DB.Preload("From").Preload("To").Order("created_at desc").Limit(p.Limit).Find(&tips ,tip)
return tips, DB.Error
}
func Count() (int64, error) {
var count int64
DB.Table("tips").Count(&count)
return count, DB.Error
}
func UserCount() (int64, error) {
var count int64
DB.Table("users").Count(&count)
return count, DB.Error
}
func TippedAmount() (float64, error) {
type Result struct {
Total float64
}
var result Result
DB.Model(&Tip{}).Select("sum(amount) as total").Scan(&result)
return result.Total, DB.Error
}