Completed
Pull Request — master (#3650)
by Matthew
14:23
created

_getPortableDatabaseDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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