Failed Conditions
Pull Request — develop (#3348)
by Sergei
63:22
created

MySqlPlatform   F

Complexity

Total Complexity 181

Size/Duplication

Total Lines 1124
Duplicated Lines 0 %

Test Coverage

Coverage 92.78%

Importance

Changes 0
Metric Value
wmc 181
eloc 382
dl 0
loc 1124
ccs 360
cts 388
cp 0.9278
rs 2
c 0
b 0
f 0

68 Methods

Rating   Name   Duplication   Size   Complexity  
A getReadLockSQL() 0 3 1
A getDefaultTransactionIsolationLevel() 0 3 1
A initializeDoctrineTypeMappings() 0 33 1
A getDropTemporaryTableSQL() 0 9 3
A getDropPrimaryKeySQL() 0 3 1
A getName() 0 3 1
A getBinaryMaxLength() 0 3 1
A getSetTransactionIsolationSQL() 0 3 1
A getVarcharMaxLength() 0 3 1
A getReservedKeywordsClass() 0 3 1
A supportsColumnLengthIndexes() 0 3 1
A quoteStringLiteral() 0 5 1
A getBlobTypeDeclarationSQL() 0 19 6
A getLocateExpression() 0 7 2
A getTimeTypeDeclarationSQL() 0 3 1
A getListTableForeignKeysSQL() 0 17 1
A getDefaultValueDeclarationSQL() 0 8 3
A getSmallIntTypeDeclarationSQL() 0 3 1
A getBigIntTypeDeclarationSQL() 0 3 1
A prefersIdentityColumns() 0 3 1
A getCollationFieldDeclaration() 0 3 1
A getDropDatabaseSQL() 0 3 1
A getDateDiffExpression() 0 3 1
A getListTablesSQL() 0 3 1
A getRemainingForeignKeyConstraintsRequiringRenamedIndexes() 0 24 6
A getIntegerTypeDeclarationSQL() 0 3 1
A getPreAlterTableAlterPrimaryKeySQL() 0 32 6
A getBooleanTypeDeclarationSQL() 0 3 1
A _getCommonIntegerTypeDeclarationSQL() 0 8 2
A getDatabaseNameSql() 0 7 2
A getCreateIndexSQLFlags() 0 12 4
A buildPartitionOptions() 0 5 2
A doModifyLimitQuery() 0 14 4
A getListTableColumnsSQL() 0 7 1
A getListViewsSQL() 0 4 1
A getPostAlterTableIndexForeignKeySQL() 0 5 1
A getAdvancedForeignKeyOptionsSQL() 0 9 2
A getCreateViewSQL() 0 3 1
A getClobTypeDeclarationSQL() 0 19 6
B getDropIndexSQL() 0 23 7
B getPreAlterTableIndexForeignKeySQL() 0 56 10
A getPreAlterTableRenameIndexForeignKeySQL() 0 14 3
A getRegexpExpression() 0 3 1
A getPostAlterTableRenameIndexForeignKeySQL() 0 20 4
F getAlterTableSQL() 0 93 21
A getListTableIndexesSQL() 0 14 2
B buildTableOptions() 0 47 8
A getDateTimeTypeDeclarationSQL() 0 7 3
A supportsInlineColumnComments() 0 3 1
A getDateTypeDeclarationSQL() 0 3 1
A getVarcharTypeDeclarationSQLSnippet() 0 4 4
A getListDatabasesSQL() 0 3 1
A getDropViewSQL() 0 3 1
A getConcatExpression() 0 3 1
A getDateArithmeticIntervalExpression() 0 5 2
A getIdentifierQuoteCharacter() 0 3 1
A getFloatDeclarationSQL() 0 3 1
A getListTableConstraintsSQL() 0 3 1
A getDecimalTypeDeclarationSQL() 0 3 1
A getUnsignedDeclaration() 0 3 2
C _getCreateTableSQL() 0 48 14
A getColumnCharsetDeclarationSQL() 0 3 1
A getListTableMetadataSQL() 0 11 2
A getCreateDatabaseSQL() 0 3 1
A supportsIdentityColumns() 0 3 1
A supportsColumnCollation() 0 3 1
A getBinaryTypeDeclarationSQLSnippet() 0 3 4
B getPreAlterTableAlterIndexForeignKeySQL() 0 33 7

How to fix   Complexity   

Complex Class

Complex classes like MySqlPlatform often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use MySqlPlatform, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Doctrine\DBAL\Platforms;
4
5
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
6
use Doctrine\DBAL\Schema\Identifier;
7
use Doctrine\DBAL\Schema\Index;
8
use Doctrine\DBAL\Schema\Table;
9
use Doctrine\DBAL\Schema\TableDiff;
10
use Doctrine\DBAL\TransactionIsolationLevel;
11
use Doctrine\DBAL\Types\BlobType;
12
use Doctrine\DBAL\Types\TextType;
13
use InvalidArgumentException;
14
use function array_diff_key;
15
use function array_merge;
16
use function array_unique;
17
use function array_values;
18
use function count;
19
use function implode;
20
use function in_array;
21
use function is_numeric;
22
use function is_string;
23
use function sprintf;
24
use function str_replace;
25
use function strtoupper;
26
use function trim;
27
28
/**
29
 * The MySqlPlatform provides the behavior, features and SQL dialect of the
30
 * MySQL database platform. This platform represents a MySQL 5.0 or greater platform that
31
 * uses the InnoDB storage engine.
32
 *
33
 * @todo   Rename: MySQLPlatform
34
 */
35
class MySqlPlatform extends AbstractPlatform
36
{
37
    public const LENGTH_LIMIT_TINYTEXT   = 255;
38
    public const LENGTH_LIMIT_TEXT       = 65535;
39
    public const LENGTH_LIMIT_MEDIUMTEXT = 16777215;
40
41
    public const LENGTH_LIMIT_TINYBLOB   = 255;
42
    public const LENGTH_LIMIT_BLOB       = 65535;
43
    public const LENGTH_LIMIT_MEDIUMBLOB = 16777215;
44
45
    /**
46
     * {@inheritDoc}
47
     */
48
    protected function doModifyLimitQuery(string $query, ?int $limit, int $offset) : string
49
    {
50 372
        if ($limit !== null) {
51
            $query .= ' LIMIT ' . $limit;
52 372
53 222
            if ($offset > 0) {
54
                $query .= ' OFFSET ' . $offset;
55 222
            }
56 222
        } elseif ($offset > 0) {
57
            // 2^64-1 is the maximum of unsigned BIGINT, the biggest limit possible
58 162
            $query .= ' LIMIT 18446744073709551615 OFFSET ' . $offset;
59
        }
60 81
61
        return $query;
62
    }
63 372
64
    /**
65
     * {@inheritDoc}
66
     */
67
    public function getIdentifierQuoteCharacter() : string
68
    {
69 1910
        return '`';
70
    }
71 1910
72
    /**
73
     * {@inheritDoc}
74
     */
75
    public function getRegexpExpression() : string
76
    {
77 69
        return 'RLIKE';
78
    }
79 69
80
    /**
81
     * {@inheritDoc}
82
     */
83
    public function getLocateExpression(string $str, string $substr, int $startPos = 1) : string
84
    {
85 12
        if ($startPos === 1) {
86
            return 'LOCATE(' . $substr . ', ' . $str . ')';
87 12
        }
88 12
89
        return 'LOCATE(' . $substr . ', ' . $str . ', ' . $startPos . ')';
90
    }
91 12
92
    /**
93
     * {@inheritDoc}
94
     */
95
    public function getConcatExpression(string ...$expressions) : string
96
    {
97 69
        return sprintf('CONCAT(%s)', implode(', ', $expressions));
98
    }
99 69
100
    /**
101
     * {@inheritdoc}
102
     */
103
    protected function getDateArithmeticIntervalExpression(string $date, string $operator, string $interval, string $unit) : string
104
    {
105 12
        $function = $operator === '+' ? 'DATE_ADD' : 'DATE_SUB';
106
107 12
        return $function . '(' . $date . ', INTERVAL ' . $interval . ' ' . $unit . ')';
108
    }
109 12
110
    /**
111
     * {@inheritDoc}
112
     */
113
    public function getDateDiffExpression(string $date1, string $date2) : string
114
    {
115 36
        return 'DATEDIFF(' . $date1 . ', ' . $date2 . ')';
116
    }
117 36
118
    /**
119
     * {@inheritDoc}
120
     */
121
    public function getListDatabasesSQL() : string
122
    {
123 93
        return 'SHOW DATABASES';
124
    }
125 93
126
    /**
127
     * {@inheritDoc}
128
     */
129
    public function getListTableConstraintsSQL(string $table) : string
130
    {
131
        return 'SHOW INDEX FROM ' . $table;
132
    }
133
134
    /**
135
     * {@inheritDoc}
136
     *
137
     * Two approaches to listing the table indexes. The information_schema is
138
     * preferred, because it doesn't cause problems with SQL keywords such as "order" or "table".
139
     */
140
    public function getListTableIndexesSQL(string $table, ?string $currentDatabase = null) : string
141
    {
142 624
        if ($currentDatabase) {
143
            $currentDatabase = $this->quoteStringLiteral($currentDatabase);
144 624
            $table           = $this->quoteStringLiteral($table);
145 624
146 624
            return 'SELECT NON_UNIQUE AS Non_Unique, INDEX_NAME AS Key_name, COLUMN_NAME AS Column_Name,' .
147
                   ' SUB_PART AS Sub_Part, INDEX_TYPE AS Index_Type' .
148
                   ' FROM information_schema.STATISTICS WHERE TABLE_NAME = ' . $table .
149
                   ' AND TABLE_SCHEMA = ' . $currentDatabase .
150
                   ' ORDER BY SEQ_IN_INDEX ASC';
151
        }
152 624
153
        return 'SHOW INDEX FROM ' . $table;
154
    }
155
156
    /**
157
     * {@inheritDoc}
158
     */
159
    public function getListViewsSQL(?string $database) : string
160
    {
161 81
        return 'SELECT * FROM information_schema.VIEWS WHERE TABLE_SCHEMA = '
162
            . $this->getDatabaseNameSql($database);
163 81
    }
164
165 81
    /**
166
     * {@inheritDoc}
167
     */
168
    public function getListTableForeignKeysSQL(string $table, ?string $database = null) : string
169
    {
170
        $table = $this->quoteStringLiteral($table);
171 645
172
        $sql = 'SELECT DISTINCT k.`CONSTRAINT_NAME`, k.`COLUMN_NAME`, k.`REFERENCED_TABLE_NAME`, ' .
173 645
               'k.`REFERENCED_COLUMN_NAME` /*!50116 , c.update_rule, c.delete_rule */ ' .
174
               'FROM information_schema.key_column_usage k /*!50116 ' .
175 645
               'INNER JOIN information_schema.referential_constraints c ON ' .
176 576
               '  c.constraint_name = k.constraint_name AND ' .
177
               '  c.table_name = ' . $table . ' */ WHERE k.table_name = ' . $table;
178
179
        $databaseNameSql = $this->getDatabaseNameSql($database);
180
181
        $sql .= ' AND k.table_schema = ' . $databaseNameSql . ' /*!50116 AND c.constraint_schema = ' . $databaseNameSql . ' */';
182
        $sql .= ' AND k.`REFERENCED_COLUMN_NAME` is not NULL';
183
184 645
        return $sql;
185
    }
186 645
187
    /**
188 645
     * {@inheritDoc}
189 645
     */
190
    public function getCreateViewSQL(string $name, string $sql) : string
191 645
    {
192
        return 'CREATE VIEW ' . $name . ' AS ' . $sql;
193
    }
194
195
    /**
196
     * {@inheritDoc}
197 12
     */
198
    public function getDropViewSQL(string $name) : string
199 12
    {
200
        return 'DROP VIEW ' . $name;
201
    }
202
203
    /**
204
     * {@inheritDoc}
205 12
     */
206
    protected function getVarcharTypeDeclarationSQLSnippet(?int $length, bool $fixed) : string
207 12
    {
208
        return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
209
                : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)');
210
    }
211
212
    /**
213 1992
     * {@inheritdoc}
214
     */
215 1992
    protected function getBinaryTypeDeclarationSQLSnippet(?int $length, bool $fixed) : string
216 1992
    {
217
        return $fixed ? 'BINARY(' . ($length ?: 255) . ')' : 'VARBINARY(' . ($length ?: 255) . ')';
218
    }
219
220
    /**
221
     * Gets the SQL snippet used to declare a CLOB column type.
222 93
     *     TINYTEXT   : 2 ^  8 - 1 = 255
223
     *     TEXT       : 2 ^ 16 - 1 = 65535
224 93
     *     MEDIUMTEXT : 2 ^ 24 - 1 = 16777215
225
     *     LONGTEXT   : 2 ^ 32 - 1 = 4294967295
226
     *
227
     * {@inheritDoc}
228
     */
229
    public function getClobTypeDeclarationSQL(array $field) : string
230
    {
231
        if (! empty($field['length']) && is_numeric($field['length'])) {
232
            $length = $field['length'];
233
234
            if ($length <= static::LENGTH_LIMIT_TINYTEXT) {
235
                return 'TINYTEXT';
236 959
            }
237
238 959
            if ($length <= static::LENGTH_LIMIT_TEXT) {
239 104
                return 'TEXT';
240
            }
241 104
242 81
            if ($length <= static::LENGTH_LIMIT_MEDIUMTEXT) {
243
                return 'MEDIUMTEXT';
244
            }
245 104
        }
246 104
247
        return 'LONGTEXT';
248
    }
249 81
250 81
    /**
251
     * {@inheritDoc}
252
     */
253
    public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration) : string
