From e5658d1f61415054029b66cd2f703f1f40138460 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 18 Oct 2025 10:43:39 -0400 Subject: Add support for migration dependencies --- internal/services/migration_executor.go | 66 +++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 internal/services/migration_executor.go (limited to 'internal/services/migration_executor.go') 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 +} -- cgit v1.2.3