MySqlPlatform::getAlterTableSQL()   F
last analyzed

Complexity

Conditions 17
Paths 1296

Size

Total Lines 80
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 45
CRAP Score 17.157

Importance

Changes 0
Metric Value
eloc 48
dl 0
loc 80
ccs 45
cts 49
cp 0.9184
rs 1.0499
c 0
b 0
f 0
cc 17
nc 1296
nop 1
crap 17.157

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