forked from samsarahq/thunder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
70 lines (60 loc) · 1.27 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
package testfixtures
import (
"database/sql"
"fmt"
"math/rand"
)
type DBConfig struct {
Username string
Password string
Hostname string
Port uint16
}
func (d DBConfig) String() string {
return fmt.Sprintf("%s:%s@tcp(%s:%d)/", d.Username, d.Password, d.Hostname, d.Port)
}
var DefaultDBConfig = DBConfig{
Username: "root",
Password: "dev",
Hostname: "localhost",
Port: 3307,
}
type TestDatabase struct {
DBName string
ControlDB *sql.DB
*sql.DB
}
func NewTestDatabase() (*TestDatabase, error) {
controlDb, err := sql.Open("mysql", DefaultDBConfig.String())
if err != nil {
return nil, err
}
name := fmt.Sprintf("thunder_test_%d", rand.Intn(1<<30))
_, err = controlDb.Exec(fmt.Sprintf("CREATE DATABASE %s", name))
if err != nil {
controlDb.Close()
return nil, err
}
db, err := sql.Open("mysql", DefaultDBConfig.String()+name)
if err != nil {
controlDb.Close()
return nil, err
}
return &TestDatabase{
DB: db,
DBName: name,
ControlDB: controlDb,
}, nil
}
func (t *TestDatabase) Close() error {
if err := t.DB.Close(); err != nil {
return err
}
if _, err := t.ControlDB.Exec(fmt.Sprintf("DROP DATABASE %s", t.DBName)); err != nil {
return err
}
if err := t.ControlDB.Close(); err != nil {
return err
}
return nil
}