-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpg.go
116 lines (107 loc) · 1.98 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package services
import (
"crypto/tls"
"fmt"
"sync"
"github.com/go-pg/pg/v10"
"github.com/urfave/cli"
)
const (
pgHostFlag = "postgres-host"
pgPortFlag = "postgres-port"
pgUserFlag = "postgres-user"
pgPasswordFlag = "postgres-password"
pgDatabaseFlag = "postgres-database"
pgSSLFlag = "postgres-ssl"
)
func RegisterPGFlags(f []cli.Flag) []cli.Flag {
return append(f,
cli.StringFlag{
Name: pgHostFlag,
Usage: "postgres host",
Value: "",
EnvVar: "PG_HOST",
},
cli.IntFlag{
Name: pgPortFlag,
Usage: "postgres port",
Value: 5432,
EnvVar: "PG_PORT",
},
cli.StringFlag{
Name: pgUserFlag,
Usage: "postgres user",
Value: "",
EnvVar: "PG_USER",
},
cli.StringFlag{
Name: pgPasswordFlag,
Usage: "postgres password",
Value: "",
EnvVar: "PG_PASSWORD",
},
cli.StringFlag{
Name: pgDatabaseFlag,
Usage: "postgres database",
Value: "",
EnvVar: "PG_DATABASE",
},
cli.BoolFlag{
Name: pgSSLFlag,
Usage: "postgres ssl",
EnvVar: "PG_SSL",
},
)
}
type PG struct {
host string
port int
user string
password string
database string
ssl bool
db *pg.DB
mux sync.Mutex
inited bool
}
func NewPG(c *cli.Context) *PG {
return &PG{
host: c.String(pgHostFlag),
port: c.Int(pgPortFlag),
user: c.String(pgUserFlag),
password: c.String(pgPasswordFlag),
database: c.String(pgDatabaseFlag),
ssl: c.Bool(pgSSLFlag),
}
}
func (s *PG) get() *pg.DB {
if s.host == "" {
return nil
}
opts := &pg.Options{}
opts.Addr = fmt.Sprintf("%v:%v", s.host, s.port)
opts.User = s.user
opts.Password = s.password
opts.Database = s.database
if s.ssl {
opts.TLSConfig = &tls.Config{
InsecureSkipVerify: true,
}
}
return pg.Connect(opts)
}
func (s *PG) Get() *pg.DB {
s.mux.Lock()
defer s.mux.Unlock()
if s.inited {
return s.db
}
s.db = s.get()
s.inited = true
return s.db
}
func (s *PG) Close() {
if s.db != nil {
s.db.Close()
}
}