From ee10268784de7b6f3add1160a81d4df2904cd1e4 Mon Sep 17 00:00:00 2001 From: Philipp Dieter Date: Thu, 20 Oct 2022 12:41:29 +0200 Subject: [PATCH] [TASK] Add testAndCreateIndex function to DatabaseUtility --- Classes/Utility/DatabaseUtility.php | 45 +++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/Classes/Utility/DatabaseUtility.php b/Classes/Utility/DatabaseUtility.php index 1084e85..01b5060 100644 --- a/Classes/Utility/DatabaseUtility.php +++ b/Classes/Utility/DatabaseUtility.php @@ -66,4 +66,49 @@ class DatabaseUtility return GeneralUtility::makeInstance(ConnectionPool::class) ->getConnectionForTable($tableName); } + + /** + * testAndCreateIndex + */ + public static function testAndCreateIndex( + $table, $indexName, $indexColumns, $type + ) { + $connection = GeneralUtility::makeInstance( + ConnectionPool::class + )->getConnectionForTable($table); + $existTestQuery = " + SHOW TABLES LIKE '${table}' + "; + $existTestResult = $connection + ->executeQuery($existTestQuery) + ->fetchAll(); + if (!count($existTestResult)) { + return; + } + $indexTestQuery = " + SHOW INDEX FROM ${table} + WHERE Key_name = '${indexName}' + "; + $indexTestResult = $connection + ->executeQuery($indexTestQuery) + ->fetchAll(); + if (count($indexTestResult)) { + return; + } + switch ($type) { + case 'btree': + $queryCreate = " + CREATE INDEX ${indexName} + USING BTREE ON ${table} (${indexColumns}) + "; + break; + case 'fulltext': + $queryCreate = " + CREATE FULLTEXT INDEX ${indexName} + ON ${table} (${indexColumns}) + "; + break; + } + $connection->executeQuery($queryCreate); + } }