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
|
package services
import (
"fmt"
"git.sr.ht/~eugenetriguba/bolt/internal/models"
"git.sr.ht/~eugenetriguba/bolt/internal/repositories"
)
// MigrationExecutor handles the core execution logic for applying and reverting migrations.
type MigrationExecutor struct {
dbRepo repositories.MigrationDBRepo
fsRepo repositories.MigrationFsRepo
}
func NewMigrationExecutor(
dbRepo repositories.MigrationDBRepo,
fsRepo repositories.MigrationFsRepo,
) *MigrationExecutor {
return &MigrationExecutor{
dbRepo: dbRepo,
fsRepo: fsRepo,
}
}
// Apply applies a migration by reading the upgrade script and executing it.
// It automatically handles transaction wrapping based on the script options.
func (e *MigrationExecutor) Apply(migration *models.Migration) error {
upgradeScript, err := e.fsRepo.ReadUpgradeScript(migration)
if err != nil {
return fmt.Errorf("unable to read upgrade script: %w", err)
}
if upgradeScript.Options.UseTransaction {
err = e.dbRepo.ApplyWithTx(upgradeScript.Contents, migration)
} else {
err = e.dbRepo.Apply(upgradeScript.Contents, migration)
}
if err != nil {
return fmt.Errorf("unable to apply migration %s: %w", migration.Name(), err)
}
return nil
}
// Revert reverts a migration by reading the downgrade script and executing it.
// It automatically handles transaction wrapping based on the script options.
func (e *MigrationExecutor) Revert(migration *models.Migration) error {
downgradeScript, err := e.fsRepo.ReadDowngradeScript(migration)
if err != nil {
return fmt.Errorf("unable to read downgrade script: %w", err)
}
if downgradeScript.Options.UseTransaction {
err = e.dbRepo.RevertWithTx(downgradeScript.Contents, migration)
} else {
err = e.dbRepo.Revert(downgradeScript.Contents, migration)
}
if err != nil {
return err
}
return nil
}
|