-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.go
88 lines (70 loc) · 1.35 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
package accountsync
import (
"database/sql"
"github.com/hashicorp/golang-lru"
"github.com/jmoiron/sqlx"
)
type DB struct {
*sqlx.DB
uc *lru.Cache
oc *lru.Cache
}
func NewDB(databaseURL string, syncCacheSize int) (*DB, error) {
db, err := sqlx.Connect("postgres", databaseURL)
if err != nil {
return nil, err
}
uc, err := lru.New(syncCacheSize)
if err != nil {
return nil, err
}
oc, err := lru.New(syncCacheSize)
if err != nil {
return nil, err
}
return &DB{
DB: db,
uc: uc,
oc: oc,
}, nil
}
func (db *DB) FindUserByGithubID(ghUserID int) (*User, error) {
var (
user *User
ok bool
)
u, found := db.uc.Get(ghUserID)
if user, ok = u.(*User); found && ok {
return user, nil
}
user = &User{}
err := db.Get(user, `SELECT * FROM users WHERE github_id = $1`, ghUserID)
if err == sql.ErrNoRows {
user = nil
err = nil
}
if user != nil {
db.uc.Add(ghUserID, user)
}
return user, err
}
func (db *DB) FindOrgByGithubID(ghOrgID int) (*Organization, error) {
var (
org *Organization
ok bool
)
o, found := db.oc.Get(ghOrgID)
if org, ok = o.(*Organization); found && ok {
return org, nil
}
org = &Organization{}
err := db.Get(org, `SELECT * FROM organizations WHERE github_id = $1`, ghOrgID)
if err == sql.ErrNoRows {
org = nil
err = nil
}
if org != nil {
db.oc.Add(ghOrgID, org)
}
return org, err
}