-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrator.go
338 lines (289 loc) · 8.18 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
// Package migration allows to perform versioned migrations in your ArangoDB.
package migrate
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/clinia/x/elasticx"
"github.com/clinia/x/errorx"
"github.com/clinia/x/mathx"
"github.com/elastic/go-elasticsearch/v8/typedapi/core/search"
"github.com/elastic/go-elasticsearch/v8/typedapi/types"
"github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/dynamicmapping"
"github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/refresh"
"github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/sortorder"
)
type (
indexSpecification struct {
Name string `json:"name"`
}
versionRecord struct {
Version uint64 `json:"version"`
Description string `json:"description,omitempty"`
Package string `json:"package"`
Timestamp time.Time `json:"timestamp"`
}
migrationVersionInfo struct {
Version uint64 `json:"version"`
Description string `json:"description"`
}
)
const defaultMigrationsIndex = "migrations"
// AllAvailable used in "Up" or "Down" methods to run all available migrations.
const AllAvailable = -1
// Migrate is type for performing migrations in provided database.
// Database versioned using dedicated collection.
// Each migration applying ("up" and "down") adds new document to collection.
// This document consists migration version, migration description and timestamp.
// Current database version determined as version in latest added document (biggest "_key") from collection mentioned above.
type Migrator struct {
engine elasticx.Engine
pkg string
migrations Migrations
migrationsIndex string
}
type NewMigratorOptions struct {
Engine elasticx.Engine
Package string
Migrations Migrations
}
func NewMigrator(opts NewMigratorOptions) *Migrator {
internalMigrations := make([]Migration, len(opts.Migrations))
copy(internalMigrations, opts.Migrations)
vers := map[uint64]bool{}
for _, m := range opts.Migrations {
if vers[m.Version] {
panic(fmt.Sprintf("duplicated migration version %v", m.Version))
}
vers[m.Version] = true
}
// To be valid index name, package name should be replaced with ":".
pkg := strings.ReplaceAll(opts.Package, "/", ":")
return &Migrator{
engine: opts.Engine,
pkg: pkg,
migrations: internalMigrations,
migrationsIndex: defaultMigrationsIndex,
}
}
// SetMigrationsIndex replaces name of index for storing migration information.
// By default it is "migrations".
func (m *Migrator) SetMigrationsIndex(name string) {
m.migrationsIndex = name
}
func (m *Migrator) indexExist(ctx context.Context, name string) (isExist bool, err error) {
indexes, err := m.getIndexes(ctx)
if err != nil {
return false, err
}
for _, c := range indexes {
if name == c.Name {
return true, nil
}
}
return false, nil
}
func (m *Migrator) createIndexIfNotExist(ctx context.Context, name string) error {
exist, err := m.indexExist(ctx, name)
if err != nil {
return err
}
if exist {
return nil
}
_, err = m.engine.CreateIndex(ctx, name, &elasticx.CreateIndexOptions{
Mappings: &types.TypeMapping{
Dynamic: &dynamicmapping.Strict,
Properties: map[string]types.Property{
"version": types.NewLongNumberProperty(),
"description": types.NewKeywordProperty(),
"package": types.NewKeywordProperty(),
"timestamp": types.NewDateProperty(),
},
},
})
if err != nil {
return err
}
return nil
}
func (m *Migrator) getIndexes(ctx context.Context) (indices []indexSpecification, err error) {
indexes, err := m.engine.Indexes(ctx)
if err != nil {
return nil, err
}
for _, index := range indexes {
indices = append(indices, indexSpecification{
Name: index.Name,
})
}
return
}
// Version returns current engine version and comment.
func (m *Migrator) Version(ctx context.Context) (migrationVersionInfo, error) {
if err := m.createIndexIfNotExist(ctx, m.migrationsIndex); err != nil {
return migrationVersionInfo{
Version: 0,
Description: "",
}, err
}
searchResponse, err := m.engine.Query(ctx, &search.Request{
Query: &types.Query{
Term: map[string]types.TermQuery{
"package": {
Value: m.pkg,
},
},
},
Sort: types.Sort{
types.SortOptions{
SortOptions: map[string]types.FieldSort{
"version": {
Order: &sortorder.Desc,
},
},
},
},
}, m.migrationsIndex)
if err != nil {
return migrationVersionInfo{
Version: 0,
Description: "",
}, err
}
if searchResponse.Hits.Total.Value == 0 {
return migrationVersionInfo{
Version: 0,
Description: "",
}, err
}
var rec versionRecord
if err := json.Unmarshal(searchResponse.Hits.Hits[0].Source_, &rec); err != nil {
return migrationVersionInfo{
Version: 0,
Description: "",
}, err
}
return migrationVersionInfo{
Version: rec.Version,
Description: rec.Description,
}, nil
}
// setVersion forcibly changes database version to provided.
func (m *Migrator) setVersion(ctx context.Context, version uint64, description string) error {
rec := versionRecord{
Version: version,
Package: m.pkg,
Timestamp: time.Now().UTC(),
Description: description,
}
index, err := m.engine.Index(ctx, m.migrationsIndex)
if err != nil {
return err
}
id := fmt.Sprintf("%s:%d", m.pkg, version)
exists, err := index.DocumentExists(ctx, id)
if err != nil {
return err
} else if exists {
pkgStr := ""
if m.pkg != "" {
pkgStr = fmt.Sprintf("with package %s and ", m.pkg)
}
return errorx.AlreadyExistsErrorf("migration %sversion %v already exists", pkgStr, version)
}
_, err = index.ReplaceDocument(ctx, id, rec, elasticx.WithRefresh(refresh.Waitfor))
if err != nil {
return err
}
return nil
}
func (m *Migrator) removeVersion(ctx context.Context, version uint64) error {
index, err := m.engine.Index(ctx, m.migrationsIndex)
if err != nil {
return err
}
id := fmt.Sprintf("%s:%d", m.pkg, version)
err = index.DeleteDocument(ctx, id, elasticx.WithRefresh(refresh.Waitfor))
if err != nil {
return err
}
return nil
}
// Up performs "up" migrations up to the specified targetVersion.
// If targetVersion<=0 all "up" migrations will be executed (if not executed yet)
// If targetVersion>0 only migrations where version<=targetVersion will be performed (if not executed yet)
func (m *Migrator) Up(ctx context.Context, targetVersion int) error {
m.migrations.Sort()
if len(m.migrations) == 0 {
return nil
}
currentVersion, err := m.Version(ctx)
if err != nil {
return err
}
var target uint64
if latest := m.migrations[len(m.migrations)-1].Version; targetVersion <= 0 {
target = latest
} else {
target = uint64(mathx.Clamp(targetVersion, 0, int(latest)))
}
version := currentVersion.Version
for i := 0; i < len(m.migrations); i++ {
migration := m.migrations[i]
if migration.Version <= version || migration.Up == nil {
continue
}
if migration.Version > target {
break
}
if err := migration.Up(ctx, m.engine); err != nil {
return err
}
if err := m.setVersion(ctx, migration.Version, migration.Description); err != nil {
return err
}
version = migration.Version
}
return nil
}
// Down performs "down" migration to bring back migrations to `version`.
// If targetVersion<=0 all "down" migrations will be performed.
// If targetVersion>0, only the down migrations where version>targetVersion will be performed (only if they were applied).
func (m *Migrator) Down(ctx context.Context, targetVersion int) error {
m.migrations.Sort()
if len(m.migrations) == 0 {
return nil
}
currentVersion, err := m.Version(ctx)
if err != nil {
return err
}
latestVer := m.migrations[len(m.migrations)-1].Version
target := uint64(mathx.Clamp(targetVersion, 0, int(latestVer)))
version := currentVersion.Version
for i := len(m.migrations) - 1; i >= 0; i-- {
migration := m.migrations[i]
if migration.Version > version || migration.Down == nil {
continue
}
if migration.Version <= uint64(target) {
// We down-ed enough
break
}
if err := migration.Down(ctx, m.engine); err != nil {
return err
}
if err := m.removeVersion(ctx, migration.Version); err != nil {
return err
}
if i == 0 {
version = 0
} else {
version = m.migrations[i-1].Version
}
}
return nil
}