-
Notifications
You must be signed in to change notification settings - Fork 6
/
repository_postgresql.go
73 lines (59 loc) · 1.39 KB
/
repository_postgresql.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
package main
import (
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
"log"
)
type PostgreSQLRepository struct {
db *pg.DB
}
func (p *PostgreSQLRepository) FindCounterById(id string) (*Counter, error) {
counter := &Counter{ID: id}
err := p.db.Select(counter)
if err != nil {
return nil, err
}
return counter, nil
}
func (p *PostgreSQLRepository) UpsertCounter(counter Counter) error {
_, err := p.db.Model(&counter).
OnConflict("(id) DO UPDATE").
Set("count = ?count").
Insert()
return err
}
func (p *PostgreSQLRepository) InsertLink(link Link) error {
return p.db.Insert(&link)
}
func (p *PostgreSQLRepository) FindLinkByShortIdInt(id uint) (*Link, error) {
link := &Link{ShortIDInt: id}
err := p.db.Model(link).
Where("short_id_int = ?short_id_int").
Select()
if err != nil {
return nil, err
}
return link, nil
}
func (p *PostgreSQLRepository) UpdateLink(link Link) error {
return p.db.Update(&link)
}
func (p *PostgreSQLRepository) close() {
p.db.Close()
}
func NewPostgreSQLRepository() *PostgreSQLRepository {
options, err := pg.ParseURL(config.DatabaseURL)
if err != nil {
log.Fatal("pg: Failed to parse URL", err)
}
db := pg.Connect(options)
for _, model := range []interface{}{&Link{}, &Counter{}} {
err := db.CreateTable(model, &orm.CreateTableOptions{
IfNotExists: true,
})
if err != nil {
log.Fatal(err)
}
}
return &PostgreSQLRepository{db}
}