254 936
    {
255
        if (isset($fieldDeclaration['version']) && $fieldDeclaration['version'] === true) {
256
            return 'TIMESTAMP';
257
        }
258
259
        return 'DATETIME';
260 361
    }
261
262 361
    /**
263 69
     * {@inheritDoc}
264
     */
265
    public function getDateTypeDeclarationSQL(array $fieldDeclaration) : string
266 361
    {
267
        return 'DATE';
268
    }
269
270
    /**
271
     * {@inheritDoc}
272 232
     */
273
    public function getTimeTypeDeclarationSQL(array $fieldDeclaration) : string
274 232
    {
275
        return 'TIME';
276
    }
277
278
    /**
279
     * {@inheritDoc}
280 220
     */
281
    public function getBooleanTypeDeclarationSQL(array $columnDef) : string
282 220
    {
283
        return 'TINYINT(1)';
284
    }
285
286
    /**
287
     * Obtain DBMS specific SQL code portion needed to set the COLLATION
288 249
     * of a field declaration to be used in statements like CREATE TABLE.
289
     *
290 249
     * @deprecated Deprecated since version 2.5, Use {@link self::getColumnCollationDeclarationSQL()} instead.
291
     *
292
     * @param string $collation name of the collation
293
     *
294
     * @return string  DBMS specific SQL code portion needed to set the COLLATION
295
     *                 of a field declaration.
296
     */
