-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrator.go
633 lines (579 loc) · 14.4 KB
/
migrator.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
package migrator
import (
"context"
"errors"
"fmt"
"reflect"
"regexp"
"strings"
"github.com/gopsql/db"
"github.com/gopsql/logger"
)
const (
sqlCreateSchemaMigrations = `
CREATE TABLE IF NOT EXISTS schema_migrations (
scope character varying NOT NULL,
version integer NOT NULL
);
`
migrationsTemplate = `package migrations
var (
Migrations []migration
)
type (
migration struct {
version int
up string
down string
}
)
func add(m migration) {
Migrations = append(Migrations, m)
}
`
migrationTemplate = `package migrations
func init() {
add(migration{
version: %d,
up: ` + "`%s`," + `
down: ` + "`%s`," + `
})
}
`
)
var (
ErrMigrationsBadType = errors.New("migrations must be slice of struct")
)
type (
Migrator struct {
Scope string
DB db.DB
Logger logger.Logger
migrations []migration
}
Migrations []Migration
Migration struct {
Version int
Name string
Up string
Down string
}
PsqlModel interface {
Columns() []string
ColumnDataTypes() map[string]string
TableName() string
Schema() string
DropSchema() string
}
migration struct {
version int
up string
down string
}
)
func NewMigrator(optionalScope ...string) *Migrator {
var scope string
if len(optionalScope) > 0 {
scope = optionalScope[0]
}
return &Migrator{
Scope: scope,
}
}
func (m *Migrator) SetConnection(dbConn db.DB) {
m.DB = dbConn
}
func (m *Migrator) SetLogger(logger logger.Logger) {
m.Logger = logger
}
// NewMigration generates migration file based on the differences between
// schemas in the database and psql models.
func (m *Migrator) NewMigration(models ...PsqlModel) (Migrations, error) {
tableNames, err := m.getTableNames()
if err != nil {
return nil, err
}
columns, err := m.getColumns()
if err != nil {
return nil, err
}
var tablesCreated []string
var columnsCreated []string
var tablesDropped []string
var columnsDropped []string
var name, up, down string
// find new tables
for _, model := range models {
tableName := model.TableName()
if tableNames.has(tableName) {
continue
}
up += "\n" + model.Schema()
down = "\n" + model.DropSchema() + down
tablesCreated = append(tablesCreated, tableName)
}
// find new columns
for _, model := range models {
tableName := model.TableName()
if !tableNames.has(tableName) {
continue
}
modelColumns := model.Columns()
modelDataTypes := model.ColumnDataTypes()
for _, modelColumn := range modelColumns {
if columns.has(tableName, modelColumn) {
continue
}
dataType, ok := modelDataTypes[modelColumn]
if !ok {
continue
}
up += fmt.Sprintf("\nALTER TABLE %s ADD COLUMN %s %s;\n",
tableName, modelColumn, dataType)
down = fmt.Sprintf("\nALTER TABLE %s DROP COLUMN %s;\n",
tableName, modelColumn) + down
columnsCreated = append(columnsCreated, modelColumn+"_to_"+tableName)
}
}
// remove old tables
for _, tableName := range tableNames {
var model PsqlModel
for _, m := range models {
if identifierEqual(m.TableName(), tableName) {
model = m
break
}
}
if model != nil {
continue
}
up += "\n" + "DROP TABLE IF EXISTS " + tableName + ";\n"
down = "\n" + columns.forTable(tableName).createTable(tableName) + down
tablesDropped = append(tablesDropped, tableName)
}
// remove old columns
groups := columns.grouped()
for tableName, cols := range groups {
var model PsqlModel
for _, m := range models {
if identifierEqual(m.TableName(), tableName) {
model = m
break
}
}
if model == nil {
continue
}
modelColumns := model.Columns()
for _, col := range cols {
if stringSliceContains(modelColumns, col.ColumnName) {
continue
}
up += "\n" + "ALTER TABLE " + tableName + " DROP COLUMN " + col.ColumnName + ";\n"
down = "\n" + "ALTER TABLE " + tableName + " ADD COLUMN " + col.ColumnName + " " + col.dataType() + ";\n" + down
columnsDropped = append(columnsDropped, col.ColumnName+"_from_"+tableName)
}
}
if len(tablesCreated) > 0 {
name = "create_" + strings.Join(tablesCreated, "_")
} else if len(tablesDropped) > 0 {
name = "drop_" + strings.Join(tablesDropped, "_")
} else if len(columnsCreated) > 0 {
name = "add_" + strings.Join(columnsCreated, "_")
} else if len(columnsDropped) > 0 {
name = "remove_" + strings.Join(columnsDropped, "_")
}
if name == "" {
name = "new_migration"
}
var migrations Migrations
var maxVer int
for _, m := range m.migrations {
if m.version > maxVer {
maxVer = m.version
}
}
if maxVer == 0 {
migrations = append(migrations, Migration{
Version: 0,
Name: "migrations",
})
}
migrations = append(migrations, Migration{
Version: maxVer + 1,
Name: name,
Up: up,
Down: down,
})
return migrations, nil
}
func (m Migration) String(optionalDelta ...int) string {
delta := 0
if len(optionalDelta) > 0 {
delta = optionalDelta[0]
}
ver := m.Version + delta
if ver < 1 {
return migrationsTemplate
}
return fmt.Sprintf(migrationTemplate, ver, m.Up, m.Down)
}
func (m Migration) FileName(optionalDelta ...int) string {
delta := 0
if len(optionalDelta) > 0 {
delta = optionalDelta[0]
}
ver := m.Version + delta
if ver < 1 {
return fmt.Sprintf("%s.go", m.Name)
}
return fmt.Sprintf("%02d_%s.go", ver, m.Name)
}
// CanonicalScope returns valid scope name.
func (m *Migrator) CanonicalScope() string {
return strings.Join(regexp.MustCompile("[A-Za-z0-9_-]+").FindStringSubmatch(m.Scope), "")
}
// SetMigrations imports migrations.
func (m *Migrator) SetMigrations(migrations interface{}) error {
if migrations == nil {
m.migrations = nil
return nil
}
if migs, ok := migrations.(Migrations); ok {
m.migrations = nil
for _, mig := range migs {
m.migrations = append(m.migrations, migration{
version: mig.Version,
up: mig.Up,
down: mig.Down,
})
}
return nil
}
rt := reflect.TypeOf(migrations)
if rt.Kind() != reflect.Slice {
return ErrMigrationsBadType
}
rv := reflect.ValueOf(migrations)
version, up, down := getFieldNames(rv)
if version == "" || up == "" || down == "" {
return ErrMigrationsBadType
}
m.migrations = nil
for i := 0; i < rv.Len(); i++ {
v := rv.Index(i)
m.migrations = append(m.migrations, migration{
version: int(v.FieldByName(version).Int()),
up: v.FieldByName(up).String(),
down: v.FieldByName(down).String(),
})
}
return nil
}
func getFieldNames(rv reflect.Value) (version, up, down string) {
rt := rv.Type()
if rt.Kind() == reflect.Slice {
rt = rt.Elem()
}
if rt.Kind() != reflect.Struct {
return
}
for i := 0; i < rt.NumField(); i++ {
field := rt.Field(i)
name := strings.ToLower(field.Name)
kind := field.Type.Kind()
if name == "version" && kind == reflect.Int {
version = field.Name
} else if name == "up" && kind == reflect.String {
up = field.Name
} else if name == "down" && kind == reflect.String {
down = field.Name
}
}
return
}
// Versions returns version numbers of migrations that have been run and not
// yet been run.
func (m *Migrator) Versions() (migrated, unmigrated []int) {
for _, migration := range m.migrations {
if m.versionExists(migration.version) {
migrated = append(migrated, migration.version)
} else {
unmigrated = append(unmigrated, migration.version)
}
}
return
}
// Migrate executes the up SQL for all the migrations that have not yet been
// run.
func (m *Migrator) Migrate() (err error) {
if len(m.migrations) == 0 {
m.Logger.Info("nothing to migrate")
return
}
err = m.migrate()
if err != nil {
m.Logger.Error(err)
}
return
}
func (m *Migrator) migrate() error {
var sql string
if m.DB.DriverName() == "sqlite" {
sql = "SELECT type FROM pragma_table_info('schema_migrations') WHERE name = 'version'"
} else {
sql = "SELECT data_type FROM information_schema.columns " +
"WHERE table_name = 'schema_migrations' AND column_name = 'version'"
}
var versionType string
err := m.DB.QueryRow(sql).Scan(&versionType)
if err != nil && err == m.DB.ErrNoRows() {
_, err = m.DB.Exec(sqlCreateSchemaMigrations)
if err != nil {
return err
}
} else if versionType != "integer" {
if m.DB.DriverName() == "sqlite" {
// no need to change column type
} else {
_, err = m.DB.Exec("ALTER TABLE schema_migrations ALTER COLUMN version TYPE integer USING version::integer")
if err != nil {
return err
}
}
}
scope := m.CanonicalScope()
migrated := false
for _, migration := range m.migrations {
if migration.version < 1 {
continue
}
if m.versionExists(migration.version) {
m.Logger.Debug("version", migration.version, "already migrated")
continue
}
m.Logger.Info("version", migration.version, "migrating")
sqlStr := migration.up
sqlStr += "\n" + fmt.Sprintf("INSERT INTO schema_migrations (scope, version) VALUES ('%s', %d);", scope, migration.version)
if err := m.execInTransaction(sqlStr); err != nil {
return err
}
m.Logger.Info("version", migration.version, "migrated")
migrated = true
}
if !migrated {
m.Logger.Info("no new migrations")
}
return nil
}
// Rollback executes the down SQL of last migration.
func (m *Migrator) Rollback() (err error) {
err = m.rollback()
if err != nil && (err == m.DB.ErrNoRows() || m.DB.ErrGetCode(err) == "42P01") { // relation not exists
m.Logger.Info("nothing to rollback")
} else if err != nil {
m.Logger.Error(err)
}
return
}
func (m *Migrator) rollback() error {
version, err := m.getLatestVersion()
if err != nil {
return err
}
scope := m.CanonicalScope()
for _, migration := range m.migrations {
if migration.version != version {
continue
}
m.Logger.Info("version", migration.version, "rollbacking")
sqlStr := migration.down
sqlStr += "\n" + fmt.Sprintf("DELETE FROM schema_migrations WHERE scope = '%s' AND version = %d;", scope, version)
m.Logger.Debug("running sql:", sqlStr)
_, err := m.DB.Exec(sqlStr)
if err == nil {
m.Logger.Info("version", migration.version, "rollbacked")
}
return err
}
return nil
}
func (m *Migrator) execInTransaction(sql string) (err error) {
ctx := context.Background()
m.Logger.Debug("BEGIN")
var tx db.Tx
tx, err = m.DB.BeginTx(ctx, "", false)
if err != nil {
return
}
defer func() {
if r := recover(); r != nil {
m.Logger.Debug("ROLLBACK")
tx.Rollback(ctx)
if rerr, ok := r.(error); ok {
err = rerr
} else {
err = errors.New(fmt.Sprint(r))
}
} else if err != nil {
m.Logger.Debug("ROLLBACK")
tx.Rollback(ctx)
} else {
m.Logger.Debug("COMMIT")
err = tx.Commit(ctx)
}
}()
m.Logger.Debug(sql)
_, err = tx.ExecContext(ctx, sql)
return
}
func (m *Migrator) versionExists(version int) bool {
scope := m.CanonicalScope()
var one int
err := m.DB.QueryRow("SELECT 1 AS one FROM schema_migrations WHERE scope = $1 AND version = $2 LIMIT 1", scope, version).Scan(&one)
if err != nil && err != m.DB.ErrNoRows() {
m.Logger.Debug("check version:", err)
}
return one == 1
}
func (m *Migrator) getLatestVersion() (int, error) {
scope := m.CanonicalScope()
var version int
err := m.DB.QueryRow("SELECT version FROM schema_migrations WHERE scope = $1 ORDER BY version DESC LIMIT 1", scope).Scan(&version)
if err != nil {
return 0, err
}
return version, nil
}
func (m *Migrator) getTableNames() (tableNames, error) {
var sql string
if m.DB.DriverName() == "sqlite" {
sql = "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"
} else {
sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'"
}
rows, err := m.DB.Query(sql)
if err != nil {
return nil, err
}
defer rows.Close()
var names tableNames
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return nil, err
}
if name == "schema_migrations" {
continue
}
names = append(names, name)
}
return names, nil
}
func (m *Migrator) getColumns() (columns, error) {
var sql string
if m.DB.DriverName() == "sqlite" {
sql = "SELECT ss.name, p.name, p.type, p.dflt_value, p.[notnull] = 0 " +
"FROM sqlite_schema ss LEFT JOIN pragma_table_info(ss.name) p ON ss.name <> p.name " +
"WHERE ss.type = 'table' AND ss.name NOT LIKE 'sqlite_%' " +
"ORDER BY ss.name, p.cid"
} else {
sql = "SELECT table_name, column_name, data_type, column_default, is_nullable " +
"FROM information_schema.columns WHERE table_schema = 'public' " +
"ORDER BY table_name, ordinal_position"
}
rows, err := m.DB.Query(sql)
if err != nil {
return nil, err
}
defer rows.Close()
var cols columns
for rows.Next() {
var col column
if err := rows.Scan(
&col.TableName, &col.ColumnName,
&col.DataType, &col.ColumnDefault,
&col.IsNullable,
); err != nil {
return nil, err
}
cols = append(cols, col)
}
return cols, nil
}
type (
tableNames []string
columns []column
column struct {
TableName string
ColumnName string
DataType string
ColumnDefault *string
IsNullable string
}
)
func (names tableNames) has(tableName string) bool {
for _, name := range names {
if identifierEqual(name, tableName) {
return true
}
}
return false
}
func (columns columns) has(tableName, columnName string) bool {
for _, column := range columns {
if identifierEqual(column.TableName, tableName) && identifierEqual(column.ColumnName, columnName) {
return true
}
}
return false
}
func (columns columns) forTable(tableName string) (filtered columns) {
for _, column := range columns {
if column.TableName == tableName {
filtered = append(filtered, column)
}
}
return
}
func (columns columns) createTable(tableName string) string {
if len(columns) == 0 {
return ""
}
var sql []string
for _, c := range columns {
sql = append(sql, "\t"+c.ColumnName+" "+c.dataType())
}
return "CREATE TABLE " + tableName + " (\n" + strings.Join(sql, ",\n") + "\n);\n"
}
func (cs columns) grouped() (groups map[string]columns) {
groups = map[string]columns{}
for _, c := range cs {
groups[c.TableName] = append(groups[c.TableName], c)
}
return
}
func (c column) dataType() string {
dataType := c.DataType
if c.ColumnDefault != nil {
dataType += " DEFAULT " + *c.ColumnDefault
}
if c.IsNullable == "NO" {
dataType += " NOT NULL"
}
if strings.Contains(dataType, "integer DEFAULT nextval") {
dataType = "SERIAL PRIMARY KEY"
}
return dataType
}
func identifierEqual(a, b string) bool {
return strings.ToLower(a) == strings.ToLower(b)
}
func stringSliceContains(slice []string, str string) bool {
for _, item := range slice {
if identifierEqual(item, str) {
return true
}
}
return false
}