-
Notifications
You must be signed in to change notification settings - Fork 3
/
migratorops.go
316 lines (306 loc) · 8.96 KB
/
migratorops.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
package pgmigrate
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/peterldowns/pgmigrate/internal/pgtools"
)
// MarkApplied (⚠️ danger) is a manual operation that marks specific migrations
// as applied without running them.
//
// You should NOT use this as part of normal operations, it exists to help
// devops/db-admin/sres interact with migration state.
//
// It returns a list of the [AppliedMigration] that have been marked as
// applied.
func (m *Migrator) MarkApplied(
ctx context.Context,
db Executor,
ids ...string,
) ([]AppliedMigration, error) {
err := m.ensureMigrationsTable(ctx, db)
if err != nil {
return nil, err
}
applied, err := m.Applied(ctx, db)
if err != nil {
return nil, err
}
appliedMap := map[string]AppliedMigration{}
for _, m := range applied {
appliedMap[m.ID] = m
}
migrationsMap := map[string]Migration{}
for _, m := range m.Migrations {
migrationsMap[m.ID] = m
}
var toMarkApplied []Migration
for _, id := range ids {
if existing, ok := appliedMap[id]; ok {
m.warn(ctx, "skipping previously applied migration",
LogField{"id", existing.ID},
LogField{"checksum", existing.Checksum},
LogField{"applied_at", existing.AppliedAt},
)
continue
}
if migration, ok := migrationsMap[id]; ok {
toMarkApplied = append(toMarkApplied, migration)
} else {
m.warn(ctx, "skipping unknown migration",
LogField{"reason", "does not exist"},
LogField{"id", id},
)
}
}
var markedAsApplied []AppliedMigration
if err := m.inTx(ctx, db, func(tx *sql.Tx) error {
for _, migration := range toMarkApplied {
ma := AppliedMigration{Migration: migration}
ma.Checksum = migration.MD5()
ma.ExecutionTimeInMillis = 0
ma.AppliedAt = time.Now().UTC()
fields := []LogField{
{"id", ma.ID},
{"checksum", ma.Checksum},
}
query := fmt.Sprintf(`
INSERT INTO %s ( id, checksum, execution_time_in_millis, applied_at )
VALUES ( $1, $2, $3, $4 )
ON CONFLICT DO NOTHING;`,
pgtools.QuoteTableAndSchema(m.TableName),
)
_, err := tx.ExecContext(ctx, query, ma.ID, ma.Checksum, ma.ExecutionTimeInMillis, ma.AppliedAt)
if err != nil {
msg := "failed to mark migration as applied"
m.error(ctx, err, msg, fields...)
return fmt.Errorf("%s: %w", msg, err)
}
markedAsApplied = append(markedAsApplied, ma)
}
return nil
}); err != nil {
return nil, err
}
return markedAsApplied, nil
}
// MarkAllApplied (⚠️ danger) is a manual operation that marks all known migrations as
// applied without running them.
//
// You should NOT use this as part of normal operations, it exists to help
// devops/db-admin/sres interact with migration state.
//
// It returns a list of the [AppliedMigration] that have been marked as
// applied.
func (m *Migrator) MarkAllApplied(
ctx context.Context,
db Executor,
) ([]AppliedMigration, error) {
var ids []string
for _, migration := range m.Migrations {
ids = append(ids, migration.ID)
}
return m.MarkApplied(ctx, db, ids...)
}
// MarkUnapplied (⚠️ danger) is a manual operation that marks specific migrations as
// unapplied (not having been run) by removing their records from the migrations
// table.
//
// You should NOT use this as part of normal operations, it exists to help
// devops/db-admin/sres interact with migration state.
//
// It returns a list of the [AppliedMigration] that have been marked as
// unapplied.
func (m *Migrator) MarkUnapplied(
ctx context.Context,
db Executor,
ids ...string,
) ([]AppliedMigration, error) {
err := m.ensureMigrationsTable(ctx, db)
if err != nil {
return nil, err
}
applied, err := m.Applied(ctx, db)
if err != nil {
return nil, err
}
appliedMap := map[string]AppliedMigration{}
for _, m := range applied {
appliedMap[m.ID] = m
}
var toRemove []string
for _, id := range ids {
if _, ok := appliedMap[id]; ok {
toRemove = append(toRemove, id)
} else {
m.warn(ctx, "skipping unknown migration",
LogField{"reason", "does not exist"},
LogField{"id", id},
)
}
}
var removed []AppliedMigration
if err := m.inTx(ctx, db, func(tx *sql.Tx) error {
query := fmt.Sprintf(`
DELETE FROM %s WHERE id = any($1) RETURNING *;
`, pgtools.QuoteTableAndSchema(m.TableName))
rows, err := tx.QueryContext(ctx, query, toRemove)
if err != nil {
return err
}
removed, err = scanAppliedMigrations(rows)
return err
}); err != nil {
return nil, err
}
return removed, err
}
// MarkAllUnapplied (⚠️ danger) is a manual operation that marks all known migrations as
// unapplied (not having been run) by removing their records from the migrations
// table.
//
// You should NOT use this as part of normal operations, it exists to help
// devops/db-admin/sres interact with migration state.
//
// It returns a list of the [AppliedMigration] that have been marked as
// unapplied.
func (m *Migrator) MarkAllUnapplied(
ctx context.Context,
db Executor,
) ([]AppliedMigration, error) {
applied, err := m.Applied(ctx, db)
if err != nil {
return nil, err
}
ids := make([]string, 0, len(applied))
for _, migration := range applied {
ids = append(ids, migration.ID)
}
return m.MarkUnapplied(ctx, db, ids...)
}
// ChecksumUpdate represents an update to a specific migration.
// This struct is used instead of a `map[migrationID]checksum“
// in order to apply multiple updates in a consistent order.
type ChecksumUpdate struct {
MigrationID string // The ID of the migration to update, `0001_initial`
NewChecksum string // The checksum to set in the migrations table, `aaaabbbbccccdddd`
}
// SetChecksums (⚠️ danger) is a manual operation that explicitly sets the recorded
// checksum of applied migrations in the migrations table.
//
// You should NOT use this as part of normal operations, it exists to help
// devops/db-admin/sres interact with migration state.
//
// It returns a list of the [AppliedMigration] whose checksums have been
// updated.
func (m *Migrator) SetChecksums(
ctx context.Context,
db Executor,
updates ...ChecksumUpdate,
) ([]AppliedMigration, error) {
err := m.ensureMigrationsTable(ctx, db)
if err != nil {
return nil, err
}
applied, err := m.Applied(ctx, db)
if err != nil {
return nil, err
}
appliedMap := map[string]AppliedMigration{}
for _, m := range applied {
appliedMap[m.ID] = m
}
var toUpdate []AppliedMigration
for _, update := range updates {
migrationID := update.MigrationID
newChecksum := update.NewChecksum
migration, ok := appliedMap[migrationID]
if !ok {
m.warn(ctx, "skipping migration",
LogField{"reason", "does not exist"},
LogField{"id", migrationID},
)
continue
}
if migration.Checksum == newChecksum {
m.info(ctx, "skipping migration",
LogField{"reason", "already has the desired checksum"},
LogField{"id", migration.ID},
LogField{"checksum", migration.Checksum},
)
continue
}
migration.Checksum = newChecksum
toUpdate = append(toUpdate, migration)
}
var updated []AppliedMigration
if err := m.inTx(ctx, db, func(tx *sql.Tx) error {
for _, migration := range toUpdate {
fields := []LogField{
{"id", migration.ID},
{"checksum", migration.Checksum},
}
query := fmt.Sprintf(
`UPDATE %s SET checksum = $1 where id = $2 and checksum != $1`,
pgtools.QuoteTableAndSchema(m.TableName),
)
m.debug(ctx, query)
_, err := tx.ExecContext(ctx, query, migration.Checksum, migration.ID)
if err != nil {
msg := "failed to set checksum"
m.error(ctx, err, msg, fields...)
return fmt.Errorf("%s: %w", msg, err)
}
updated = append(updated, migration)
}
return nil
}); err != nil {
return nil, err
}
return updated, nil
}
// RecalculateChecksums (⚠️ danger) is a manual operation that explicitly
// recalculates the checksums of the specified migrations and updates their
// records in the migrations table to have the calculated checksum.
//
// You should NOT use this as part of normal operations, it exists to help
// devops/db-admin/sres interact with migration state.
//
// It returns a list of the [AppliedMigration] whose checksums have been
// recalculated.
func (m *Migrator) RecalculateChecksums(
ctx context.Context,
db Executor,
ids ...string,
) ([]AppliedMigration, error) {
allChecksums := make(map[string]string, len(m.Migrations))
for _, migration := range m.Migrations {
allChecksums[migration.ID] = migration.MD5()
}
updates := make([]ChecksumUpdate, 0, len(ids))
for _, id := range ids {
if checksum, ok := allChecksums[id]; ok {
updates = append(updates, ChecksumUpdate{MigrationID: id, NewChecksum: checksum})
} else {
m.warn(ctx, "skipping migration",
LogField{"reason", "does not exist"},
LogField{"id", id},
)
}
}
return m.SetChecksums(ctx, db, updates...)
}
func (m *Migrator) RecalculateAllChecksums(
ctx context.Context,
db Executor,
) ([]AppliedMigration, error) {
updates := make([]ChecksumUpdate, 0, len(m.Migrations))
for _, migration := range m.Migrations {
updates = append(updates, ChecksumUpdate{
MigrationID: migration.ID,
NewChecksum: migration.MD5(),
})
}
return m.SetChecksums(ctx, db, updates...)
}