-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathapi_postgres.go
76 lines (62 loc) · 1.22 KB
/
api_postgres.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
package db
import (
"database/sql"
"sync"
_ "github.com/lib/pq"
)
type luaPG struct {
config *dbConfig
sync.Mutex
db *sql.DB
}
func init() {
RegisterDriver(`postgres`, &luaPG{})
}
var (
sharedPG = make(map[string]*luaPG, 0)
sharedPGLock = &sync.Mutex{}
)
func (pg *luaPG) constructor(config *dbConfig) (luaDB, error) {
sharedPGLock.Lock()
defer sharedPGLock.Unlock()
if config.sharedMode {
result, ok := sharedPG[config.connString]
if ok {
return result, nil
}
}
db, err := sql.Open(`postgres`, config.connString)
if err != nil {
return nil, err
}
result := &luaPG{config: config}
db.SetMaxIdleConns(config.maxOpenConns)
db.SetMaxOpenConns(config.maxOpenConns)
result.db = db
if config.sharedMode {
sharedPG[config.connString] = result
}
return result, nil
}
func (pg *luaPG) getTXOptions() *sql.TxOptions {
return &sql.TxOptions{ReadOnly: pg.config.readOnly}
}
func (pg *luaPG) getDB() *sql.DB {
pg.Lock()
defer pg.Unlock()
return pg.db
}
func (pg *luaPG) closeDB() error {
pg.Lock()
defer pg.Unlock()
err := pg.db.Close()
if err != nil {
return err
}
if pg.config.sharedMode {
sharedPGLock.Lock()
delete(sharedPG, pg.config.connString)
sharedPGLock.Unlock()
}
return nil
}