297
    public function getCollationFieldDeclaration(string $collation) : string
298
    {
299
        return $this->getColumnCollationDeclarationSQL($collation);
300
    }
301
302
    /**
303
     * {@inheritDoc}
304
     *
305
     * MySql prefers "autoincrement" identity columns since sequences can only
306
     * be emulated with a table.
307
     */
308
    public function prefersIdentityColumns() : bool
309
    {
310
        return true;
311
    }
312
313
    /**
314
     * {@inheritDoc}
315 81
     *
316
     * MySql supports this through AUTO_INCREMENT columns.
317 81
     */
318
    public function supportsIdentityColumns() : bool
319
    {
320
        return true;
321
    }
322
323
    /**
324
     * {@inheritDoc}
325 105
     */
326
    public function supportsInlineColumnComments() : bool
327 105
    {
328
        return true;
329
    }
330
331
    /**
332
     * {@inheritDoc}
333 4241
     */
334
    public function supportsColumnCollation() : bool
335 4241
    {
336
        return true;
337
    }
338
339
    /**
340
     * {@inheritDoc}
341 219
     */
342
    public function getListTablesSQL() : string
343 219
    {
344
        return "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'";
345
    }
346
347
    /**
348
     * {@inheritDoc}
349 906
     */
350
    public function getListTableColumnsSQL(string $table, ?string $database = null) : string
351 906
    {
352
        return 'SELECT COLUMN_NAME AS Field, COLUMN_TYPE AS Type, IS_NULLABLE AS `Null`, ' .
353
               'COLUMN_KEY AS `Key`, COLUMN_DEFAULT AS `Default`, EXTRA AS Extra, COLUMN_COMMENT AS Comment, ' .
354
               'CHARACTER_SET_NAME AS CharacterSet, COLLATION_NAME AS Collation ' .
355
               'FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ' . $this->getDatabaseNameSql($database) . ' ' .
356
               'AND TABLE_NAME = ' . $this->quoteStringLiteral($table);
357 720
    }
358
359 720
    public function getListTableMetadataSQL(string $table, ?string $database = null) : string
