-
Notifications
You must be signed in to change notification settings - Fork 18
/
database.go
83 lines (69 loc) · 1.78 KB
/
database.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
package db
import (
"context"
"fmt"
"net/url"
"time"
_ "github.com/jackc/pgx/v4/stdlib"
"github.com/jmoiron/sqlx"
"github.com/circleci/ex/config/secret"
"github.com/circleci/ex/o11y"
)
type Config struct {
Host string
Port int
User string
Pass secret.String
Name string
SSL bool
// If these are unset, then defaults will be chosen
ConnMaxLifetime time.Duration
MaxOpenConns int
MaxIdleConns int
}
// New connects to a database. The context passed in is expected to carry an o11y provider
// and is only used for reporting (not for cancellation),
func New(ctx context.Context, dbName, appName string, options Config) (db *sqlx.DB, err error) {
_, span := o11y.StartSpan(ctx, "config: connect to database")
defer o11y.End(span, &err)
host := fmt.Sprintf("%s:%d", options.Host, options.Port)
span.AddField("database", dbName)
span.AddField("host", host)
span.AddField("dbname", options.Name)
span.AddField("username", options.User)
params := url.Values{}
params.Set("connect_timeout", "5")
params.Set("application_name", appName)
if options.SSL {
params.Set("sslmode", "require")
} else {
params.Set("sslmode", "disable")
}
uri := url.URL{
Scheme: "postgres",
User: url.UserPassword(options.User, options.Pass.Value()),
Host: host,
Path: options.Name,
RawQuery: params.Encode(),
}
db, err = sqlx.Open("pgx", uri.String())
if err != nil {
return nil, err
}
if options.ConnMaxLifetime == 0 {
db.SetConnMaxLifetime(time.Hour)
} else {
db.SetConnMaxLifetime(options.ConnMaxLifetime)
}
if options.MaxOpenConns == 0 {
db.SetMaxOpenConns(100)
} else {
db.SetMaxOpenConns(options.MaxOpenConns)
}
if options.MaxIdleConns == 0 {
db.SetMaxIdleConns(100)
} else {
db.SetMaxIdleConns(options.MaxIdleConns)
}
return db, nil
}