forked from coaidev/coai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquota.go
64 lines (55 loc) · 1.78 KB
/
quota.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
package auth
import "database/sql"
func (u *User) GetQuota(db *sql.DB) float32 {
var quota float32
if err := db.QueryRow("SELECT quota FROM quota WHERE user_id = ?", u.GetID(db)).Scan("a); err != nil {
return 0.
}
return quota
}
func (u *User) GetUsedQuota(db *sql.DB) float32 {
var quota float32
if err := db.QueryRow("SELECT used FROM quota WHERE user_id = ?", u.GetID(db)).Scan("a); err != nil {
return 0.
}
return quota
}
func (u *User) SetQuota(db *sql.DB, quota float32) bool {
_, err := db.Exec(`
INSERT INTO quota (user_id, quota, used) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE quota = ?
`, u.GetID(db), quota, 0., quota)
return err == nil
}
func (u *User) SetUsedQuota(db *sql.DB, used float32) bool {
_, err := db.Exec(`
INSERT INTO quota (user_id, quota, used) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE used = ?
`, u.GetID(db), 0., used, used)
return err == nil
}
func (u *User) IncreaseQuota(db *sql.DB, quota float32) bool {
_, err := db.Exec(`
INSERT INTO quota (user_id, quota, used) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE quota = quota + ?
`, u.GetID(db), quota, 0., quota)
return err == nil
}
func (u *User) IncreaseUsedQuota(db *sql.DB, used float32) bool {
_, err := db.Exec(`
INSERT INTO quota (user_id, quota, used) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE used = used + ?
`, u.GetID(db), 0., used, used)
return err == nil
}
func (u *User) DecreaseQuota(db *sql.DB, quota float32) bool {
_, err := db.Exec(`
INSERT INTO quota (user_id, quota, used) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE quota = quota - ?
`, u.GetID(db), quota, 0., quota)
return err == nil
}
func (u *User) UseQuota(db *sql.DB, quota float32) bool {
if quota == 0 {
return true
}
if !u.DecreaseQuota(db, quota) {
return false
}
return u.IncreaseUsedQuota(db, quota)
}