This repository has been archived by the owner on Jul 29, 2020. It is now read-only.
/
conn.go
132 lines (107 loc) · 2.42 KB
/
conn.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package connection
import (
"fmt"
"sync"
"github.com/jmoiron/sqlx"
"github.com/prest/config"
// Used pg drive on sqlx
_ "github.com/lib/pq"
)
var (
err error
pool *ConnectionPool
currDatabase string
)
// ConnectionPool struct
type ConnectionPool struct {
Mtx *sync.Mutex
DB map[string]*sqlx.DB
}
// GetURI postgres connection URI
func GetURI(DBName string) string {
var dbURI string
if DBName == "" {
DBName = config.PrestConf.PGDatabase
}
dbURI = fmt.Sprintf("user=%s dbname=%s host=%s port=%v sslmode=%v connect_timeout=%d",
config.PrestConf.PGUser,
DBName,
config.PrestConf.PGHost,
config.PrestConf.PGPort,
config.PrestConf.SSLMode,
config.PrestConf.PGConnTimeout)
if config.PrestConf.PGPass != "" {
dbURI += " password=" + config.PrestConf.PGPass
}
if config.PrestConf.SSLCert != "" {
dbURI += " sslcert=" + config.PrestConf.SSLCert
}
if config.PrestConf.SSLKey != "" {
dbURI += " sslkey=" + config.PrestConf.SSLKey
}
if config.PrestConf.SSLRootCert != "" {
dbURI += " sslrootcert=" + config.PrestConf.SSLRootCert
}
return dbURI
}
// Get get postgres connection
func Get() (*sqlx.DB, error) {
var DB *sqlx.DB
DB = getDatabaseFromPool(GetDatabase())
if DB != nil {
return DB, nil
}
DB, err = sqlx.Connect("postgres", GetURI(GetDatabase()))
if err != nil {
return nil, err
}
DB.SetMaxIdleConns(config.PrestConf.PGMaxIdleConn)
DB.SetMaxOpenConns(config.PrestConf.PGMAxOpenConn)
AddDatabaseToPool(GetDatabase(), DB)
return DB, nil
}
// GetPool of connection
func GetPool() *ConnectionPool {
if pool == nil {
pool = &ConnectionPool{
Mtx: &sync.Mutex{},
DB: make(map[string]*sqlx.DB),
}
}
return pool
}
func getDatabaseFromPool(name string) *sqlx.DB {
var DB *sqlx.DB
var p *ConnectionPool
p = GetPool()
p.Mtx.Lock()
DB = p.DB[GetURI(name)]
p.Mtx.Unlock()
return DB
}
// AddDatabaseToPool add connection to pool
func AddDatabaseToPool(name string, DB *sqlx.DB) {
var p *ConnectionPool
p = GetPool()
p.Mtx.Lock()
p.DB[GetURI(name)] = DB
p.Mtx.Unlock()
}
// MustGet get postgres connection
func MustGet() *sqlx.DB {
var err error
var DB *sqlx.DB
DB, err = Get()
if err != nil {
panic(fmt.Sprintf("Unable to connect to database: %v\n", err))
}
return DB
}
// SetDatabase set current database in use
func SetDatabase(name string) {
currDatabase = name
}
// GetDatabase get current database in use
func GetDatabase() string {
return currDatabase
}