-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
connection.go
54 lines (46 loc) · 1.73 KB
/
connection.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 pg
import (
"fmt"
"time"
// need to make sure pgx driver is registered before opening connection
_ "github.com/jackc/pgx/v4/stdlib"
uuid "github.com/satori/go.uuid"
"github.com/scylladb/go-reflectx"
"github.com/smartcontractkit/sqlx"
"github.com/smartcontractkit/chainlink/v2/core/store/dialects"
)
type ConnectionConfig interface {
DatabaseDefaultIdleInTxSessionTimeout() time.Duration
DatabaseDefaultLockTimeout() time.Duration
ORMMaxOpenConns() int
ORMMaxIdleConns() int
}
func NewConnection(uri string, dialect dialects.DialectName, config ConnectionConfig) (db *sqlx.DB, err error) {
if dialect == dialects.TransactionWrappedPostgres {
// Dbtx uses the uri as a unique identifier for each transaction. Each ORM
// should be encapsulated in it's own transaction, and thus needs its own
// unique id.
//
// We can happily throw away the original uri here because if we are using
// txdb it should have already been set at the point where we called
// txdb.Register
uri = uuid.NewV4().String()
}
// Initialize sql/sqlx
db, err = sqlx.Open(string(dialect), uri)
if err != nil {
return nil, err
}
db.MapperFunc(reflectx.CamelToSnakeASCII)
// Set default connection options
lockTimeout := config.DatabaseDefaultLockTimeout().Milliseconds()
idleInTxSessionTimeout := config.DatabaseDefaultIdleInTxSessionTimeout().Milliseconds()
stmt := fmt.Sprintf(`SET TIME ZONE 'UTC'; SET lock_timeout = %d; SET idle_in_transaction_session_timeout = %d; SET default_transaction_isolation = %q`,
lockTimeout, idleInTxSessionTimeout, DefaultIsolation.String())
if _, err = db.Exec(stmt); err != nil {
return nil, err
}
db.SetMaxOpenConns(config.ORMMaxOpenConns())
db.SetMaxIdleConns(config.ORMMaxIdleConns())
return db, nil
}