This repository has been archived by the owner on Oct 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathdbconf.go
224 lines (191 loc) · 4.85 KB
/
dbconf.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package goose
import (
"database/sql"
"errors"
"fmt"
"log"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/kylelemons/go-gypsy/yaml"
)
// DBDriver encapsulates the info needed to work with
// a specific database driver
type DBDriver struct {
Name string
DSN string
Import string
Dialect SqlDialect
}
type DBConf struct {
MigrationsDir string
Driver DBDriver
}
var defaultDBConfYaml = `
migrationsDir: $DB_MIGRATIONS_DIR
driver: $DB_DRIVER
import: $DB_DRIVER_IMPORT
dialect: $DB_DIALECT
dsn: $DB_DSN
`
// findDBConf looks for a dbconf.yaml file starting at the given directory and
// walking up in the directory hierarchy.
// Returns empty string if not found.
func findDBConf(dbDir string) string {
dbDir, err := filepath.Abs(dbDir)
if err != nil {
return ""
}
for {
paths := []string{
"dbconf.yaml",
"dbconf.yml",
filepath.Join("db", "dbconf.yaml"),
filepath.Join("db", "dbconf.yml"),
}
for _, path := range paths {
path = filepath.Join(dbDir, path)
if _, err := os.Stat(path); err == nil {
return path
}
}
nextDir := filepath.Dir(dbDir)
if nextDir == dbDir {
// at the root
break
}
dbDir = nextDir
}
return ""
}
func confGet(f *yaml.File, env string, name string) (string, error) {
if env != "" {
if v, err := f.Get(fmt.Sprintf("%s.%s", env, name)); err == nil {
return os.ExpandEnv(v), nil
}
}
v, err := f.Get(name)
if err != nil {
return "", err
}
return os.ExpandEnv(v), nil
}
// extract configuration details from the given file
func NewDBConf(dbDir, env string) (*DBConf, error) {
cfgFile := findDBConf(dbDir)
var f *yaml.File
if cfgFile == "" {
root, _ := yaml.Parse(strings.NewReader(defaultDBConfYaml))
f = &yaml.File{
Root: root,
}
} else {
dbDir = filepath.Dir(cfgFile)
var err error
f, err = yaml.ReadFile(cfgFile)
if err != nil {
return nil, fmt.Errorf("error loading config file: %s", err)
}
}
migrationsDir := filepath.Join(dbDir, "migrations")
if md, err := confGet(f, env, "migrationsDir"); err == nil {
if filepath.IsAbs(md) {
migrationsDir = md
} else {
migrationsDir = filepath.Join(dbDir, md)
}
}
drv, err := confGet(f, env, "driver")
if err != nil {
return nil, err
}
var imprt string
// see if "driver" param is a full import path
if i := strings.LastIndex(drv, "/"); i != -1 {
imprt = drv
drv = imprt[i+1:]
}
dsn, err := confGet(f, env, "dsn")
if _, ok := err.(*yaml.NodeNotFound); ok {
log.Println("WARNING: Database 'dsn' not specified. Please check ensure " +
"that you have a 'dsn' node set in your dbconf file. If you " +
"are not using a conf file please ensure that you have set " +
"the 'DB_DSN' environment variable.")
}
d := newDBDriver(drv, dsn)
if imprt != "" {
d.Import = imprt
}
// allow the configuration to override the Import for this driver
if imprt, err := confGet(f, env, "import"); err == nil && imprt != "" {
d.Import = imprt
}
// allow the configuration to override the Dialect for this driver
if dialect, err := confGet(f, env, "dialect"); err == nil && dialect != "" {
d.Dialect = dialectByName(dialect)
}
if !d.IsValid() {
return nil, errors.New(fmt.Sprintf("Invalid DBConf: %v", d))
}
return &DBConf{
MigrationsDir: migrationsDir,
Driver: d,
}, nil
}
// Create a new DBDriver and populate driver specific
// fields for drivers that we know about.
// Further customization may be done in NewDBConf
func newDBDriver(name, open string) DBDriver {
d := DBDriver{
Name: name,
DSN: open,
}
switch strings.ToLower(name) {
case "postgres":
d.Name = "postgres"
d.Import = "github.com/lib/pq"
d.Dialect = &PostgresDialect{}
case "redshift":
d.Name = "postgres"
d.Import = "github.com/lib/pq"
d.Dialect = &RedshiftDialect{}
case "mymysql":
d.Import = "github.com/ziutek/mymysql/godrv"
d.Dialect = &MySqlDialect{}
case "mysql":
d.Import = "github.com/go-sql-driver/mysql"
d.Dialect = &MySqlDialect{}
case "sqlite3":
d.Name = "sqlite3"
d.Import = "github.com/mattn/go-sqlite3"
d.Dialect = &Sqlite3Dialect{}
}
return d
}
// ensure we have enough info about this driver
func (drv *DBDriver) IsValid() bool {
return len(drv.Import) > 0 && drv.Dialect != nil
}
// OpenDBFromDBConf wraps database/sql.DB.Open() and configures
// the newly opened DB based on the given DBConf.
//
// Callers must Close() the returned DB.
func OpenDBFromDBConf(conf *DBConf) (*sql.DB, error) {
// we depend on time parsing, so make sure it's enabled with the mysql driver
if conf.Driver.Name == "mysql" {
i := strings.Index(conf.Driver.DSN, "?")
if i == -1 {
i = len(conf.Driver.DSN)
conf.Driver.DSN = conf.Driver.DSN + "?"
}
i++
q, err := url.ParseQuery(conf.Driver.DSN[i:])
if err != nil {
return nil, err
}
q.Set("parseTime", "true")
conf.Driver.DSN = conf.Driver.DSN[:i] + q.Encode()
}
return sql.Open(conf.Driver.Name, conf.Driver.DSN)
}