360
    {
361 720
        return sprintf(
362 651
            <<<'SQL'
363
SELECT ENGINE, AUTO_INCREMENT, TABLE_COLLATION, TABLE_COMMENT, CREATE_OPTIONS
364 69
FROM information_schema.TABLES
365
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = %s AND TABLE_NAME = %s
366
SQL
367
            ,
368
            $database ? $this->quoteStringLiteral($database) : 'DATABASE()',
369
            $this->quoteStringLiteral($table)
370 720
        );
371
    }
372
373 414
    /**
374
     * {@inheritDoc}
375 414
     */
376
    public function getCreateDatabaseSQL(string $database) : string
377 414
    {
378
        return 'CREATE DATABASE ' . $database;
379
    }
380
381
    /**
382 414
     * {@inheritDoc}
383 414
     */
384
    public function getDropDatabaseSQL(string $database) : string
385
    {
386
        return 'DROP DATABASE ' . $database;
387
    }
388
389
    /**
390 93
     * {@inheritDoc}
391
     */
392 93
    protected function _getCreateTableSQL(string $tableName, array $columns, array $options = []) : array
393
    {
394
        $queryFields = $this->getColumnDeclarationListSQL($columns);
395
396
        if (isset($options['uniqueConstraints']) && ! empty($options['uniqueConstraints'])) {
397
            foreach ($options['uniqueConstraints'] as $name => $definition) {
398 93
                $queryFields .= ', ' . $this->getUniqueConstraintDeclarationSQL($name, $definition);
399
            }
400 93
        }
401
402
        // add all indexes
403
        if (isset($options['indexes']) && ! empty($options['indexes'])) {
404
            foreach ($options['indexes'] as $index => $definition) {
405
                $queryFields .= ', ' . $this->getIndexDeclarationSQL($index, $definition);
406 2999
            }
407
        }
408 2999
409
        // attach all primary keys
410 2999
        if (isset($options['primary']) && ! empty($options['primary'])) {
411
            $keyColumns   = array_unique(array_values($options['primary']));
412
            $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')';
413
        }
414
415
        $query = 'CREATE ';
416
417 2999
        if (! empty($options['temporary'])) {
418 664
            $query .= 'TEMPORARY ';
419 664
        }
420
421
        $query .= 'TABLE ' . $tableName . ' (' . $queryFields . ') ';
422
        $query .= $this->buildTableOptions($options);
423
        $query .= $this->buildPartitionOptions($options);
424 2999
425 1569
        $sql    = [$query];
426 1569
        $engine = 'INNODB';
427
428
        if (isset($options['engine'])) {
429 2999
            $engine = strtoupper(trim($options['engine']));
430
        }
431 2999
432
        // Propagate foreign key constraints only for InnoDB.
433
        if (isset($options['foreignKeys']) && $engine === 'INNODB') {
434
            foreach ((array) $options['foreignKeys'] as $definition) {
435 2999
                $sql[] = $this->getCreateForeignKeySQL($definition, $tableName);
436 2999
            }
437 2999
        }
438
439 2999
        return $sql;
440 2999
    }
441
442 2999
    /**
443 231
     * {@inheritdoc}
444
     */
445
    public function getDefaultValueDeclarationSQL(array $field) : string
446
    {
447 2999
        // Unset the default value if the given field definition does not allow default values.
448 1948
        if ($field['type'] instanceof TextType || $field['type'] instanceof BlobType) {
449 234
            $field['default'] = null;
450
        }
451
452
        return parent::getDefaultValueDeclarationSQL($field);
453 2999
    }
454
455
    /**
456
     * Build SQL for table options
457
     *
458
     * @param mixed[] $options
459 4310
     */
460
    private function buildTableOptions(array $options) : string
461
    {
462 4310
        if (isset($options['table_options'])) {
463 780
            return $options['table_options'];
464
        }
465
466 4310
        $tableOptions = [];
467
468
        // Charset
469
        if (! isset($options['charset'])) {
470
            $options['charset'] = 'utf8';
471
        }
472
473
        $tableOptions[] = sprintf('DEFAULT CHARACTER SET %s', $options['charset']);
474
475
        // Collate
476 2999
        if (! isset($options['collate'])) {
477
            $options['collate'] = $options['charset'] . '_unicode_ci';
478 2999
        }
479
480
        $tableOptions[] = sprintf('COLLATE %s', $options['collate']);
481
482 2999
        // Engine
483
        if (! isset($options['engine'])) {
484
            $options['engine'] = 'InnoDB';
485 2999
        }
486 2987
487
        $tableOptions[] = sprintf('ENGINE = %s', $options['engine']);
488
489 2999
        // Auto increment
490
        if (isset($options['auto_increment'])) {
491
            $tableOptions[] = sprintf('AUTO_INCREMENT = %s', $options['auto_increment']);
492 2999
        }
493 2987
494
        // Comment
495
        if (isset($options['comment'])) {
496 2999
            $comment = trim($options['comment'], " '");
497
498
            $tableOptions[] = sprintf('COMMENT = %s ', $this->quoteStringLiteral($comment));
499 2999
        }
500 2768
501
        // Row format
502
        if (isset($options['row_format'])) {
503 2999
            $tableOptions[] = sprintf('ROW_FORMAT = %s', $options['row_format']);
504
        }
505
506 2999
        return implode(' ', $tableOptions);
507
    }
508
509
    /**
510
     * Build SQL for partition options.
511 2999
     *
512
     * @param mixed[] $options
513
     */
514
    private function buildPartitionOptions(array $options) : string
515
    {
516
        return isset($options['partition_options'])
517
            ? ' ' . $options['partition_options']
518 2999
            : '';
519
    }
520
521
    /**
522 2999
     * {@inheritDoc}
523
     */
524
    public function getAlterTableSQL(TableDiff $diff)
