Passed
Pull Request — master (#3645)
by Matthew
14:01
created

MySqlSchemaManager   F

Complexity

Total Complexity 65

Size/Duplication

Total Lines 326
Duplicated Lines 0 %

Test Coverage

Coverage 95.65%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 65
eloc 173
c 1
b 0
f 0
dl 0
loc 326
ccs 154
cts 161
cp 0.9565
rs 3.2

10 Methods

Rating   Name   Duplication   Size   Complexity  
A _getPortableTableDefinition() 0 3 1
A _getPortableDatabaseDefinition() 0 3 1
B _getPortableTableForeignKeysList() 0 41 8
A _getPortableViewDefinition() 0 3 1
A _getPortableTableIndexesList() 0 20 6
A _getPortableUserDefinition() 0 5 1
A listTableDetails() 0 28 4
A parseCreateOptions() 0 15 4
F _getPortableTableColumnDefinition() 0 107 32
B getMariaDb1027ColumnDefault() 0 20 7

How to fix   Complexity   

Complex Class

Complex classes like MySqlSchemaManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use MySqlSchemaManager, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Doctrine\DBAL\Schema;
4
5
use Doctrine\DBAL\Platforms\MariaDb1027Platform;
6
use Doctrine\DBAL\Platforms\MySqlPlatform;
7
use Doctrine\DBAL\Types\Type;
8
use const CASE_LOWER;
9
use function array_change_key_case;
10
use function array_shift;
11
use function array_values;
12
use function assert;
13
use function explode;
14
use function is_string;
15
use function preg_match;
16
use function strpos;
17
use function strtok;
18
use function strtolower;
19
use function strtr;
20
21
/**
22
 * Schema manager for the MySql RDBMS.
23
 */
24
class MySqlSchemaManager extends AbstractSchemaManager
25
{
26
    /**
27
     * @see https://mariadb.com/kb/en/library/string-literals/#escape-sequences
28
     */
29
    private const MARIADB_ESCAPE_SEQUENCES = [
30
        '\\0' => "\0",
31
        "\\'" => "'",
32
        '\\"' => '"',
33
        '\\b' => "\b",
34
        '\\n' => "\n",
35
        '\\r' => "\r",
36
        '\\t' => "\t",
37
        '\\Z' => "\x1a",
38
        '\\\\' => '\\',
39
        '\\%' => '%',
40
        '\\_' => '_',
41
42
        // Internally, MariaDB escapes single quotes using the standard syntax
43
        "''" => "'",
44
    ];
45
46
    /**
47
     * {@inheritdoc}
48
     */
49 504
    protected function _getPortableViewDefinition($view)
50
    {
51 504
        return new View($view['TABLE_NAME'], $view['VIEW_DEFINITION']);
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 1388
    protected function _getPortableTableDefinition($table)
58
    {
59 1388
        return array_shift($table);
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    protected function _getPortableUserDefinition($user)
66
    {
67
        return [
68
            'user' => $user['User'],
69
            'password' => $user['Password'],
70
        ];
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76 1283
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
77
    {
78 1283
        foreach ($tableIndexes as $k => $v) {
79 1283
            $v = array_change_key_case($v, CASE_LOWER);
80 1283
            if ($v['key_name'] === 'PRIMARY') {
81 1283
                $v['primary'] = true;
82
            } else {
83 1283
                $v['primary'] = false;
84
            }
85 1283
            if (strpos($v['index_type'], 'FULLTEXT') !== false) {
86 1014
                $v['flags'] = ['FULLTEXT'];
87 1283
            } elseif (strpos($v['index_type'], 'SPATIAL') !== false) {
88 999
                $v['flags'] = ['SPATIAL'];
89
            }
90 1283
            $v['length'] = isset($v['sub_part']) ? (int) $v['sub_part'] : null;
91
92 1283
            $tableIndexes[$k] = $v;
93
        }
94
95 1283
        return parent::_getPortableTableIndexesList($tableIndexes, $tableName);
96
    }
97
98
    /**
99
     * {@inheritdoc}
100
     */
101 714
    protected function _getPortableDatabaseDefinition($database)
102
    {
103 714
        return $database['Database'];
104
    }
105
106
    /**
107
     * {@inheritdoc}
108
     */
109 1283
    protected function _getPortableTableColumnDefinition($tableColumn)
110
    {
111 1283
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
112
113 1283
        $dbType = strtolower($tableColumn['type']);
114 1283
        $dbType = strtok($dbType, '(), ');
115 1283
        assert(is_string($dbType));
116
117 1283
        $length = $tableColumn['length'] ?? strtok('(), ');
118
119 1283
        $fixed = null;
120
121 1283
        if (! isset($tableColumn['name'])) {
122 1283
            $tableColumn['name'] = '';
123
        }
124
125 1283
        $scale     = null;
126 1283
        $precision = null;
127
128 1283
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
129
130
        // In cases where not connected to a database DESCRIBE $table does not return 'Comment'
131 1283
        if (isset($tableColumn['comment'])) {
132 1283
            $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
133 1283
            $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
134
        }
135
136
        switch ($dbType) {
137 1283
            case 'char':
138 1283
            case 'binary':
139 853
                $fixed = true;
140 853
                break;
141 1283
            case 'float':
142 1283
            case 'double':
143 1283
            case 'real':
144 1283
            case 'numeric':
145 1283
            case 'decimal':
146 838
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['type'], $match)) {
147 838
                    $precision = $match[1];
148 838
                    $scale     = $match[2];
149 838
                    $length    = null;
150
                }
151 838
                break;
152 1283
            case 'tinytext':
153 868
                $length = MySqlPlatform::LENGTH_LIMIT_TINYTEXT;
154 868
                break;
155 1283
            case 'text':
156 868
                $length = MySqlPlatform::LENGTH_LIMIT_TEXT;
157 868
                break;
158 1283
            case 'mediumtext':
159 868
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMTEXT;
160 868
                break;
161 1283
            case 'tinyblob':
162
                $length = MySqlPlatform::LENGTH_LIMIT_TINYBLOB;
163
                break;
164 1283
            case 'blob':
165 868
                $length = MySqlPlatform::LENGTH_LIMIT_BLOB;
166 868
                break;
167 1283
            case 'mediumblob':
168 868
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMBLOB;
169 868
                break;
170 1283
            case 'tinyint':
171 1283
            case 'smallint':
172 1283
            case 'mediumint':
173 1283
            case 'int':
174 1283
            case 'integer':
175 1283
            case 'bigint':
176 1283
            case 'year':
177 1283
                $length = null;
178 1283
                break;
179
        }
180
181 1283
        if ($this->_platform instanceof MariaDb1027Platform) {
182 338
            $columnDefault = $this->getMariaDb1027ColumnDefault($this->_platform, $tableColumn['default']);
183
        } else {
184 945
            $columnDefault = $tableColumn['default'];
185
        }
186
187
        $options = [
188 1283
            'length'        => $length !== null ? (int) $length : null,
189 1283
            'unsigned'      => strpos($tableColumn['type'], 'unsigned') !== false,
190 1283
            'fixed'         => (bool) $fixed,
191 1283
            'default'       => $columnDefault,
192 1283
            'notnull'       => $tableColumn['null'] !== 'YES',
193
            'scale'         => null,
194
            'precision'     => null,
195 1283
            'autoincrement' => strpos($tableColumn['extra'], 'auto_increment') !== false,
196 1283
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
197 429
                ? $tableColumn['comment']
198
                : null,
199
        ];
200
201 1283
        if ($scale !== null && $precision !== null) {
202 838
            $options['scale']     = (int) $scale;
203 838
            $options['precision'] = (int) $precision;
204
        }
205
206 1283
        $column = new Column($tableColumn['field'], Type::getType($type), $options);
207
208 1283
        if (isset($tableColumn['characterset'])) {
209 1283
            $column->setPlatformOption('charset', $tableColumn['characterset']);
210
        }
211 1283
        if (isset($tableColumn['collation'])) {
212 1283
            $column->setPlatformOption('collation', $tableColumn['collation']);
213
        }
214
215 1283
        return $column;
216
    }
217
218
    /**
219
     * Return Doctrine/Mysql-compatible column default values for MariaDB 10.2.7+ servers.
220
     *
221
     * - Since MariaDb 10.2.7 column defaults stored in information_schema are now quoted
222
     *   to distinguish them from expressions (see MDEV-10134).
223
     * - CURRENT_TIMESTAMP, CURRENT_TIME, CURRENT_DATE are stored in information_schema
224
     *   as current_timestamp(), currdate(), currtime()
225
     * - Quoted 'NULL' is not enforced by Maria, it is technically possible to have
226
     *   null in some circumstances (see https://jira.mariadb.org/browse/MDEV-14053)
227
     * - \' is always stored as '' in information_schema (normalized)
228
     *
229
     * @link https://mariadb.com/kb/en/library/information-schema-columns-table/
230
     * @link https://jira.mariadb.org/browse/MDEV-13132
231
     *
232
     * @param string|null $columnDefault default value as stored in information_schema for MariaDB >= 10.2.7
233
     */
234 338
    private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?string $columnDefault) : ?string
235
    {
236 338
        if ($columnDefault === 'NULL' || $columnDefault === null) {
237 338
            return null;
238
        }
239
240 338
        if (preg_match('/^\'(.*)\'$/', $columnDefault, $matches)) {
241 326
            return strtr($matches[1], self::MARIADB_ESCAPE_SEQUENCES);
242
        }
243
244
        switch ($columnDefault) {
245 338
            case 'current_timestamp()':
246 338
                return $platform->getCurrentTimestampSQL();
247 334
            case 'curdate()':
248 206
                return $platform->getCurrentDateSQL();
249 334
            case 'curtime()':
250 206
                return $platform->getCurrentTimeSQL();
251
        }
252
253 334
        return $columnDefault;
254
    }
255
256
    /**
257
     * {@inheritdoc}
258
     */
259 1297
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
260
    {
261 1297
        $list = [];
262 1297
        foreach ($tableForeignKeys as $value) {
263 578
            $value = array_change_key_case($value, CASE_LOWER);
264 578
            if (! isset($list[$value['constraint_name']])) {
265 578
                if (! isset($value['delete_rule']) || $value['delete_rule'] === 'RESTRICT') {
266 461
                    $value['delete_rule'] = null;
267
                }
268 578
                if (! isset($value['update_rule']) || $value['update_rule'] === 'RESTRICT') {
269 461
                    $value['update_rule'] = null;
270
                }
271
272 578
                $list[$value['constraint_name']] = [
273 578
                    'name' => $value['constraint_name'],
274
                    'local' => [],
275
                    'foreign' => [],
276 578
                    'foreignTable' => $value['referenced_table_name'],
277 578
                    'onDelete' => $value['delete_rule'],
278 578
                    'onUpdate' => $value['update_rule'],
279
                ];
280
            }
281 578
            $list[$value['constraint_name']]['local'][]   = $value['column_name'];
282 578
            $list[$value['constraint_name']]['foreign'][] = $value['referenced_column_name'];
283
        }
284
285 1297
        $result = [];
286 1297
        foreach ($list as $constraint) {
287 578
            $result[] = new ForeignKeyConstraint(
288 578
                array_values($constraint['local']),
289 578
                $constraint['foreignTable'],
290 578
                array_values($constraint['foreign']),
291 578
                $constraint['name'],
292
                [
293 578
                    'onDelete' => $constraint['onDelete'],
294 578
                    'onUpdate' => $constraint['onUpdate'],
295
                ]
296
            );
297
        }
298
299 1297
        return $result;
300
    }
301
302 1283
    public function listTableDetails($tableName)
303
    {
304 1283
        $table = parent::listTableDetails($tableName);
305
306
        /** @var MySqlPlatform $platform */
307 1283
        $platform = $this->_platform;
308 1283
        $sql      = $platform->getListTableMetadataSQL($tableName);
309
310 1283
        $tableOptions = $this->_conn->fetchAssoc($sql);
311
312 1283
        if ($tableOptions === false) {
313 729
            return $table;
314
        }
315
316 1283
        $table->addOption('engine', $tableOptions['ENGINE']);
317
318 1283
        if ($tableOptions['TABLE_COLLATION'] !== null) {
319 1283
            $table->addOption('collation', $tableOptions['TABLE_COLLATION']);
320
        }
321
322 1283
        if ($tableOptions['AUTO_INCREMENT'] !== null) {
323 1283
            $table->addOption('autoincrement', $tableOptions['AUTO_INCREMENT']);
324
        }
325
326 1283
        $table->addOption('comment', $tableOptions['TABLE_COMMENT']);
327 1283
        $table->addOption('create_options', $this->parseCreateOptions($tableOptions['CREATE_OPTIONS']));
328
329 1283
        return $table;
330
    }
331
332
    /**
333
     * @return string[]|true[]
334
     */
335 1283
    private function parseCreateOptions(?string $string) : array
336
    {
337 1283
        $options = [];
338
339 1283
        if ($string === null || $string === '') {
340 1283
            return $options;
341
        }
342
343 759
        foreach (explode(' ', $string) as $pair) {
344 759
            $parts = explode('=', $pair, 2);
345
346 759
            $options[$parts[0]] = $parts[1] ?? true;
347
        }
348
349 759
        return $options;
350
    }
351
}
352