Completed
Push — master ( 292d81...c07ed1 )
by Sergei
47:58 queued 44:41
created

MySqlSchemaManager::_getPortableTableDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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