Completed
Pull Request — master (#2412)
by Benoît
14:20
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
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\DBAL\Schema;
21
22
use Doctrine\DBAL\Platforms\MariaDb1027Platform;
23
use Doctrine\DBAL\Platforms\MySqlPlatform;
24
use Doctrine\DBAL\Types\Type;
25
use const CASE_LOWER;
26
use function array_change_key_case;
27
use function array_shift;
28
use function array_values;
29
use function end;
30
use function preg_match;
31
use function preg_replace;
32
use function str_replace;
33
use function stripslashes;
34
use function strpos;
35
use function strtok;
36
use function strtolower;
37
38
/**
39
 * Schema manager for the MySql RDBMS.
40
 *
41
 * @author Konsta Vesterinen <[email protected]>
42
 * @author Lukas Smith <[email protected]> (PEAR MDB2 library)
43
 * @author Roman Borschel <[email protected]>
44
 * @author Benjamin Eberlei <[email protected]>
45
 * @since  2.0
46
 */
47
class MySqlSchemaManager extends AbstractSchemaManager
48
{
49
    /**
50
     * {@inheritdoc}
51
     */
52 8
    protected function _getPortableViewDefinition($view)
53
    {
54 8
        return new View($view['TABLE_NAME'], $view['VIEW_DEFINITION']);
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60 590
    protected function _getPortableTableDefinition($table)
61
    {
62 590
        return array_shift($table);
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    protected function _getPortableUserDefinition($user)
69
    {
70
        return [
71
            'user' => $user['User'],
72
            'password' => $user['Password'],
73
        ];
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79 302
    protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
80
    {
81 302
        foreach ($tableIndexes as $k => $v) {
82 168
            $v = array_change_key_case($v, CASE_LOWER);
83 168
            if ($v['key_name'] === 'PRIMARY') {
84 128
                $v['primary'] = true;
85
            } else {
86 112
                $v['primary'] = false;
87
            }
88 168
            if (strpos($v['index_type'], 'FULLTEXT') !== false) {
89 24
                $v['flags'] = ['FULLTEXT'];
90 160
            } elseif (strpos($v['index_type'], 'SPATIAL') !== false) {
91 24
                $v['flags'] = ['SPATIAL'];
92
            }
93 168
            $v['length'] = $v['sub_part'] ?? null;
94 168
            $tableIndexes[$k] = $v;
95
        }
96
97 302
        return parent::_getPortableTableIndexesList($tableIndexes, $tableName);
98
    }
99
100
    /**
101
     * {@inheritdoc}
102
     */
103
    protected function _getPortableSequenceDefinition($sequence)
104
    {
105
        return end($sequence);
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111 16
    protected function _getPortableDatabaseDefinition($database)
112
    {
113 16
        return $database['Database'];
114
    }
115
116
    /**
117
     * {@inheritdoc}
118
     */
119 366
    protected function _getPortableTableColumnDefinition($tableColumn)
120
    {
121 366
        $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
122
123 366
        $dbType = strtolower($tableColumn['type']);
124 366
        $dbType = strtok($dbType, '(), ');
125 366
        $length = $tableColumn['length'] ?? strtok('(), ');
126
127 366
        $fixed = null;
128
129 366
        if ( ! isset($tableColumn['name'])) {
130 366
            $tableColumn['name'] = '';
131
        }
132
133 366
        $scale     = null;
134 366
        $precision = null;
135
136 366
        $type = $this->_platform->getDoctrineTypeMapping($dbType);
137
138
        // In cases where not connected to a database DESCRIBE $table does not return 'Comment'
139 366
        if (isset($tableColumn['comment'])) {
140 366
            $type                   = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
141 366
            $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
142
        }
143
144
        switch ($dbType) {
145 366
            case 'char':
146 350
            case 'binary':
147 48
                $fixed = true;
148 48
                break;
149 350
            case 'float':
150 350
            case 'double':
151 342
            case 'real':
152 342
            case 'numeric':
153 342
            case 'decimal':
154 56
                if (preg_match('([A-Za-z]+\(([0-9]+)\,([0-9]+)\))', $tableColumn['type'], $match)) {
155 48
                    $precision = $match[1];
156 48
                    $scale     = $match[2];
157 48
                    $length    = null;
158
                }
159 56
                break;
160 334
            case 'tinytext':
161 24
                $length = MySqlPlatform::LENGTH_LIMIT_TINYTEXT;
162 24
                break;
163 334
            case 'text':
164 24
                $length = MySqlPlatform::LENGTH_LIMIT_TEXT;
165 24
                break;
166 334
            case 'mediumtext':
167 24
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMTEXT;
168 24
                break;
169 334
            case 'tinyblob':
170
                $length = MySqlPlatform::LENGTH_LIMIT_TINYBLOB;
171
                break;
172 334
            case 'blob':
173 24
                $length = MySqlPlatform::LENGTH_LIMIT_BLOB;
174 24
                break;
175 334
            case 'mediumblob':
176 24
                $length = MySqlPlatform::LENGTH_LIMIT_MEDIUMBLOB;
177 24
                break;
178 334
            case 'tinyint':
179 334
            case 'smallint':
180 334
            case 'mediumint':
181 334
            case 'int':
182 182
            case 'integer':
183 182
            case 'bigint':
184 182
            case 'year':
185 272
                $length = null;
186 272
                break;
187
        }
188
189 366
        if ($this->_platform instanceof MariaDb1027Platform) {
190 90
            $columnDefault = $this->getMariaDb1027ColumnDefault($this->_platform, $tableColumn['default']);
191
        } else {
192 276
            $columnDefault = $tableColumn['default'];
193
        }
194
195
        $options = [
196 366
            'length'        => $length !== null ? (int) $length : null,
197 366
            'unsigned'      => strpos($tableColumn['type'], 'unsigned') !== false,
198 366
            'fixed'         => (bool) $fixed,
199 366
            'default'       => $columnDefault,
200 366
            'notnull'       => $tableColumn['null'] !== 'YES',
201
            'scale'         => null,
202
            'precision'     => null,
203 366
            'autoincrement' => strpos($tableColumn['extra'], 'auto_increment') !== false,
204 366
            'comment'       => isset($tableColumn['comment']) && $tableColumn['comment'] !== ''
205 112
                ? $tableColumn['comment']
206
                : null,
207
        ];
208
209 366
        if ($scale !== null && $precision !== null) {
210 48
            $options['scale']     = (int) $scale;
211 48
            $options['precision'] = (int) $precision;
212
        }
213
214 366
        $column = new Column($tableColumn['field'], Type::getType($type), $options);
215
216 366
        if (isset($tableColumn['collation'])) {
217 168
            $column->setPlatformOption('collation', $tableColumn['collation']);
218
        }
219
220 366
        return $column;
221
    }
222
223
    /**
224
     * Return Doctrine/Mysql-compatible column default values for MariaDB 10.2.7+ servers.
225
     *
226
     * - Since MariaDb 10.2.7 column defaults stored in information_schema are now quoted
227
     *   to distinguish them from expressions (see MDEV-10134).
228
     * - CURRENT_TIMESTAMP, CURRENT_TIME, CURRENT_DATE are stored in information_schema
229
     *   as current_timestamp(), currdate(), currtime()
230
     * - Quoted 'NULL' is not enforced by Maria, it is technically possible to have
231
     *   null in some circumstances (see https://jira.mariadb.org/browse/MDEV-14053)
232
     * - \' is always stored as '' in information_schema (normalized)
233
     *
234
     * @link https://mariadb.com/kb/en/library/information-schema-columns-table/
235
     * @link https://jira.mariadb.org/browse/MDEV-13132
236
     *
237
     * @param null|string $columnDefault default value as stored in information_schema for MariaDB >= 10.2.7
238
     */
239 90
    private function getMariaDb1027ColumnDefault(MariaDb1027Platform $platform, ?string $columnDefault) : ?string
240
    {
241 90
        if ($columnDefault === 'NULL' || $columnDefault === null) {
242 82
            return null;
243
        }
244 20
        if ($columnDefault[0] === "'") {
245 16
            return stripslashes(
246 16
                str_replace("''", "'",
247 16
                    preg_replace('/^\'(.*)\'$/', '$1', $columnDefault)
248
                )
249
            );
250
        }
251
        switch ($columnDefault) {
252 12
            case 'current_timestamp()':
253 8
                return $platform->getCurrentTimestampSQL();
254 10
            case 'curdate()':
255 6
                return $platform->getCurrentDateSQL();
256 10
            case 'curtime()':
257 6
                return $platform->getCurrentTimeSQL();
258
        }
259 8
        return $columnDefault;
260
    }
261
262
    /**
263
     * {@inheritdoc}
264
     */
265 289
    protected function _getPortableTableForeignKeysList($tableForeignKeys)
266
    {
267 289
        $list = [];
268 289
        foreach ($tableForeignKeys as $value) {
269 75
            $value = array_change_key_case($value, CASE_LOWER);
270 75
            if ( ! isset($list[$value['constraint_name']])) {
271 75
                if ( ! isset($value['delete_rule']) || $value['delete_rule'] === "RESTRICT") {
272 67
                    $value['delete_rule'] = null;
273
                }
274 75
                if ( ! isset($value['update_rule']) || $value['update_rule'] === "RESTRICT") {
275 75
                    $value['update_rule'] = null;
276
                }
277
278 75
                $list[$value['constraint_name']] = [
279 75
                    'name' => $value['constraint_name'],
280
                    'local' => [],
281
                    'foreign' => [],
282 75
                    'foreignTable' => $value['referenced_table_name'],
283 75
                    'onDelete' => $value['delete_rule'],
284 75
                    'onUpdate' => $value['update_rule'],
285
                ];
286
            }
287 75
            $list[$value['constraint_name']]['local'][]   = $value['column_name'];
288 75
            $list[$value['constraint_name']]['foreign'][] = $value['referenced_column_name'];
289
        }
290
291 289
        $result = [];
292 289
        foreach ($list as $constraint) {
293 75
            $result[] = new ForeignKeyConstraint(
294 75
                array_values($constraint['local']),
295 75
                $constraint['foreignTable'],
296 75
                array_values($constraint['foreign']),
297 75
                $constraint['name'],
298
                [
299 75
                    'onDelete' => $constraint['onDelete'],
300 75
                    'onUpdate' => $constraint['onUpdate'],
301
                ]
302
            );
303
        }
304
305 289
        return $result;
306
    }
307
}
308