-
Notifications
You must be signed in to change notification settings - Fork 226
/
mysql.go
100 lines (87 loc) · 2.33 KB
/
mysql.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package mysql
import (
"database/sql"
"fmt"
"net/url"
"github.com/NYTimes/gizmo/config"
)
// Config holds everything you need to
// connect and interact with a MySQL DB.
type Config struct {
Pw string `envconfig:"MYSQL_PW"`
User string `envconfig:"MYSQL_USER"`
Port int `envconfig:"MYSQL_PORT"`
DBName string `envconfig:"MYSQL_DB_NAME"`
Location string `envconfig:"MYSQL_LOCATION"`
Host string `envconfig:"MYSQL_HOST_NAME"`
ReadTimeout string `envconfig:"MYSQL_READ_TIMEOUT"`
WriteTimeout string `envconfig:"MYSQL_WRITE_TIMEOUT"`
AddtlDSNOptions string `envconfig:"MYSQL_ADDTL_DSN_OPTIONS"`
}
const (
// DefaultLocation is the default location for MySQL connections.
DefaultLocation = "America/New_York"
// DefaultMySQLPort is the default port for MySQL connections.
DefaultMySQLPort = 3306
)
var (
// MaxOpenConns will be used to set a MySQL
// drivers MaxOpenConns value.
MaxOpenConns = 1
// MaxIdleConns will be used to set a MySQL
// drivers MaxIdleConns value.
MaxIdleConns = 1
)
// DB will attempt to open a sql connection with
// the credentials and the current MySQLMaxOpenConns
// and MySQLMaxIdleConns values.
// Users must import a mysql driver in their
// main to use this.
func (m *Config) DB() (*sql.DB, error) {
db, err := sql.Open("mysql", m.String())
if err != nil {
return db, err
}
db.SetMaxIdleConns(MaxIdleConns)
db.SetMaxOpenConns(MaxOpenConns)
return db, nil
}
// String will return the MySQL connection string.
func (m *Config) String() string {
if m.Port == 0 {
m.Port = DefaultMySQLPort
}
if m.Location != "" {
m.Location = url.QueryEscape(m.Location)
} else {
m.Location = url.QueryEscape(DefaultLocation)
}
args, _ := url.ParseQuery(m.AddtlDSNOptions)
args.Set("parseTime", "true")
if m.ReadTimeout != "" {
args.Set("readTimeout", m.ReadTimeout)
}
if m.WriteTimeout != "" {
args.Set("writeTimeout", m.WriteTimeout)
}
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?loc=%s&%s",
m.User,
m.Pw,
m.Host,
m.Port,
m.DBName,
m.Location,
args.Encode(),
)
}
// LoadConfigFromEnv will attempt to load a MySQL object
// from environment variables. If not populated, nil
// is returned.
func LoadConfigFromEnv() *Config {
var mysql Config
config.LoadEnvConfig(&mysql)
if mysql.Host != "" {
return &mysql
}
return nil
}