-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhermes.go
54 lines (42 loc) · 1.17 KB
/
hermes.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
package hermes
import (
"context"
"sync"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
)
var dataTypes []pgtype.DataType
var dtMutex sync.RWMutex
// Connect creates a pgx database connection pool and returns it.
func Connect(uri string) (*DB, error) {
config, err := pgxpool.ParseConfig(uri)
if err != nil {
return nil, err
}
return ConnectConfig(config)
}
// ConnectConfig creates a pgx database connection pool based on a pool configuration and returns
// it.
func ConnectConfig(config *pgxpool.Config) (*DB, error) {
config.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
dtMutex.RLock()
defer dtMutex.RUnlock()
for _, dt := range dataTypes {
conn.ConnInfo().RegisterDataType(dt)
}
return nil
}
pool, err := pgxpool.ConnectConfig(context.Background(), config)
if err != nil {
return nil, err
}
return &DB{pool}, nil
}
// Register a new datatype to be associated with connections, such as a custom UUID or time data
// types. Best to call this before calling Connect.
func Register(dataType pgtype.DataType) {
dtMutex.Lock()
defer dtMutex.Unlock()
dataTypes = append(dataTypes, dataType)
}