Completed
Push — master ( d197f6...1397b8 )
by Morris
32:43 queued 21:43
created

Collation::run()   D

Complexity

Conditions 10
Paths 47

Size

Total Lines 43
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 28
nc 47
nop 1
dl 0
loc 43
rs 4.8196
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Morris Jobke <[email protected]>
6
 * @author Robin Appelman <[email protected]>
7
 * @author Thomas Müller <[email protected]>
8
 *
9
 * @license AGPL-3.0
10
 *
11
 * This code is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU Affero General Public License, version 3,
13
 * as published by the Free Software Foundation.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18
 * GNU Affero General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Affero General Public License, version 3,
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
22
 *
23
 */
24
25
namespace OC\Repair;
26
27
use Doctrine\DBAL\Exception\DriverException;
28
use Doctrine\DBAL\Platforms\MySqlPlatform;
29
use OCP\IConfig;
30
use OCP\IDBConnection;
31
use OCP\ILogger;
32
use OCP\Migration\IOutput;
33
use OCP\Migration\IRepairStep;
34
35
class Collation implements IRepairStep {
36
	/**  @var IConfig */
37
	protected $config;
38
39
	/** @var ILogger */
40
	protected $logger;
41
42
	/** @var IDBConnection */
43
	protected $connection;
44
45
	/** @var bool */
46
	protected $ignoreFailures;
47
48
	/**
49
	 * @param IConfig $config
50
	 * @param ILogger $logger
51
	 * @param IDBConnection $connection
52
	 * @param bool $ignoreFailures
53
	 */
54
	public function __construct(IConfig $config, ILogger $logger, IDBConnection $connection, $ignoreFailures) {
55
		$this->connection = $connection;
56
		$this->config = $config;
57
		$this->logger = $logger;
58
		$this->ignoreFailures = $ignoreFailures;
59
	}
60
61
	public function getName() {
62
		return 'Repair MySQL collation';
63
	}
64
65
	/**
66
	 * Fix mime types
67
	 */
68
	public function run(IOutput $output) {
69
		if (!$this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
0 ignored issues
show
Bug introduced by
The class Doctrine\DBAL\Platforms\MySqlPlatform does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
70
			$output->info('Not a mysql database -> nothing to do');
71
			return;
72
		}
73
74
		$characterSet = $this->config->getSystemValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
75
76
		$tables = $this->getAllNonUTF8BinTables($this->connection);
77
		foreach ($tables as $table) {
78
			$output->info("Change row format for $table ...");
79
			$query = $this->connection->prepare('ALTER TABLE `' . $table . '` ROW_FORMAT = DYNAMIC;');
80
			try {
81
				$query->execute();
82
			} catch (DriverException $e) {
0 ignored issues
show
Bug introduced by
The class Doctrine\DBAL\Exception\DriverException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
83
				// Just log this
84
				$this->logger->logException($e);
85
				if (!$this->ignoreFailures) {
86
					throw $e;
87
				}
88
			}
89
90
			$output->info("Change collation for $table ...");
91
			if ($characterSet === 'utf8mb4') {
92
				// need to set row compression first
93
				$query = $this->connection->prepare('ALTER TABLE `' . $table . '` ROW_FORMAT=COMPRESSED;');
94
				$query->execute();
95
			}
96
			$query = $this->connection->prepare('ALTER TABLE `' . $table . '` CONVERT TO CHARACTER SET ' . $characterSet . ' COLLATE ' . $characterSet . '_bin;');
97
			try {
98
				$query->execute();
99
			} catch (DriverException $e) {
0 ignored issues
show
Bug introduced by
The class Doctrine\DBAL\Exception\DriverException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
100
				// Just log this
101
				$this->logger->logException($e);
102
				if (!$this->ignoreFailures) {
103
					throw $e;
104
				}
105
			}
106
		}
107
		if (empty($tables)) {
108
			$output->info('All tables already have the correct collation -> nothing to do');
109
		}
110
	}
111
112
	/**
113
	 * @param IDBConnection $connection
114
	 * @return string[]
115
	 */
116
	protected function getAllNonUTF8BinTables(IDBConnection $connection) {
117
		$dbName = $this->config->getSystemValue("dbname");
118
		$characterSet = $this->config->getSystemValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
119
120
		// fetch tables by columns
121
		$statement = $connection->executeQuery(
122
			"SELECT DISTINCT(TABLE_NAME) AS `table`" .
123
			"	FROM INFORMATION_SCHEMA . COLUMNS" .
124
			"	WHERE TABLE_SCHEMA = ?" .
125
			"	AND (COLLATION_NAME <> '" . $characterSet . "_bin' OR CHARACTER_SET_NAME <> '" . $characterSet . "')" .
126
			"	AND TABLE_NAME LIKE \"*PREFIX*%\"",
127
			array($dbName)
128
		);
129
		$rows = $statement->fetchAll();
130
		$result = [];
131
		foreach ($rows as $row) {
132
			$result[$row['table']] = true;
133
		}
134
135
		// fetch tables by collation
136
		$statement = $connection->executeQuery(
137
			"SELECT DISTINCT(TABLE_NAME) AS `table`" .
138
			"	FROM INFORMATION_SCHEMA . TABLES" .
139
			"	WHERE TABLE_SCHEMA = ?" .
140
			"	AND TABLE_COLLATION <> '" . $characterSet . "_bin'" .
141
			"	AND TABLE_NAME LIKE \"*PREFIX*%\"",
142
			[$dbName]
143
		);
144
		$rows = $statement->fetchAll();
145
		foreach ($rows as $row) {
146
			$result[$row['table']] = true;
147
		}
148
149
		return array_keys($result);
150
	}
151
}
152
153