-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrator.go
238 lines (201 loc) · 5.8 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
// Package migration allows to perform versioned migrations in your ArangoDB.
package arangox
import (
"context"
"fmt"
"time"
arangoDriver "github.com/arangodb/go-driver"
"github.com/clinia/x/mathx"
)
type collectionSpecification struct {
Name string `json:"name"`
Type int `json:"type"`
}
type versionRecord struct {
Version uint64 `json:"version"`
Description string `json:"description,omitempty"`
Package string `json:"package"`
Timestamp time.Time `json:"timestamp"`
}
const defaultMigrationsCollection = "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 {
db arangoDriver.Database
pkg string
migrations Migrations
migrationsCollection string
}
type NewMigratorOptions struct {
Database arangoDriver.Database
Package string
Migrations Migrations
}
func NewMigrator(in NewMigratorOptions) *Migrator {
internalMigrations := make(Migrations, len(in.Migrations))
copy(internalMigrations, in.Migrations)
vers := map[uint64]bool{}
for _, m := range in.Migrations {
if vers[m.Version] {
panic(fmt.Sprintf("duplicated migration version %v", m.Version))
}
vers[m.Version] = true
}
return &Migrator{
db: in.Database,
pkg: in.Package,
migrations: internalMigrations,
migrationsCollection: defaultMigrationsCollection,
}
}
// SetMigrationsCollection replaces name of collection for storing migration information.
// By default it is "migrations".
func (m *Migrator) SetMigrationsCollection(name string) {
m.migrationsCollection = name
}
func (m *Migrator) createCollectionIfNotExist(ctx context.Context, name string) error {
exist, err := m.db.CollectionExists(ctx, name)
if err != nil {
return err
}
if exist {
return nil
}
col, err := m.db.CreateCollection(ctx, name, nil)
if err != nil {
return err
}
_, _, err = col.EnsurePersistentIndex(ctx, []string{"version", "package"}, &arangoDriver.EnsurePersistentIndexOptions{
Unique: true,
})
if err != nil {
return err
}
return nil
}
// Version returns current database version and comment.
func (m *Migrator) Version(ctx context.Context) (current uint64, latest uint64, desc string, outErr error) {
m.migrations.Sort()
if len(m.migrations) > 0 {
latest = m.migrations[len(m.migrations)-1].Version
}
if err := m.createCollectionIfNotExist(ctx, m.migrationsCollection); err != nil {
return 0, latest, "", err
}
cursor, err := m.db.Query(ctx, `
FOR m IN @@collection
FILTER m.package == @pkg
SORT m.version DESC
LIMIT 1
RETURN m
`, map[string]interface{}{
"@collection": m.migrationsCollection,
"pkg": m.pkg,
})
if err != nil {
return 0, latest, "", err
}
defer cursor.Close()
var rec versionRecord
_, err = cursor.ReadDocument(ctx, &rec)
if err != nil {
_, ok := err.(arangoDriver.NoMoreDocumentsError)
if ok {
return 0, latest, "", nil
}
return 0, latest, "", err
}
return rec.Version, latest, rec.Description, 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()
currentVersion, latest, _, err := m.Version(ctx)
if err != nil {
return err
}
var target uint64
if targetVersion <= 0 {
target = latest
} else {
target = uint64(mathx.Clamp(targetVersion, 0, int(latest)))
}
col, err := m.db.Collection(ctx, m.migrationsCollection)
if err != nil {
return err
}
for i := 0; i < len(m.migrations); i++ {
migration := m.migrations[i]
if migration.Version <= currentVersion || migration.Up == nil {
continue
}
if migration.Version > target {
break
}
if err := migration.Up(ctx, m.db); err != nil {
return err
}
rec := versionRecord{
Version: migration.Version,
Package: m.pkg,
Timestamp: time.Now().UTC(),
Description: migration.Description,
}
_, err = col.CreateDocument(ctx, rec)
if err != nil {
return err
}
}
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()
version, latest, _, err := m.Version(ctx)
if err != nil {
return err
}
target := uint64(mathx.Clamp(targetVersion, 0, int(latest)))
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.db); err != nil {
return err
}
if i == 0 {
version = 0
} else {
version = m.migrations[i-1].Version
}
}
_, err = m.db.Query(ctx, `
FOR m IN @@collection
FILTER m.package == @pkg AND m.version > @version
REMOVE m IN @@collection
LET removed = OLD
RETURN removed
`, map[string]interface{}{
"@collection": m.migrationsCollection,
"pkg": m.pkg,
"version": version,
})
if err != nil {
return err
}
return nil
}