aboutsummaryrefslogtreecommitdiffstats
path: root/internal/services/migration_executor.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/services/migration_executor.go')
-rw-r--r--internal/services/migration_executor.go66
1 files changed, 66 insertions, 0 deletions
diff --git a/internal/services/migration_executor.go b/internal/services/migration_executor.go
new file mode 100644
index 0000000..e9f827e
--- /dev/null
+++ b/internal/services/migration_executor.go
@@ -0,0 +1,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
+}