-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
52 lines (40 loc) · 1.04 KB
/
db.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
package db
import (
"database/sql"
"fmt"
"net/url"
// supported drivers
_ "github.com/mattn/go-sqlite3"
)
type logger interface {
Debug(string, ...interface{})
}
// Config contains database configuration.
type Config struct {
Addr string `yaml:"addr"`
MaxOpenConnections int `yaml:"max_open_connections"`
}
// New returns a database instance.
func New(cfg *Config, logger logger) (*sql.DB, error) {
if cfg == nil {
cfg = &Config{}
}
if cfg.Addr == "" {
return nil, fmt.Errorf("addr is not set")
}
u, err := url.Parse(cfg.Addr)
if err != nil {
return nil, fmt.Errorf("failed to parse addr: %w", err)
}
addr := fmt.Sprintf("%s%s?%s", u.Hostname(), u.Path, u.RawQuery)
logger.Debug("connecting to ':%s' on '%s'", u.Scheme, addr)
db, err := sql.Open(u.Scheme, addr)
if err != nil {
return nil, fmt.Errorf("failed to connect to database: %w", err)
}
db.SetMaxOpenConns(cfg.MaxOpenConnections)
if err := db.Ping(); err != nil {
return nil, fmt.Errorf("failed to ping the database: %w", err)
}
return db, nil
}