-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgopg.go
80 lines (65 loc) · 1.54 KB
/
gopg.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
package dbeval
import (
"os"
"time"
"github.com/go-pg/pg"
"upper.io/db.v3/postgresql"
)
// Notes:
// - trivial to insert multiple records with a single statement
// - treats zero value as DEFAULT rather than zero value 🤔
// - found a bug in my schema (not null without default)
type GoPG struct {
db *pg.DB
}
func (g *GoPG) Connect(ds string, connLifetime time.Duration, idleConns, openConns int) {
if g.db != nil {
check(g.db.Close())
g.db = nil
}
url, err := postgresql.ParseURL(ds)
check(err)
g.db = pg.Connect(&pg.Options{
User: os.Getenv("USER"), // HACK
Database: url.Database,
PoolSize: openConns,
})
}
func (g *GoPG) CreateDatabase() {
_, err := g.db.Exec(createdb)
check(err)
}
func (g *GoPG) DropDatabase() {
_, err := g.db.Exec(dropdb)
check(err)
}
func (g *GoPG) CreateSchema() {
_, err := g.db.Exec(schema)
check(err)
}
func (g *GoPG) InsertAuthors(as []*Author) {
check(g.db.RunInTransaction(func(tx *pg.Tx) error {
return tx.Insert(&as)
}))
}
func (g *GoPG) InsertArticles(as []*Article) {
check(g.db.RunInTransaction(func(tx *pg.Tx) error {
return tx.Insert(&as)
}))
}
func (g *GoPG) FindAuthorByID(id int64) *Author {
a := &Author{ID: id}
check(g.db.Select(a))
return a
}
func (g *GoPG) FindAuthorsByName(name string) []*Author {
var as []*Author
check(g.db.Model(&as).Where("name = ?", name).Select())
return as
}
func (g *GoPG) RecentArticles(n int) []*Article {
var as []*Article
check(g.db.Model(&as).Order("published_at DESC").Limit(n).Select())
return as
}
var _ Implementation = &GoPG{}