-
Notifications
You must be signed in to change notification settings - Fork 2
/
migrate.go
197 lines (160 loc) · 4.05 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
package truss
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"regexp"
"strings"
"time"
"github.com/luno/jettison/errors"
"github.com/luno/jettison/j"
)
type migration struct {
ID int64
QueryHash string
SchemaHash string
CreatedAt time.Time
}
var bootstrapQuery = `
CREATE TABLE IF NOT EXISTS migrations (
id BIGINT NOT NULL AUTO_INCREMENT,
query_hash CHAR(64) NOT NULL,
schema_hash CHAR(64) NOT NULL,
created_at DATETIME(3) NOT NULL,
PRIMARY KEY (id)
);`
func Migrate(ctx context.Context, dbc *sql.DB, queries []string) error {
_, err := dbc.ExecContext(ctx, bootstrapQuery)
if err != nil {
return err
}
sh, err := schemaHash(ctx, dbc)
if err != nil {
return errors.Wrap(err, "bootstrap schema hash")
}
ml, err := listMigrations(ctx, dbc)
if err != nil {
return err
}
if len(ml) > len(queries) {
return errors.New("more migrations than queries")
} else if len(ml) > 0 && ml[len(ml)-1].SchemaHash != sh {
return errors.New("schema hash and last migration mismatch")
}
for i, m := range ml {
if m.QueryHash != s2h(queries[i]) {
return errors.New("migration and query mismatch", j.MKV{"i": i})
}
}
for i := len(ml); i < len(queries); i++ {
err := applyMigration(ctx, dbc, queries[i])
if err != nil {
return err
}
}
return nil
}
func applyMigration(ctx context.Context, dbc *sql.DB, query string) error {
tx, err := dbc.Begin()
if err != nil {
return err
}
defer tx.Rollback()
_, err = tx.ExecContext(ctx, query)
if err != nil {
return err
}
sh, err := schemaHash(ctx, tx)
if err != nil {
return err
}
_, err = tx.ExecContext(ctx, "INSERT INTO migrations "+
"(query_hash, schema_hash, created_at) "+
"VALUES (?, ?, now())", s2h(query), sh)
if err != nil {
return err
}
return tx.Commit()
}
// s2h returns a hex encoded sha256 hash (len=64) of the provided query.
func s2h(s string) string {
h := sha256.Sum256([]byte(s))
return hex.EncodeToString(h[:])
}
func schemaHash(ctx context.Context, dbc common) (string, error) {
schema, err := MakeCreateSchema(ctx, dbc)
if err != nil {
return "", err
}
return s2h(schema), nil
}
type common interface {
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
}
var autoincExp = regexp.MustCompile(`\sAUTO_INCREMENT=\d+`)
func MakeCreateSchema(ctx context.Context, dbc common) (string, error) {
tables, err := queryStrings(ctx, dbc, "SHOW TABLES")
if err != nil {
return "", errors.Wrap(err, "show tables")
}
var creates []string
for _, table := range tables {
var noop, create string
err := dbc.QueryRowContext(ctx, "SHOW CREATE TABLE "+table).Scan(&noop, &create)
if err != nil {
return "", errors.Wrap(err, "show crete table")
}
create = strings.TrimSpace(create)
create = autoincExp.ReplaceAllString(create, "")
creates = append(creates, create)
}
header := "-- Schema generated by truss. DO NOT EDIT.\n\n"
return header + strings.Join(creates, "\n\n"), nil
}
const cols = " `id`, `query_hash`, `schema_hash`, `created_at` "
func listMigrations(ctx context.Context, dbc *sql.DB) ([]migration, error) {
rows, err := dbc.QueryContext(ctx, "select "+cols+" from migrations order by id asc")
if err != nil {
return nil, err
}
defer rows.Close()
var res []migration
for rows.Next() {
r, err := scan(rows)
if err != nil {
return nil, err
}
res = append(res, r)
}
return res, rows.Err()
}
func queryStrings(ctx context.Context, dbc common, query string) ([]string, error) {
rows, err := dbc.QueryContext(ctx, query)
if err != nil {
return nil, err
}
defer rows.Close()
var res []string
for rows.Next() {
var r string
err := rows.Scan(&r)
if err != nil {
return nil, err
}
res = append(res, r)
}
return res, rows.Err()
}
type rows interface {
Scan(...interface{}) error
}
func scan(rows rows) (migration, error) {
var m migration
err := rows.Scan(&m.ID, &m.QueryHash, &m.SchemaHash, &m.CreatedAt)
if err != nil {
return migration{}, err
}
return m, nil
}