From bb0b7d2850df380ad8c2b480be8e70ad4c41ad7e Mon Sep 17 00:00:00 2001
From: Bart Jaskulski <bjaskulski@protonmail.com>
Date: Fri, 8 Nov 2024 15:49:20 +0100
Subject: [PATCH] feat: add support for conditional execution of migrations

Signed-off-by: Bart Jaskulski <bjaskulski@protonmail.com>
---
 src/AbstractMigration.php | 9 ++++++++-
 src/WpdbMigrator.php      | 7 ++++++-
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git a/src/AbstractMigration.php b/src/AbstractMigration.php
index 7a82702..a83514d 100644
--- a/src/AbstractMigration.php
+++ b/src/AbstractMigration.php
@@ -20,5 +20,12 @@ abstract class AbstractMigration {
 
 	abstract public function up(): bool;
 
-	public function down(): void {}
+	/**
+	 * Allow to skip migration if it is not needed. Tracking of migration version just by wp_options
+	 * value may be subject to random issues, so as a backup, this method can be used to avoid
+	 * errornous migrations like creating alredy exising columns.
+	 */
+	public function is_needed(): bool {
+		return true;
+	}
 }
diff --git a/src/WpdbMigrator.php b/src/WpdbMigrator.php
index d35821f..bf896e1 100644
--- a/src/WpdbMigrator.php
+++ b/src/WpdbMigrator.php
@@ -133,7 +133,12 @@ class WpdbMigrator implements Migrator {
 
 				$this->logger->info( sprintf( 'DB update %s:%s', $current_version, $migration->get_version() ) );
 
-				$success = $migration->get_migration()->up();
+				$success = null;
+				if ( $migration->get_migration()->is_needed() ) {
+					$success = $migration->get_migration()->up();
+				} else {
+					$success = true;
+				}
 
 				if ( $success ) {
 					$this->logger->info( sprintf( 'DB update %s:%s -> ', $current_version, $migration->get_version() ) . 'OK' );
-- 
GitLab