forked from pydio/cells
-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrate.go
268 lines (232 loc) · 7.31 KB
/
migrate.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
package sql
import (
"context"
"database/sql"
"errors"
"flag"
"fmt"
"regexp"
"sort"
"strings"
"time"
"github.com/pydio/cells/common/log"
"github.com/rubenv/sql-migrate"
"gopkg.in/gorp.v1"
)
var tableName = "gorp_migrations"
var schemaName = ""
func newTxError(migration *migrate.PlannedMigration, err error) error {
return &migrate.TxError{
Migration: migration.Migration,
Err: err,
}
}
// Set the name of the table used to store migration info.
//
// Should be called before any other call such as (Exec, ExecMax, ...).
func SetTable(name string) {
if name != "" {
tableName = name
}
}
// SetSchema sets the name of a schema that the migration table be referenced.
func SetSchema(name string) {
if name != "" {
schemaName = name
}
}
type migrationById []*migrate.Migration
func (b migrationById) Len() int { return len(b) }
func (b migrationById) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b migrationById) Less(i, j int) bool { return b[i].Less(b[j]) }
// Execute a set of migrations
//
// Returns the number of applied migrations.
func ExecMigration(db *sql.DB, dialect string, m migrate.MigrationSource, dir migrate.MigrationDirection, prefix string) (int, error) {
return ExecMax(db, dialect, m, dir, 0, prefix)
}
// Execute a set of migrations
//
// Will apply at most `max` migrations. Pass 0 for no limit (or use Exec).
//
// Returns the number of applied migrations.
func ExecMax(db *sql.DB, dialect string, m migrate.MigrationSource, dir migrate.MigrationDirection, max int, prefix string) (int, error) {
migrations, dbMap, err := PlanMigration(db, dialect, m, dir, max, prefix)
if err != nil {
return 0, err
}
// Apply migrations
applied := 0
for _, migration := range migrations {
var executor migrate.SqlExecutor
if migration.DisableTransaction {
executor = dbMap
} else {
executor, err = dbMap.Begin()
if err != nil {
return applied, newTxError(migration, err)
}
}
for _, stmt := range migration.Queries {
if _, err := executor.Exec(stmt); err != nil {
if trans, ok := executor.(*gorp.Transaction); ok {
trans.Rollback()
}
return applied, newTxError(migration, err)
}
}
switch dir {
case migrate.Up:
err = executor.Insert(&migrate.MigrationRecord{
Id: migration.Id,
AppliedAt: time.Now(),
})
if err != nil {
if trans, ok := executor.(*gorp.Transaction); ok {
trans.Rollback()
}
return applied, newTxError(migration, err)
}
case migrate.Down:
_, err := executor.Delete(&migrate.MigrationRecord{
Id: migration.Id,
})
if err != nil {
if trans, ok := executor.(*gorp.Transaction); ok {
trans.Rollback()
}
return applied, newTxError(migration, err)
}
default:
panic("Not possible")
}
if trans, ok := executor.(*gorp.Transaction); ok {
if err := trans.Commit(); err != nil {
return applied, newTxError(migration, err)
}
}
applied++
}
return applied, nil
}
func prefixedIdToNumber(id, prefix string) (numberId, newPrefix string, e error) {
if flag.Lookup("test.v") != nil {
return id, prefix, nil
}
numberPrefixRegex := regexp.MustCompile(`^(` + prefix + `_?)(\d*.?\d+).*$`)
res := numberPrefixRegex.FindStringSubmatch(id)
if len(res) > 0 {
newPrefix = res[1]
numberId = strings.Replace(res[2], ".", "", -1)
} else {
e = fmt.Errorf("unsupported format for migration file %s. prefix was %s", id, prefix)
}
return
}
// Plan a migration.
func PlanMigration(db *sql.DB, dialect string, m migrate.MigrationSource, dir migrate.MigrationDirection, max int, prefix string) ([]*migrate.PlannedMigration, *gorp.DbMap, error) {
dbMap, err := getMigrationDbMap(db, dialect)
if err != nil {
return nil, nil, err
}
migrations, err := m.FindMigrations()
if err != nil {
return nil, nil, err
}
if len(migrations) == 0 {
return nil, nil, fmt.Errorf("missing migrations for prefix " + prefix + " - did you maybe compile without generate step?")
}
var migrationRecords []migrate.MigrationRecord
_, err = dbMap.Select(&migrationRecords, fmt.Sprintf("SELECT * FROM %s WHERE id LIKE '%s%%'", dbMap.Dialect.QuotedTableForQuery(schemaName, tableName), prefix))
if err != nil {
return nil, nil, err
}
originals := map[string]string{}
for _, m := range migrations {
var numberId string
if numberId, prefix, err = prefixedIdToNumber(m.Id, prefix); err != nil {
return nil, nil, err
} else {
originals[numberId] = m.Id
m.Id = numberId
}
}
// Sort migrations that have been run by Id.
var existingMigrations []*migrate.Migration
for _, migrationRecord := range migrationRecords {
if numberId, _, e := prefixedIdToNumber(migrationRecord.Id, prefix); e == nil {
existingMigrations = append(existingMigrations, &migrate.Migration{
Id: numberId,
})
}
}
sort.Sort(migrationById(existingMigrations))
// Get last migration that was run
record := &migrate.Migration{}
if len(existingMigrations) > 0 {
record = existingMigrations[len(existingMigrations)-1]
}
result := make([]*migrate.PlannedMigration, 0)
// Add missing migrations up to the last run migration.
// This can happen for example when merges happened.
if len(existingMigrations) > 0 {
result = append(result, migrate.ToCatchup(migrations, existingMigrations, record)...)
}
// Figure out which migrations to apply
toApply := migrate.ToApply(migrations, record.Id, dir)
toApplyCount := len(toApply)
if max > 0 && max < toApplyCount {
toApplyCount = max
}
for _, v := range toApply[0:toApplyCount] {
// Restore original ID
v.Id = originals[v.Id]
log.Logger(context.Background()).Debug("Apply Migration " + v.Id + " for prefix " + prefix)
if dir == migrate.Up {
result = append(result, &migrate.PlannedMigration{
Migration: v,
Queries: v.Up,
DisableTransaction: v.DisableTransactionUp,
})
} else if dir == migrate.Down {
result = append(result, &migrate.PlannedMigration{
Migration: v,
Queries: v.Down,
DisableTransaction: v.DisableTransactionDown,
})
}
}
return result, dbMap, nil
}
func getMigrationDbMap(db *sql.DB, dialect string) (*gorp.DbMap, error) {
d, ok := migrate.MigrationDialects[dialect]
if !ok {
return nil, fmt.Errorf("Unknown dialect: %s", dialect)
}
// When using the mysql driver, make sure that the parseTime option is
// configured, otherwise it won't map time columns to time.Time. See
// https://github.com/rubenv/sql-migrate/issues/2
if dialect == "mysql" {
var out *time.Time
err := db.QueryRow("SELECT NOW()").Scan(&out)
if err != nil {
if err.Error() == "sql: Scan error on column index 0: unsupported driver -> Scan pair: []uint8 -> *time.Time" ||
err.Error() == "sql: Scan error on column index 0: unsupported Scan, storing driver.Value type []uint8 into type *time.Time" {
return nil, errors.New(`Cannot parse dates.
Make sure that the parseTime option is supplied to your database connection.
Check https://github.com/go-sql-driver/mysql#parsetime for more info.`)
} else {
return nil, err
}
}
}
// Create migration database map
dbMap := &gorp.DbMap{Db: db, Dialect: d}
dbMap.AddTableWithNameAndSchema(migrate.MigrationRecord{}, schemaName, tableName).SetKeys(false, "Id")
//dbMap.TraceOn("", log.New(os.Stdout, "migrate: ", log.Lmicroseconds))
err := dbMap.CreateTablesIfNotExists()
if err != nil {
return nil, err
}
return dbMap, nil
}