525
    {
526
        $columnSql  = [];
527
        $queryParts = [];
528
        $newName    = $diff->getNewName();
529
530
        if ($newName !== false) {
531
            $queryParts[] = 'RENAME TO ' . $newName->getQuotedName($this);
532 2999
        }
533
534 2999
        foreach ($diff->addedColumns as $column) {
535
            if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) {
536 2999
                continue;
537
            }
538
539
            $columnArray            = $column->toArray();
540
            $columnArray['comment'] = $this->getColumnComment($column);
541
            $queryParts[]           = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
542 2041
        }
543
544 2041
        foreach ($diff->removedColumns as $column) {
545 2041
            if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) {
546 2041
                continue;
547 138
            }
548
549
            $queryParts[] =  'DROP ' . $column->getQuotedName($this);
550 2041
        }
551 426
552
        foreach ($diff->changedColumns as $columnDiff) {
553
            if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) {
554
                continue;
555 426
            }
556 426
557 426
            $column      = $columnDiff->column;
558
            $columnArray = $column->toArray();
559
560 2041
            // Don't propagate default value changes for unsupported column types.
561 219
            if ($columnDiff->hasChanged('default') &&
562
                count($columnDiff->changedProperties) === 1 &&
563
                ($columnArray['type'] instanceof TextType || $columnArray['type'] instanceof BlobType)
564
            ) {
565 219
                continue;
566
            }
567
568 2041
            $columnArray['comment'] = $this->getColumnComment($column);
569 681
            $queryParts[]           =  'CHANGE ' . ($columnDiff->getOldColumnName()->getQuotedName($this)) . ' '
570
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
571
        }
572
573
        foreach ($diff->renamedColumns as $oldColumnName => $column) {
574 681
            if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) {
575 681
                continue;
576
            }
577
578 681
            $oldColumnName          = new Identifier($oldColumnName);
579 681
            $columnArray            = $column->toArray();
580 681
            $columnArray['comment'] = $this->getColumnComment($column);
581
            $queryParts[]           =  'CHANGE ' . $oldColumnName->getQuotedName($this) . ' '
582 54
                    . $this->getColumnDeclarationSQL($column->getQuotedName($this), $columnArray);
583
        }
584
585 627
        if (isset($diff->addedIndexes['primary'])) {
586 627
            $keyColumns   = array_unique(array_values($diff->addedIndexes['primary']->getColumns()));
587 627
            $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
588
            unset($diff->addedIndexes['primary']);
589
        } elseif (isset($diff->changedIndexes['primary'])) {
590 2041
            // Necessary in case the new primary key includes a new auto_increment column
591 288
            foreach ($diff->changedIndexes['primary']->getColumns() as $columnName) {
592
                if (isset($diff->addedColumns[$columnName]) && $diff->addedColumns[$columnName]->getAutoincrement()) {
593
                    $keyColumns   = array_unique(array_values($diff->changedIndexes['primary']->getColumns()));
594
                    $queryParts[] = 'DROP PRIMARY KEY';
595 288
                    $queryParts[] = 'ADD PRIMARY KEY (' . implode(', ', $keyColumns) . ')';
596 288
                    unset($diff->changedIndexes['primary']);
597 288
                    break;
598 288
                }
599 288
            }
600
        }
601
602 2041
        $sql      = [];
603 254
        $tableSql = [];
604 254
605 254
        if (! $this->onSchemaAlterTable($diff, $tableSql)) {
606
            if (count($queryParts) > 0) {
607
                $sql[] = 'ALTER TABLE ' . $diff->getName($this)->getQuotedName($this) . ' ' . implode(', ', $queryParts);
608 2041
            }
609 2041
            $sql = array_merge(
610
                $this->getPreAlterTableIndexForeignKeySQL($diff),
611 2041
                $sql,
612 2041
                $this->getPostAlterTableIndexForeignKeySQL($diff)
613 1112
            );
614
        }
615 2041
616 2041
        return array_merge($sql, $tableSql, $columnSql);
617 2041
    }
618 2041
619
    /**
620
     * {@inheritDoc}
621
     */
622 2041
    protected function getPreAlterTableIndexForeignKeySQL(TableDiff $diff) : array
623
    {
624
        $sql   = [];
625
        $table = $diff->getName($this)->getQuotedName($this);
626
627
        foreach ($diff->changedIndexes as $changedIndex) {
628 2041
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $changedIndex));
629
        }
630 2041
631 2041
        foreach ($diff->removedIndexes as $remKey => $remIndex) {
632
            $sql = array_merge($sql, $this->getPreAlterTableAlterPrimaryKeySQL($diff, $remIndex));
633 2041
634 392
            foreach ($diff->addedIndexes as $addKey => $addIndex) {
635
                if ($remIndex->getColumns() === $addIndex->getColumns()) {
636
                    $indexClause = 'INDEX ' . $addIndex->getName();
637 2041
638 243
                    if ($addIndex->isPrimary()) {
639
                        $indexClause = 'PRIMARY KEY';
640 243
                    } elseif ($addIndex->isUnique()) {
641 69
                        $indexClause = 'UNIQUE INDEX ' . $addIndex->getName();
642 69
                    }
643
644 69
                    $query  = 'ALTER TABLE ' . $table . ' DROP INDEX ' . $remIndex->getName() . ', ';
645
                    $query .= 'ADD ' . $indexClause;
646 69
                    $query .= ' (' . $this->getIndexFieldDeclarationListSQL($addIndex) . ')';
647 69
648
                    $sql[] = $query;
649
650 69
                    unset($diff->removedIndexes[$remKey], $diff->addedIndexes[$addKey]);
651 69
652 69
                    break;
653
                }
654 69
            }
655
        }
656 69
657
        $engine = 'INNODB';
658 243
659
        if ($diff->fromTable instanceof Table && $diff->fromTable->hasOption('engine')) {
660
            $engine = strtoupper(trim($diff->fromTable->getOption('engine')));
661
        }
