-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb.go
50 lines (43 loc) · 917 Bytes
/
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
package gocommerce
import (
"context"
"database/sql"
"os"
_ "github.com/go-sql-driver/mysql" //nolint
)
var defaultSockets = []string{
"/var/run/mysqld/mysqld.sock",
"/var/lib/mysql/mysql.sock",
}
// NB copy StoreConfig, as we may modify it
func ConnectDB(ctx context.Context, cfg DBConfig) (*sql.DB, error) {
// Mimic libmysql behavior, where "localhost" is overridden with
// system specific unix socket.
if cfg.Host == "localhost" || cfg.Host == "" {
for _, s := range defaultSockets {
if isSocket(s) {
cfg.Host = s
break
}
}
}
db, err := sql.Open("mysql", cfg.DSN())
if err != nil {
return nil, err
}
if ctx == nil {
ctx = context.Background()
}
err = db.PingContext(ctx)
if err != nil {
return nil, err
}
return db, nil
}
func isSocket(path string) bool {
s, e := os.Stat(path)
if e != nil {
return false
}
return s.Mode()&os.ModeSocket == os.ModeSocket
}