Skip to content

Commit f490e54

Browse files
committed
fix: simplify migrateDownByVersion and improve migrateTo rollback
- Remove redundant history check from migrateDownByVersion (already checked in migrateTo) - Improve migrateTo to check history once before rollback loop - Update appliedVersions array after each rollback to avoid duplicate attempts - This ensures all migrations are rolled back correctly in order
1 parent c0e04ca commit f490e54

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

src/migrations/MigrationRunner.php

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -234,13 +234,6 @@ public function migrateDown(int $step = 1): array
234234
*/
235235
protected function migrateDownByVersion(string $version): void
236236
{
237-
$history = $this->getMigrationHistory();
238-
$appliedVersions = array_column($history, 'version');
239-
240-
if (!in_array($version, $appliedVersions, true)) {
241-
return; // Not applied, nothing to rollback
242-
}
243-
244237
try {
245238
$this->db->startTransaction();
246239
$migration = $this->loadMigration($version);
@@ -298,10 +291,19 @@ public function migrateTo(string $version): void
298291
// Rollback migrations in reverse order (newest first)
299292
// We need to rollback from currentIndex down to targetIndex+1
300293
$migrationsToRollback = array_slice($allMigrations, $targetIndex + 1, $currentIndex - $targetIndex);
301-
294+
295+
// Get current history once before rollback loop
296+
$history = $this->getMigrationHistory();
297+
$appliedVersions = array_column($history, 'version');
298+
302299
// Rollback each migration that needs to be rolled back, in reverse order
303300
foreach (array_reverse($migrationsToRollback) as $migrationVersion) {
304-
$this->migrateDownByVersion($migrationVersion);
301+
// Only rollback if migration is actually applied
302+
if (in_array($migrationVersion, $appliedVersions, true)) {
303+
$this->migrateDownByVersion($migrationVersion);
304+
// Remove from appliedVersions to avoid duplicate rollback attempts
305+
$appliedVersions = array_values(array_diff($appliedVersions, [$migrationVersion]));
306+
}
305307
}
306308
} else {
307309
// Apply

0 commit comments

Comments
 (0)