Completed
Pull Request — master (#3610)
by Sergei
03:27 queued 10s
created

MySqlSchemaManager::_getPortableTableIndexesList()   B

Complexity

Conditions 6
Paths 13

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 12
cts 12
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 476
     * {@inheritdoc}
50
     */
51 476
    protected function _getPortableViewDefinition(array $view) : View
52
    {
53
        return new View($view['TABLE_NAME'], $view['VIEW_DEFINITION']);
54
    }
55
56
    /**
57 1266
     * {@inheritdoc}
58
     */
59 1266
    protected function _getPortableTableDefinition(array $table) : string
60
    {
61
        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 1168
     * {@inheritdoc}
77
     */
78 1168
    protected function _getPortableTableIndexesList(array $tableIndexRows, string $tableName) : array
79 1168
    {
80 1168
        foreach ($tableIndexRows as $k => $v) {
81 1168
            $v = array_change_key_case($v, CASE_LOWER);
82
            if ($v['key_name'] === 'PRIMARY') {
83 1168
                $v['primary'] = true;
84
            } else {
85 1168
                $v['primary'] = false;
86 952
            }
87 1168
            if (strpos($v['index_type'], 'FULLTEXT') !== false) {
88 938
                $v['flags'] = ['FULLTEXT'];
89
            } elseif (strpos($v['index_type'], 'SPATIAL') !== false) {
90 1168
                $v['flags'] = ['SPATIAL'];
91
            }
92 1168
            $v['length'] = isset($v['sub_part']) ? (int) $v['sub_part'] : null;
93
94
            $tableIndexRows[$k] = $v;
95 1168
        }
96
97
        return parent::_getPortableTableIndexesList($tableIndexRows, $tableName);
98
    }
99
100
    /**
101 672
     * {@inheritdoc}
102
     */
103 672
    protected function _getPortableDatabaseDefinition(array $database) : string
104
    {
105
        return $database['Database'];
106
    }
107
108
    /**
109 1168
     * {@inheritdoc}
110
     */
111 1168
    protected function _getPortableTableColumnDefinition(array $tableColumn) : Column
112
    {
113 1168
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
114 1168
115 1168
        $dbType = strtolower($tableColumn['type']);
116
        $dbType = strtok($dbType, '(), ');
117 1168
        assert(is_string($dbType));
118
119 1168
        $length = $tableColumn['length'] ?? strtok('(), ');
120
121 1168
        $fixed = false;
122 1168
123
        if (! isset($tableColumn['name'])) {
124
            $tableColumn['name'] = '';
125 1168
        }
126 1168
127
        $scale     = 0;
128 1168
        $precision = null;
129
130
        $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'])
131 1168
            ?? $this->_platform->getDoctrineTypeMapping($dbType);
132 1168
133 1168
        switch ($dbType) {
134
            case 'char':
135
            case 'binary':
136
                $fixed = true;
137 1168
                break;
138 1168
            case 'float':
139 802
            case 'double':
140 802
            case 'real':
141 1168
            case 'numeric':
142 1168
            case 'decimal':
143 1168
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['type'], $match)) {
144 1168
                    $precision = (int) $match[1];
145 1168
                    $scale     = (int) $match[2];
146 788
                    $length    = null;
147 788
                }
148 788
                break;
149 788
            case 'tinytext':
150
                $length = MySqlPlatform::LENGTH_LIMIT_TINYTEXT;
151 788
                break;
152 1168
            case 'text':
153 816
                $length = MySqlPlatform::LENGTH_LIMIT_TEXT;
154 816
                break;
155 1168
            case 'mediumtext':
156 816
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMTEXT;
157 816
                break;
158 1168
            case 'tinyblob':
159 816
                $length = MySqlPlatform::LENGTH_LIMIT_TINYBLOB;
160 816
                break;
161 1168
            case 'blob':
162
                $length = MySqlPlatform::LENGTH_LIMIT_BLOB;
163
                break;
164 1168
            case 'mediumblob':
165 816
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMBLOB;
166 816
                break;
167 1168
            case 'tinyint':
168 816
            case 'smallint':
169 816
            case 'mediumint':
170 1168
            case 'int':
171 1168
            case 'integer':
172 1168
            case 'bigint':
173 1168
            case 'year':
174 1168
                $length = null;
175 1168
                break;
176 1168
        }
177 1168
178 1168
        if ($this->_platform instanceof MariaDb1027Platform) {
179
            $columnDefault = $this->getMariaDb1027ColumnDefault($this->_platform, $tableColumn['default']);
180
        } else {
181 1168
            $columnDefault = $tableColumn['default'];
182 322
        }
183
184 846
        $options = [
185
            'length'        => $length !== null ? (int) $length : null,
186
            'unsigned'      => strpos($tableColumn['type'], 'unsigned') !== false,
187
            'fixed'         => $fixed,
188 1168
            'default'       => $columnDefault,
189 1168
            'notnull'       => $tableColumn['null'] !== 'YES',
190 1168
            'scale'         => $scale,
191 1168
            'precision'     => $precision,
192 1168
            'autoincrement' => strpos($tableColumn['extra'], 'auto_increment') !== false,
193
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
194
                ? $tableColumn['comment']
195 1168
                : null,
196 1168
        ];
197 406
198
        $column = new Column($tableColumn['field'], Type::getType($type), $options);
199
200
        if (isset($tableColumn['characterset'])) {
201 1168
            $column->setPlatformOption('charset', $tableColumn['characterset']);
202 788
        }
203 788
        if (isset($tableColumn['collation'])) {
204
            $column->setPlatformOption('collation', $tableColumn['collation']);
205
        }
206 1168
207
        return $column;
208 1168
    }
