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