forked from deusdat/arangomigo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimpls.go
759 lines (688 loc) · 19 KB
/
impls.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
package arangomigo
import (
"context"
"crypto/md5"
"crypto/tls"
"encoding/hex"
"fmt"
"log"
"github.com/pkg/errors"
"github.com/arangodb/go-driver"
"github.com/arangodb/go-driver/http"
)
const (
migCol string = "arangomigo"
)
// Migration all the operations necessary to modify a database, even make one.
type Migration interface {
Migrate(ctx context.Context, driver driver.Database, extras map[string]interface{}) error
FileName() string
SetFileName(name string)
CheckSum() string
SetCheckSum(sum string)
}
// FileName gets the filename of the migrations configuration.
func (op *Operation) FileName() string {
return op.fileName
}
// SetFileName updates the filename of the migration
func (op *Operation) SetFileName(fileName string) {
op.fileName = fileName
}
// CheckSum gets the checksum for the migration's file
func (op *Operation) CheckSum() string {
return op.checksum
}
// SetCheckSum sets the checksum of the file, in hex.
func (op *Operation) SetCheckSum(sum string) {
op.checksum = sum
}
// End Common operation implementations
func PerformMigrations(ctx context.Context, c Config, ms []Migration) error {
var pms []PairedMigrations
for i, migration := range ms {
name := fmt.Sprintf("%d.migration", i)
migration.SetFileName(name)
chk := md5.Sum([]byte(name))
migration.SetCheckSum(hex.EncodeToString(chk[:]))
pms = append(pms, PairedMigrations{change: migration, undo: nil})
}
return perform(ctx, c, pms)
}
// Entry point in actually executing the migrations
func perform(ctx context.Context, c Config, pm []PairedMigrations) error {
cl, err := client(c)
db, err := loadDb(ctx, c, cl, &pm, c.Extras)
if e(err) {
return err
}
err = migrateNow(ctx, db, pm, c.Extras)
return err
}
// Processed marker. Declared here since it's impl related.
type migration struct {
Key string `json:"_key"`
Checksum string
}
func migrateNow(
ctx context.Context,
db driver.Database,
pms []PairedMigrations,
extras map[string]interface{},
) error {
log.Println("Starting migration now")
mcol, err := db.Collection(ctx, migCol)
if e(err) {
return err
}
for _, pm := range pms {
m := pm.change
u := pm.undo
// Since migrations are stored by their file names, just see if it exists
migRan, err := mcol.DocumentExists(ctx, m.FileName())
if e(err) {
return err
}
if !migRan {
err := m.Migrate(ctx, db, extras)
if !e(err) {
if temp, ok := m.(*Database); !ok || temp.Action == MODIFY {
_, err := mcol.CreateDocument(ctx, &migration{Key: m.FileName(), Checksum: m.CheckSum()})
if e(err) {
return err
}
}
} else if e(err) && driver.IsArangoError(err) && u != nil {
// This probably means a migration issue, back out.
err = u.Migrate(ctx, db, extras)
if e(err) {
return err
}
} else {
return err
}
}
}
return nil
}
func pointyBool(bool2 bool) *bool {
return &bool2
}
func loadDb(
ctx context.Context,
conf Config,
cl driver.Client,
pm *[]PairedMigrations,
extras map[string]interface{}) (driver.Database, error) {
// Checks to see if the database exists
dbName := conf.Db
db, err := cl.Database(ctx, dbName)
if err != nil && driver.IsNotFoundGeneral(err) {
// Creating a database requires extra setup.
m := (*pm)[0].change
o, ok := m.(*Database)
if !ok {
return nil, errors.Errorf("Database %s does not exist and first migration is not the DB creation", dbName)
}
if o.Name != dbName {
return nil, errors.New("Configuration's dbname does not match migration name")
}
o.cl = cl
err = m.Migrate(ctx, db, extras)
if err == nil {
db = o.db
log.Printf("Target db is now %s\n", db.Name())
}
} else if err == nil {
m := (*pm)[0].change
switch m.(type) {
case *Database:
*pm = (*pm)[1:]
}
}
if err == nil {
// Check to see if the migration coll is there.
_, err := db.Collection(ctx, migCol)
if driver.IsNotFoundGeneral(err) {
ko := driver.CollectionKeyOptions{}
ko.AllowUserKeysPtr = pointyBool(true)
options := driver.CreateCollectionOptions{}
options.KeyOptions = &ko
if _, err := db.CreateCollection(ctx, migCol, &options); err != nil {
log.Printf("Failed to create collection %s", migCol)
return db, err
}
}
}
return db, err
}
// Create the client used to talk to ArangoDB
func client(c Config) (driver.Client, error) {
conn, err := http.NewConnection(http.ConnectionConfig{
Endpoints: c.Endpoints,
TLSConfig: &tls.Config{
InsecureSkipVerify: c.SkipSslVerify,
},
})
if e(err) {
return nil, errors.New("Couldn't create connection to Arango\n" + err.Error())
}
cl, err := driver.NewClient(driver.ClientConfig{
Connection: conn,
Authentication: driver.BasicAuthentication(c.Username, c.Password),
})
return cl, err
}
func e(err error) bool {
return err != nil
}
func (d *Database) Migrate(ctx context.Context, db driver.Database, extras map[string]interface{}) error {
var oerr error
switch d.Action {
case CREATE:
if d.db != nil { // no idea why this works.
return nil
}
options := driver.CreateDatabaseOptions{}
active := true
for _, u := range d.Allowed {
options.Users = append(
options.Users,
driver.CreateDatabaseUserOptions{
UserName: directReplace(u.Username, extras).(string),
Password: directReplace(u.Password, extras).(string),
Active: &active,
},
)
}
newdb, err := d.cl.CreateDatabase(ctx, d.Name, &options)
if err == nil {
d.db = newdb
} else {
oerr = err
}
case DELETE:
err := db.Remove(ctx)
if e(err) {
oerr = err
}
default:
oerr = errors.Errorf("Database migration does not support op %s", d.Action)
}
return errors.Wrap(oerr, "Couldn't create database")
}
// directReplace attempts to use the key value to find a lookup in the map.
// if one exists, it returns the values; otherwise returns the key.
func directReplace(key string, extras map[string]interface{}) interface{} {
if val, ok := extras[key]; ok {
return val
}
return key
}
func (cl Collection) Migrate(ctx context.Context, db driver.Database, _ map[string]interface{}) error {
switch cl.Action {
case CREATE:
options := driver.CreateCollectionOptions{}
if cl.Compactable != nil {
options.DoCompact = cl.Compactable
}
if cl.JournalSize != nil {
options.JournalSize = *cl.JournalSize
}
if cl.WaitForSync != nil {
options.WaitForSync = *cl.WaitForSync
}
if cl.ShardKeys != nil {
options.ShardKeys = *cl.ShardKeys
}
if cl.Volatile != nil {
options.IsVolatile = *cl.Volatile
}
if cl.CollectionType != "" {
options.Type = driver.CollectionTypeDocument
if cl.CollectionType == "edge" {
options.Type = driver.CollectionTypeEdge
}
}
// Configures the user keys
ko := driver.CollectionKeyOptions{}
if cl.AllowUserKeys != nil {
ko.AllowUserKeysPtr = cl.AllowUserKeys
}
options.KeyOptions = &ko
_, err := db.CreateCollection(ctx, cl.Name, &options)
if e(err) {
return err
}
case DELETE:
col, err := db.Collection(ctx, cl.Name)
if e(err) {
return errors.Wrapf(err, "Couldn't find collection '%s' to delete", cl.Name)
}
err = col.Remove(ctx)
if !e(err) {
log.Printf("Deleted collection '%s'\n", cl.Name)
}
return errors.Wrapf(err, "Couldn't delete collection '%s'.", cl.Name)
case MODIFY:
col, err := db.Collection(ctx, cl.Name)
if e(err) {
return errors.Wrapf(err, "Couldn't find collection '%s' to delete", cl.Name)
}
options := driver.SetCollectionPropertiesOptions{}
if cl.JournalSize != nil {
options.JournalSize = int64(*cl.JournalSize)
}
if cl.WaitForSync != nil {
options.WaitForSync = cl.WaitForSync
}
err = col.SetProperties(ctx, options)
return errors.Wrapf(err, "Couldn't update collection '%s'", col.Name())
}
return nil
}
func (g Graph) Migrate(ctx context.Context, db driver.Database, _ map[string]interface{}) error {
switch g.Action {
case CREATE:
options := driver.CreateGraphOptions{}
// Only set smart if we know the user set something.
if g.Smart != nil {
options.IsSmart = *g.Smart
}
options.SmartGraphAttribute = g.SmartGraphAttribute
// Set the number of shards.
numShards := 1
if g.Shards > 0 {
numShards = g.Shards
}
options.NumberOfShards = numShards
// Map the edge collections.
for _, ed := range g.EdgeDefinitions {
options.EdgeDefinitions = append(
options.EdgeDefinitions,
driver.EdgeDefinition{
Collection: ed.Collection,
To: ed.To,
From: ed.From,
})
}
// Map the Orphan Vertices
options.OrphanVertexCollections = g.OrphanVertices
_, err := db.CreateGraphV2(ctx, g.Name, &options)
return err
case DELETE:
aG, err := db.Graph(ctx, g.Name)
if e(err) {
return errors.Wrapf(err, "Couldn't find graph with name %s. Can't delete.", g.Name)
}
err = aG.Remove(ctx)
if !e(err) {
log.Printf("Deleted graph '%s'\n", g.Name)
}
return errors.Wrapf(err, "Couldn't remove graph %s", g.Name)
case MODIFY:
aG, err := db.Graph(ctx, g.Name)
if e(err) {
return errors.Wrapf(err, "Couldn't find graph with name %s. Can't modify.", g.Name)
}
// Order matters. If an edge and a vertex are removed, the edge has to
// go first, otherwise Arango will throw an error.
if len(g.RemoveEdges) > 0 {
for _, re := range g.RemoveEdges {
ec, _, err := aG.EdgeCollection(ctx, re)
if driver.IsNotFoundGeneral(err) {
log.Printf("Couldn't find edge collection '%s' to remove.\n", re)
continue
}
if err = ec.Remove(ctx); e(err) {
return errors.Wrapf(err, "Couldn't remove edge collection '%s'", re)
}
}
}
if len(g.RemoveVertices) > 0 {
for _, v := range g.RemoveVertices {
vc, err := aG.VertexCollection(ctx, v)
if driver.IsNotFoundGeneral(err) {
log.Printf("Couldn't find vertex '%s' to remove.", v)
}
if err = vc.Remove(ctx); e(err) {
return errors.Wrapf(err, "Couldn't remove vertex collection '%s'", v)
}
}
}
if len(g.OrphanVertices) > 0 {
for _, o := range g.OrphanVertices {
_, err := aG.CreateVertexCollection(ctx, o)
if e(err) {
return errors.Wrapf(err, "Couldn't add orphan vertex '%s'", o)
}
}
}
if len(g.EdgeDefinitions) > 0 {
for i, ed := range g.EdgeDefinitions {
if exists, err := aG.EdgeCollectionExists(ctx, ed.Collection); exists && !e(err) {
// Assume an update
constraints := driver.VertexConstraints{
From: ed.From,
To: ed.To,
}
return errors.Wrapf(
aG.SetVertexConstraints(ctx, ed.Collection, constraints),
"Couldn't update edge constrain #%d",
i,
)
} else if !exists && !e(err) {
vc := driver.VertexConstraints{}
vc.From = ed.From
vc.To = ed.To
_, err = aG.CreateEdgeCollection(ctx, ed.Collection, vc)
if e(err) {
return errors.Wrapf(err, "Couldn't create edge collection '%s'", ed.Collection)
}
} else {
return errors.WithStack(err)
}
}
}
return nil
default:
return errors.Errorf("Unknown action %s", g.Action)
}
}
func (i FullTextIndex) Migrate(ctx context.Context, db driver.Database, _ map[string]interface{}) error {
cl, err := db.Collection(ctx, i.Collection)
if e(err) {
return errors.Wrapf(
err,
"Couldn't create full text index on collection '%s'. Collection not found",
i.Collection,
)
}
switch i.Action {
case DELETE:
err = dropIndex(ctx, cl, i.Name)
return errors.Wrapf(
err,
"Could not drop full text index with name '%s' in collection %s",
i.Name, i.Collection,
)
case CREATE:
options := driver.EnsureFullTextIndexOptions{}
options.MinLength = i.MinLength
options.Name = i.Name
options.InBackground = i.InBackground
_, _, err = cl.EnsureFullTextIndex(ctx, i.Fields, &options)
return errors.Wrapf(
err,
"Could not create full text index with fields '%s' in collection %s",
i.Fields, i.Collection,
)
default:
return errors.Errorf("Unknown action %s", i.Action)
}
}
func (i GeoIndex) Migrate(ctx context.Context, db driver.Database, _ map[string]interface{}) error {
cl, err := db.Collection(ctx, i.Collection)
if e(err) {
return errors.Wrapf(
err,
"Couldn't create geo index on collection '%s'. Collection not found",
i.Collection,
)
}
switch i.Action {
case DELETE:
err = dropIndex(ctx, cl, i.Name)
return errors.Wrapf(
err,
"Could not drop geo index with name '%s' in collection %s",
i.Name, i.Collection,
)
case CREATE:
options := driver.EnsureGeoIndexOptions{}
options.GeoJSON = i.GeoJSON
options.Name = i.Name
options.InBackground = i.InBackground
_, _, err = cl.EnsureGeoIndex(ctx, i.Fields, &options)
return errors.Wrapf(
err,
"Could not create geo index with fields '%s' in collection %s",
i.Fields, i.Collection,
)
default:
return errors.Errorf("Unknown action %s", i.Action)
}
}
func (i HashIndex) Migrate(ctx context.Context, db driver.Database, _ map[string]interface{}) error {
cl, err := db.Collection(ctx, i.Collection)
if e(err) {
return errors.Wrapf(
err,
"Couldn't create hash index on collection '%s'. Collection not found",
i.Collection,
)
}
switch i.Action {
case DELETE:
err = dropIndex(ctx, cl, i.Name)
return errors.Wrapf(
err,
"Could not drop hash index with name '%s' in collection %s",
i.Name, i.Collection,
)
case CREATE:
options := driver.EnsureHashIndexOptions{}
options.NoDeduplicate = i.NoDeduplicate
options.Sparse = i.Sparse
options.Unique = i.Unique
options.Name = i.Name
options.InBackground = i.InBackground
_, _, err = cl.EnsureHashIndex(ctx, i.Fields, &options)
return errors.Wrapf(
err,
"Could not create hash index with fields '%s' in collection %s",
i.Fields, i.Collection,
)
default:
return errors.Errorf("Unknown action %s", i.Action)
}
}
func (i PersistentIndex) Migrate(ctx context.Context, db driver.Database, _ map[string]interface{}) error {
cl, err := db.Collection(ctx, i.Collection)
if e(err) {
return errors.Wrapf(
err,
"Couldn't create persistent index on collection '%s'. Collection not found",
i.Collection,
)
}
switch i.Action {
case DELETE:
err = dropIndex(ctx, cl, i.Name)
return errors.Wrapf(
err,
"Could not drop persistent index with name '%s' in collection %s",
i.Name, i.Collection,
)
case CREATE:
options := driver.EnsurePersistentIndexOptions{}
options.Sparse = i.Sparse
options.Unique = i.Unique
options.Name = i.Name
options.InBackground = i.InBackground
_, _, err = cl.EnsurePersistentIndex(ctx, i.Fields, &options)
return errors.Wrapf(
err,
"Could not create persistent index with fields '%s' in collection %s",
i.Fields, i.Collection,
)
default:
return errors.Errorf("Unknown action %s", i.Action)
}
}
func (i TTLIndex) Migrate(ctx context.Context, db driver.Database, _ map[string]interface{}) error {
cl, err := db.Collection(ctx, i.Collection)
if e(err) {
return errors.Wrapf(
err,
"Couldn't create ttl index on collection '%s'. Collection not found",
i.Collection,
)
}
switch i.Action {
case DELETE:
err = dropIndex(ctx, cl, i.Name)
return errors.Wrapf(
err,
"Could not drop ttl index with name '%s' in collection %s",
i.Name, i.Collection,
)
case CREATE:
options := driver.EnsureTTLIndexOptions{}
options.Name = i.Name
options.InBackground = i.InBackground
_, _, err = cl.EnsureTTLIndex(ctx, i.Field, i.ExpireAfter, &options)
return errors.Wrapf(
err,
"Could not create ttl index with field '%s' in collection %s",
i.Field, i.Collection,
)
default:
return errors.Errorf("Unknown action %s", i.Action)
}
}
func (i SkiplistIndex) Migrate(ctx context.Context, db driver.Database, _ map[string]interface{}) error {
cl, err := db.Collection(ctx, i.Collection)
if e(err) {
return errors.Wrapf(
err,
"Couldn't create skiplist index on collection '%s'. Collection not found",
i.Collection,
)
}
switch i.Action {
case DELETE:
err = dropIndex(ctx, cl, i.Name)
return errors.Wrapf(
err,
"Could not drop skiplist index with name '%s' in collection %s",
i.Name, i.Collection,
)
case CREATE:
options := driver.EnsureSkipListIndexOptions{}
options.Sparse = i.Sparse
options.Unique = i.Unique
options.NoDeduplicate = i.NoDeduplicate
options.Name = i.Name
options.InBackground = i.InBackground
_, _, err = cl.EnsureSkipListIndex(ctx, i.Fields, &options)
return errors.Wrapf(
err,
"Could not create skiplist index with fields '%s' in collection %s",
i.Fields, i.Collection,
)
default:
return errors.Errorf("Unknown action %s", i.Action)
}
}
func (i PipelineAnalyzer) Migrate(ctx context.Context, db driver.Database, _ map[string]interface{}) error {
switch i.Action {
case DELETE:
a, err := db.Analyzer(ctx, i.Name)
if e(err) {
return errors.Wrapf(err, "Error removing analyzer %s", i.Name)
}
err = a.Remove(ctx, true)
return errors.Wrapf(err, "Failed %s", i.Action)
case CREATE:
_, _, err := db.EnsureAnalyzer(ctx, driver.ArangoSearchAnalyzerDefinition{
Name: i.Name,
Type: "pipeline",
Properties: i.Properties,
Features: i.Features,
})
return errors.Wrapf(err, "Failed %s", i.Action)
default:
return errors.Errorf("Unknown action %s", i.Action)
}
}
func (i InvertedIndex) Migrate(ctx context.Context, db driver.Database, _ map[string]interface{}) error {
cl, err := db.Collection(ctx, i.Collection)
if e(err) {
return errors.Wrapf(
err,
"Couldn't create inverted index on collection '%s'. Collection not found",
i.Collection,
)
}
switch i.Action {
case DELETE:
err = dropIndex(ctx, cl, i.Name)
return errors.Wrapf(
err,
"Could not drop inverted index with name '%s' in collection %s",
i.Name, i.Collection,
)
case CREATE:
options := driver.InvertedIndexOptions{}
options.Name = i.Name
options.Fields = i.InvertedIndexFields()
options.InBackground = i.InBackground
options.Analyzer = i.Analyzer
asc := true
options.PrimarySort.Fields = []driver.ArangoSearchPrimarySortEntry{
{Field: i.Fields[0], Ascending: &asc},
}
_, _, err = cl.EnsureInvertedIndex(ctx, &options)
return errors.Wrapf(
err,
"Could not create inverted index with fields '%s' in collection %s",
i.Fields, i.Collection,
)
default:
return errors.Errorf("Unknown action %s", i.Action)
}
}
func (a AQL) Migrate(ctx context.Context, db driver.Database, extras map[string]interface{}) error {
escaped := make(map[string]interface{})
for k, v := range a.BindVars {
if vstr, ok := v.(string); ok {
escaped[k] = directReplace(vstr, extras)
} else {
escaped[k] = v
}
}
cur, err := db.Query(ctx, a.Query, escaped)
if e(err) {
return errors.Wrapf(err, "Couldn't execute query '%s'", a.Query)
}
defer func(cur driver.Cursor) {
err := cur.Close()
if err != nil {
log.Printf("could not close cursor")
}
}(cur)
return nil
}
func dropIndex(ctx context.Context, cl driver.Collection, name string) error {
var exists bool
var idx driver.Index
var err error
exists, err = cl.IndexExists(ctx, name)
if e(err) {
return errors.Wrapf(err, "Error finding index '%s'", name)
}
if exists {
// get index
idx, err = cl.Index(ctx, name)
if e(err) {
return errors.Wrapf(err, "Error retrieving index '%s'", name)
}
// drop index
err = idx.Remove(ctx)
if e(err) {
return errors.Wrapf(err, "Error dropping index '%s'", name)
}
}
return nil
}