662
663 2041
        // Suppress foreign key constraint propagation on non-supporting engines.
664
        if ($engine !== 'INNODB') {
665 2041
            $diff->addedForeignKeys   = [];
666 93
            $diff->changedForeignKeys = [];
667
            $diff->removedForeignKeys = [];
668
        }
669
670 2041
        $sql = array_merge(
671 69
            $sql,
672 69
            $this->getPreAlterTableAlterIndexForeignKeySQL($diff),
673 69
            parent::getPreAlterTableIndexForeignKeySQL($diff),
674
            $this->getPreAlterTableRenameIndexForeignKeySQL($diff)
675
        );
676 2041
677 2041
        return $sql;
678 2041
    }
679 2041
680 2041
    /**
681
     * @return string[]
682
     */
683 2041
    private function getPreAlterTableAlterPrimaryKeySQL(TableDiff $diff, Index $index) : array
684
    {
685
        $sql = [];
686
687
        if (! $index->isPrimary() || ! $diff->fromTable instanceof Table) {
688
            return $sql;
689 623
        }
690
691 623
        $tableName = $diff->getName($this)->getQuotedName($this);
692
693 623
        // Dropping primary keys requires to unset autoincrement attribute on the particular column first.
694 243
        foreach ($index->getColumns() as $columnName) {
695
            if (! $diff->fromTable->hasColumn($columnName)) {
696
                continue;
697 380
            }
698
699
            $column = $diff->fromTable->getColumn($columnName);
700 380
701 380
            if ($column->getAutoincrement() !== true) {
702 69
                continue;
703
            }
704
705 380
            $column->setAutoincrement(false);
706
707 380
            $sql[] = 'ALTER TABLE ' . $tableName . ' MODIFY ' .
708 311
                $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
709
710
            // original autoincrement information might be needed later on by other parts of the table alteration
711 219
            $column->setAutoincrement(true);
712
        }
713 219
714 219
        return $sql;
715
    }
716
717 219
    /**
718
     * @param TableDiff $diff The table diff to gather the SQL for.
719
     *
720 380
     * @return string[]
721
     */
722
    private function getPreAlterTableAlterIndexForeignKeySQL(TableDiff $diff) : array
723
    {
724
        $sql   = [];
725
        $table = $diff->getName($this)->getQuotedName($this);
726
727
        foreach ($diff->changedIndexes as $changedIndex) {
728 2041
            // Changed primary key
729
            if (! $changedIndex->isPrimary() || ! ($diff->fromTable instanceof Table)) {
730 2041
                continue;
731 2041
            }
732
733 2041
            foreach ($diff->fromTable->getPrimaryKeyColumns() as $columnName) {
734
                $column = $diff->fromTable->getColumn($columnName);
735 392
736 93
                // Check if an autoincrement column was dropped from the primary key.
737
                if (! $column->getAutoincrement() || in_array($columnName, $changedIndex->getColumns())) {
738
                    continue;
739 299
                }
740 299
741
                // The autoincrement attribute needs to be removed from the dropped column
742
                // before we can drop and recreate the primary key.
743 299
                $column->setAutoincrement(false);
744 230
745
                $sql[] = 'ALTER TABLE ' . $table . ' MODIFY ' .
746
                    $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray());
747
748
                // Restore the autoincrement attribute as it might be needed later on
749 69
                // by other parts of the table alteration.
750
                $column->setAutoincrement(true);
751 69
            }
752 69
        }
753
754
        return $sql;
755
    }
756 299
757
    /**
758
     * @param TableDiff $diff The table diff to gather the SQL for.
759
     *
760 2041
     * @return string[]
761
     */
762
    protected function getPreAlterTableRenameIndexForeignKeySQL(TableDiff $diff) : array
763
    {
764
        $sql       = [];
765
        $tableName = $diff->getName($this)->getQuotedName($this);
766
767
        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
768 1405
            if (in_array($foreignKey, $diff->changedForeignKeys, true)) {
769
                continue;
770 1405
            }
771 1405
772
            $sql[] = $this->getDropForeignKeySQL($foreignKey, $tableName);
773 1405
        }
774 56
775
        return $sql;
776
    }
777
778 56
    /**
779
     * Returns the remaining foreign key constraints that require one of the renamed indexes.
780
     *
781 1405
     * "Remaining" here refers to the diff between the foreign keys currently defined in the associated
782
     * table and the foreign keys to be removed.
783
     *
784
     * @param TableDiff $diff The table diff to evaluate.
785
     *
786
     * @return ForeignKeyConstraint[]
787
     */
788
    private function getRemainingForeignKeyConstraintsRequiringRenamedIndexes(TableDiff $diff) : array
789
    {
790
        if (empty($diff->renamedIndexes) || ! $diff->fromTable instanceof Table) {
791
            return [];
792
        }
793
794 1405
        $foreignKeys = [];
795
        /** @var ForeignKeyConstraint[] $remainingForeignKeys */
796 1405
        $remainingForeignKeys = array_diff_key(
797 1165
            $diff->fromTable->getForeignKeys(),
798
            $diff->removedForeignKeys
799
        );
800 250
801
        foreach ($remainingForeignKeys as $foreignKey) {
802 250
            foreach ($diff->renamedIndexes as $index) {
803 250
                if ($foreignKey->intersectsIndexColumns($index)) {
804 250
                    $foreignKeys[] = $foreignKey;
805
806
                    break;
807 250
                }
808 56
            }
809 56
        }
810 56
811
        return $foreignKeys;
812 56
    }
813
814
    /**
815
     * {@inheritdoc}
816
     */
817 250
    protected function getPostAlterTableIndexForeignKeySQL(TableDiff $diff) : array
