Failed Conditions
Push — master ( 489cb9...e0a92b )
by Sergei
34s queued 21s
created

MySqlSchemaManager::_getPortableTableIndexesList()   A

Complexity

Conditions 6
Paths 13

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6.288

Importance

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