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 }