From dc62342b6dd914cb1448b3ed1bdcd1e405161f20 Mon Sep 17 00:00:00 2001 From: Matthias Schmidt Date: Tue, 6 Aug 2019 19:53:38 +0200 Subject: [PATCH] Add DatabaseEditor::(getForeignKeys|getIndexInformation)() --- .../database/editor/DatabaseEditor.class.php | 24 ++++- .../editor/MySQLDatabaseEditor.class.php | 88 +++++++++++++++++++ 2 files changed, 110 insertions(+), 2 deletions(-) diff --git a/wcfsetup/install/files/lib/system/database/editor/DatabaseEditor.class.php b/wcfsetup/install/files/lib/system/database/editor/DatabaseEditor.class.php index 3592bd0e97..15eaf875c7 100644 --- a/wcfsetup/install/files/lib/system/database/editor/DatabaseEditor.class.php +++ b/wcfsetup/install/files/lib/system/database/editor/DatabaseEditor.class.php @@ -1,6 +1,7 @@ dbObj->prepareStatement($sql); + $statement->execute([ + $this->dbObj->getDatabaseName(), + $tableName + ]); + $keyInformation = $statement->fetchAll(\PDO::FETCH_ASSOC); + + $validActions = ['CASCADE', 'SET NULL', 'NO ACTION']; + + $foreignKeys = []; + foreach ($keyInformation as $information) { + if (!isset($foreignKeys[$information['CONSTRAINT_NAME']])) { + $foreignKeys[$information['CONSTRAINT_NAME']] = [ + 'columns' => [$information['COLUMN_NAME']], + 'referencedColumns' => [$information['REFERENCED_COLUMN_NAME']], + 'referencedTable' => $information['REFERENCED_TABLE_NAME'], + 'ON DELETE' => in_array($information['DELETE_RULE'], $validActions) ? $information['DELETE_RULE'] : null, + 'ON UPDATE' => in_array($information['UPDATE_RULE'], $validActions) ? $information['UPDATE_RULE'] : null + ]; + } + else { + $foreignKeys[$information['CONSTRAINT_NAME']]['columns'][] = $information['COLUMN_NAME']; + $foreignKeys[$information['CONSTRAINT_NAME']]['referencedColumns'][] = $information['REFERENCED_COLUMN_NAME']; + } + } + + foreach ($foreignKeys as $keyName => $keyData) { + $foreignKeys[$keyName]['columns'] = array_unique($foreignKeys[$keyName]['columns']); + $foreignKeys[$keyName]['referencedColumns'] = array_unique($foreignKeys[$keyName]['referencedColumns']); + } + + return $foreignKeys; + } + + /** + * @inheritDoc + */ + public function getIndexInformation($tableName) { + $sql = "SHOW INDEX + FROM `".$tableName."`"; + $statement = $this->dbObj->prepareStatement($sql); + $statement->execute(); + $indices = $statement->fetchAll(\PDO::FETCH_ASSOC); + + $indexInformation = []; + foreach ($indices as $index) { + if (!isset($indexInformation[$index['Key_name']])) { + $type = null; + if ($index['Index_type'] === 'FULLTEXT') { + $type = 'FULLTEXT'; + } + else if ($index['Key_name'] === 'PRIMARY') { + $type = 'PRIMARY'; + } + else if ($index['Non_unique'] == 0) { + $type = 'UNIQUE'; + } + + $indexInformation[$index['Key_name']] = [ + 'columns' => [$index['Column_name']], + 'type' => $type + ]; + } + else { + $indexInformation[$index['Key_name']]['columns'][] = $index['Column_name']; + } + } + + return $indexInformation; + } + /** * @inheritDoc */ -- 2.20.1