818
    {
819
        return array_merge(
820
            parent::getPostAlterTableIndexForeignKeySQL($diff),
821
            $this->getPostAlterTableRenameIndexForeignKeySQL($diff)
822
        );
823 2041
    }
824
825 2041
    /**
826 2041
     * @param TableDiff $diff The table diff to gather the SQL for.
827 2041
     *
828
     * @return string[]
829
     */
830
    protected function getPostAlterTableRenameIndexForeignKeySQL(TableDiff $diff) : array
831
    {
832
        $sql     = [];
833
        $newName = $diff->getNewName();
834
835
        if ($newName !== false) {
836 1405
            $tableName = $newName->getQuotedName($this);
837
        } else {
838 1405
            $tableName = $diff->getName($this)->getQuotedName($this);
839 1405
        }
840 92
841 1405
        foreach ($this->getRemainingForeignKeyConstraintsRequiringRenamedIndexes($diff) as $foreignKey) {
842
            if (in_array($foreignKey, $diff->changedForeignKeys, true)) {
843 1405
                continue;
844 56
            }
845
846
            $sql[] = $this->getCreateForeignKeySQL($foreignKey, $tableName);
847
        }
848 56
849
        return $sql;
850
    }
851 1405
852
    /**
853
     * {@inheritDoc}
854
     */
855
    protected function getCreateIndexSQLFlags(Index $index) : string
856
    {
857 1251
        $type = '';
858
        if ($index->isUnique()) {
859 1251
            $type .= 'UNIQUE ';
860 1251
        } elseif ($index->hasFlag('fulltext')) {
861 267
            $type .= 'FULLTEXT ';
862 1020
        } elseif ($index->hasFlag('spatial')) {
863 81
            $type .= 'SPATIAL ';
864 939
        }
865 81
866
        return $type;
867
    }
868 1251
869
    /**
870
     * {@inheritDoc}
871
     */
872
    public function getIntegerTypeDeclarationSQL(array $columnDef) : string
873
    {
874 3039
        return 'INT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
875
    }
876 3039
877
    /**
878
     * {@inheritDoc}
879
     */
880
    public function getBigIntTypeDeclarationSQL(array $columnDef) : string
881
    {
882 180
        return 'BIGINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
883
    }
884 180
885
    /**
886
     * {@inheritDoc}
887
     */
888
    public function getSmallIntTypeDeclarationSQL(array $columnDef) : string
889
    {
890 12
        return 'SMALLINT' . $this->_getCommonIntegerTypeDeclarationSQL($columnDef);
891
    }
892 12
893
    /**
894
     * {@inheritdoc}
895
     */
896
    public function getFloatDeclarationSQL(array $fieldDeclaration) : string
897
    {
898 606
        return 'DOUBLE PRECISION' . $this->getUnsignedDeclaration($fieldDeclaration);
899
    }
900 606
901
    /**
902
     * {@inheritdoc}
903
     */
904
    public function getDecimalTypeDeclarationSQL(array $columnDef) : string
905
    {
906 654
        return parent::getDecimalTypeDeclarationSQL($columnDef) . $this->getUnsignedDeclaration($columnDef);
907
    }
908 654
909
    /**
910
     * Get unsigned declaration for a column.
911
     *
912
     * @param mixed[] $columnDef
913
     */
914
    private function getUnsignedDeclaration(array $columnDef) : string
915
    {
916
        return ! empty($columnDef['unsigned']) ? ' UNSIGNED' : '';
917
    }
918 3891
919
    /**
920 3891
     * {@inheritDoc}
921
     */
922
    protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) : string
923
    {
924
        $autoinc = '';
925
        if (! empty($columnDef['autoincrement'])) {
926 3039
            $autoinc = ' AUTO_INCREMENT';
927
        }
928 3039
929 3039
        return $this->getUnsignedDeclaration($columnDef) . $autoinc;
930 471
    }
931
932
    /**
933 3039
     * {@inheritDoc}
934
     */
935
    public function getColumnCharsetDeclarationSQL(string $charset) : string
936
    {
937
        return 'CHARACTER SET ' . $charset;
938
    }
939 615
940
    /**
941 615
     * {@inheritDoc}
942 615
     */
943
    public function getAdvancedForeignKeyOptionsSQL(ForeignKeyConstraint $foreignKey) : string
944
    {
945 615
        $query = '';
946
        if ($foreignKey->hasOption('match')) {
947 615
            $query .= ' MATCH ' . $foreignKey->getOption('match');
948
        }
949
        $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey);
950
951
        return $query;
952
    }
953 806
954
    /**
955 806
     * {@inheritDoc}
956 554
     */
957 262
    public function getDropIndexSQL($index, $table = null) : string
