Failed Conditions
Push — master ( 379085...b45ed5 )
by Marco
54s queued 28s
created

MySqlSchemaManager::getMariaDb1027ColumnDefault()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7.0099

Importance

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