Completed
Pull Request — master (#2415)
by Benoît
29:26 queued 26:11
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 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 136
                $v['primary'] = true;
62
            } else {
63 112
                $v['primary'] = false;
64
            }
65 168
            if (strpos($v['index_type'], 'FULLTEXT') !== false) {
66 32
                $v['flags'] = ['FULLTEXT'];
67 160
            } elseif (strpos($v['index_type'], 'SPATIAL') !== false) {
68 32
                $v['flags'] = ['SPATIAL'];
69
            }
70 168
            $tableIndexes[$k] = $v;
71
        }
72
73 302
        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 366
    protected function _getPortableTableColumnDefinition($tableColumn)
96
    {
97 366
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
98
99 366
        $dbType = strtolower($tableColumn['type']);
100 366
        $dbType = strtok($dbType, '(), ');
101 366
        $length = $tableColumn['length'] ?? strtok('(), ');
102
103 366
        $fixed = null;
104
105 366
        if (! isset($tableColumn['name'])) {
106 366
            $tableColumn['name'] = '';
107
        }
108
109 366
        $scale     = null;
110 366
        $precision = null;
111
112 366
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
113
114
        // In cases where not connected to a database DESCRIBE $table does not return 'Comment'
115 366
        if (isset($tableColumn['comment'])) {
116 366
            $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
117 366
            $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
118
        }
119
120
        switch ($dbType) {
121 366
            case 'char':
122 350
            case 'binary':
123 56
                $fixed = true;
124 56
                break;
125 350
            case 'float':
126 350
            case 'double':
127 342
            case 'real':
128 342
            case 'numeric':
129 342
            case 'decimal':
130 64
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['type'], $match)) {
131 56
                    $precision = $match[1];
132 56
                    $scale     = $match[2];
133 56
                    $length    = null;
134
                }
135 64
                break;
136 334
            case 'tinytext':
137 32
                $length = MySqlPlatform::LENGTH_LIMIT_TINYTEXT;
138 32
                break;
139 334
            case 'text':
140 32
                $length = MySqlPlatform::LENGTH_LIMIT_TEXT;
141 32
                break;
142 334
            case 'mediumtext':
143 32
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMTEXT;
144 32
                break;
145 334
            case 'tinyblob':
146
                $length = MySqlPlatform::LENGTH_LIMIT_TINYBLOB;
147
                break;
148 334
            case 'blob':
149 32
                $length = MySqlPlatform::LENGTH_LIMIT_BLOB;
150 32
                break;
151 334
            case 'mediumblob':
152 32
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMBLOB;
153 32
                break;
154 334
            case 'tinyint':
155 334
            case 'smallint':
156 334
            case 'mediumint':
157 334
            case 'int':
158 182
            case 'integer':
159 182
            case 'bigint':
160 182
            case 'year':
161 272
                $length = null;
162 272
                break;
163
        }
164
165 366
        if ($this->_platform instanceof MariaDb1027Platform) {
166 90
            $columnDefault = $this->getMariaDb1027ColumnDefault($this->_platform, $tableColumn['default']);
167
        } else {
168 276
            $columnDefault = $tableColumn['default'];
169
        }
170
171
        $options = [
172 366
            'length'        => $length !== null ? (int) $length : null,
173 366
            'unsigned'      => strpos($tableColumn['type'], 'unsigned') !== false,
174 366
            'fixed'         => (bool) $fixed,
175 366
            'default'       => $columnDefault,
176 366
            'notnull'       => $tableColumn['null'] !== 'YES',
177
            'scale'         => null,
178
            'precision'     => null,
179 366
            'autoincrement' => strpos($tableColumn['extra'], 'auto_increment') !== false,
180 366
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
181 112
                ? $tableColumn['comment']
182
                : null,
183
        ];
184
185 366
        if ($scale !== null && $precision !== null) {
186 56
            $options['scale']     = (int) $scale;
187 56
            $options['precision'] = (int) $precision;
188
        }
189
190 366
        $column = new Column($tableColumn['field'], Type::getType($type), $options);
191
192 366
        if (isset($tableColumn['collation'])) {
193 168
            $column->setPlatformOption('collation', $tableColumn['collation']);
194
        }
195
196 366
        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 90
    private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?string $columnDefault) : ?string
216
    {
217 90
        if ($columnDefault === 'NULL' || $columnDefault === null) {
218 82
            return null;
219
        }
220 22
        if ($columnDefault[0] === "'") {
221 18
            return stripslashes(
222 18
                str_replace(
223 18
                    "''",
224 18
                    "'",
225 18
                    preg_replace('/^\'(.*)\'$/', '$1', $columnDefault)
226
                )
227
            );
228
        }
229
        switch ($columnDefault) {
230 14
            case 'current_timestamp()':
231 10
                return $platform->getCurrentTimestampSQL();
232 12
            case 'curdate()':
233 8
                return $platform->getCurrentDateSQL();
234 12
            case 'curtime()':
235 8
                return $platform->getCurrentTimeSQL();
236
        }
237 10
        return $columnDefault;
238
    }
239
240
    /**
241
     * {@inheritdoc}
242
     */
243 289
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
244
    {
245 289
        $list = [];
246 289
        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 289
        $result = [];
270 289
        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 289
        return $result;
284
    }
285
286 24
    public function listTables()
287
    {
288 24
        $tables = parent::listTables();
289
290
        /** @var MySqlPlatform $platform */
291 24
        $platform = $this->_platform;
292 24
        $sql = $platform->getListTablesMetadataSQL();
293
294 24
        $options = [];
295
296 24
        foreach ($this->_conn->fetchAll($sql) as $tableOptions) {
297 24
            $options[$tableOptions['TABLE_NAME']] = $tableOptions;
298
        }
299
300 24
        foreach ($tables as $table) {
301 24
            $tableName = $table->getName();
302 24
            $tableOptions = $options[$tableName];
303
304 24
            $table->addOption('engine', $tableOptions['ENGINE']);
305 24
            if ($tableOptions['TABLE_COLLATION']) {
306 24
                $table->addOption('collation', $tableOptions['TABLE_COLLATION']);
307
            }
308 24
            if ($tableOptions['AUTO_INCREMENT']) {
309 24
                $table->addOption('autoincrement', $tableOptions['AUTO_INCREMENT']);
310
            }
311 24
            if ($tableOptions['TABLE_COMMENT']) {
312 24
                $table->addOption('comment', $tableOptions['TABLE_COMMENT']);
313
            }
314 24
            if ($tableOptions['CREATE_OPTIONS']) {
315 24
                $table->addOption('create_options', $tableOptions['CREATE_OPTIONS']);
316
            }
317
        }
318
319 24
        return $tables;
320
    }
321
}
322