forked from jackc/pgx
/
opendbpool.go
60 lines (47 loc) · 1.32 KB
/
opendbpool.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
// +build go1.10
package stdlib
import (
"context"
"database/sql"
"database/sql/driver"
"github.com/jackc/pgx"
)
// OptionOpenDB options for configuring the driver when opening a new db pool.
type OptionOpenDBFromPool func(*poolConnector)
// OptionAfterConnect provide a callback for after connect.
func OptionPreferSimpleProtocol(preferSimpleProtocol bool) OptionOpenDBFromPool {
return func(dc *poolConnector) {
dc.preferSimpleProtocol = preferSimpleProtocol
}
}
// OpenDBFromPool create a sql.DB connection from a pgx.ConnPool
func OpenDBFromPool(pool *pgx.ConnPool, opts ...OptionOpenDBFromPool) *sql.DB {
c := poolConnector{
pool: pool,
driver: pgxDriver,
}
for _, opt := range opts {
opt(&c)
}
return sql.OpenDB(c)
}
type poolConnector struct {
pool *pgx.ConnPool
driver *Driver
preferSimpleProtocol bool
}
// Connect implement driver.Connector interface
func (pc poolConnector) Connect(ctx context.Context) (driver.Conn, error) {
var (
err error
conn *pgx.Conn
)
if conn, err = pc.pool.Acquire(); err != nil {
return nil, err
}
return &Conn{conn: conn, driver: pc.driver, connConfig: pgx.ConnConfig{PreferSimpleProtocol: pc.preferSimpleProtocol}}, nil
}
// Driver implement driver.Connector interface
func (pc poolConnector) Driver() driver.Driver {
return pc.driver
}