-
Notifications
You must be signed in to change notification settings - Fork 3
/
database.go
63 lines (50 loc) · 1.24 KB
/
database.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
package main
import (
"bytes"
"log"
"os"
_ "github.com/go-sql-driver/mysql"
"gopkg.in/yaml.v2"
)
func databasePath(file string, environment string) string {
yamlFile, err := os.ReadFile(file)
if err != nil {
log.Fatalf("cannot read %q: %v", file, err)
}
dbConfig := make(map[string]map[string]string)
err = yaml.Unmarshal(yamlFile, &dbConfig)
if err != nil {
log.Fatalf("cannot parse %q: %v", file, err)
}
buffer := new(bytes.Buffer)
envConfig := dbConfig[environment]
if len(envConfig) == 0 {
log.Fatalf("invalid RAILS_ENV: %q", environment)
}
host := envConfig["host"]
port := envConfig["port"]
socket := envConfig["socket"]
username := envConfig["username"]
password := envConfig["password"]
database := envConfig["database"]
buffer.WriteString(username)
if password != "" {
buffer.WriteString(":" + password)
}
buffer.WriteString("@")
if socket != "" {
buffer.WriteString("unix(" + socket + ")")
} else if host != "" {
buffer.WriteString("tcp(" + host + ":")
if port == "" {
buffer.WriteString("3306")
} else {
buffer.WriteString(port)
}
buffer.WriteString(")")
} else {
log.Fatal("socket or host must be set in database config")
}
buffer.WriteString("/" + database)
return buffer.String()
}