Completed
Pull Request — master (#2415)
by Benoît
22:09
created

MySqlSchemaManager::listTableDetails()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 32
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 5

Importance

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