Completed
Pull Request — 2.10.x (#3967)
by
unknown
11:59
created

MySqlSchemaManager::_getPortableUserDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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