-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdb.go
187 lines (162 loc) · 4.48 KB
/
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
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
package main
import (
"bufio"
"compress/gzip"
"database/sql"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
_ "github.com/go-sql-driver/mysql"
migrate "github.com/rubenv/sql-migrate"
"github.com/spf13/viper"
)
func getDB() *sql.DB { //Create database connection
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?multiStatements=true&parseTime=true&maxAllowedPacket=0", viper.GetString("db-user"), viper.GetString("db-pass"), viper.GetString("db-host"), viper.GetString("db-port"), viper.GetString("db-database"))
dialect := "mysql"
db, err := sql.Open(dialect, dsn)
if err != nil {
panic(err)
}
db.SetConnMaxLifetime(time.Minute * 3)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
return db
}
func checkDBConnection() {
tries := 0
for tries < 1000 {
db := getDB()
_, err := db.Query("SELECT 1") //Query doesn't need to do anything, we just use to see if DB is not dead
if err == nil {
db.Close()
log.Info("DB connection re-established.")
break
}
db.Close()
log.Info("DB connection died, writing for server...")
time.Sleep(2 * time.Second)
tries += 1
}
}
func GetNumberOfTables() int {
db := getDB()
var value string
sqlStatement := `SELECT count(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ?;`
err := db.QueryRow(sqlStatement, viper.GetString("db-database")).Scan(&value)
if err != nil {
log.Fatal("Failed to query db; ", err)
}
number, _ := strconv.Atoi(value)
db.Close()
return number
}
//Read in gzipped file into an in-memory string array
func ReadGzFile(filename string) ([]string, error) {
f, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer f.Close()
gr, err := gzip.NewReader(f)
if err != nil {
log.Fatal(err)
}
defer gr.Close()
var lines []string
scanner := bufio.NewScanner(gr)
buf := make([]byte, 0, 64*1024)
scanner.Buffer(buf, 1024*1024)
for scanner.Scan() {
if !strings.HasPrefix(scanner.Text(), "--") { //We don't want comments
if strings.TrimSpace(scanner.Text()) != "" { //Or blank lines
if scanner.Text()[len(scanner.Text())-1:] == ";" {
newString := scanner.Text()[:len(scanner.Text())-1] + "[LINEBREAK]"
lines = append(lines, newString)
} else {
lines = append(lines, scanner.Text())
}
}
}
}
output := strings.Join(lines, "")
var queryset []string
for _, str := range strings.Split(output, "[LINEBREAK]") {
if str != "" {
queryset = append(queryset, str)
}
}
for i, s := range queryset {
log.Trace(i, " ##", s, "##")
}
return queryset, scanner.Err()
}
func BuildMigration(fileName string, data []string) *migrate.Migration {
//Build our migration for base file
log.Debug("Building migration for base file ", fileName)
migration := &migrate.Migration{
Id: "BASE_" + fileName,
Up: data,
Down: []string{},
}
return migration
}
func InstallBase() {
var files []string
//Walk base dir for all files and put that into an array
err := filepath.Walk(viper.GetString("base-dir"), func(path string, info os.FileInfo, err error) error {
if !info.IsDir() { //We only want files, not dirs
files = append(files, path)
}
return nil
})
if err != nil {
log.Error("ERROR: ", err)
}
log.Trace("Base files to install: ")
for _, file := range files {
log.Trace(file)
}
migrations := []*migrate.Migration{}
migrate.SetTable("base_migrations")
for _, file := range files {
log.Debug("Decompressing ", file, "...")
//Un-gzip the files...
fileData, err := ReadGzFile(file)
if err != nil {
log.Error("Failed to read in GZ data: ", err)
}
log.Info("Building migration for ", file, "...")
newMigration := BuildMigration(file, fileData)
migrations = append(migrations, newMigration)
log.Info("Executing migration...")
migrationSource := &migrate.MemoryMigrationSource{migrations}
//Create a new DB connection (to avoid exhausting limit)
db := getDB()
n, err := migrate.Exec(db, "mysql", migrationSource, migrate.Up)
if err != nil {
log.Error("Error installing migration: ", err)
//Check if DB died
checkDBConnection()
}
db.Close()
log.Info("Applied ", n, " migrations!")
}
}
func InstallMigrations() {
// OR: Read migrations from a folder:
migrationSource := &migrate.FileMigrationSource{
Dir: viper.GetString("migrations-dir"),
}
migrate.SetTable("migrations")
//Create a new DB connection (to avoid exhausting limit)
db := getDB()
n, err := migrate.Exec(db, "mysql", migrationSource, migrate.Up)
if err != nil {
log.Error("Error installing migration: ", err)
}
db.Close()
log.Info("Applied %d migrations!\n", n)
}