forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql.go
195 lines (163 loc) · 5 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
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
188
189
190
191
192
193
194
195
package pop
import (
"fmt"
"io"
"os"
"os/exec"
"strings"
// Load MySQL Go driver
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"github.com/markbates/pop/columns"
"github.com/markbates/pop/fizz"
"github.com/markbates/pop/fizz/translators"
"github.com/pkg/errors"
)
var _ dialect = &mysql{}
type mysql struct {
ConnectionDetails *ConnectionDetails
}
func (m *mysql) Details() *ConnectionDetails {
return m.ConnectionDetails
}
func (m *mysql) URL() string {
c := m.ConnectionDetails
if m.ConnectionDetails.URL != "" {
return strings.TrimPrefix(m.ConnectionDetails.URL, "mysql://")
}
s := "%s:%s@(%s:%s)/%s?parseTime=true&multiStatements=true&readTimeout=1s"
return fmt.Sprintf(s, c.User, c.Password, c.Host, c.Port, c.Database)
}
func (m *mysql) urlWithoutDb() string {
c := m.ConnectionDetails
s := "%s:%s@(%s:%s)/?parseTime=true&multiStatements=true&readTimeout=1s"
return fmt.Sprintf(s, c.User, c.Password, c.Host, c.Port)
}
func (m *mysql) MigrationURL() string {
return m.URL()
}
func (m *mysql) Create(s store, model *Model, cols columns.Columns) error {
return errors.Wrap(genericCreate(s, model, cols), "mysql create")
}
func (m *mysql) Update(s store, model *Model, cols columns.Columns) error {
return errors.Wrap(genericUpdate(s, model, cols), "mysql update")
}
func (m *mysql) Destroy(s store, model *Model) error {
return errors.Wrap(genericDestroy(s, model), "mysql destroy")
}
func (m *mysql) SelectOne(s store, model *Model, query Query) error {
return errors.Wrap(genericSelectOne(s, model, query), "mysql select one")
}
func (m *mysql) SelectMany(s store, models *Model, query Query) error {
return errors.Wrap(genericSelectMany(s, models, query), "mysql select many")
}
// CreateDB creates a new database, from the given connection credentials
func (m *mysql) CreateDB() error {
deets := m.ConnectionDetails
db, err := sqlx.Open(deets.Dialect, m.urlWithoutDb())
if err != nil {
return errors.Wrapf(err, "error creating MySQL database %s", deets.Database)
}
defer db.Close()
query := fmt.Sprintf("CREATE DATABASE `%s` DEFAULT COLLATE `utf8_general_ci`", deets.Database)
Log(query)
_, err = db.Exec(query)
if err != nil {
return errors.Wrapf(err, "error creating MySQL database %s", deets.Database)
}
fmt.Printf("created database %s\n", deets.Database)
return nil
}
// DropDB drops an existing database, from the given connection credentials
func (m *mysql) DropDB() error {
deets := m.ConnectionDetails
db, err := sqlx.Open(deets.Dialect, m.urlWithoutDb())
if err != nil {
return errors.Wrapf(err, "error dropping MySQL database %s", deets.Database)
}
defer db.Close()
query := fmt.Sprintf("DROP DATABASE `%s`", deets.Database)
Log(query)
_, err = db.Exec(query)
if err != nil {
return errors.Wrapf(err, "error dropping MySQL database %s", deets.Database)
}
fmt.Printf("dropped database %s\n", deets.Database)
return nil
}
func (m *mysql) TranslateSQL(sql string) string {
return sql
}
func (m *mysql) FizzTranslator() fizz.Translator {
t := translators.NewMySQL(m.URL(), m.Details().Database)
return t
}
func (m *mysql) Lock(fn func() error) error {
return fn()
}
func (m *mysql) DumpSchema(w io.Writer) error {
deets := m.Details()
cmd := exec.Command("mysqldump", "-d", "-h", deets.Host, "-P", deets.Port, "-u", deets.User, fmt.Sprintf("--password=%s", deets.Password), deets.Database)
if deets.Port == "socket" {
cmd = exec.Command("mysqldump", "-d", "-S", deets.Host, "-u", deets.User, fmt.Sprintf("--password=%s", deets.Password), deets.Database)
}
Log(strings.Join(cmd.Args, " "))
cmd.Stdout = w
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
return err
}
fmt.Printf("dumped schema for %s\n", m.Details().Database)
return nil
}
func (m *mysql) LoadSchema(r io.Reader) error {
deets := m.Details()
cmd := exec.Command("mysql", "-u", deets.User, fmt.Sprintf("--password=%s", deets.Password), "-h", deets.Host, "-P", deets.Port, "-D", deets.Database)
if deets.Port == "socket" {
cmd = exec.Command("mysql", "-u", deets.User, fmt.Sprintf("--password=%s", deets.Password), "-S", deets.Host, "-D", deets.Database)
}
in, err := cmd.StdinPipe()
if err != nil {
return err
}
go func() {
defer in.Close()
io.Copy(in, r)
}()
Log(strings.Join(cmd.Args, " "))
err = cmd.Start()
if err != nil {
return err
}
err = cmd.Wait()
if err != nil {
return err
}
fmt.Printf("loaded schema for %s\n", m.Details().Database)
return nil
}
func (m *mysql) TruncateAll(tx *Connection) error {
stmts := []struct {
Stmt string `db:"stmt"`
}{}
err := tx.RawQuery(mysqlTruncate, m.Details().Database).All(&stmts)
if err != nil {
return err
}
if len(stmts) == 0 {
return nil
}
qs := []string{}
for _, x := range stmts {
qs = append(qs, x.Stmt)
}
return tx.RawQuery(strings.Join(qs, " ")).Exec()
}
func newMySQL(deets *ConnectionDetails) dialect {
cd := &mysql{
ConnectionDetails: deets,
}
return cd
}
const mysqlTruncate = "SELECT concat('TRUNCATE TABLE `', TABLE_NAME, '`;') as stmt FROM INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = ?"