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