forked from Onyx-Protocol/Onyx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrate.go
222 lines (195 loc) · 5.45 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
// Package migrate implements database migration for Chain Core.
package migrate
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
"chain/database/pg"
"chain/errors"
"chain/log"
)
// Run runs all built-in migrations.
func Run(db pg.DB) error {
ctx := context.Background()
// Create the migrations table if not yet created.
_, err := db.Exec(ctx, createMigrationTableSQL)
if err != nil {
return errors.Wrap(err, "creating migration table")
}
err = convertOldStatus(db)
if err != nil {
return err
}
err = loadStatus(db, migrations)
if err != nil {
return err
}
for _, m := range migrations {
if !m.AppliedAt.IsZero() {
continue
}
fmt.Println("Pending migration:", m.Name)
_, err := db.Exec(ctx, m.SQL)
if err != nil {
return errors.Wrapf(err, "migration %s", m.Name)
}
// The migration and the insertion cannot be grouped in a single
// transaction, because some migrations contain SQL that cannot be
// run within a transaction.
err = insertAppliedMigration(db, m)
if err != nil {
return err
}
log.Write(ctx, "migration", m.Name, "status", "success")
}
return nil
}
// PrintStatus prints the status of each built-in migration.
func PrintStatus(db pg.DB) error {
err := loadStatus(db, migrations)
if err != nil {
return err
}
fmt.Printf("%-60s\t%-6s\t%s\n", "filename", "hash", "applied_at")
for _, m := range migrations {
appliedAt := "(pending)"
if !m.AppliedAt.IsZero() {
appliedAt = m.AppliedAt.Format(time.RFC3339)
}
fmt.Printf("%-60s\t%-6s\t%s\n", m.Name, m.Hash[:6], appliedAt)
}
return nil
}
const createMigrationTableSQL = `
CREATE TABLE IF NOT EXISTS migrations (
filename text NOT NULL,
hash text NOT NULL,
applied_at timestamp with time zone DEFAULT now() NOT NULL,
PRIMARY KEY(filename)
);
`
// byFilename implements sort.Interface allowing sorting by the
// filename of the migration. This should sort by date because of
// the migration file naming scheme.
type byFilename []migration
func (m byFilename) Len() int { return len(m) }
func (m byFilename) Less(i, j int) bool { return m[i].Name < m[j].Name }
func (m byFilename) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m migration) String() string {
return fmt.Sprintf("%s - %s", m.Name, m.Hash[:5])
}
// migrationFiles returns a slice of the filenames of all migrations in the
// given directory.
func migrationFiles(migrationDirectory string) ([]string, error) {
var filenames []string
err := filepath.Walk(migrationDirectory, func(name string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if filepath.Ext(name) != ".sql" && filepath.Ext(name) != ".go" {
return nil
}
filenames = append(filenames, filepath.Base(name))
return nil
})
return filenames, err
}
// loadStatus sets AppliedAt on each item of ms that appears
// in table "migrations" in db.
// It is an error for the stored hash to be different
// from the migration's computed hash.
func loadStatus(db pg.DB, ms []migration) error {
ctx := context.Background()
const q = `
SELECT count(*) FROM pg_tables
WHERE schemaname='public' AND tablename='migrations'
`
var n int
err := db.QueryRow(ctx, q).Scan(&n)
if err != nil {
log.Fatal(ctx, log.KeyError, err)
}
if n == 0 {
return nil // no schema; nothing has been applied
}
rows, err := db.Query(ctx, `SELECT filename, hash, applied_at FROM migrations`)
if err != nil {
return errors.Wrap(err)
}
defer rows.Close()
for rows.Next() {
var name, hash string
var t time.Time
err := rows.Scan(&name, &hash, &t)
if err != nil {
return errors.Wrap(err)
}
m := find(name, ms)
if m != nil {
if m.Hash != hash {
return errors.Wrap(fmt.Errorf("%s hash mismatch %s != %s", name, hash, m.Hash))
}
m.AppliedAt = t
}
}
return errors.Wrap(rows.Err())
}
// Well this is funny. We are going to migrate our migrations.
// We squashed our migration history into a single migration
// (2016-10-17.0.core.schema-snapshot.sql), but some deployed
// systems are running a database from before the squash.
// So we'll detect that case and convert it here to the new
// format before attempting to run any new migrations.
// If they are running a schema older than the last migration
// just before the squash, we cannot help them here.
func convertOldStatus(db pg.DB) error {
ctx := context.Background()
// last migration in the old regime
const q = `
SELECT count(*) FROM migrations
WHERE filename='2016-10-10.0.mockhsm.add-key-types.sql'
AND hash='00ac8143767fe4a44855cab1ec57afd52c44fd4d727055db9e8584c3e9b10983'
`
var n int
err := db.QueryRow(ctx, q).Scan(&n)
if err != nil {
return errors.Wrap(err)
}
if n == 0 {
return nil // no conversion necessary/possible
}
_, err = db.Exec(ctx, `
TRUNCATE migrations;
INSERT INTO migrations (filename, hash, applied_at)
VALUES (
'2016-10-17.0.core.schema-snapshot.sql',
'cff5210e2d6af410719c223a76443f73c5c12fe875f0efecb9a0a5937cf029cd',
now()
);
`)
return errors.Wrap(err)
}
// find finds name in ms.
// It returns nil if not found.
func find(name string, ms []migration) *migration {
for i := range ms {
if ms[i].Name == name {
return &ms[i]
}
}
return nil
}
func insertAppliedMigration(db pg.DB, m migration) error {
ctx := context.Background()
const q = `
INSERT INTO migrations (filename, hash, applied_at)
VALUES($1, $2, NOW())
`
_, err := db.Exec(ctx, q, m.Name, m.Hash)
if err != nil {
return errors.Wrap(err, "recording applied migration")
}
return nil
}