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
|
package repositories
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"git.sr.ht/~eugenetriguba/bolt/internal/configloader"
"git.sr.ht/~eugenetriguba/bolt/internal/models"
"git.sr.ht/~eugenetriguba/bolt/internal/sqlparse"
)
var ErrMigrationVersionConflict = errors.New("migration version conflict")
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) (sqlparse.MigrationScript, error)
ReadDowngradeScript(migration *models.Migration) (sqlparse.MigrationScript, 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 {
newMigrationPath := filepath.Join(mr.migrationsDirPath, migration.Name()+".sql")
file, err := os.Create(newMigrationPath)
if err != nil {
return fmt.Errorf("unable to create file at %s: %w", newMigrationPath, err)
}
defer file.Close()
var template strings.Builder
if len(migration.Dependencies) > 0 {
template.WriteString("-- depends: ")
template.WriteString(strings.Join(migration.Dependencies, ", "))
template.WriteString("\n")
}
template.WriteString("-- migrate:up\n\n-- migrate:down\n")
_, err = file.WriteString(template.String())
if err != nil {
return fmt.Errorf("unable to write template to new migration script: %w", 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 := mr.dirEntryToMigration(entry)
if err != nil {
return nil, err
}
_, exists := migrations[migration.Version]
if exists {
return nil, fmt.Errorf(
"%w: a local migration file with version %s already exists",
ErrMigrationVersionConflict,
migration.Version,
)
}
migrations[migration.Version] = migration
}
return migrations, nil
}
func (mr migrationFsRepo) 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(),
)
}
version := parts[0]
message := strings.TrimSuffix(parts[1], filepath.Ext(parts[1])) // Remove .sql
migration := &models.Migration{
Version: version,
Message: message,
Applied: false,
}
scriptPath := filepath.Join(mr.migrationsDirPath, entry.Name())
dependencies, err := mr.parseDependenciesFromFile(scriptPath)
if err != nil {
return nil, fmt.Errorf("unable to parse dependencies from %s: %w", entry.Name(), err)
}
migration.Dependencies = dependencies
return migration, nil
}
func (mr migrationFsRepo) parseDependenciesFromFile(scriptPath string) ([]string, error) {
scriptContents, err := mr.readScriptContents(scriptPath)
if err != nil {
return nil, err
}
sqlParser := sqlparse.NewSqlParser()
migration, err := sqlParser.Parse(strings.NewReader(scriptContents))
if err != nil {
return nil, err
}
return migration.Dependencies, nil
}
func (mr migrationFsRepo) ReadUpgradeScript(
migration *models.Migration,
) (sqlparse.MigrationScript, error) {
scriptPath := filepath.Join(
mr.migrationsDirPath,
migration.Name()+".sql",
)
upgradeScript, _, err := mr.getMigrationScripts(scriptPath)
return upgradeScript, err
}
func (mr migrationFsRepo) ReadDowngradeScript(
migration *models.Migration,
) (sqlparse.MigrationScript, error) {
scriptPath := filepath.Join(
mr.migrationsDirPath,
migration.Name()+".sql",
)
_, downgradeScript, err := mr.getMigrationScripts(scriptPath)
return downgradeScript, err
}
func (mr migrationFsRepo) getMigrationScripts(
scriptPath string,
) (sqlparse.MigrationScript, sqlparse.MigrationScript, error) {
scriptContents, err := mr.readScriptContents(scriptPath)
if err != nil {
return sqlparse.MigrationScript{}, sqlparse.MigrationScript{}, fmt.Errorf(
"unable to read %s script: %w",
scriptPath,
err,
)
}
sqlParser := sqlparse.NewSqlParser()
migration, err := sqlParser.Parse(strings.NewReader(scriptContents))
return migration.UpgradeScript, migration.DowngradeScript, err
}
func (mr migrationFsRepo) readScriptContents(scriptPath string) (string, error) {
contents, err := os.ReadFile(scriptPath)
if err != nil {
return "", err
}
return string(contents), nil
}
|