Completed
Pull Request — master (#2415)
by Benoît
22:09
created

getPreAlterTableIndexForeignKeySQL()   B

Complexity

Conditions 10
Paths 48

Size

Total Lines 56
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 10.0027

Importance

Changes 0
Metric Value
eloc 32
dl 0
loc 56
ccs 32
cts 33
cp 0.9697
rs 7.6666
c 0
b 0
f 0
cc 10
nc 48
nop 1
crap 10.0027

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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