Completed
Pull Request — master (#3610)
by Sergei
31:59 queued 28:53
created

MySqlSchemaManager::_getPortableTableIndexesList()   B

Complexity

Conditions 6
Paths 13

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6

Importance

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

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
329
     */
330 878
    private function parseCreateOptions(?string $string) : array
331
    {
332 878
        $options = [];
333
334 878
        if ($string === null || $string === '') {
335 861
            return $options;
336
        }
337
338 51
        foreach (explode(' ', $string) as $pair) {
339 51
            $parts = explode('=', $pair, 2);
340
341 51
            $options[$parts[0]] = $parts[1] ?? true;
342
        }
343
344 51
        return $options;
345
    }
346
}
347