/
config.go
55 lines (41 loc) · 1.27 KB
/
config.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
package db
import (
"context"
"fmt"
"github.com/0xPolygon/cdk-data-availability/log"
"github.com/jmoiron/sqlx"
)
// Config provide fields to configure the pool
type Config struct {
// Database name
Name string `mapstructure:"Name"`
// Database User name
User string `mapstructure:"User"`
// Database Password of the user
Password string `mapstructure:"Password"`
// Host address of database
Host string `mapstructure:"Host"`
// Port Number of database
Port string `mapstructure:"Port"`
// EnableLog
// DEPRECATED
EnableLog bool `mapstructure:"EnableLog"`
// MaxConns is the maximum number of connections in the pool.
MaxConns int `mapstructure:"MaxConns"`
}
// InitContext initializes DB connection by the given config
func InitContext(ctx context.Context, cfg Config) (*sqlx.DB, error) {
psqlInfo := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.Name)
conn, err := sqlx.ConnectContext(ctx, "postgres", psqlInfo)
if err != nil {
log.Errorf("Unable to connect to database: %v\n", err)
return nil, err
}
conn.DB.SetMaxIdleConns(cfg.MaxConns)
if err = conn.PingContext(ctx); err != nil {
log.Errorf("Unable to ping the database: %v\n", err)
return nil, err
}
return conn, nil
}