-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
mysql.go
96 lines (80 loc) · 1.91 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
package testutils
import (
"fmt"
"io/ioutil"
"log"
"path"
"runtime"
"strings"
"github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"github.com/whywaita/myshoes/pkg/datastore"
)
const schemaDirRelativePathFormat = "%s/../../pkg/datastore/mysql/%s"
func execSchema(fpath string) {
b, err := ioutil.ReadFile(fpath)
if err != nil {
log.Fatalf("schema reading error: %v", err)
}
queries := strings.Split(string(b), ";")
for _, query := range queries[:len(queries)-1] {
_, err = testDB.Exec(query)
if err != nil {
log.Fatalf("exec schema error: %v, query: %s", err, query)
}
}
}
func createTablesIfNotExist() {
_, pwd, _, _ := runtime.Caller(0)
schemaPath := fmt.Sprintf(schemaDirRelativePathFormat, path.Dir(pwd), "schema.sql")
execSchema(schemaPath)
}
func truncateTables() {
rows, err := testDB.Query("SHOW TABLES")
if err != nil {
log.Fatalf("show tables error: %#v", err)
}
defer rows.Close()
for rows.Next() {
var tableName string
err = rows.Scan(&tableName)
if err != nil {
log.Fatalf("show table error: %#v", err)
continue
}
cmds := []string{
"SET FOREIGN_KEY_CHECKS = 0",
fmt.Sprintf("TRUNCATE %s", tableName),
"SET FOREIGN_KEY_CHECKS = 1",
}
for _, cmd := range cmds {
_, err := testDB.Exec(cmd)
if err != nil {
mysqlErr, ok := err.(*mysql.MySQLError)
if ok {
if mysqlErr.Number == 0xde2 {
// is rejected
continue
}
} else {
log.Fatalf("truncate error: %#v", err)
continue
}
}
}
}
}
// GetTestDatastore return pointer of datastore
func GetTestDatastore() (datastore.Datastore, func()) {
if testDatastore == nil {
panic("datastore is not initialized yet")
}
return testDatastore, func() { truncateTables() }
}
// GetTestDB return pointer of testDB
func GetTestDB() (*sqlx.DB, func()) {
if testDB == nil {
panic("testDB is not initialized yet")
}
return testDB, func() { truncateTables() }
}