forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dialect_mysql.go
198 lines (164 loc) · 5.71 KB
/
dialect_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
196
197
198
package pop
import (
"bytes"
"database/sql"
"fmt"
"io"
"os"
"os/exec"
"strings"
// Load MySQL Go driver
_ "github.com/go-sql-driver/mysql"
"github.com/gobuffalo/fizz"
"github.com/gobuffalo/fizz/translators"
"github.com/gobuffalo/pop/columns"
"github.com/gobuffalo/pop/logging"
"github.com/markbates/going/defaults"
"github.com/pkg/errors"
)
func init() {
AvailableDialects = append(AvailableDialects, "mysql")
}
var _ dialect = &mysql{}
type mysql struct {
ConnectionDetails *ConnectionDetails
}
func (m *mysql) Name() string {
return "mysql"
}
func (m *mysql) Details() *ConnectionDetails {
return m.ConnectionDetails
}
func (m *mysql) URL() string {
deets := m.ConnectionDetails
if deets.URL != "" {
// Force multiStatements=true, migrations can fail otherwise.
if !strings.Contains(deets.URL, "multiStatements=true") {
log(logging.Warn, "multiStatements=true option is required to work with pop migrations. Please add it to the database URL in the config")
deets.URL += "&multiStatements=true"
}
return strings.TrimPrefix(deets.URL, "mysql://")
}
encoding := defaults.String(deets.Encoding, "utf8mb4_general_ci")
s := "%s:%s@(%s:%s)/%s?parseTime=true&multiStatements=true&readTimeout=1s&collation=%s"
return fmt.Sprintf(s, deets.User, deets.Password, deets.Host, deets.Port, deets.Database, encoding)
}
func (m *mysql) urlWithoutDb() string {
deets := m.ConnectionDetails
if deets.URL != "" {
// respect user's own URL definition (with options).
url := strings.TrimPrefix(deets.URL, "mysql://")
return strings.Replace(url, "/"+deets.Database+"?", "/?", 1)
}
encoding := defaults.String(deets.Encoding, "utf8mb4_general_ci")
s := "%s:%s@(%s:%s)/?parseTime=true&multiStatements=true&readTimeout=1s&collation=%s"
return fmt.Sprintf(s, deets.User, deets.Password, deets.Host, deets.Port, encoding)
}
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 := sql.Open(deets.Dialect, m.urlWithoutDb())
if err != nil {
return errors.Wrapf(err, "error creating MySQL database %s", deets.Database)
}
defer db.Close()
encoding := defaults.String(deets.Encoding, "utf8mb4_general_ci")
query := fmt.Sprintf("CREATE DATABASE `%s` DEFAULT COLLATE `%s`", deets.Database, encoding)
log(logging.SQL, query)
_, err = db.Exec(query)
if err != nil {
return errors.Wrapf(err, "error creating MySQL database %s", deets.Database)
}
log(logging.Info, "created database %s", deets.Database)
return nil
}
// DropDB drops an existing database, from the given connection credentials
func (m *mysql) DropDB() error {
deets := m.ConnectionDetails
db, err := sql.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(logging.SQL, query)
_, err = db.Exec(query)
if err != nil {
return errors.Wrapf(err, "error dropping MySQL database %s", deets.Database)
}
log(logging.Info, "dropped database %s", 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(logging.SQL, strings.Join(cmd.Args, " "))
cmd.Stdout = w
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
return err
}
log(logging.Info, "dumped schema for %s", m.Details().Database)
return nil
}
// LoadSchema executes a schema sql file against the configured database.
func (m *mysql) LoadSchema(r io.Reader) error {
return genericLoadSchema(m.ConnectionDetails, m.MigrationURL(), r)
}
// TruncateAll truncates all tables for the given connection.
func (m *mysql) TruncateAll(tx *Connection) error {
stmts := []string{}
err := tx.RawQuery(mysqlTruncate, m.Details().Database).All(&stmts)
if err != nil {
return err
}
if len(stmts) == 0 {
return nil
}
var qb bytes.Buffer
// #49: Disable foreign keys before truncation
qb.WriteString("SET SESSION FOREIGN_KEY_CHECKS = 0; ")
qb.WriteString(strings.Join(stmts, " "))
// #49: Re-enable foreign keys after truncation
qb.WriteString(" SET SESSION FOREIGN_KEY_CHECKS = 1;")
return tx.RawQuery(qb.String()).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 = ? AND table_type <> 'VIEW'"