-
Notifications
You must be signed in to change notification settings - Fork 280
/
config.go
105 lines (84 loc) · 2.17 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
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
package main
import (
"database/sql"
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"github.com/rubenv/sql-migrate"
"gopkg.in/gorp.v1"
"gopkg.in/yaml.v2"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
)
var dialects = map[string]gorp.Dialect{
"sqlite3": gorp.SqliteDialect{},
"postgres": gorp.PostgresDialect{},
"mysql": gorp.MySQLDialect{Engine: "InnoDB", Encoding: "UTF8"},
}
var ConfigFile string
var ConfigEnvironment string
func ConfigFlags(f *flag.FlagSet) {
f.StringVar(&ConfigFile, "config", "dbconfig.yml", "Configuration file to use.")
f.StringVar(&ConfigEnvironment, "env", "development", "Environment to use.")
}
type Environment struct {
Dialect string `yaml:"dialect"`
DataSource string `yaml:"datasource"`
Dir string `yaml:"dir"`
TableName string `yaml:"table"`
SchemaName string `yaml:"schema"`
}
func ReadConfig() (map[string]*Environment, error) {
file, err := ioutil.ReadFile(ConfigFile)
if err != nil {
return nil, err
}
config := make(map[string]*Environment)
err = yaml.Unmarshal(file, config)
if err != nil {
return nil, err
}
return config, nil
}
func GetEnvironment() (*Environment, error) {
config, err := ReadConfig()
if err != nil {
return nil, err
}
env := config[ConfigEnvironment]
if env == nil {
return nil, errors.New("No environment: " + ConfigEnvironment)
}
if env.Dialect == "" {
return nil, errors.New("No dialect specified")
}
if env.DataSource == "" {
return nil, errors.New("No data source specified")
}
env.DataSource = os.ExpandEnv(env.DataSource)
if env.Dir == "" {
env.Dir = "migrations"
}
if env.TableName != "" {
migrate.SetTable(env.TableName)
}
if env.SchemaName != "" {
migrate.SetSchema(env.SchemaName)
}
return env, nil
}
func GetConnection(env *Environment) (*sql.DB, string, error) {
db, err := sql.Open(env.Dialect, env.DataSource)
if err != nil {
return nil, "", fmt.Errorf("Cannot connect to database: %s", err)
}
// Make sure we only accept dialects that were compiled in.
_, exists := dialects[env.Dialect]
if !exists {
return nil, "", fmt.Errorf("Unsupported dialect: %s", env.Dialect)
}
return db, env.Dialect, nil
}