209 1168
210
    /**
211 1168
     * Return Doctrine/Mysql-compatible column default values for MariaDB 10.2.7+ servers.
212 1168
     *
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 1168
     * - 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
    private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?string $columnDefault) : ?string
227
    {
228
        if ($columnDefault === 'NULL' || $columnDefault === null) {
229
            return null;
230
        }
231
232
        if (preg_match('/^\'(.*)\'$/', $columnDefault, $matches)) {
233
            return strtr($matches[1], self::MARIADB_ESCAPE_SEQUENCES);
234 322
        }
235
236 322
        switch ($columnDefault) {
237 322
            case 'current_timestamp()':
238
                return $platform->getCurrentTimestampSQL();
239
            case 'curdate()':
240 322
                return $platform->getCurrentDateSQL();
241 310
            case 'curtime()':
242
                return $platform->getCurrentTimeSQL();
243
        }
244
245 322
        return $columnDefault;
246 322
    }
247 318
248 204
    /**
249 318
     * {@inheritdoc}
250 204
     */
251
    protected function _getPortableTableForeignKeysList(array $tableForeignKeys) : array
252
    {
253 318
        $list = [];
254
        foreach ($tableForeignKeys as $value) {
255
            $value = array_change_key_case($value, CASE_LOWER);
256
            if (! isset($list[$value['constraint_name']])) {
257
                if (! isset($value['delete_rule']) || $value['delete_rule'] === 'RESTRICT') {
258
                    $value['delete_rule'] = null;
259 1181
                }
260
                if (! isset($value['update_rule']) || $value['update_rule'] === 'RESTRICT') {
261 1181
                    $value['update_rule'] = null;
262 1181
                }
263 545
264 545
                $list[$value['constraint_name']] = [
265 545
                    'name' => $value['constraint_name'],
266 471
                    'local' => [],
267
                    'foreign' => [],
268 545
                    'foreignTable' => $value['referenced_table_name'],
269 471
                    'onDelete' => $value['delete_rule'],
270
                    'onUpdate' => $value['update_rule'],
271
                ];
272 545
            }
273 545
            $list[$value['constraint_name']]['local'][]   = $value['column_name'];
274
            $list[$value['constraint_name']]['foreign'][] = $value['referenced_column_name'];
275
        }
276 545
277 545
        $result = [];
278 545
        foreach ($list as $constraint) {
279
            $result[] = new ForeignKeyConstraint(
280
                array_values($constraint['local']),
281 545
                $constraint['foreignTable'],
282 545
                array_values($constraint['foreign']),
283
                $constraint['name'],
284
                [
285 1181
                    'onDelete' => $constraint['onDelete'],
286 1181
                    'onUpdate' => $constraint['onUpdate'],
287 545
                ]
288 545
            );
289 545
        }
290 545
291 545
        return $result;
292
    }
293 545
294 545
    /**
295
     * {@inheritdoc}
296
     */
297
    public function listTableDetails(string $tableName) : Table
298
    {
299 1181
        $table = parent::listTableDetails($tableName);
300
301
        /** @var MySqlPlatform $platform */
302 1168
        $platform = $this->_platform;
303
        $sql      = $platform->getListTableMetadataSQL($tableName);
304 1168
305
        $tableOptions = $this->_conn->fetchAssoc($sql);
306
307 1168
        if ($tableOptions === false) {
308 1168
            return $table;
309
        }
310 1168
311
        $table->addOption('engine', $tableOptions['ENGINE']);
312 1168
313 686
        if ($tableOptions['TABLE_COLLATION'] !== null) {
314
            $table->addOption('collation', $tableOptions['TABLE_COLLATION']);
315
        }
316 1168
317
        if ($tableOptions['AUTO_INCREMENT'] !== null) {
318 1168
            $table->addOption('autoincrement', $tableOptions['AUTO_INCREMENT']);
319 1168
        }
320
321
        $table->addOption('comment', $tableOptions['TABLE_COMMENT']);
322 1168
        $table->addOption('create_options', $this->parseCreateOptions($tableOptions['CREATE_OPTIONS']));
323 1168
324
        return $table;
325
    }
326 1168
327 1168
    /**
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 1168
     */
330
    private function parseCreateOptions(?string $string) : array
331
    {
332
        $options = [];
333
334
        if ($string === null || $string === '') {
335 1168
            return $options;
336
        }
337 1168
338
        foreach (explode(' ', $string) as $pair) {
339 1168
            $parts = explode('=', $pair, 2);
340 1168
341
            $options[$parts[0]] = $parts[1] ?? true;
342
        }
343 714
344 714
        return $options;
345
    }
346
}
347