958 262
    {
959
        if ($index instanceof Index) {
960
            $indexName = $index->getQuotedName($this);
961
        } elseif (is_string($index)) {
962
            $indexName = $index;
963 806
        } else {
964 12
            throw new InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $index parameter to be string or \Doctrine\DBAL\Schema\Index.');
965 794
        }
966
967
        if ($table instanceof Table) {
968
            $table = $table->getQuotedName($this);
969 806
        } elseif (! is_string($table)) {
970
            throw new InvalidArgumentException('MysqlPlatform::getDropIndexSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
971
        }
972 449
973
        if ($index instanceof Index && $index->isPrimary()) {
974
            // mysql primary keys are always named "PRIMARY",
975 357
            // so we cannot use them in statements because of them being keyword.
976
            return $this->getDropPrimaryKeySQL($table);
977
        }
978
979
        return 'DROP INDEX ' . $indexName . ' ON ' . $table;
980
    }
981
982
    protected function getDropPrimaryKeySQL(string $table) : string
983 449
    {
984
        return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
985 449
    }
986
987
    /**
988
     * {@inheritDoc}
989
     */
990
    public function getSetTransactionIsolationSQL(int $level) : string
991 69
    {
992
        return 'SET SESSION TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level);
993 69
    }
994
995
    /**
996
     * {@inheritDoc}
997
     */
998
    public function getName() : string
999 1200
    {
1000
        return 'mysql';
1001 1200
    }
1002
1003
    /**
1004
     * {@inheritDoc}
1005
     */
1006
    public function getReadLockSQL() : string
1007
    {
1008
        return 'LOCK IN SHARE MODE';
1009
    }
1010
1011
    /**
1012
     * {@inheritDoc}
1013
     */
1014
    protected function initializeDoctrineTypeMappings() : void
1015 415
    {
1016
        $this->doctrineTypeMapping = [
1017 415
            'bigint'     => 'bigint',
1018
            'binary'     => 'binary',
1019
            'blob'       => 'blob',
1020
            'char'       => 'string',
1021
            'date'       => 'date',
1022
            'datetime'   => 'datetime',
1023
            'decimal'    => 'decimal',
1024
            'double'     => 'float',
1025
            'float'      => 'float',
1026
            'int'        => 'integer',
1027
            'integer'    => 'integer',
1028
            'longblob'   => 'blob',
1029
            'longtext'   => 'text',
1030
            'mediumblob' => 'blob',
1031
            'mediumint'  => 'integer',
1032
            'mediumtext' => 'text',
1033
            'numeric'    => 'decimal',
1034
            'real'       => 'float',
1035
            'set'        => 'simple_array',
1036
            'smallint'   => 'smallint',
1037
            'string'     => 'string',
1038
            'text'       => 'text',
1039
            'time'       => 'time',
1040
            'timestamp'  => 'datetime',
1041
            'tinyblob'   => 'blob',
1042
            'tinyint'    => 'boolean',
1043
            'tinytext'   => 'text',
1044
            'varbinary'  => 'binary',
1045
            'varchar'    => 'string',
1046
            'year'       => 'date',
1047
        ];
1048
    }
1049 415
1050
    /**
1051
     * {@inheritDoc}
1052
     */
1053
    public function getVarcharMaxLength() : int
1054 1992
    {
1055
        return 65535;
1056 1992
    }
1057
1058
    /**
1059
     * {@inheritdoc}
1060
     */
1061
    public function getBinaryMaxLength() : int
1062 69
    {
1063
        return 65535;
1064 69
    }
1065
1066
    /**
1067
     * {@inheritDoc}
1068
     */
1069
    protected function getReservedKeywordsClass()
1070 1526
    {
1071
        return Keywords\MySQLKeywords::class;
1072 1526
    }
1073
1074
    /**
1075
     * {@inheritDoc}
1076
     *
1077
     * MySQL commits a transaction implicitly when DROP TABLE is executed, however not
1078
     * if DROP TEMPORARY TABLE is executed.
1079
     */
1080
    public function getDropTemporaryTableSQL($table) : string
1081 24
    {
1082
        if ($table instanceof Table) {
1083 24
            $table = $table->getQuotedName($this);
1084
        } elseif (! is_string($table)) {
1085 24
            throw new InvalidArgumentException('getDropTemporaryTableSQL() expects $table parameter to be string or \Doctrine\DBAL\Schema\Table.');
1086
        }
1087
1088
        return 'DROP TEMPORARY TABLE ' . $table;
1089 24
    }
1090
1091
    /**
1092
     * Gets the SQL Snippet used to declare a BLOB column type.
1093
     *     TINYBLOB   : 2 ^  8 - 1 = 255
1094
     *     BLOB       : 2 ^ 16 - 1 = 65535
1095
     *     MEDIUMBLOB : 2 ^ 24 - 1 = 16777215
1096
     *     LONGBLOB   : 2 ^ 32 - 1 = 4294967295
1097
     *
1098
     * {@inheritDoc}
1099
     */
1100
    public function getBlobTypeDeclarationSQL(array $field) : string
1101 231
    {
1102
        if (! empty($field['length']) && is_numeric($field['length'])) {
1103 231
            $length = $field['length'];
1104 93
1105
            if ($length <= static::LENGTH_LIMIT_TINYBLOB) {
1106 93
                return 'TINYBLOB';
1107 81
            }
1108
1109
            if ($length <= static::LENGTH_LIMIT_BLOB) {
1110 93
                return 'BLOB';
1111 81
            }
1112
1113
            if ($length <= static::LENGTH_LIMIT_MEDIUMBLOB) {
1114 93
                return 'MEDIUMBLOB';
1115 81
            }
1116
        }
1117
1118
        return 'LONGBLOB';
1119 231
    }
1120
1121
    /**
1122
     * {@inheritdoc}
1123
     */
1124
    public function quoteStringLiteral(string $str) : string
1125 2355
    {
1126
        $str = str_replace('\\', '\\\\', $str); // MySQL requires backslashes to be escaped aswell.
1127 2355
1128
        return parent::quoteStringLiteral($str);
1129 2355
    }
1130
1131
    /**
1132
     * {@inheritdoc}
1133
     */
1134
    public function getDefaultTransactionIsolationLevel() : int
1135 23
    {
1136
        return TransactionIsolationLevel::REPEATABLE_READ;
1137 23
    }
1138
1139
    /**
1140
     * {@inheritdoc}
1141
     */
1142
    public function supportsColumnLengthIndexes() : bool
1143 3101
    {
1144
        return true;
1145 3101
    }
1146
1147
    /**
1148
     * Returns an SQL expression representing the given database name or current database name
1149
     *
1150
     * @param string|null $database Database name
1151
     */
1152
    private function getDatabaseNameSql(?string $database) : string
1153
    {
1154
        if ($database === null) {
1155
            return 'DATABASE()';
1156
        }
1157
1158
        return $this->quoteStringLiteral($database);
1159
    }
1160
}
1161