-
Notifications
You must be signed in to change notification settings - Fork 5
/
pg.go
87 lines (75 loc) · 1.62 KB
/
pg.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
package database
import (
"context"
"fmt"
"github.com/dipdup-net/go-lib/config"
pg "github.com/go-pg/pg/v10"
"github.com/pkg/errors"
)
// PgGo -
type PgGo struct {
conn *pg.DB
}
// NewPgGo -
func NewPgGo() *PgGo {
return new(PgGo)
}
// DB -
func (db *PgGo) DB() *pg.DB {
return db.conn
}
// Connect -
func (db *PgGo) Connect(ctx context.Context, cfg config.Database) error {
if cfg.Kind != config.DBKindPostgres {
return errors.Wrap(ErrUnsupportedDatabaseType, cfg.Kind)
}
var conn *pg.DB
if cfg.Path != "" {
opt, err := pg.ParseURL(cfg.Path)
if err != nil {
return err
}
conn = pg.Connect(opt)
} else {
conn = pg.Connect(&pg.Options{
Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
User: cfg.User,
Password: cfg.Password,
Database: cfg.Database,
})
}
db.conn = conn
return nil
}
// Close -
func (db *PgGo) Close() error {
return db.conn.Close()
}
// Ping -
func (db *PgGo) Ping(ctx context.Context) error {
if db.conn == nil {
return ErrConnectionIsNotInitialized
}
return db.conn.Ping(ctx)
}
// State -
func (db *PgGo) State(indexName string) (*State, error) {
var s State
err := db.conn.Model(&s).Where("index_name = ?", indexName).Limit(1).Select()
return &s, err
}
// CreateState -
func (db *PgGo) CreateState(s *State) error {
_, err := db.conn.Model(s).Insert()
return err
}
// UpdateState -
func (db *PgGo) UpdateState(s *State) error {
_, err := db.conn.Model(s).Where("index_name = ?", s.IndexName).Update()
return err
}
// DeleteState -
func (db *PgGo) DeleteState(s *State) error {
_, err := db.conn.Model(s).Where("index_name = ?", s.IndexName).Delete()
return err
}