From e38fd951d1ea2ee0cb2221d225bb0259e89df01b Mon Sep 17 00:00:00 2001 From: alex-mailpoet Date: Tue, 30 May 2023 20:14:43 +0300 Subject: [PATCH] Check indexes exist when adding them [MAILPOET-5364] --- .../Migrations/Migration_20230503_210945.php | 17 ++++++++++++----- mailpoet/lib/Migrator/Migration.php | 12 ++++++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/mailpoet/lib/Migrations/Migration_20230503_210945.php b/mailpoet/lib/Migrations/Migration_20230503_210945.php index d8a004a2e2..4d02e3c1ed 100644 --- a/mailpoet/lib/Migrations/Migration_20230503_210945.php +++ b/mailpoet/lib/Migrations/Migration_20230503_210945.php @@ -8,10 +8,17 @@ use MailPoet\Migrator\Migration; class Migration_20230503_210945 extends Migration { public function run(): void { $subscribersTable = $this->getTableName(SubscriberEntity::class); - $this->connection->executeQuery( - "ALTER TABLE `{$subscribersTable}` - ADD INDEX `first_name` (`first_name`(10)), - ADD INDEX `last_name` (`last_name`(10))" - ); + if (!$this->indexExists($subscribersTable, 'first_name')) { + $this->connection->executeQuery( + "ALTER TABLE `{$subscribersTable}` + ADD INDEX `first_name` (`first_name`(10))" + ); + } + if (!$this->indexExists($subscribersTable, 'last_name')) { + $this->connection->executeQuery( + "ALTER TABLE `{$subscribersTable}` + ADD INDEX `last_name` (`last_name`(10))" + ); + } } } diff --git a/mailpoet/lib/Migrator/Migration.php b/mailpoet/lib/Migrator/Migration.php index efa5ff4ec8..0b8defb94f 100644 --- a/mailpoet/lib/Migrator/Migration.php +++ b/mailpoet/lib/Migrator/Migration.php @@ -53,4 +53,16 @@ abstract class Migration { AND column_name = ? ", [Env::$dbName, $tableName, $columnName])->fetchOne() !== false; } + + protected function indexExists(string $tableName, string $indexName): bool { + // We had a problem with the dbName value in ENV for some customers, because it doesn't match DB name in information schema. + // So we decided to use the DATABASE() value instead. + return $this->connection->executeQuery(" + SELECT 1 + FROM information_schema.statistics + WHERE table_schema = COALESCE(DATABASE(), ?) + AND table_name = ? + AND index_name = ? + ", [Env::$dbName, $tableName, $indexName])->fetchOne() !== false; + } }