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