-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnect.go
More file actions
79 lines (72 loc) · 1.95 KB
/
connect.go
File metadata and controls
79 lines (72 loc) · 1.95 KB
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
package dotpgx
import (
"crypto/tls"
"github.com/inconshreveable/log15"
"github.com/jackc/pgx"
)
type dbRuntime struct {
AppName string `usage:"Application name reported to PostgreSQL"`
}
// Config for database
type Config struct {
Name string `usage:"PostgreSQL database name"`
Host string `usage:"PostgreSQL host"`
Port uint `usage:"Postgresql port number"`
TLS bool `usage:"Enable TLS communication with database server"`
User string `usage:"PostgreSQL username"`
Password string `usage:"PostgreSQL password"`
MaxConnections int `usage:"Maximum DB connection pool size"`
RunTime dbRuntime
}
// Default config for database
var Default = Config{
Name: "dotpgx_test",
Host: "/run/postgresql",
Port: 5432,
User: "postgres",
MaxConnections: 5,
RunTime: dbRuntime{
AppName: "dotpgx connection lib",
},
}
// ConnPoolConfig parses the Config into a pgx.ConnPoolConfig
func (c Config) ConnPoolConfig() pgx.ConnPoolConfig {
cpc := pgx.ConnPoolConfig{
MaxConnections: c.MaxConnections,
ConnConfig: pgx.ConnConfig{
Database: c.Name,
Host: c.Host,
Port: uint16(c.Port),
User: c.User,
Password: c.Password,
},
}
if c.TLS {
cpc.ConnConfig.TLSConfig = &tls.Config{
ServerName: c.Host,
}
}
if c.RunTime != (dbRuntime{}) {
cpc.RuntimeParams = make(map[string]string)
if c.RunTime.AppName != "" {
cpc.RuntimeParams["application_name"] = c.RunTime.AppName
}
}
return cpc
}
// InitDB is a wrapper for New() and ParsePath().
// Config is the dotpgx config, which will be parsed into a pgx.ConnPoolConfig.
// Path is where sql queries will be parsed from.
func InitDB(c Config, path string) (db *DB, err error) {
if db, err = New(c.ConnPoolConfig()); err != nil {
return
}
if path == "" {
return
}
if err = db.ParsePath(path); err != nil {
return
}
log15.Debug("Loaded sql", "queries", db.List())
return
}