Skip to content

Commit

Permalink
Work on batch rollback in the Migrator
Browse files Browse the repository at this point in the history
  • Loading branch information
nicksagona committed Oct 20, 2023
1 parent 0b146c0 commit 17ad171
Showing 1 changed file with 55 additions and 3 deletions.
58 changes: 55 additions & 3 deletions src/Sql/Migrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,13 @@ public function rollback(mixed $steps = 1): Migrator
$stepsToRun = [];
$class = null;

foreach ($this->migrations as $timestamp => $migration) {
if (strtotime($timestamp) <= strtotime((int)$this->current)) {
$stepsToRun[] = $timestamp;
if (is_string($steps) && str_starts_with($steps, 'batch-')) {
$stepsToRun = $this->getByBatch($steps);
} else {
foreach ($this->migrations as $timestamp => $migration) {
if (strtotime($timestamp) <= strtotime((int)$this->current)) {
$stepsToRun[] = $timestamp;
}
}
}

Expand Down Expand Up @@ -364,6 +368,54 @@ public function getNextBatch(): int
return $batch;
}

/**
* Get current batch
*
* @return int
*/
public function getCurrentBatch(): int
{
$batch = 0;

if (($this->isTable()) && ($this->hasTable())) {
$class = $this->getTable();
if (!empty($class)) {
$current = $class::findOne(null, ['order' => 'batch DESC']);
if (!empty($current->batch)) {
$batch = (int)$current->batch;
}
}
}

return $batch;
}

/**
* Get migrations by batch
*
* @param string|int $batch
* @return array
*/
public function getByBatch(string|int $batch): array
{
if (is_string($batch) && str_starts_with($batch, 'batch-')) {
$batch = substr($batch, 6);
}

$batchMigrations = [];

if (($this->isTable()) && ($this->hasTable()) && ($batch == $this->getCurrentBatch())) {
$class = $this->getTable();
if (!empty($class)) {
$batchMigrations = array_values(
$class::findBy(['batch' => $batch], ['order' => 'migration_id DESC'])->toArray('migration_id')
);
}
}

return $batchMigrations;
}

/**
* Load the current migration timestamp
*
Expand Down

0 comments on commit 17ad171

Please sign in to comment.