aboutsummaryrefslogtreecommitdiffstats
path: root/internal/repositories/migration_fs_repo.go
blob: e535013c7677188a4443b789ae876e95b78409f4 (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
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
package repositories

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strings"

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

type ErrIsNotDir struct {
	path string
}

func (e *ErrIsNotDir) Error() string {
	return fmt.Sprintf(
		"The specified migrations directory path '%s' is not a directory.",
		e.path,
	)
}

type MigrationFsRepo interface {
	Create(migration *models.Migration) error
	List() (map[string]*models.Migration, error)
	ReadUpgradeScript(migration *models.Migration) (string, error)
	ReadDowngradeScript(migration *models.Migration) (string, error)
}

type migrationFsRepo struct {
	migrationsDirPath string
}

func NewMigrationFsRepo(
	migrationsConfig *configloader.MigrationsConfig,
) (MigrationFsRepo, error) {
	fileInfo, err := os.Stat(migrationsConfig.DirectoryPath)
	if errors.Is(err, fs.ErrNotExist) {
		err = os.MkdirAll(migrationsConfig.DirectoryPath, 0755)
		if err != nil {
			return nil, fmt.Errorf(
				"unable to create migration directory at %s: %w",
				migrationsConfig.DirectoryPath,
				err,
			)
		}
	} else if err != nil {
		return nil, fmt.Errorf(
			"unable to check if migration directory at %s exists: %w",
			migrationsConfig.DirectoryPath,
			err,
		)
	} else if !fileInfo.IsDir() {
		return nil, &ErrIsNotDir{path: migrationsConfig.DirectoryPath}
	}

	return &migrationFsRepo{migrationsDirPath: migrationsConfig.DirectoryPath}, nil
}

func (mr migrationFsRepo) Create(migration *models.Migration) error {
	newMigrationDir := filepath.Join(mr.migrationsDirPath, mr.migrationDirname(migration))

	err := os.Mkdir(newMigrationDir, 0755)
	if err != nil {
		return err
	}

	_, err = os.Create(filepath.Join(newMigrationDir, "upgrade.sql"))
	if err != nil {
		return err
	}

	_, err = os.Create(filepath.Join(newMigrationDir, "downgrade.sql"))
	if err != nil {
		return err
	}

	return nil
}

func (mr migrationFsRepo) List() (map[string]*models.Migration, error) {
	entries, err := os.ReadDir(mr.migrationsDirPath)
	if err != nil {
		return nil, err
	}

	var migrations = make(map[string]*models.Migration, 0)
	for _, entry := range entries {
		migration, err := dirEntryToMigration(entry)
		if err != nil {
			return nil, err
		}
		migrations[migration.Version] = migration
	}

	return migrations, nil
}

func dirEntryToMigration(entry fs.DirEntry) (*models.Migration, error) {
	parts := strings.SplitN(entry.Name(), "_", 2)
	if len(parts) != 2 {
		return nil, fmt.Errorf(
			"%s is an invalid migration name: expected a "+
				"migration directory of the format <version>_<message>",
			entry.Name(),
		)
	}
	return &models.Migration{
		Version: parts[0],
		Message: parts[1],
		Applied: false,
	}, nil
}

func (mr migrationFsRepo) ReadUpgradeScript(migration *models.Migration) (string, error) {
	upgradeScriptPath := filepath.Join(
		mr.migrationsDirPath,
		mr.migrationDirname(migration),
		"upgrade.sql",
	)
	return mr.readScriptContents(upgradeScriptPath)
}

func (mr migrationFsRepo) ReadDowngradeScript(
	migration *models.Migration,
) (string, error) {
	downgradeScriptPath := filepath.Join(
		mr.migrationsDirPath,
		mr.migrationDirname(migration),
		"downgrade.sql",
	)
	return mr.readScriptContents(downgradeScriptPath)
}

func (mr migrationFsRepo) readScriptContents(scriptPath string) (string, error) {
	contents, err := os.ReadFile(scriptPath)
	if err != nil {
		return "", err
	}

	return string(contents), nil
}

// migrationDirname creates the directory name that
// should be used for this migration.
func (mr migrationFsRepo) migrationDirname(migration *models.Migration) string {
	return fmt.Sprintf("%s_%s", migration.Version, mr.normalizeMessage(migration))
}

// normalizeMessage normalizes the Message of a migration
// to be filesystem friendly.
func (mr migrationFsRepo) normalizeMessage(migration *models.Migration) string {
	message := strings.ToLower(migration.Message)
	message = strings.TrimSpace(message)
	message = strings.ReplaceAll(message, " ", "_")
	return message
}