-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
migrate.go
1946 lines (1688 loc) · 44.8 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
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package migrate implements migrations on Hasura GraphQL Engine.
//
// This package is borrowed from https://github.com/golang-migrate/migrate with
// additions for Hasura specific yaml file support and a improved Rails-like
// migration pattern.
package migrate
import (
"bytes"
"container/list"
"errors"
"fmt"
"io"
"io/fs"
"os"
"sync"
"text/tabwriter"
"time"
"github.com/cheggaaa/pb/v3"
"golang.org/x/term"
herrors "github.com/hasura/graphql-engine/cli/v2/internal/errors"
"github.com/hasura/graphql-engine/cli/v2/internal/hasura"
"github.com/hasura/graphql-engine/cli/v2/migrate/database"
"github.com/hasura/graphql-engine/cli/v2/migrate/source"
"github.com/hasura/graphql-engine/cli/v2/util"
log "github.com/sirupsen/logrus"
)
// DefaultPrefetchMigrations sets the number of migrations to pre-read
// from the source. This is helpful if the source is remote, but has little
// effect for a local source (i.e. file system).
// Please note that this setting has a major impact on the memory usage,
// since each pre-read migration is buffered in memory. See DefaultBufferSize.
var DefaultPrefetchMigrations = uint64(10)
// DefaultLockTimeout sets the max time a database driver has to acquire a lock.
var DefaultLockTimeout = 15 * time.Second
var (
ErrNoChange = fmt.Errorf("no change")
ErrNilVersion = fmt.Errorf("no migration")
ErrLocked = fmt.Errorf("database locked")
ErrNoMigrationFiles = fmt.Errorf("no migration files found")
ErrLockTimeout = fmt.Errorf("timeout: can't acquire database lock")
ErrApplied = fmt.Errorf("Version already applied in database")
ErrNotApplied = fmt.Errorf("Migration not applied in database")
ErrNoMigrationMode = fmt.Errorf("Migration mode is disabled")
ErrMigrationMode = fmt.Errorf("Migration mode is enabled")
)
const (
applyingMigrationsMessage = "Applying migrations"
)
func newProgressBar(str string, w io.Writer, pbLogs bool) *pb.ProgressBar {
// Default behaviour in non-interactive mode
if !pbLogs && !term.IsTerminal(int(os.Stdout.Fd())) {
return nil
}
// bar template configuration
str = fmt.Sprintf(`"%v: "`, str)
var barTemplateConfiguration string = fmt.Sprintf(`{{ cyan %s }} {{ counters .}} {{ bar . "[" "=" ">" "." "]"}} {{percent .}}`, str)
bar := pb.ProgressBarTemplate(barTemplateConfiguration).New(0)
bar.SetRefreshRate(time.Millisecond)
// non-interactive mode with progressbar-logs flag
if pbLogs && !term.IsTerminal(int(os.Stdout.Fd())) {
bar.Set(pb.Terminal, true)
}
bar.Set(pb.CleanOnFinish, true)
if w != nil {
bar.SetWriter(w)
}
return bar
}
func startProgressBar(bar *pb.ProgressBar) {
if bar != nil {
bar.Start()
}
}
func finishProgressBar(bar *pb.ProgressBar) {
if bar != nil {
bar.Finish()
}
}
func incrementProgressBar(bar *pb.ProgressBar) {
if bar != nil {
bar.Increment()
}
}
func setTotalProgressBar(bar *pb.ProgressBar, val int64) {
if bar != nil {
bar.SetTotal(val)
}
}
func setWidthProgressBar(bar *pb.ProgressBar, pbLogs bool) {
if pbLogs && !term.IsTerminal(int(os.Stdout.Fd())) && bar.Width() == 0 {
bar.SetWidth(220)
}
}
// ErrShortLimit is an error returned when not enough migrations
// can be returned by a source for a given limit.
type ErrShortLimit struct {
Short uint64
}
// Error implements the error interface.
func (e ErrShortLimit) Error() string {
return fmt.Sprintf("limit %v short", e.Short)
}
type ErrDirty struct {
Version int64
}
func (e ErrDirty) Error() string {
return fmt.Sprintf("Dirty database version %v. Fix and force version.", e.Version)
}
type Migrate struct {
sourceName string
sourceURL string
sourceDrv source.Driver
databaseName string
databaseURL string
databaseDrv database.Driver
// Logger is the global logger object to print logs.
Logger *log.Logger
stderr io.Writer
stdout io.Writer
// GracefulStop accepts `true` and will stop executing migrations
// as soon as possible at a safe break point, so that the database
// is not corrupted.
GracefulStop chan bool
isGracefulStop bool
isLockedMu *sync.Mutex
isLocked bool
// PrefetchMigrations defaults to DefaultPrefetchMigrations,
// but can be set per Migrate instance.
PrefetchMigrations uint64
// LockTimeout defaults to DefaultLockTimeout,
// but can be set per Migrate instance.
LockTimeout time.Duration
//CMD
isCMD bool
status *Status
SkipExecution bool
DryRun bool
ProgressBarLogs bool
}
type NewMigrateOpts struct {
sourceUrl, databaseUrl string
cmd bool
configVersion int
logger *log.Logger
Stdout io.Writer
Stderr io.Writer
hasuraOpts *database.HasuraOpts
}
// New returns a new Migrate instance from a source URL and a database URL.
// The URL scheme is defined by each driver.
func New(opts NewMigrateOpts) (*Migrate, error) {
var op herrors.Op = "migrate.New"
m := newCommon(opts.cmd)
m.stdout = opts.Stdout
m.stderr = opts.Stderr
sourceName, err := schemeFromUrl(opts.sourceUrl)
if err != nil {
log.Debug(err)
return nil, herrors.E(op, err)
}
m.sourceName = sourceName
m.sourceURL = opts.sourceUrl
databaseName, err := schemeFromUrl(opts.databaseUrl)
if err != nil {
log.Debug(err)
return nil, herrors.E(op, err)
}
m.databaseName = databaseName
m.databaseURL = opts.databaseUrl
if opts.logger == nil {
opts.logger = log.New()
}
m.Logger = opts.logger
sourceDrv, err := source.Open(opts.sourceUrl, opts.logger)
if err != nil {
log.Debug(err)
return nil, herrors.E(op, err)
}
m.sourceDrv = sourceDrv
if opts.configVersion >= 2 {
m.sourceDrv.DefaultParser(source.DefaultParsev2)
}
databaseDrv, err := database.Open(opts.databaseUrl, opts.cmd, opts.logger, opts.hasuraOpts)
if err != nil {
log.Debug(err)
return nil, herrors.E(op, err)
}
m.databaseDrv = databaseDrv
err = m.ReScan()
if err != nil {
return nil, herrors.E(op, err)
}
return m, nil
}
func newCommon(cmd bool) *Migrate {
return &Migrate{
GracefulStop: make(chan bool, 1),
PrefetchMigrations: DefaultPrefetchMigrations,
isLockedMu: &sync.Mutex{},
LockTimeout: DefaultLockTimeout,
isCMD: cmd,
}
}
func (m *Migrate) ReScan() error {
var op herrors.Op = "migrate.Migrate.ReScan"
err := m.sourceDrv.Scan()
if err != nil {
m.Logger.Debug(err)
return herrors.E(op, err)
}
err = m.databaseDrv.Scan()
if err != nil {
m.Logger.Debug(err)
return herrors.E(op, err)
}
err = m.calculateStatus()
if err != nil {
return herrors.E(op, err)
}
return nil
}
// Close closes the source and the database.
func (m *Migrate) Close() error {
var op herrors.Op = "migrate.Migrate.Close"
sourceSrvClose := make(chan error)
go func() {
sourceSrvClose <- m.sourceDrv.Close()
}()
err := <-sourceSrvClose
if err != nil {
return herrors.E(op, err)
}
return nil
}
func (m *Migrate) calculateStatus() error {
var op herrors.Op = "migrate.Migrate.calculateStatus"
m.status = NewStatus()
err := m.readStatusFromSource()
if err != nil {
return herrors.E(op, err)
}
if err = m.readStatusFromDatabase(); err != nil {
return herrors.E(op, err)
}
return nil
}
func (m *Migrate) readStatusFromSource() error {
var op herrors.Op = "migrate.Migrate.readStatusFromSource"
firstVersion, err := m.sourceDrv.First()
if err != nil {
var pathErr *os.PathError
if errors.As(err, &pathErr) {
return nil
}
return herrors.E(op, err)
}
m.status.Append(m.newMigrationStatus(firstVersion, "source", false))
from := int64(firstVersion)
lastVersion, err := m.sourceDrv.GetLocalVersion()
if err != nil {
return herrors.E(op, err)
}
m.status.Append(m.newMigrationStatus(lastVersion, "source", false))
to := int64(lastVersion)
for from < to {
next, err := m.sourceDrv.Next(suint64(from))
if err != nil {
return herrors.E(op, err)
}
m.status.Append(m.newMigrationStatus(next, "source", false))
from = int64(next)
}
return nil
}
func (m *Migrate) readStatusFromDatabase() error {
firstVersion, ok := m.databaseDrv.First()
if !ok {
return nil
}
m.status.Append(m.newMigrationStatus(firstVersion.Version, "database", firstVersion.Dirty))
from := int64(firstVersion.Version)
lastVersion, ok := m.databaseDrv.Last()
if !ok {
return nil
}
m.status.Append(m.newMigrationStatus(lastVersion.Version, "database", lastVersion.Dirty))
to := int64(lastVersion.Version)
for from < to {
next, ok := m.databaseDrv.Next(suint64(from))
if !ok {
return nil
}
m.status.Append(m.newMigrationStatus(next.Version, "database", next.Dirty))
from = int64(next.Version)
}
return nil
}
func (m *Migrate) newMigrationStatus(version uint64, driverType string, dirty bool) *MigrationStatus {
var migrStatus *MigrationStatus
migrStatus, ok := m.status.Read(version)
if !ok {
migrStatus = &MigrationStatus{
Version: version,
Name: m.sourceDrv.ReadName(version),
IsDirty: dirty,
}
}
switch driverType {
case "source":
migrStatus.IsPresent = true
case "database":
migrStatus.IsApplied = true
migrStatus.IsDirty = dirty
default:
return nil
}
return migrStatus
}
func (m *Migrate) GetStatus() (*Status, error) {
var op herrors.Op = "migrate.Migrate.GetStatus"
err := m.calculateStatus()
if err != nil {
return nil, herrors.E(op, err)
}
return m.status, nil
}
func (m *Migrate) GetSetting(name string) (string, error) {
var op herrors.Op = "migrate.Migrate.GetSetting"
val, err := m.databaseDrv.GetSetting(name)
if err != nil {
return "", herrors.E(op, err)
}
return val, nil
}
func (m *Migrate) UpdateSetting(name string, value string) error {
var op herrors.Op = "migrate.Migrate.UpdateSetting"
if err := m.databaseDrv.UpdateSetting(name, value); err != nil {
return herrors.E(op, err)
}
return nil
}
func (m *Migrate) Version() (version uint64, dirty bool, err error) {
var op herrors.Op = "migrate.Migrate.Version"
v, d, err := m.databaseDrv.Version()
if err != nil {
return 0, false, herrors.E(op, err)
}
if v == database.NilVersion {
return 0, false, herrors.E(op, ErrNilVersion)
}
return suint64(v), d, nil
}
func (m *Migrate) GetUnappliedMigrations(version uint64) []uint64 {
return m.sourceDrv.GetUnappliedMigrations(version)
}
func (m *Migrate) ExportSchemaDump(includeSchemas []string, excludeSchemas []string, sourceName string, sourceKind hasura.SourceKind) ([]byte, error) {
var op herrors.Op = "migrate.Migrate.ExportSchemaDump"
b, err := m.databaseDrv.ExportSchemaDump(includeSchemas, excludeSchemas, sourceName, sourceKind)
if err != nil {
return b, herrors.E(op, err)
}
return b, nil
}
func (m *Migrate) RemoveVersions(versions []uint64) error {
var op herrors.Op = "migrate.Migrate.RemoveVersions"
mode, err := m.databaseDrv.GetSetting("migration_mode")
if err != nil {
return herrors.E(op, err)
}
if mode != "true" {
return herrors.E(op, ErrNoMigrationMode)
}
if err := m.lock(); err != nil {
return herrors.E(op, err)
}
for _, version := range versions {
err = m.databaseDrv.RemoveVersion(int64(version))
if err != nil {
return herrors.E(op, err)
}
}
if err = m.unlockErr(nil); err != nil {
return herrors.E(op, err)
}
return nil
}
func (m *Migrate) Query(data interface{}) error {
var op herrors.Op = "migrate.Migrate.Query"
mode, err := m.databaseDrv.GetSetting("migration_mode")
if err != nil {
return herrors.E(op, err)
}
if mode == "true" {
return herrors.E(op, ErrMigrationMode)
}
if err = m.databaseDrv.Query(data); err != nil {
return herrors.E(op, err)
}
return nil
}
// Squash migrations from version v into a new migration.
// Returns a list of migrations that are squashed: vs
// the squashed metadata for all UP steps: um
// the squashed SQL for all UP steps: us
// the squashed metadata for all down steps: dm
// the squashed SQL for all down steps: ds
func (m *Migrate) Squash(v1 uint64, v2 int64) (vs []int64, us []byte, ds []byte, err error) {
var op herrors.Op = "migrate.Migrate.Squash"
// check the migration mode on the database
mode, err := m.databaseDrv.GetSetting("migration_mode")
if err != nil {
return vs, us, ds, herrors.E(op, err)
}
// if migration_mode is false, set err to ErrNoMigrationMode and return
if mode != "true" {
return vs, us, ds, herrors.E(op, ErrNoMigrationMode)
}
// concurrently squash all the up migrations
// read all up migrations from source and send each migration
// to the returned channel
retUp := make(chan interface{}, m.PrefetchMigrations)
go m.squashUp(v1, v2, retUp)
// concurrently squash all down migrations
// read all down migrations from source and send each migration
// to the returned channel
retDown := make(chan interface{}, m.PrefetchMigrations)
go m.squashDown(v1, v2, retDown)
// combine squashed up and down migrations into a single one when they're ready
dataUp := make(chan interface{}, m.PrefetchMigrations)
dataDown := make(chan interface{}, m.PrefetchMigrations)
retVersions := make(chan int64, m.PrefetchMigrations)
go func() {
if err := m.squashMigrations(retUp, retDown, dataUp, dataDown, retVersions); err != nil {
m.Logger.Error(err)
}
}()
// make a chan for errors
errChn := make(chan error, 2)
// create a waitgroup to wait for all goroutines to finish execution
var wg sync.WaitGroup
// add three tasks to waitgroup since we used 3 goroutines above
wg.Add(3)
// read from dataUp chan when all up migrations are squashed and compiled
go func() {
// defer to mark one task in the waitgroup as complete
defer wg.Done()
buf := &bytes.Buffer{}
for r := range dataUp {
// check the type of value returned through the chan
switch data := r.(type) {
case error:
// it's an error, set error and return
// note: this return is returning the goroutine, not the current function
m.isGracefulStop = true
errChn <- r.(error)
return
case []byte:
// it's SQL, concat all of them
buf.WriteString("\n")
buf.Write(data)
}
}
// set us as the bytes written into buf
us = buf.Bytes()
}()
// read from dataDown when it is ready:
go func() {
// defer to mark another task in the waitgroup as complete
defer wg.Done()
buf := &bytes.Buffer{}
for r := range dataDown {
// check the type of value returned through the chan
switch data := r.(type) {
case error:
// it's an error, set error and return
// note: this return is returning the goroutine, not the current function
m.isGracefulStop = true
errChn <- r.(error)
return
case []byte:
// it's SQL, concat all of them
buf.WriteString("\n")
buf.Write(data)
}
}
// set ds as the bytes written into buf
ds = buf.Bytes()
}()
// read retVersions - versions that are squashed
go func() {
// defer to mark another task in the waitgroup as complete
defer wg.Done()
for r := range retVersions {
// append each version into the versions array
vs = append(vs, r)
}
}()
// returns from the above goroutines pass the control here.
// wait until all tasks (3) in the workgroup are completed
wg.Wait()
// close the errChn
close(errChn)
// check for errors in the error channel
for e := range errChn {
return vs, us, ds, herrors.E(op, e)
}
if err != nil {
return vs, us, ds, herrors.E(op, err)
}
return vs, us, ds, nil
}
// Migrate looks at the currently active migration version,
// then migrates either up or down to the specified version.
func (m *Migrate) Migrate(version uint64, direction string) error {
var op herrors.Op = "migrate.Migrate.Migrate"
mode, err := m.databaseDrv.GetSetting("migration_mode")
if err != nil {
return herrors.E(op, err)
}
if mode != "true" {
return herrors.E(op, ErrNoMigrationMode)
}
if err := m.lock(); err != nil {
return herrors.E(op, err)
}
ret := make(chan interface{}, m.PrefetchMigrations)
bar := newProgressBar(applyingMigrationsMessage, m.stderr, m.ProgressBarLogs)
go m.read(version, direction, ret, bar)
if m.DryRun {
if e := m.unlockErr(m.runDryRun(ret)); e != nil {
return herrors.E(op, e)
}
return nil
} else {
if e := m.unlockErr(m.runMigrations(ret, bar)); e != nil {
return herrors.E(op, e)
}
return nil
}
}
func (m *Migrate) QueryWithVersion(version uint64, data io.ReadCloser, skipExecution bool) error {
var op herrors.Op = "migrate.Migrate.QueryWithVersion"
mode, err := m.databaseDrv.GetSetting("migration_mode")
if err != nil {
return herrors.E(op, err)
}
if mode != "true" {
return herrors.E(op, ErrNoMigrationMode)
}
if err := m.lock(); err != nil {
return herrors.E(op, err)
}
if !skipExecution {
if err := m.databaseDrv.Run(data, "meta", ""); err != nil {
m.databaseDrv.ResetQuery()
if e := m.unlockErr(err); e != nil {
return herrors.E(op, e)
}
return nil
}
}
if version != 0 {
if err := m.databaseDrv.SetVersion(int64(version), false); err != nil {
m.databaseDrv.ResetQuery()
if e := m.unlockErr(err); e != nil {
return herrors.E(op, e)
}
return nil
}
}
if err := m.unlockErr(nil); err != nil {
return herrors.E(op, err)
}
return nil
}
// Steps looks at the currently active migration version.
// It will migrate up if n > 0, and down if n < 0.
func (m *Migrate) Steps(n int64) error {
var op herrors.Op = "migrate.Migrate.Steps"
mode, err := m.databaseDrv.GetSetting("migration_mode")
if err != nil {
return herrors.E(op, err)
}
if mode != "true" {
return herrors.E(op, ErrNoMigrationMode)
}
if n == 0 {
return herrors.E(op, ErrNoChange)
}
if err := m.lock(); err != nil {
return herrors.E(op, err)
}
ret := make(chan interface{}, m.PrefetchMigrations)
bar := newProgressBar(applyingMigrationsMessage, m.stderr, m.ProgressBarLogs)
if n > 0 {
go m.readUp(n, ret, bar)
} else {
go m.readDown(-n, ret, bar)
}
if m.DryRun {
if err := m.unlockErr(m.runDryRun(ret)); err != nil {
return herrors.E(op, err)
}
return nil
} else {
if err := m.unlockErr(m.runMigrations(ret, bar)); err != nil {
return herrors.E(op, err)
}
return nil
}
}
// Up looks at the currently active migration version
// and will migrate all the way up (applying all up migrations).
func (m *Migrate) Up() error {
var op herrors.Op = "migrate.Migrate.Up"
mode, err := m.databaseDrv.GetSetting("migration_mode")
if err != nil {
return herrors.E(op, err)
}
if mode != "true" {
return herrors.E(op, ErrNoMigrationMode)
}
if err := m.lock(); err != nil {
return herrors.E(op, err)
}
curVersion, dirty, err := m.databaseDrv.Version()
if err != nil {
return herrors.E(op, err)
}
if dirty {
return herrors.E(op, ErrDirty{curVersion})
}
ret := make(chan interface{}, m.PrefetchMigrations)
bar := newProgressBar(applyingMigrationsMessage, m.stderr, m.ProgressBarLogs)
go m.readUp(-1, ret, bar)
if m.DryRun {
if err := m.unlockErr(m.runDryRun(ret)); err != nil {
return herrors.E(op, err)
}
return nil
} else {
if err := m.unlockErr(m.runMigrations(ret, bar)); err != nil {
return herrors.E(op, err)
}
return nil
}
}
// Down looks at the currently active migration version
// and will migrate all the way down (applying all down migrations).
func (m *Migrate) Down() error {
var op herrors.Op = "migrate.Migrate.Down"
mode, err := m.databaseDrv.GetSetting("migration_mode")
if err != nil {
return herrors.E(op, err)
}
if mode != "true" {
return herrors.E(op, ErrNoMigrationMode)
}
if err := m.lock(); err != nil {
return herrors.E(op, err)
}
curVersion, dirty, err := m.databaseDrv.Version()
if err != nil {
return herrors.E(op, err)
}
if dirty {
return herrors.E(op, ErrDirty{curVersion})
}
ret := make(chan interface{}, m.PrefetchMigrations)
bar := newProgressBar(applyingMigrationsMessage, m.stderr, m.ProgressBarLogs)
go m.readDown(-1, ret, bar)
if m.DryRun {
if err := m.unlockErr(m.runDryRun(ret)); err != nil {
return herrors.E(op, err)
}
return nil
} else {
if err := m.unlockErr(m.runMigrations(ret, bar)); err != nil {
return herrors.E(op, err)
}
return nil
}
}
func (m *Migrate) squashUp(from uint64, to int64, ret chan<- interface{}) {
defer close(ret)
currentVersion := from
count := int64(0)
limit := int64(-1)
if m.stop() {
return
}
for limit == -1 {
if int64(from) == to {
return
}
if currentVersion == from {
// during the first iteration of the loop
// check if a next version exists for "--from" version
if err := m.versionUpExists(from); err != nil {
ret <- err
return
}
// If next version exists this function will return an instance of
// migration.go.Migrate struct
// this reads the SQL up migration
// even if a migration file does'nt exist in the source
// a empty migration will be returned
migr, err := m.newMigration(from, int64(from))
if err != nil {
ret <- err
return
}
ret <- migr
// write the body of the migration to reader
// the migr instance sent via the channel will then start reading
// from it
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
count++
}
// get the next version using source driver
// earlier in the first iteration we knew what version to operate on
// but here we have to find the next version
next, err := m.sourceDrv.Next(currentVersion)
if errors.Is(err, fs.ErrNotExist) {
// no limit, but no migrations applied?
if count == 0 {
ret <- ErrNoChange
return
}
// when there is no more migrations return
if limit == -1 {
return
}
}
if err != nil {
ret <- err
return
}
// Check if next files exists (yaml or sql)
if err = m.versionUpExists(next); err != nil {
ret <- err
return
}
migr, err := m.newMigration(next, int64(next))
if err != nil {
ret <- err
return
}
ret <- migr
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
if int64(next) == to {
return
}
currentVersion = next
count++
}
}
func (m *Migrate) squashDown(v1 uint64, v2 int64, ret chan<- interface{}) {
defer close(ret)
// get the last version from the source driver
var err error
var from uint64
if v2 == -1 {
from, err = m.sourceDrv.GetLocalVersion()
if err != nil {
ret <- err
return
}
} else {
from = uint64(v2)
}
for {
if m.stop() {
return
}
if from < v1 {
return
}
prev, err := m.sourceDrv.Prev(from)
if errors.Is(err, fs.ErrNotExist) {
migr, err := m.newMigration(from, -1)
if err != nil {
ret <- err
return
}
ret <- migr
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
return
} else if err != nil {
ret <- err
return
}
err = m.versionDownExists(from)
if err == nil {
migr, err := m.newMigration(from, int64(prev))
if err != nil {
ret <- err
return
}
ret <- migr
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
} else {
m.Logger.Warnf("%v", err)
}
from = prev
}
}
// read reads either up or down migrations from source `from` to `to`.
// Each migration is then written to the ret channel.
// If an error occurs during reading, that error is written to the ret channel, too.
// Once read is done reading it will close the ret channel.
func (m *Migrate) read(version uint64, direction string, ret chan<- interface{}, bar *pb.ProgressBar) {
defer close(ret)
setTotalProgressBar(bar, 1)
if direction == "up" {
if m.stop() {
return
}
// Check if this version present in DB
ok := m.databaseDrv.Read(version)
if ok {
ret <- ErrApplied
return
}
// Check if next version exists (yaml or sql)
if err := m.versionUpExists(version); err != nil {
ret <- err
return
}
migr, err := m.newMigration(version, int64(version))
if err != nil {
ret <- err
return
}
ret <- migr
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
} else {
// it's going down
if m.stop() {
return
}
// Check if this version present in DB