aboutsummaryrefslogtreecommitdiffstats
path: root/internal/services/migration_executor.go
diff options
context:
space:
mode:
authorEugene Triguba <hello@eugenetriguba.com>2025-10-18 10:43:39 -0400
committerEugene Triguba <hello@eugenetriguba.com>2025-11-26 11:46:57 -0500
commite5658d1f61415054029b66cd2f703f1f40138460 (patch)
treec609e209f4cebc62dd985d1b773558f47eb73bf6 /internal/services/migration_executor.go
parentAdd is-branch main check for docs deployment (diff)
downloadcli-e5658d1f61415054029b66cd2f703f1f40138460.zip
Add support for migration dependencies
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
+}