Completed
Push — develop ( 7c38e8...152bc9 )
by Sergei
64:01 queued 11s
created

MySqlSchemaManager::_getPortableTableDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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