Failed Conditions
Push — master ( cfe3be...296b0e )
by Sergei
33:23 queued 11s
created

_getPortableSequenceDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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