From 17ad1712a50b47c58a94bc5ef014ab646f66a467 Mon Sep 17 00:00:00 2001 From: Nick Sagona Date: Fri, 20 Oct 2023 08:50:47 -0500 Subject: [PATCH] Work on batch rollback in the Migrator --- src/Sql/Migrator.php | 58 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 3 deletions(-) diff --git a/src/Sql/Migrator.php b/src/Sql/Migrator.php index 5b5f9c7..e783cc9 100644 --- a/src/Sql/Migrator.php +++ b/src/Sql/Migrator.php @@ -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; + } } } @@ -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 *