-
Notifications
You must be signed in to change notification settings - Fork 0
/
migration_test.go
342 lines (271 loc) · 8.6 KB
/
migration_test.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package migration
import (
"database/sql"
"fmt"
"os"
"strings"
"testing"
code_based "github.com/stimtech/go-migration/v2/test/code-based"
code_based_fail "github.com/stimtech/go-migration/v2/test/code-based-fail"
_ "github.com/go-sql-driver/mysql"
_ "github.com/jackc/pgx/v4/stdlib"
_ "github.com/mattn/go-sqlite3"
"github.com/stretchr/testify/assert"
"go.uber.org/zap"
)
type SQLDialect string
const (
MySQL = SQLDialect("mysql")
PostGreSQL = SQLDialect("pgx")
Sqlite = SQLDialect("sqlite3")
)
// To run these tests on mysql and postgres, uncomment the connectionStrings
// and start mysql and postgres using `docker-compose up`.
func TestService_Migrate(t *testing.T) {
connectionStrings := map[SQLDialect]string{
//MySQL: "mig:mig@tcp(127.0.0.1:3306)/mig?parseTime=true",
//PostGreSQL: "postgresql://mig:[email protected]:5432/mig",
Sqlite: "mig.db",
}
for d, c := range connectionStrings {
t.Run(fmt.Sprintf("[%s] %s", d, "Init - ok"), func(t *testing.T) {
db, err := sql.Open(string(d), c)
if !assert.NoError(t, err) {
return
}
defer func() { _ = db.Close() }()
s := New(db, ZapOption{Logger: zap.NewNop()}, Config{MigrationFolder: "test/init"})
dropTables(s, d)
err = s.Migrate()
assert.NoError(t, err)
tables, err := getTableNames(s, d)
if !assert.NoError(t, err, "could not query for tables") {
return
}
assert.Equal(t, []string{"migration", "migration_lock", "test"}, tables)
})
t.Run(fmt.Sprintf("[%s] %s", d, "Init again - ok"), func(t *testing.T) {
db, err := sql.Open(string(d), c)
if !assert.NoError(t, err) {
return
}
defer func() { _ = db.Close() }()
s := New(db, ZapOption{Logger: zap.NewNop()}, Config{MigrationFolder: "test/init"})
err = s.Migrate()
assert.NoError(t, err)
tables, err := getTableNames(s, d)
if !assert.NoError(t, err, "could not query for tables") {
return
}
assert.Equal(t, []string{"migration", "migration_lock", "test"}, tables)
})
t.Run(fmt.Sprintf("[%s] %s", d, "Different init - fail"), func(t *testing.T) {
db, err := sql.Open(string(d), c)
if !assert.NoError(t, err) {
return
}
defer func() { _ = db.Close() }()
s := New(db, ZapOption{Logger: zap.NewNop()}, Config{MigrationFolder: "test/diff-init"})
err = s.Migrate()
assert.Error(t, err)
tables, err := getTableNames(s, d)
if !assert.NoError(t, err, "could not query for tables") {
return
}
assert.Equal(t, []string{"migration", "migration_lock", "test"}, tables)
})
t.Run(fmt.Sprintf("[%s] %s", d, "Multiple files - ok"), func(t *testing.T) {
db, err := sql.Open(string(d), c)
if !assert.NoError(t, err) {
return
}
defer func() { _ = db.Close() }()
s := New(db, ZapOption{Logger: zap.NewNop()}, Config{MigrationFolder: "test/multi"})
err = s.Migrate()
assert.NoError(t, err)
tables, err := getTableNames(s, d)
if !assert.NoError(t, err, "could not query for tables") {
return
}
assert.Equal(t, []string{"migration", "migration_lock", "multi", "multi2", "test"}, tables)
})
t.Run(fmt.Sprintf("[%s] %s", d, "Failing statement - fail"), func(t *testing.T) {
db, err := sql.Open(string(d), c)
if !assert.NoError(t, err) {
return
}
defer func() { _ = db.Close() }()
s := New(db, ZapOption{Logger: zap.NewNop()}, Config{MigrationFolder: "."},
FSOption{FileSystem: os.DirFS("test/failing-stmt")})
err = s.Migrate()
assert.Error(t, err)
tables, err := getTableNames(s, d)
if !assert.NoError(t, err, "could not query for tables") {
return
}
if d == MySQL { // MySQL can't roll back DDL statements
assert.Equal(t, []string{"migration", "migration_lock", "multi", "multi2", "should_rollback", "test"}, tables)
} else {
assert.Equal(t, []string{"migration", "migration_lock", "multi", "multi2", "test"}, tables)
}
})
t.Run(fmt.Sprintf("[%s] %s", d, "Missing folder - fail"), func(t *testing.T) {
db, err := sql.Open(string(d), c)
if !assert.NoError(t, err) {
return
}
defer func() { _ = db.Close() }()
s := New(db, ZapOption{Logger: zap.NewNop()}, Config{MigrationFolder: "test/no-folder"})
err = s.Migrate()
assert.Error(t, err)
if assert.Error(t, err) {
assert.True(t, strings.Contains(err.Error(), "failed to list available migrations"))
}
})
t.Run(fmt.Sprintf("[%s] %s", d, "No read access to file - fail"), func(t *testing.T) {
db, err := sql.Open(string(d), c)
if !assert.NoError(t, err) {
return
}
defer func() { _ = db.Close() }()
s := New(db, ZapOption{Logger: zap.NewNop()}, Config{MigrationFolder: "test/no-access"})
_ = os.Chmod("test/no-access/no-access.sql", os.ModeExclusive)
defer func() { _ = os.Chmod("test/no-access/no-access.sql", os.ModePerm) }()
err = s.Migrate()
if assert.Error(t, err) {
assert.True(t, strings.Contains(err.Error(), "permission denied"))
}
})
t.Run(fmt.Sprintf("[%s] %s", d, "Code based migrations"), func(t *testing.T) {
db, err := sql.Open(string(d), c)
if !assert.NoError(t, err) {
return
}
defer func() { _ = db.Close() }()
s := New(db, ZapOption{Logger: zap.NewNop()}, Config{MigrationFolder: "test/code-based"}, FuncMigrationOption{
Migration: &code_based.CBTest2{
Name: "cb_test2.go",
},
})
err = s.Migrate()
assert.NoError(t, err)
// Check that schema matches expected layout.
tables, err := getTableNames(s, d)
if !assert.NoError(t, err, "could not query for tables") {
return
}
if d == MySQL { // MySQL can't roll back DDL statements
assert.Equal(t, []string{
"cb_1_initial",
"cb_2_from_code",
"migration",
"migration_lock",
"multi",
"multi2",
"should_rollback",
"test",
}, tables)
} else {
assert.Equal(t, []string{
"cb_1_initial",
"cb_2_from_code",
"migration",
"migration_lock",
"multi",
"multi2",
"test",
}, tables)
}
// Check that values in tables inserted as expected.
{ // Table created through SQL.
t1Val := &sql.NullString{}
err = db.QueryRow("select id from cb_1_initial limit 1;").Scan(t1Val)
assert.NoError(t, err)
assert.NotNil(t, t1Val)
assert.Equal(t, "grodanboll", t1Val.String)
}
{ // Table created through code and updated using SQL.
t2Val := &sql.NullString{}
err = db.QueryRow("select name from cb_2_from_code limit 1;").Scan(t2Val)
assert.NoError(t, err)
assert.NotNil(t, t2Val)
assert.Equal(t, "kallekula", t2Val.String)
}
})
t.Run(fmt.Sprintf("[%s] %s", d, "Code based migrations - Failing statement rolled back"), func(t *testing.T) {
db, err := sql.Open(string(d), c)
if !assert.NoError(t, err) {
return
}
defer func() { _ = db.Close() }()
s := New(db, ZapOption{Logger: zap.NewNop()}, Config{MigrationFolder: "test/code-based-fail"}, FuncMigrationOption{
Migration: &code_based_fail.CBFailTest2{
Name: "cb_fail_test2.go",
},
})
err = s.Migrate()
assert.Error(t, err)
assert.Contains(t, err.Error(), "failed to apply func migration cb_fail_test2.go")
// Check that only values from SQL based migration remains. Values
// from func migration should have been rolled back.
count := 0
err = db.QueryRow("select count(*) from cb_2_initial;").Scan(&count)
assert.NoError(t, err)
assert.Equal(t, 1, count)
val := &sql.NullString{}
err = db.QueryRow("select id from cb_2_initial limit 1;").Scan(val)
assert.NoError(t, err)
assert.NotNil(t, val)
assert.Equal(t, "should_remain", val.String)
})
}
}
func getTableNames(s *Service, d SQLDialect) ([]string, error) {
var tables []string
switch d {
case MySQL:
res, err := s.db.Query("show tables")
if err != nil {
return nil, err
}
for res.Next() {
var tn string
if err := res.Scan(&tn); err != nil {
return nil, err
}
tables = append(tables, tn)
}
case PostGreSQL:
res, err := s.db.Query(
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_name")
if err != nil {
return nil, err
}
for res.Next() {
var tn string
if err := res.Scan(&tn); err != nil {
return nil, err
}
tables = append(tables, tn)
}
case Sqlite:
res, err := s.db.Query("select name from sqlite_master where type='table' order by name")
if err != nil {
return nil, err
}
for res.Next() {
var tn string
if err := res.Scan(&tn); err != nil {
return nil, err
}
tables = append(tables, tn)
}
}
return tables, nil
}
func dropTables(s *Service, d SQLDialect) {
tables, _ := getTableNames(s, d)
for _, t := range tables {
_, _ = s.db.Exec("drop table if exists " + t)
}
}