aboutsummaryrefslogtreecommitdiffstats
path: root/internal/services/migration.go
blob: 622ffc35a41b98e3bce7a17b61c27b517e5991ba (plain) (blame)
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
package services

import (
	"sort"

	"github.com/eugenetriguba/bolt/internal/models"
	"github.com/eugenetriguba/bolt/internal/repositories"
)

type MigrationService struct {
	dbRepo *repositories.MigrationDBRepo
	fsRepo *repositories.MigrationFsRepo
}

func NewMigrationService(
	dbRepo *repositories.MigrationDBRepo,
	fsRepo *repositories.MigrationFsRepo,
) *MigrationService {
	return &MigrationService{dbRepo: dbRepo, fsRepo: fsRepo}
}

type sortOrder int

const (
	SortOrderDesc sortOrder = iota
	SortOrderAsc
)

func (ms *MigrationService) ApplyAllMigrations() error {
	migrations, err := ms.ListMigrations(SortOrderAsc)
	if err != nil {
		return err
	}

	for _, migration := range migrations {
		if !migration.Applied {
			ms.ApplyMigration(migration)
		}
	}

	return nil
}

func (ms *MigrationService) ApplyMigration(migration *models.Migration) error {
	scriptContents, err := ms.fsRepo.ReadUpgradeScript(migration)
	if err != nil {
		return err
	}

	err = ms.dbRepo.Apply(scriptContents, migration)
	if err != nil {
		return err
	}

	return nil
}

func (ms *MigrationService) RevertMigration(migration *models.Migration) error {
	scriptContents, err := ms.fsRepo.ReadDowngradeScript(migration)
	if err != nil {
		return err
	}

	err = ms.dbRepo.Revert(scriptContents, migration)
	if err != nil {
		return err
	}

	return nil
}

func (ms *MigrationService) CreateMigration(migration *models.Migration) error {
	return ms.fsRepo.Create(migration)
}

func (ms *MigrationService) ListMigrations(order sortOrder) ([]*models.Migration, error) {
	// Assumption: All migration versions that have been applied
	// to the database exist locally in the list of filesystem migrations.
	// This would hold true unless someone decided to apply a migration and,
	// for whatever reason, delete it later from their filesystem.
	migrations, err := ms.fsRepo.List()
	if err != nil {
		return nil, err
	}

	appliedMigrations, err := ms.dbRepo.List()
	if err != nil {
		return nil, err
	}

	var flatMigrations []*models.Migration
	for _, migration := range migrations {
		_, ok := appliedMigrations[migration.Version]
		if ok {
			migration.Applied = true
		}
		flatMigrations = append(flatMigrations, migration)
	}

	sort.Slice(flatMigrations, func(i, j int) bool {
		if order == SortOrderAsc {
			return flatMigrations[i].Version < flatMigrations[j].Version
		} else {
			return flatMigrations[i].Version > flatMigrations[j].Version
		}
	})

	return flatMigrations, nil
}